In this section
- VEDIC Daily Operations storage · vedic- / tools/daily_operations.py lines 1–322
- VEDIC Daily Source Policy storage · vedic- / tools/daily_source_policy.py lines 1–210
- VEDIC Dictionary Shards storage · vedic- / tools/dictionary_shards.py lines 1–86
VEDIC Daily Operations
A Python command-line tool in the tools folder that merges candidates (`merge_candidates`), covering command candidates, dictionary, admitted queue archive and family research, using SHA-256.
storagevedic- / tools/daily_operations.py · lines 1–322 of 322 · Entry point · pattern research (shared by 2 files)
- What it does
- Defines 20 functions or classes, including require, run, git, gh_json, read_json. Uses libraries argparse, hashlib, json, os, re. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file source-command-candidates.json; JSON file dictionary.json; JSON file admitted-queue-archive.json; JSON file family-research.json; JSON file state-update.json; JSON file checkpoint.json; JSON file policy-candidates.json; JSON file proposal.json.
- Downstream impact
- Used directly by 2 files: VEDIC Test Daily Operations (vedic-); VEDIC Modular Consumer Workflow (vedic-). Reached from 1 other entry point, including VEDIC Anatomy Workflow (vedic-).
- What it achieves
- It reads JSON (`read_json`), writes JSON (`write_json`) and loads state (`load_state`). Retain scheduled family progress and prepare reviewable VEDIC Git bundles. It reads `family-research.json` and writes `family-research.json`. It accepts `--output`, `--commit` and `--run-id`.
- Why it matters
- Run by VEDIC Modular Consumer Workflow. Checked by VEDIC Test Daily Operations.
- Application
- vedic- · tools · Python CLI
- Uses
- VEDIC Daily Accelerator (import), VEDIC Source Admissions (import), VEDIC Family Pulse (script call), VEDIC Daily Source Policy (script call), VEDIC Allocate Commands (script call), argparse, hashlib, json, os, re, subprocess, sys, tempfile
- Used by
- imported by VEDIC Test Daily Operations (import), run by VEDIC Modular Consumer Workflow (workflow run)
- Produces
- require, run, git, gh_json, read_json, json_bytes, write_json, oid, command, remote_oid, family_receipt, state_receipt
- Defines here
- require, run, git, gh_json, read_json, json_bytes, write_json, oid, command, remote_oid, family_receipt, state_receipt, load_state, legacy_checkpoint, research, persist, merge_candidates, proposal, review_pr, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/daily_operations.py:1-322 · blob 665d4124557e04c4ef240ec8545a4498000181b9 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Retain scheduled family progress and prepare reviewable VEDIC Git bundles."""
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys
import tempfile
from datetime import datetime, timezone
from pathlib import Path
import daily_accelerator
ROOT = Path(__file__).resolve().parents[1]
STATE_REF = "refs/heads/automation/vedic-daily-state"
STATE_SCHEMA = "vedic.daily-state.v1"
FAMILY_SCHEMA = "vedic.daily-family-pulse.v2"
BUNDLE_REF = "refs/heads/automation/vedic-daily-proposal-bundle"
PROPOSAL_PREFIX = "automation/vedic-daily-proposal-"
PROPOSAL_SCHEMA = "vedic.daily-proposal.v1"
QUEUE = "data/source-command-candidates.json"
DICTIONARY = "data/dictionary.json"
ARCHIVE = "data/admitted-queue-archive.json"
MAX_BATCH = 20
MAX_BUNDLE_BYTES = 16 * 1024 * 1024
IDENTITY = {
"GIT_AUTHOR_NAME": "VEDIC daily automation",
"GIT_AUTHOR_EMAIL": "vedic-daily@users.noreply.github.com",
"GIT_COMMITTER_NAME": "VEDIC daily automation",
"GIT_COMMITTER_EMAIL": "vedic-daily@users.noreply.github.com",
}
def require(condition, message):
if not condition:
raise ValueError(message)
def run(root, *args, data=None, env=None):
return subprocess.run(args, cwd=root, input=data, stdout=subprocess.PIPE, check=True,
timeout=200, env={**os.environ, **(env or {})}).stdout
def git(root, *args, **kwargs):
return run(root, "git", *args, **kwargs)
def gh_json(root, *args):
return json.loads(run(root, "gh", *args))
def read_json(path):
return json.loads(path.read_bytes())
def json_bytes(value):
return (json.dumps(value, ensure_ascii=False, indent=2) + "\n").encode("utf-8")
def write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(json_bytes(value))
def oid(value):
require(isinstance(value, str) and re.fullmatch(r"[0-9a-f]{40}", value), "invalid Git commit")
return value
def command(root, *args):
return run(root, sys.executable, *args)
def remote_oid(root, ref):
lines = git(root, "ls-remote", "--refs", "origin", ref).decode().splitlines()
if not lines:
return None
require(len(lines) == 1 and lines[0].endswith("\t" + ref), "ambiguous remote ref")
return oid(lines[0].split("\t")[0])
def family_receipt(receipt):
require(receipt.get("schema") == FAMILY_SCHEMA, "unsupported family checkpoint schema")
old, new, count = (receipt.get(key) for key in ("previous_cursor", "next_cursor", "scanned_families"))
require(all(type(value) is int for value in (old, new, count)) and 0 <= old <= new and
0 <= count <= 100 and (new > old) == (count > 0), "invalid family progress")
family_hash = receipt.get("cursor_family_hash")
require((new == 0 and family_hash is None) or
(isinstance(family_hash, str) and re.fullmatch(r"[0-9a-f]{40,64}", family_hash)),
"invalid checkpoint identity")
require(receipt.get("status") == ("research_candidates" if count else "no_change"),
"invalid family receipt status")
return receipt
def state_receipt(state):
require(state.get("schema") == STATE_SCHEMA, "unsupported durable checkpoint schema")
oid(state["source_commit"])
require(type(state.get("run_id")) is int and state["run_id"] > 0, "invalid checkpoint run ID")
family_receipt(state["family"])
if "accelerator" in state:
daily_accelerator.validate(state["accelerator"])
return state
def load_state(root):
existing = remote_oid(root, STATE_REF)
if existing is None:
return None, None
git(root, "fetch", "--no-tags", "--depth=1", "origin", STATE_REF)
fetched = oid(git(root, "rev-parse", "FETCH_HEAD").decode().strip())
return fetched, state_receipt(json.loads(git(root, "show", f"{fetched}:checkpoint.json")))
def legacy_checkpoint(root, run_id, scratch):
current = gh_json(root, "run", "view", str(run_id), "--json", "createdAt")
created = current["createdAt"]
date = created.split("T", 1)[0]
if date < "2026-11-27":
return None
runs = gh_json(root, "run", "list", "--workflow", "modular-consumer.yml", "--event", "schedule",
"--branch", "main", "--status", "success", "--created", f"2026-11-27..{date}",
"--limit", "100", "--json", "databaseId,createdAt")
prior = max((item for item in runs if item["createdAt"] < created),
key=lambda item: item["createdAt"], default=None)
if prior is None:
return None
previous = str(prior["databaseId"])
artifacts = gh_json(root, "api", f"repos/{os.environ['GITHUB_REPOSITORY']}/actions/runs/{previous}/artifacts")
available = {record["name"] for record in artifacts["artifacts"] if not record["expired"]}
name = f"vedic-research-{previous}"
if name not in available:
attempt = gh_json(root, "run", "view", previous, "--json", "attempt")["attempt"]
name = f"vedic-research-{previous}-{attempt}"
require(name in available, "earlier family receipt expired; restore a known durable checkpoint")
run(root, "gh", "run", "download", previous, "--name", name,
"--dir", str(scratch))
receipts = list(scratch.rglob("family-research.json"))
require(len(receipts) == 1, "expected one earlier family receipt; restore a known durable checkpoint")
return family_receipt(read_json(receipts[0]))
def research(root, output, source_commit, run_id, accelerator=False):
output.mkdir(parents=True, exist_ok=True)
base, state = load_state(root) if run_id else (None, None)
if state and state["run_id"] == run_id:
write_json(output / "family-research.json", state["family"])
if "accelerator" in state:
write_json(output / daily_accelerator.RECEIPT, {
"status": "already_recorded", "checkpoint": state["accelerator"],
})
write_json(output / "state-update.json", {"base": base, "checkpoint": state})
print("Family progress was already recorded for this run.")
return
require(not state or state["run_id"] < run_id, "a later scheduled run already recorded progress")
with tempfile.TemporaryDirectory(prefix="vedic-daily-state-") as path:
scratch = Path(path)
checkpoint = state["family"] if state else legacy_checkpoint(root, run_id, scratch) if run_id else None
args = ["tools/family_pulse.py", "--output", str(output)]
if checkpoint:
checkpoint_path = scratch / "checkpoint.json"
write_json(checkpoint_path, checkpoint)
args.extend(("--checkpoint", str(checkpoint_path)))
print(command(root, *args).decode())
receipt = family_receipt(read_json(output / "family-research.json"))
require(receipt["previous_cursor"] == (checkpoint["next_cursor"] if checkpoint else 0),
"family output does not advance the input cursor")
progress = state.get("accelerator") if state else None
if accelerator:
progress = daily_accelerator.research(root, output, progress)
if run_id:
result = {"schema": STATE_SCHEMA, "source_commit": oid(source_commit), "run_id": run_id, "family": receipt}
if progress is not None:
result["accelerator"] = progress
write_json(output / "state-update.json", {"base": base, "checkpoint": result})
def persist(root, update, source_commit, run_id):
checkpoint = state_receipt(update["checkpoint"])
require(checkpoint["source_commit"] == oid(source_commit) and checkpoint["run_id"] == run_id,
"checkpoint does not belong to this scheduled run")
base, previous = load_state(root)
if previous == checkpoint:
print("Family progress was already recorded for this run.")
return
require(base == update["base"], "durable checkpoint changed while processing; retry from its latest state")
require(not previous or previous["run_id"] < run_id, "scheduled run would replace newer family progress")
require(not previous or checkpoint["family"]["previous_cursor"] == previous["family"]["next_cursor"],
"checkpoint does not continue durable family progress")
daily_accelerator.verify_advance(previous.get("accelerator") if previous else None, checkpoint.get("accelerator"))
blob = git(root, "hash-object", "-w", "--stdin", data=json_bytes(checkpoint)).decode().strip()
tree = git(root, "mktree", data=f"100644 blob {blob}\tcheckpoint.json\n".encode()).decode().strip()
parent = ("-p", base) if base else ()
commit = git(root, "commit-tree", tree, *parent, "-m", f"Record VEDIC daily family progress ({run_id})",
env=IDENTITY).decode().strip()
git(root, "push", "--porcelain", "origin", f"{oid(commit)}:{STATE_REF}")
print(f"Stored family cursor {checkpoint['family']['next_cursor']} at {commit}.")
def merge_candidates(queue, discovered):
from source_admissions import candidate_id
require(queue.get("schema") == discovered.get("schema") == "vedic.source-candidates.v1", "candidate schema")
require(isinstance(discovered.get("records"), list) and len(discovered["records"]) <= MAX_BATCH,
"policy candidate budget")
known = {candidate_id(candidate): candidate for candidate in queue["records"]}
for candidate in discovered["records"]:
key = candidate_id(candidate)
if key in known:
require(candidate == known[key], "reviewed candidate identity conflicts with existing queue record")
continue
known[key] = candidate
queue["records"].append(candidate)
return queue
def proposal(root, output, created_at=None):
require(not git(root, "branch", "--show-current"), "proposal requires an isolated detached checkout")
require(not git(root, "status", "--porcelain", "--untracked-files=no"), "proposal requires a clean checkout")
head = oid(git(root, "rev-parse", "HEAD").decode().strip())
date = created_at or datetime.now(timezone.utc).isoformat(timespec="seconds")
identity = {**IDENTITY, "GIT_AUTHOR_DATE": date, "GIT_COMMITTER_DATE": date}
output.mkdir(parents=True, exist_ok=True)
discovery_path = output / "policy-candidates.json"
print(command(root, "tools/daily_source_policy.py", "--output", str(discovery_path)).decode())
queue_path = root / QUEUE
queue = read_json(queue_path)
discovery = read_json(discovery_path)
initial_count = len(queue["records"])
combined = merge_candidates(queue, discovery)
if len(combined["records"]) > initial_count:
write_json(queue_path, combined)
git(root, "add", "--", QUEUE)
git(root, "-c", "commit.gpgSign=false", "commit", "-m", "Queue VEDIC source policy candidates", env=identity)
manifest = oid(git(root, "log", "-1", "--format=%H", "--", QUEUE).decode().strip())
with tempfile.TemporaryDirectory(prefix="vedic-daily-proposal-") as folder:
staged = Path(folder) / "staged"
result = json.loads(command(root, "tools/source_admissions.py", "--prepare", "--limit", str(MAX_BATCH),
"--output-dir", str(staged)))
receipt = {"schema": PROPOSAL_SCHEMA, "base": head, "manifest_commit": manifest,
"added": result["added"], "held": result["held"], "dictionary_count": result["count"]}
if result["added"]:
for relative in (DICTIONARY, ARCHIVE):
(root / relative).write_bytes((staged / relative).read_bytes())
git(root, "add", "--", DICTIONARY, ARCHIVE)
git(root, "-c", "commit.gpgSign=false", "commit", "-m", "Apply reviewed VEDIC source admissions", env=identity)
print(command(root, "tools/allocate_commands.py", "--check").decode())
print(command(root, "tools/source_admissions.py", "--check", "--online").decode())
candidate = oid(git(root, "rev-parse", "HEAD").decode().strip())
git(root, "update-ref", BUNDLE_REF, candidate)
bundle = output / "proposal.bundle"
git(root, "bundle", "create", str(bundle), BUNDLE_REF, "^" + head)
require(bundle.stat().st_size <= MAX_BUNDLE_BYTES, "proposal bundle exceeds its byte budget")
receipt.update(status="ready_for_review", head=candidate, bundle_ref=BUNDLE_REF,
bundle_sha256=hashlib.sha256(bundle.read_bytes()).hexdigest())
else:
receipt["status"] = "no_change"
write_json(output / "proposal.json", receipt)
print(json_bytes(receipt).decode())
def review_pr(root, output, repository):
receipt = read_json(output / "proposal.json")
require(receipt["schema"] == PROPOSAL_SCHEMA and receipt["status"] == "ready_for_review", "proposal is not ready")
base, candidate = oid(receipt["base"]), oid(receipt["head"])
bundle = output / "proposal.bundle"
require(bundle.stat().st_size <= MAX_BUNDLE_BYTES and
hashlib.sha256(bundle.read_bytes()).hexdigest() == receipt["bundle_sha256"], "proposal bundle integrity")
if remote_oid(root, "refs/heads/main") != base:
print("Main advanced before PR opening. The proposal remains available for review in the run artifact.")
return
open_prs = gh_json(root, "pr", "list", "--repo", repository, "--base", "main", "--state", "open",
"--limit", "100", "--json", "headRefName,url")
for record in open_prs:
if record["headRefName"].startswith(PROPOSAL_PREFIX):
print(f"A daily review PR is already open: {record['url']}")
return
git(root, "bundle", "verify", str(bundle))
local_ref = "refs/vedic-daily/review"
git(root, "fetch", str(bundle), f"{BUNDLE_REF}:{local_ref}")
require(git(root, "rev-parse", local_ref).decode().strip() == candidate, "bundle head differs from receipt")
changed = set(git(root, "diff", "--name-only", base, candidate).decode().splitlines())
require({DICTIONARY, ARCHIVE} <= changed <= {QUEUE, DICTIONARY, ARCHIVE}, "unexpected proposal paths")
branch = PROPOSAL_PREFIX + candidate[:20]
git(root, "push", "--porcelain", "origin", f"{candidate}:refs/heads/{branch}")
message = (f"Proposed {len(receipt['added'])} source-reviewed meanings.\n\n"
f"Pinned reviewed manifest: `{receipt['manifest_commit']}`.\n\n"
"Review evidence and wait for CI. Use a merge commit to retain the pinned manifest commit.")
with tempfile.TemporaryDirectory(prefix="vedic-daily-review-") as folder:
body = Path(folder) / "body.md"
body.write_text(message, encoding="utf-8")
print(run(root, "gh", "pr", "create", "--repo", repository, "--base", "main", "--head", branch,
"--title", "VEDIC: apply bounded daily source admissions", "--body-file", str(body)).decode())
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("stage", choices=("research", "persist", "proposal", "review-pr"))
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--commit", default=os.environ.get("GITHUB_SHA"))
parser.add_argument("--run-id", type=int)
parser.add_argument("--accelerator", action="store_true")
parser.add_argument("--created-at")
parser.add_argument("--repository", default=os.environ.get("GITHUB_REPOSITORY"))
args = parser.parse_args()
output = args.output.resolve()
if args.stage == "research":
research(ROOT, output, args.commit, args.run_id, args.accelerator)
elif args.stage == "persist":
require(args.run_id is not None, "missing scheduled run ID")
persist(ROOT, read_json(output / "state-update.json"), args.commit, args.run_id)
elif args.stage == "proposal":
proposal(ROOT, output, args.created_at)
else:
require(args.repository == "Ventusltd/vedic-", "unexpected repository for review PR")
review_pr(ROOT, output, args.repository)
if __name__ == "__main__":
main()VEDIC Daily Source Policy
A Python command-line tool in the tools folder that fetches SatNav contracts, admitted queue archive and solar.
storagevedic- / tools/daily_source_policy.py · lines 1–210 of 210 · Entry point
- What it does
- It fetches SatNav contracts, admitted queue archive and solar. Defines pinned_functions, reproduce_candidate, discover_candidates, main. Uses libraries argparse, ast, hashlib, json, pathlib. Side effects: reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: solar.
- Inputs & outputs
- In: JSON file satnav-source-contracts.json; JSON file admitted-queue-archive.json; DuckDB queries; command-line arguments.
- Downstream impact
- Used directly by 4 files: VEDIC Daily Operations (vedic-); VEDIC Source Admissions (vedic-); VEDIC Test Daily Operations (vedic-); VEDIC Test Daily Source Policy (vedic-). Reached from 4 other entry points, including VEDIC Anatomy Workflow (vedic-); VEDIC Modular Consumer Workflow (vedic-); VEDIC Allocate Commands (vedic-).
- What it achieves
- It is built from the pinned functions helper (`pinned_functions`), the reproduce candidate helper (`reproduce_candidate`) and the discover candidates helper (`discover_candidates`). Reproduce static command contracts from a bounded set of reviewed source pins. It accepts `--output`.
- Why it matters
- Imported by VEDIC Source Admissions. Run by VEDIC Daily Operations. Checked by 2 tests, including VEDIC Test Daily Operations.
- Application
- vedic- · tools · Python CLI
- Uses
- VEDIC Daily Intelligence (import), VEDIC Source Evidence (import), VEDIC Source Admissions (import), argparse, ast, hashlib, json, pathlib, urllib.parse
- Used by
- run by VEDIC Daily Operations (script call), imported by VEDIC Source Admissions (import), run by VEDIC Test Daily Operations (script call), imported by VEDIC Test Daily Source Policy (import)
- Produces
- pinned_functions, reproduce_candidate, discover_candidates, main
- Defines here
- pinned_functions, reproduce_candidate, discover_candidates, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/daily_source_policy.py:1-210 · blob c08f50ededa6bd810ebc482decc7db80471ab575 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Reproduce static command contracts from a bounded set of reviewed source pins."""
import argparse
import ast
import hashlib
import json
from pathlib import Path
from urllib.parse import quote
from daily_intelligence import MAX_BYTES, PIN, ROOT, fetch
from source_evidence import (
LIGHTNING_LAYER_SOURCE,
LIGHTNING_LAYER_SYMBOL,
source_link,
verify_blob,
verify_exact_span,
)
POLICY = "vedic.static-source.v1"
# A name or a high similarity score cannot establish these contracts. Each
# descriptor is scoped to the reviewable immutable source file below.
CONTRACTS = {
"audit_file": {
"word": "AUDIT SECTOR PARQUET",
"purpose": "Check a sector intelligence Parquet file against its schema, keys and staged values.",
"inputs": ["DuckDB connection with the staged dataset", "Parquet file path",
"sector dataset definition", "stage label"],
"output": "Audit record with row counts, key checks, typed value checks, null counts, compression and file digest.",
"limits": "Requires the matching staged data and sector schema. Refuses schema, key, typed value, required-null or compression mismatches.",
},
"build_browser_projection": {
"word": "BUILD SECTOR BROWSER PROJECTION",
"purpose": "Build a topic-ranked browser data projection from landed sector intelligence Parquet files.",
"inputs": ["DuckDB connection", "landed sector items, topic and binding file paths",
"sector intelligence contract with browser row limit"],
"output": "Browser projection with fields, bounded topic rows and counts before the limit.",
"limits": "Uses the existing sector release ordering and per-topic cap. Refuses selected rows with project bindings or news eligibility. Publication is separate.",
},
"validate_contract": {
"word": "VERIFY SECTOR DATA CONTRACT",
"purpose": "Check that a Pipeline News sector release contract matches its declared dataset and storage rules.",
"inputs": ["Pipeline News sector release contract for the pinned generation"],
"output": "Validated dataset definitions indexed by dataset name.",
"limits": "Specific to the source generation, provenance, dataset order, keys, physical types, ZSTD layout and federation policy. A mismatch raises an error.",
},
"validate_ledger": {
"word": "CHECK SECTOR DATA LEDGER",
"purpose": "Check a Pipeline News sector ledger against its generation, schema, keys and source policy.",
"inputs": ["sector data ledger", "validated sector contract", "dataset definitions indexed by name"],
"output": "Returns normally when checks pass and raises an error on an invalid ledger.",
"limits": "Specific to the pinned generation. Checks UTC provenance, row structure, key and reference integrity, and the pinned source policy.",
},
}
LIGHTNING_CONTRACT = {
"word": "REGISTER LIGHTNING MAP LAYER",
"purpose": "Add the archived GridAtlas satellite-flash point layer to the map configuration when it is absent.",
"inputs": ["GridAtlas map initialization options with a layer-group configuration",
"original map initializer captured by the cartridge"],
"output": "The original initializer's result after adding the point-layer configuration if needed.",
"limits": "Source-only record for the archived cartridge. An existing layer is kept and the feed is registered without preload. The layer describes optical satellite flashes.",
"symbol": LIGHTNING_LAYER_SYMBOL,
"source": LIGHTNING_LAYER_SOURCE,
"estate_group": "GridAtlas",
"discipline": "Geospatial visualisation",
"periodic_category": "map layers",
"vedic_class_candidate": "Computation",
"aliases": [],
"receipt": source_link(LIGHTNING_LAYER_SOURCE),
}
SOLAR_LOOP_AREA_SOURCE = {
"repo": "Ventusltd/solar-electrical-topology-analysis-engine-text-based",
"commit": "d3b4c497144c2c9b3e8f0e82117e7e9abe4672b9",
"blob": "e3014bc950722a78e91810e97610b05326e94531",
"path": "src/solar_topology/geometry_receipts.py",
"first": 50,
"last": 122,
}
SOLAR_LOOP_AREA_CONTRACT = {
"word": "ESTIMATE SOLAR LOOP AREA",
"purpose": "Estimate weighted DC conductor loop area for one solar string from declared segment geometry.",
"inputs": ["Solar string segment rows with a single run, topology and string and contiguous segment indexes from one",
"Conductor length in metres, pole separation in millimetres and a dimensionless participation weight per segment"],
"output": "Deterministic geometry receipt with loop area in square metres, per-segment contributions, route lengths, paired-route fraction and warnings.",
"limits": "Engineering screening approximation. Supply finite, nonnegative lengths and separations. The estimate uses declared geometry and weights and warns about missing separation on participating segments and assumed or defaulted geometry.",
"symbol": "calculate_geometry_receipt",
"source": SOLAR_LOOP_AREA_SOURCE,
"estate_group": "Solar Electrical Topology",
"discipline": "Solar electrical design",
"periodic_category": "conductor geometry",
"vedic_class_candidate": "Computation",
"aliases": [],
"receipt": source_link(SOLAR_LOOP_AREA_SOURCE),
}
FIND_CAPABILITY_SOURCE = {
"repo": "Ventusltd/seed-data",
"commit": "153c1159ff58edcb8be5f598c2c78d13c85b6afd",
"blob": "b67bcb84f2a5efb1e88885f97a910bf857e05c21",
"path": "experiments/economical-seeds/vedic_candidate.py",
"first": 12,
"last": 31,
}
FIND_CAPABILITY_CONTRACT = {
"word": "FIND CAPABILITY",
"purpose": "Find candidate instruments for a stated objective in a bounded SEED catalogue.",
"inputs": ["Non-blank objective text", "Curated SEED SQLite catalogue",
"Optional integer result limit from one to five, default three"],
"output": "Lookup status, up to the requested number of demonstrated instrument matches with evidence locators, and query metrics.",
"limits": "Lexical lookup over the selected catalogue. An empty result only describes that catalogue. The result is a shortlist; execution planning and actual invocation remain separate.",
"symbol": "invoke",
"source": FIND_CAPABILITY_SOURCE,
"estate_group": "SEED",
"discipline": "Capability retrieval",
"periodic_category": "evidence catalogue lookup",
"vedic_class_candidate": "Data",
"aliases": [],
"receipt": source_link(FIND_CAPABILITY_SOURCE),
}
# Owner-reviewed SatNav contracts; exact receipts are reproduced by the existing admission gate.
SATNAV_CONTRACTS = tuple(
{key: value for key, value in candidate.items() if key != "policy_receipt"}
for candidate in json.loads((ROOT / "data/satnav-source-contracts.json").read_bytes())["records"]
)
EXPLICIT_CONTRACTS = (LIGHTNING_CONTRACT, SOLAR_LOOP_AREA_CONTRACT, FIND_CAPABILITY_CONTRACT, *SATNAV_CONTRACTS)
def pinned_functions(raw):
if len(raw) > MAX_BYTES:
raise ValueError("Policy source exceeds the byte budget")
git_blob = hashlib.sha1(f"blob {len(raw)}\0".encode() + raw).hexdigest()
if git_blob != PIN["blob"]:
raise ValueError("Policy source blob differs from the reviewed pin")
try:
tree = ast.parse(raw)
except (SyntaxError, ValueError) as error:
raise ValueError("Invalid policy Python source") from error
for name, contract in CONTRACTS.items():
functions = [node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == name]
if len(functions) != 1 or functions[0].decorator_list:
raise ValueError(f"Expected one plain top-level policy function: {name}")
function = functions[0]
source = {**PIN, "first": function.lineno, "last": function.end_lineno}
yield source, {
**contract,
"symbol": name,
"source": source,
"estate_group": "Pipeline News",
"discipline": "Data engineering",
"periodic_category": "sector intelligence",
"vedic_class_candidate": "Computation",
"aliases": [],
"receipt": f"https://github.com/{PIN['repo']}/blob/{PIN['commit']}/{quote(PIN['path'])}"
f"#L{source['first']}-L{source['last']}",
}
def reproduce_candidate(source, raw):
"""Reconstruct the exact allowed command for verification from source bytes."""
for candidate in EXPLICIT_CONTRACTS:
if source == candidate["source"]:
verify_blob(source, raw)
return candidate
if any(source.get(key) != value for key, value in PIN.items()):
raise ValueError("Source is outside the reviewed static policy")
for anchor, candidate in pinned_functions(raw):
if source == anchor:
return candidate
raise ValueError("Source span is outside the reviewed static policy")
def discover_candidates(raw, archive):
from source_admissions import candidate_id, make_policy_receipt
admitted = {row["candidate_id"] for row in archive["records"]}
records = []
for _, candidate in pinned_functions(raw):
if candidate_id(candidate) in admitted:
continue
records.append({**candidate, "policy_receipt": make_policy_receipt(candidate, raw)})
return {"schema": "vedic.source-candidates.v1", "records": records}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
archive = json.loads((ROOT / "data/admitted-queue-archive.json").read_bytes())
queue = discover_candidates(fetch(PIN), archive)
from source_admissions import candidate_id, make_policy_receipt, read_policy_source
admitted = {row["candidate_id"] for row in archive["records"]}
for candidate in EXPLICIT_CONTRACTS:
if candidate_id(candidate) in admitted:
continue
source = candidate["source"]
raw = read_policy_source(source["repo"], source["commit"], source["path"])
verify_exact_span(source, candidate["symbol"], raw)
queue["records"].append({**candidate, "policy_receipt": make_policy_receipt(candidate, raw)})
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(queue, indent=2) + "\n", encoding="utf-8")
print(f"Reproduced {len(queue['records'])} pending static source contracts")
if __name__ == "__main__":
main()VEDIC Dictionary Shards
A Python module in the tools folder covering command and translation geodesy, and uses data from the GridAtlas and SatNav repositories.
storagevedic- / tools/dictionary_shards.py · lines 1–86 of 86 · pattern write_bundle (shared by 2 files)
- What it does
- Defines tokens, encode, build, code_sources, write_bundle. Uses libraries json, re, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: data source: gridatlas data; data source: satnav data; JSON file command-index.json; JSON file dictionary.json; JSON file translation-geodesy.json.
- Downstream impact
- Used directly by 7 files: VEDIC Browser Smoke (vedic-); VEDIC Check Pages Candidate (vedic-); VEDIC Estate Crib Search (vedic-); VEDIC Estate Domain Scan (vedic-); and 3 more. Reached from 12 other entry points, including VEDIC Anatomy Workflow (vedic-); VEDIC Modular Consumer Workflow (vedic-); VEDIC Release Rehearsal Workflow (vedic-).
- What it achieves
- It writes bundle (`write_bundle`) and is built from the tokens step (`tokens`) and the encode step (`encode`). Deterministic Pages-only search index and 100-command detail pages.
- Why it matters
- Imported by 5 files, including VEDIC Check Pages Candidate, VEDIC Estate Crib Search and VEDIC Estate Domain Scan. Checked by 2 tests, including VEDIC Browser Smoke.
- Application
- vedic- · tools · Python module
- Uses
- json, re, pathlib
- Used by
- imported by VEDIC Browser Smoke (import), imported by VEDIC Check Pages Candidate (import), imported by VEDIC Estate Crib Search (import), imported by VEDIC Estate Domain Scan (import), imported by VEDIC Family Pulse (import), imported by VEDIC Stage Pages (import), imported by VEDIC Test Dictionary Shards (import)
- Produces
- tokens, encode, build, write_bundle
- Defines here
- tokens, encode, build, code_sources, write_bundle
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/dictionary_shards.py:1-86 · blob cd6988d15a1a8ddf72535dfe10c5e09ffba6f118 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Deterministic Pages-only search index and 100-command detail pages."""
import json
import re
from pathlib import Path
INDEX = "data/command-index.json"
PREFIX = "data/command-pages/"
SIZE = 100
PATTERNS = {
"Find and select": "find search choose pick nearest lookup geocode query locate".split(),
"Measure and calculate": "measure calculate distance bearing area length loss voltage power energy estimate convert".split(),
"Check and validate": "validate verify check assert invariant quality".split(),
"Load and transform data": "load fetch read decode normalize normalise parse index sample import export convert".split(),
"Filter and rank": "filter rank score sort select".split(),
"Navigate and display": "navigate render display fly view open present map browse link guidance".split(),
"Explain and inspect": "explain describe inspect report summarise summarize".split(),
"Build and combine": "build combine compose aggregate total balance merge".split(),
}
def tokens(value):
value = re.sub(r"([a-z0-9])([A-Z])", r"\1 \2", str(value))
return " ".join(re.findall(r"[^\W_]+",value.casefold()))
def encode(value):
return (json.dumps(value,ensure_ascii=False,separators=(",",":"))+"\n").encode()
def build(d,t):
translations={r["id"]:r for r in t["records"]}
meanings={key:r.get("purpose","") for key,r in translations.items()}
identities={e["gg_id"]:e for e in d["entries"]}
def code_sources(entry, seen=None):
if seen is None:
seen=set()
identity=entry["gg_id"]
if identity in seen:
return []
seen.add(identity)
tr=translations.get(entry.get("translation_ref"),{})
src=tr.get("source") or entry.get("source")
if src:
symbol=tr.get("name") or (entry.get("translation_ref") or "").rsplit(":",1)[-1] or entry["word"]
return [{"symbol":symbol,"source":{k:src[k] for k in ("repo","commit","path","first","last")}}]
return [s for cid in entry.get("components",[]) for s in code_sources(identities[cid],seen)]
rows=sorted(d["entries"],key=lambda e:(e["word"].casefold(),e["number"]))
result, index = {}, []
for start in range(0,len(rows),SIZE):
path=f"{PREFIX}{start//SIZE+1:06d}.json"
detail=[]
for e in rows[start:start+SIZE]:
purpose=meanings.get(e.get("translation_ref"),e.get("purpose","")) or ""
symbol=(e.get("translation_ref") or "").rsplit(":",1)[-1]
aliases=e.get("aliases",[])
tags=e.get("pattern_tags",[])
if not isinstance(tags,list) or any(not isinstance(x,str) or not x.strip() or len(x)>64 for x in tags):
raise ValueError("invalid reviewed pattern tags")
terms=set(tokens(" ".join([e["word"],symbol,purpose,*aliases])).split())
patterns=sorted(set(tags+[p for p,w in PATTERNS.items() if terms.intersection(w)]),key=str.casefold)
row={k:e[k] for k in ("gg_id","number","word","estate_group","discipline","vedic_class_candidate","created_utc")}
app=e.get("application") or {}
# Presentation mapping only; preserve permanent source-admission replay.
if e["estate_group"] == "SatNav":
app = {**app, "name": "SatNav",
"url": "https://ventusltd.github.io/gridatlas/atlas/v/satnav-road-to-field-202611281800/",
"instructions": "Open the field application. Exact command source and full teleprint are separate; application launch is not an executable VEDIC binding.",
"teleprint_url": "https://raw.githubusercontent.com/Ventusltd/satnav/ae4496f947086cca02e54a2ddb9bda572672214b/teleprint/satnav-source-20261129.txt"}
row.update(purpose=purpose, launch=[app["name"],app["url"]] if app else None,
priority=e.get("priority",9),page=path,components=e.get("components",[]),patterns=patterns,code_sources=code_sources(e),
search=tokens(" ".join([e["word"],e["gg_id"],purpose,e["estate_group"],e["discipline"],
e["vedic_class_candidate"],symbol,*aliases,*patterns,
*("family "+str(n) for n in e.get("modular_family_refs",[]))])))
index.append(row)
detail.append({**e,"patterns":patterns,**({"application":app} if app else {})})
result[path]=encode({"schema":"vedic.command-page.v1","entries":detail})
result[INDEX]=encode({"schema":"vedic.command-index.v1","count":len(index),"page_size":SIZE,"resources":d["resources"],"entries":index})
return result
def write_bundle(root):
root=Path(root)
files=build(json.loads((root/"data/dictionary.json").read_bytes()),json.loads((root/"data/translation-geodesy.json").read_bytes()))
for p in (root/PREFIX).glob("*.json"):
p.unlink()
for name,raw in files.items():
p=root/name
p.parent.mkdir(parents=True,exist_ok=True)
p.write_bytes(raw)
return files