GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / vedic- / tools

VEDIC Canonical Sources and 3 more files

A Python command-line tool in the tools folder that reads engine graph, using SHA-256.

575 lines of Python from vedic-, in 4 files. Topic: AI agents and coordination. Section 1672 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. VEDIC Canonical Sources storage · vedic- / tools/canonical_sources.py lines 1–210
  2. VEDIC Check Pages Candidate storage · vedic- / tools/check_pages_candidate.py lines 1–79
  3. VEDIC Daily Accelerator storage · vedic- / tools/daily_accelerator.py lines 1–153
  4. VEDIC Daily Intelligence storage · vedic- / tools/daily_intelligence.py lines 1–133

VEDIC Canonical Sources

A Python command-line tool in the tools folder that reads engine graph, using SHA-256.

storagevedic- / tools/canonical_sources.py · lines 1–210 of 210 · Entry point · pattern digest (shared by 56 files)

What it does
It loads engine graph. Defines 10 functions or classes, including git, blob, digest, source_counts, by_blob. Uses libraries argparse, collections, hashlib, json, pathlib. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
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 engine-graph.json; JSON file current.json; SQLite database; command-line arguments. Out: JSON file canonical-manifest.json.
Downstream impact
Used directly by 2 files: VEDIC Canonical Intelligence (vedic-); VEDIC Package Modular Intelligence (vedic-).
What it achieves
It is built from the git step (`git`), the blob step (`blob`) and the digest step (`digest`). Join pinned engine and GridAtlas architecture to existing Modular Star addresses. It writes `canonical-manifest.json`.
Why it matters
Imported by VEDIC Canonical Intelligence and VEDIC Package Modular Intelligence.
Application
vedic- · tools · Python CLI
Uses
VEDIC Modular Features (import), argparse, collections, hashlib, json, pathlib, re, sqlite3, subprocess
Used by
imported by VEDIC Canonical Intelligence (import), imported by VEDIC Package Modular Intelligence (import)
Produces
git, blob, digest, source_counts, by_blob, git_line_bases, kuiper_engine_keys, output_table, build, main
Defines here
git, blob, digest, source_counts, by_blob, git_line_bases, kuiper_engine_keys, output_table, build, 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/canonical_sources.py:1-210 · blob 69f3465722d7830ab56a297eec503e6afe2b4c13 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Join pinned engine and GridAtlas architecture to existing Modular Star addresses."""

import argparse
from collections import Counter, defaultdict
import hashlib
import json
from pathlib import Path, PurePosixPath
import re
import sqlite3
import subprocess

import pyarrow as pa
import pyarrow.parquet as pq

from modular_features import atomic_write


def git(repo, *arguments):
    return subprocess.check_output(["git", "-C", str(repo), *arguments])


def blob(repo, commit, path):
    ref = f"{commit}:{path}"
    data = git(repo, "cat-file", "blob", ref)
    return git(repo, "rev-parse", "--verify", ref).decode().strip(), data


def digest(data):
    return hashlib.sha256(data).hexdigest()


def source_counts(db, library):
    counts = {name: db.execute(f"SELECT count(*) FROM {name}").fetchone()[0]
              for name in ("line", "scan", "element", "family", "tablet", "commit_info", "occurrence")}
    stamp = re.compile(r"(^|[^0-9])\d{8}(\d{4})?(?=[^0-9]|$)")
    places = defaultdict(set)
    for family, repo, path in db.execute(
        """SELECT DISTINCT e.family,o.repo,o.path FROM tablet_element te
           JOIN element e ON te.element=e.n JOIN occurrence o ON o.tablet=te.tablet
           JOIN scan s ON s.repo=o.repo AND s.commit_sha=o.commit_sha"""
    ):
        lineage = stamp.sub(r"\1{stamp}", path)
        places[family].add((repo, lineage))
    counts["repeated_current_families"] = sum(len(paths) >= 2 for paths in places.values())
    counts["compiled_function_exports"] = len(re.findall(
        rb"(?m)^export const f\d+_", library))
    return counts


def by_blob(db, repository, commit, path, oid, prefix_scope):
    return [
        {"repository": repository, "commit": commit, "path": path, "blob": oid,
         "element_id": element, "family_id": family, "symbol": name, "first_line": first,
         "last_line": last, "kind": kind, "needs": json.loads(needs) if needs else None,
         "standalone_candidate": bool(standalone), "source_role": prefix_scope}
        for element, family, name, first, last, kind, needs, standalone in db.execute(
            """SELECT e.n,e.family,te.name,te.first,te.last,e.kind,e.needs,e.standalone
               FROM tablet t JOIN tablet_element te ON te.tablet=t.n
               JOIN element e ON e.n=te.element WHERE t.git_blob=? ORDER BY te.first,e.n""", (oid,))
    ]


def git_line_bases(repo, commit):
    tree = git(repo, "ls-tree", "-r", "-z", commit)
    entries = []
    for line in tree.split(b"\0"):
        if not line:
            continue
        header, path = line.split(b"\t", 1)
        _, kind, oid = header.split()
        if kind == b"blob":
            entries.append((path.decode(), oid))
    received = subprocess.check_output(
        ["git", "-C", str(repo), "cat-file", "--batch"],
        input=b"\n".join(oid for _, oid in entries) + b"\n",
    )
    pos, running = 0, 0
    offsets = {}
    for path, expected_oid in entries:
        stop = received.index(b"\n", pos)
        oid, kind, length = received[pos:stop].split()
        if oid != expected_oid or kind != b"blob":
            raise ValueError("Unexpected Git batch frame")
        start = stop + 1
        size = int(length)
        pos = start + size + 1
        raw = received[start:pos-1]
        if received[pos-1:pos] != b"\n" or len(raw) != size:
            raise ValueError("Unexpected Git blob length")
        if b"\0" not in raw[:8000]:
            lines = raw.count(b"\n") + int(bool(raw) and not raw.endswith(b"\n"))
            offsets[path] = (running, lines)
            running += lines
    return offsets, running


def kuiper_engine_keys(kuiper, engine, engine_commit, rows):
    wafer = "f7a4cb9e3a764a72b7133bb275bb5387ea083be2"
    _, register = blob(kuiper, wafer, "cosmos/repos.tsv")
    _, ledger = blob(kuiper, wafer, "cosmos/wafer.tsv")
    names = {}
    for line in register.decode().splitlines():
        if line and not line.startswith("#"):
            fields = line.split("\t")
            names[int(fields[0])] = fields[1]
    offset = 0
    for line in ledger.decode().splitlines():
        if not line or line.startswith("#"):
            continue
        _, total, repo_id, prefix, gap, *_ = line.split("\t")
        offset += int(gap)
        if names[int(repo_id)] == "ventus-grid-engine" and engine_commit.startswith(prefix):
            break
        offset += int(total)
    else:
        return 0
    bases, count = git_line_bases(engine, engine_commit)
    if count != int(total):
        raise ValueError("Pinned engine tree and Kuiper wafer line counts disagree")
    assigned = 0
    for row in rows:
        if row["repository"] != "Ventusltd/ventus-grid-engine":
            continue
        base, file_count = bases[row["path"]]
        if not 1 <= row["first_line"] <= row["last_line"] <= file_count:
            raise ValueError("Element extends beyond its file")
        row.update(kuiper_first_key=offset + base + row["first_line"] - 1,
                   kuiper_last_key=offset + base + row["last_line"] - 1, kuiper_wafer=wafer)
        assigned += 1
    return assigned


def output_table(path, rows):
    if path.exists():
        raise ValueError(f"Refusing to replace frozen output {path.name}")
    records = pa.Table.from_pylist(rows)
    atomic_write(path, lambda target: pq.write_table(records, target, compression="zstd"))
    return {"name": path.name, "rows": len(rows), "size_bytes": path.stat().st_size,
            "sha256": digest(path.read_bytes())}


def build(db, engine, grid, kuiper, stars, out):
    engine_commit = "7c2a7b42905674fdcd3aa4bb50af14bc352a7747"
    grid_commit = "afffa9781f6130529ae93052604cd3d98d172a35"
    stars_commit = "1cf9c7530c7d287ccf9b3cffd70f693fb83c8402"
    graph_oid, graph_bytes = blob(engine, engine_commit, "genome/engine-graph.json")
    atlas_oid, atlas_bytes = blob(grid, grid_commit, "atlas/current.json")
    _, library = blob(stars, stars_commit, "library/standalone.mjs")
    graph, atlas = json.loads(graph_bytes), json.loads(atlas_bytes)
    if atlas["architecture"] != "IMMUTABLE_SHELL_PLUS_HASHED_CARTRIDGES":
        raise ValueError("Unsupported GridAtlas composition architecture")
    nodes, edges, bindings, architecture = [], [], [], []
    with sqlite3.connect(db.resolve().as_uri() + "?mode=ro&immutable=1", uri=True) as cx:
        counts = source_counts(cx, library)
        for index, node in enumerate(graph["nodes"]):
            path = node["label"]
            source_oid = None
            if node["type"] == "canonical" and path.startswith("engine/"):
                source_oid, _ = blob(engine, engine_commit, path)
                bindings.extend(by_blob(cx, "Ventusltd/ventus-grid-engine", engine_commit, path,
                                        source_oid, "engine_graph_canonical_module"))
            nodes.append({"graph_index": index, "label": path, "kind": node["type"],
                          "recorded_reason": node.get("reason"), "recorded_url": node.get("gh"),
                          "engine_blob": source_oid, "graph_blob": graph_oid, "graph_commit": engine_commit})
        for item in graph["edges"]:
            source, target = item["from"], item["to"]
            if not 0 <= source < len(nodes) or not 0 <= target < len(nodes):
                raise ValueError("Engine graph edge endpoint missing")
            edges.append({"source_graph_index": source, "target_graph_index": target,
                          "relationship": item["type"], "evidence_json": json.dumps(item.get("evidence")),
                          "graph_blob": graph_oid})
        shell = "atlas/" + atlas["shell"]["index"].removeprefix("./")
        entries = [(item, "runtime_cartridge", "atlas/" + item["path"].removeprefix("./"))
                   for item in atlas["cartridges"]]
        entries.extend([({}, "runtime_router", "atlas/index.html"), ({}, "immutable_shell", shell)])
        positions = {key: idx for idx, key in enumerate(atlas["cartridge_order"])}
        for item, role, path in entries:
            if ".." in PurePosixPath(path).parts:
                raise ValueError("Composition path escapes the atlas")
            source_oid, raw = blob(grid, grid_commit, path)
            if item and item["sha256"] != digest(raw):
                raise ValueError(f"GridAtlas cartridge hash mismatch: {path}")
            architecture.append({"generation": atlas["generation"], "role": role, "path": path, "blob": source_oid,
                                 "commit": grid_commit, "composition_blob": atlas_oid, "sha256": digest(raw),
                                 "cartridge_id": item.get("id"), "load_ordinal": positions.get(item.get("id")),
                                 "slot": item.get("slot"), "anchor": item.get("after") or item.get("replace_script")})
            bindings.extend(by_blob(cx, "Ventusltd/gridatlas", grid_commit, path, source_oid, role))
    for row in bindings:
        row.update(kuiper_first_key=None, kuiper_last_key=None, kuiper_wafer=None)
    assigned = kuiper_engine_keys(kuiper, engine, engine_commit, bindings)
    tables = [output_table(out / f"{name}.parquet", rows)
              for name, rows in (("canonical-bindings", bindings), ("engine-nodes", nodes),
                                 ("engine-edges", edges), ("gridatlas-composition", architecture))]
    report = {"inventory_counts": counts, "gridatlas_generation": atlas["generation"],
              "matched_engine_kuiper_ranges": assigned, "engine_graph_relations": dict(Counter(e["relationship"] for e in edges)),
              "tables": tables, "notes": "Graph edges are registered evidence claims, not proof of interchangeability or package admission."}
    atomic_write(out/"canonical-manifest.json", lambda p: p.write_text(json.dumps(report, indent=2)+"\n", encoding="utf-8"))
    return report


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ("db", "engine", "grid", "kuiper", "stars", "out"):
        parser.add_argument(name, type=Path)
    args = parser.parse_args()
    print(json.dumps(build(args.db, args.engine, args.grid, args.kuiper, args.stars, args.out), indent=2))


if __name__ == "__main__":
    main()

VEDIC Check Pages Candidate

A Python command-line tool in the tools folder that reads dictionary and translation geodesy. It is built from the exercise pagination helper (`exercise_pagination`) and the exercise public helper (`exercise_public`).

storagevedic- / tools/check_pages_candidate.py · lines 1–79 of 79 · Entry point

What it does
It loads dictionary and translation geodesy. Defines exercise_pagination, exercise_public, main. Uses libraries json, shutil, pathlib, tempfile, argparse. 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: JSON file dictionary.json; JSON file release.json; JSON file translation-geodesy.json; command-line arguments.
Downstream impact
Used directly by 2 files: VEDIC Anatomy Workflow (vedic-); VEDIC Release Rehearsal Workflow (vedic-).
What it achieves
Exercise the deployable Pages bundle and a private pagination fixture.
Why it matters
Run by VEDIC Anatomy Workflow and VEDIC Release Rehearsal Workflow.
Application
vedic- · tools · Python CLI
Uses
VEDIC Browser Smoke (import), VEDIC Dictionary Shards (import), VEDIC Stage Pages (import), json, shutil, pathlib, tempfile, argparse
Used by
run by VEDIC Anatomy Workflow (workflow run), run by VEDIC Release Rehearsal Workflow (workflow run)
Produces
exercise_pagination, exercise_public, main
Defines here
exercise_pagination, exercise_public, 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/check_pages_candidate.py:1-79 · blob 1beb5554cdec07297897648e564d9e1e8604188b · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Exercise the deployable Pages bundle and a private pagination fixture."""
import json
import shutil
from pathlib import Path
from tempfile import TemporaryDirectory

from browser_smoke import main as browser_smoke
from dictionary_shards import build as build_command_shards, write_bundle as write_command_shards
from stage_pages import stage, validate_publication, CATALOGUE, PUBLICATION, FIRST_PROSE_ROUTE, TELEPRINTER_PROSE_ROUTE, V1_ROUTE, V2_ROUTE, V3_ROUTE
import argparse


def exercise_pagination(site):
    dictionary = site / "data" / "dictionary.json"
    data = json.loads(dictionary.read_bytes())
    entries = data["entries"]
    if len(entries) < 101:
        number = max(entry["number"] for entry in entries)
        template = next(entry for entry in entries if entry.get("source"))
        missing = 101 - len(entries)
        for index in range(missing):
            entries.append({
                **template,
                "gg_id": f"UI-FIXTURE-{index + 1}",
                "number": number + index + 1,
                "word": ("<img src=/fixture-should-never-request>" if index == missing - 1 else f"Pagination fixture {index + 1}"),
                "priority": number + index + 1,
            })
        dictionary.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
    write_command_shards(site)
    print(f"Browser pagination fixture: {len(entries)} rows", flush=True)
    browser_smoke(site, run_demos=False, offline=True)


def exercise_public(public):
    manifest = json.loads((public / "release.json").read_bytes())
    assert "prose_count" not in manifest
    for name, raw in build_command_shards(json.loads((public/"data/dictionary.json").read_bytes()), json.loads((public/"data/translation-geodesy.json").read_bytes())).items():
        assert (public/name).read_bytes()==raw
    assert manifest["row_count"] == len(json.loads((public / "data/dictionary.json").read_bytes())["entries"])
    for base in (public, *(public / r for r in (V1_ROUTE, V2_ROUTE, V3_ROUTE))):
        assert not (base / CATALOGUE).exists()
        assert not (base / PUBLICATION).exists()
    prior, latest = (public / route for route in (FIRST_PROSE_ROUTE, TELEPRINTER_PROSE_ROUTE))
    for archive, count in ((prior, 6), (latest, 8)):
        assert validate_publication({name: (archive / name).read_bytes() for name in (CATALOGUE, PUBLICATION)}) == count
    prior_rows = json.loads((prior / CATALOGUE).read_bytes())["records"]
    archived_rows = json.loads((latest / CATALOGUE).read_bytes())["records"]
    assert archived_rows[:len(prior_rows)] == prior_rows
    for base in (public, public / V3_ROUTE):
        html = (base / 'index.html').read_text(encoding='utf-8')
        assert 'id="package-evidence"' in html and 'Package download unavailable' in html
    for route in (V1_ROUTE, V2_ROUTE):
        assert 'id="package-evidence"' not in (public / route / 'index.html').read_text(encoding='utf-8')
    baseline = json.loads((latest / "data/dictionary.json").read_bytes())["entries"]
    current = json.loads((public / "data/dictionary.json").read_bytes())["entries"]
    assert current[:len(baseline)] == baseline
    browser_smoke(public, run_demos=False, offline=True)
    for route in (V1_ROUTE,V2_ROUTE,V3_ROUTE,FIRST_PROSE_ROUTE,TELEPRINTER_PROSE_ROUTE):
        browser_smoke(public, run_demos=False, offline=True, base_path=route)

def main():
    p=argparse.ArgumentParser()
    p.add_argument('staged',nargs='?',type=Path)
    args=p.parse_args()
    with TemporaryDirectory(prefix="vedic-pages-") as directory:
        root = Path(directory)
        public = args.staged or root / "public"
        if args.staged is None:
            stage(public)
        print("Browser smoke: exact staged Pages payload", flush=True)
        exercise_public(public)
        fixture = root / "fixture"
        shutil.copytree(public, fixture)
        exercise_pagination(fixture)


if __name__ == "__main__":
    main()

VEDIC Daily Accelerator

A Python module in the tools folder that reads accelerator research, estate crib library, features and domain lines, using SHA-256.

storagevedic- / tools/daily_accelerator.py · lines 1–153 of 153 · pattern research (shared by 2 files)

What it does
It loads accelerator research, estate crib library, features and domain lines. Defines validate, same_campaign, verify_advance, method_digest, research. Uses libraries hashlib, json, pathlib, re, tempfile. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
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 accelerator-research.json; JSON file estate-crib-library.json; Parquet file features.parquet; Parquet file lines.parquet; Parquet file domain-lines.parquet; JSON file vogel-shots.json. Out: JSON file.
Downstream impact
Used directly by 2 files: VEDIC Daily Operations (vedic-); VEDIC Test Daily Accelerator (vedic-). Reached from 3 other entry points, including VEDIC Anatomy Workflow (vedic-); VEDIC Modular Consumer Workflow (vedic-); VEDIC Test Daily Operations (vedic-).
What it achieves
It verifies advance (`verify_advance`) and is built from the validate step (`validate`) and the same campaign helper (`same_campaign`). Run the nightly NumPy accelerator and retain a compact research checkpoint. It reads `lines.parquet`.
Why it matters
Imported by VEDIC Daily Operations. Checked by VEDIC Test Daily Accelerator.
Application
vedic- · tools · Python module
Uses
VEDIC Modular Snapshot (import), VEDIC Estate Crib Search (import), VEDIC Estate Domain Scan (import), VEDIC Modular Features (import), hashlib, json, pathlib, re, tempfile, numpy, pyarrow.parquet
Used by
imported by VEDIC Daily Operations (import), imported by VEDIC Test Daily Accelerator (import)
Produces
validate, same_campaign, verify_advance, method_digest, research
Defines here
validate, same_campaign, verify_advance, method_digest, research
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_accelerator.py:1-153 · blob 8ce499bb34a07dc542fec2e96f488023d470cb0c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Run the nightly NumPy accelerator and retain a compact research checkpoint."""

import hashlib
import json
from pathlib import Path
import re
import tempfile

from modular_snapshot import download_snapshot, inventory

SCHEMA = "vedic.daily-accelerator.v1"
PROBES_PER_GROUP = 16
FIRST_ELEMENT_SEED = 193908
FIRST_DOMAIN_SEED = 20261131
RECEIPT = "accelerator-research.json"
METHOD_FILES = (
    "tools/estate_crib_search.py",
    "tools/estate_domain_scan.py",
    "tools/modular_features.py",
    "tools/dictionary_shards.py",
    "tools/daily_accelerator.py",
    "data/estate-crib-library.json",
)


def validate(state):
    if not isinstance(state, dict) or state.get("schema") != SCHEMA:
        raise ValueError("Invalid accelerator checkpoint schema")
    for key in ("database_sha256", "method_sha256"):
        if not isinstance(state.get(key), str) or not re.fullmatch(r"[a-f0-9]{64}", state[key]):
            raise ValueError("Invalid accelerator checkpoint digest")
    rounds = state.get("completed_rounds")
    if type(rounds) is not int or rounds < 1:
        raise ValueError("Invalid accelerator round")
    coverage = state.get("probe_coverage")
    if not isinstance(coverage, dict) or not coverage:
        raise ValueError("Missing accelerator probe coverage")
    for group, row in coverage.items():
        if not group or not isinstance(row, dict):
            raise ValueError("Invalid accelerator probe group")
        total = row.get("total")
        if (type(total) is not int or total < PROBES_PER_GROUP or type(row.get("tested")) is not int or
                row["tested"] != min(total, rounds * PROBES_PER_GROUP)):
            raise ValueError("Invalid accelerator probe coverage")
    return state


def same_campaign(previous, method_sha256):
    return previous is not None and previous["method_sha256"] == method_sha256


def verify_advance(previous, current):
    if current == previous:
        return
    if current is None:
        raise ValueError("Missing existing accelerator progress")
    if same_campaign(previous, current["method_sha256"]):
        before = {group: row["total"] for group, row in previous["probe_coverage"].items()}
        after = {group: row["total"] for group, row in current["probe_coverage"].items()}
        if current["completed_rounds"] != previous["completed_rounds"] + 1 or before != after:
            raise ValueError("Accelerator checkpoint skipped a round or changed its probe universe")
    elif current["completed_rounds"] != 1:
        raise ValueError("A new accelerator campaign must start at its first round")


def method_digest(root):
    digest = hashlib.sha256()
    for name in METHOD_FILES:
        payload = (root / name).read_bytes().replace(b"\r\n", b"\n")
        digest.update(name.encode() + b"\0" + hashlib.sha256(payload).digest())
    return digest.hexdigest()


def research(root, output, previous):
    import numpy as np
    import pyarrow.parquet as pq

    from estate_crib_search import GROUPS, search
    from estate_domain_scan import scan_estate
    from modular_features import extract

    if previous is not None:
        validate(previous)
    method = method_digest(root)
    library = root / "data/estate-crib-library.json"
    with tempfile.TemporaryDirectory(prefix="vedic-accelerator-") as directory:
        scratch = Path(directory)
        database, producer, hashes = download_snapshot(scratch, require_digest=True)
        snapshot = inventory(database)["producer_inventory"]
        db_digest = hashes["database_sha256"]
        same = same_campaign(previous, method)
        round_index = previous["completed_rounds"] if same else 0
        campaign_seed = int(method, 16)

        features = scratch / "features.parquet"
        extracted = extract(database, features, workers=2, limit=None)
        elements_dir, domains_dir = scratch / "elements", scratch / "domains"
        element_seed, domain_seed = FIRST_ELEMENT_SEED + round_index, FIRST_DOMAIN_SEED + round_index
        elements = search(features, database, elements_dir, element_seed, backend="numpy",
                          campaign=(campaign_seed, round_index))
        domains = scan_estate(database, library, domains_dir, domain_seed, backend="numpy")
        if extracted["elements"] != snapshot["element"] or domains["lines"] != snapshot["line"]:
            raise ValueError("Accelerator did not cover the source snapshot")
        element_lines = pq.read_table(elements_dir / "lines.parquet")
        domain_lines = pq.read_table(domains_dir / "domain-lines.parquet")
        if not np.array_equal(element_lines["line_id"].to_numpy(), domain_lines["line_id"].to_numpy()):
            raise ValueError("Accelerator passes used different source-line identities")
        single_group = np.isin(element_lines["command_group"].to_numpy(), [group[0] for group in GROUPS])
        domain_mask = domain_lines["lexical_domain_mask"].to_numpy() | domain_lines["source_context_mask"].to_numpy()
        sample = json.loads((elements_dir / "vogel-shots.json").read_bytes())
        shot_fields = ("element_id", "family_id", "command_group")
        shots = {kind: [{key: row[key] for key in shot_fields} for row in sample[kind]]
                 for kind in ("survivors", "unresolved")}
        domain_shots = json.loads((domains_dir / "vogel-shots.json").read_bytes())
        checkpoint = validate({"schema": SCHEMA, "database_sha256": db_digest, "method_sha256": method,
                               "completed_rounds": round_index + 1, "probe_coverage": elements["probe_coverage"]})
        verify_advance(previous, checkpoint)
        coverage = checkpoint["probe_coverage"]
        tested = sum(row["tested"] for row in coverage.values())
        previously_tested = sum(row["tested"] for row in previous["probe_coverage"].values()) if same else 0
        receipt = {
            "checkpoint": checkpoint,
            "backend": "numpy",
            "cpu_gpu_parity": None,
            "producer_asset": producer,
            "source_inventory": {key: snapshot[key] for key in ("line", "element", "family")},
            "seeds": {"elements": element_seed, "domain_sampling": domain_seed},
            "counts": {
                "distinct_hypotheses_tested": tested,
                "new_hypotheses_tested": tested - previously_tested,
                "distinct_hypotheses_available": sum(row["total"] for row in coverage.values()),
                "element_hypothesis_pairs": elements["element_hypothesis_pairs"],
                "line_domain_pairs": domains["line_group_pairs"],
                "line_ids_with_one_group_or_domain_context": int(np.count_nonzero(single_group | domain_mask)),
                "line_ids_with_domain_association": domains["any_domain_lines"],
                "elements_with_one_group": snapshot["element"] - elements["tables"]["elements"]["counts"].get("REVIEW REQUIRED", 0),
                "lines_truncated_for_lexical_scan": domains["bounded_long_lines"],
                "elements_with_truncated_features": extracted["lexically_truncated_elements"],
            },
            "vogel_samples": {"elements": shots, "domains": domain_shots},
            "sha256": {"features": extracted["parquet_sha256"], "elements": elements["tables"]["elements"]["sha256"],
                       "domain_lines": domains["parquet_sha256"]},
            "scope": "All indexed elements and lines in this snapshot. Cumulative coverage counts configured "
                     "crib hypotheses across successful snapshots. Results are leads for review.",
        }
    with (output / RECEIPT).open("x", encoding="utf-8") as stream:
        json.dump(receipt, stream, indent=2)
        stream.write("\n")
    counts = receipt["counts"]
    print(f"Nightly accelerator round {checkpoint['completed_rounds']}: "
          f"{counts['distinct_hypotheses_tested']}/{counts['distinct_hypotheses_available']} "
          f"crib hypotheses covered, {snapshot['element']} elements and {snapshot['line']} line IDs scanned.")
    return checkpoint

VEDIC Daily Intelligence

A Python command-line tool in the tools folder that fetches daily research and dictionary, using SHA-256.

storagevedic- / tools/daily_intelligence.py · lines 1–133 of 133 · Entry point · pattern normalized (shared by 4 files)

What it does
It fetches daily research and dictionary. Defines 7 functions or classes, including sha256, normalized, fetch, discover, exhausted. Uses libraries argparse, ast, datetime, hashlib, json. 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).
Inputs & outputs
In: JSON file daily-research.json; JSON file dictionary.json; command-line arguments.
Downstream impact
Used directly by 3 files: VEDIC Daily Source Policy (vedic-); VEDIC Test Daily Intelligence (vedic-); VEDIC Modular Consumer Workflow (vedic-). Reached from 7 other entry points, including VEDIC Anatomy Workflow (vedic-); VEDIC Allocate Commands (vedic-); VEDIC Daily Operations (vedic-).
What it achieves
It writes receipt (`write_receipt`) and is built from the sha256 step (`sha256`) and the normalized step (`normalized`). Discover one pinned computational function for review. It accepts `--date` and `--output`.
Why it matters
Imported by VEDIC Daily Source Policy. Run by VEDIC Modular Consumer Workflow. Checked by VEDIC Test Daily Intelligence.
Application
vedic- · tools · Python CLI
Uses
argparse, ast, datetime, hashlib, json, pathlib, re, urllib.request
Used by
imported by VEDIC Daily Source Policy (import), imported by VEDIC Test Daily Intelligence (import), run by VEDIC Modular Consumer Workflow (workflow run)
Produces
sha256, normalized, fetch, discover, exhausted, write_receipt, main
Defines here
sha256, normalized, fetch, discover, exhausted, write_receipt, 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_intelligence.py:1-133 · blob 402a9fd1ddd77a080433d84307f9cd423c8a2f79 · 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
"""Discover one pinned computational function for review. No source is executed."""
import argparse
import ast
import datetime as dt
import hashlib
import json
from pathlib import Path
import re
from urllib.request import Request, urlopen

ROOT = Path(__file__).resolve().parents[1]
PIN = {
    "repo": "Ventusltd/pipelinenews",
    "commit": "d71672c221e0b4121e415204f91ccf642bc9894f",
    "path": "build/python/202609010719-build-sector-intelligence-parquet.py",
    "blob": "a0431a7383a2fd0166f667a19c922de4919cf3c8",
}
SYMBOLS = ("audit_file", "build_browser_projection", "validate_contract", "validate_ledger")
MAX_BYTES = 256 * 1024
MAX_FUNCTION_LINES = 180
PLAN_START = dt.date(2026, 11, 26)


def sha256(data):
    return hashlib.sha256(data).hexdigest()


def normalized(value):
    return " ".join(re.findall(r"[a-z0-9]+", value.casefold()))


def fetch(pin):
    url = f"https://raw.githubusercontent.com/{pin['repo']}/{pin['commit']}/{pin['path']}"
    with urlopen(Request(url, headers={"User-Agent": "VEDIC-daily-commands"}), timeout=20) as response:
        return response.read(MAX_BYTES + 1)


def discover(raw, dictionary, day, pin=PIN, symbols=SYMBOLS):
    if len(raw) > MAX_BYTES:
        raise ValueError("Source exceeds daily byte budget")
    blob = hashlib.sha1(f"blob {len(raw)}\0".encode() + raw).hexdigest()
    if blob != pin["blob"]:
        raise ValueError("Source blob differs from pinned evidence")
    if dictionary.get("schema") != "vedic.dictionary.v1" or not isinstance(dictionary.get("entries"), list):
        raise ValueError("Invalid dictionary evidence")
    offset = (day - PLAN_START).days
    if not 0 <= offset < len(symbols):
        return exhausted(dictionary, day)
    symbol = symbols[offset]
    matches = [node for node in ast.parse(raw).body if isinstance(node, ast.FunctionDef)
               and node.name == symbol]
    if len(matches) != 1:
        raise ValueError("Pinned computational function is absent or ambiguous")
    function = matches[0]
    first = min([function.lineno, *(node.lineno for node in function.decorator_list)])
    last = function.end_lineno
    if not 1 <= first <= last or last - first + 1 > MAX_FUNCTION_LINES:
        raise ValueError("Function exceeds daily line budget")
    source = {**pin, "first": first, "last": last}
    label = normalized(symbol).upper()
    duplicates = []
    potential_homonyms = []
    for entry in dictionary["entries"]:
        existing = entry.get("source") or {}
        same_origin = all(existing.get(key) == pin[key] for key in pin)
        known = [entry["word"], *entry.get("aliases", []), entry.get("translation_ref", "").rsplit(":", 1)[-1]]
        same_span = same_origin and existing["first"] <= last and first <= existing["last"]
        if same_span:
            duplicates.append(entry["gg_id"])
        elif any(isinstance(text, str) and normalized(text) == normalized(symbol) for text in known):
            duplicates.append(entry["gg_id"])
            potential_homonyms.append(entry["gg_id"])
    key = sha256(json.dumps(source, sort_keys=True).encode())
    result = {
        "schema": "vedic.daily-command-discovery.v1", "utc_date": day.isoformat(),
        "checkpoint": key, "source": source, "source_sha256": sha256(raw),
        "dictionary_sha256": sha256(json.dumps(dictionary, sort_keys=True).encode()),
        "existing_matches": sorted(set(duplicates)), "status": "no_change" if duplicates else "review_required",
        "candidate": None, "exceptions": [{"reason": "label_collision_requires_semantic_review", "gg_id": value}
                                            for value in sorted(set(potential_homonyms))],
    }
    if not duplicates:
        args = function.args
        result["candidate"] = {
            "id": "candidate:" + key, "label_hint": label, "symbol": symbol,
            "parameters": [node.arg for node in (*args.posonlyargs, *args.args, *args.kwonlyargs)],
            "output_annotation": ast.unparse(function.returns) if function.returns else None,
            "evidence": "Pinned function boundary; semantic equivalence and executable behavior require review.",
        }
    return result


def exhausted(dictionary, day):
    return {
        "schema": "vedic.daily-command-discovery.v1", "utc_date": day.isoformat(),
        "status": "no_change", "candidate": None, "existing_matches": [],
        "checkpoint": "pinned-plan-exhausted", "exceptions": [],
        "dictionary_sha256": sha256(json.dumps(dictionary, sort_keys=True).encode()),
        "reason": "No unvisited scheduled scope in this pinned plan. Renew the plan through reviewed changes.",
    }


def write_receipt(path, result):
    body = (json.dumps(result, sort_keys=True, indent=2) + "\n").encode()
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists() and path.read_bytes() != body:
        raise ValueError("Existing receipt differs; choose a new receipt path")
    path.write_bytes(body)
    print(body.decode(), end="")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--date", type=dt.date.fromisoformat)
    parser.add_argument("--output", type=Path, default=ROOT / "receipts" / "daily-research.json")
    args = parser.parse_args()
    day = args.date or dt.datetime.now(dt.timezone.utc).date()
    try:
        dictionary = json.loads((ROOT / "data/dictionary.json").read_bytes())
        if not 0 <= (day - PLAN_START).days < len(SYMBOLS):
            result = exhausted(dictionary, day)
        else:
            result = discover(fetch(PIN), dictionary, day)
    except (ValueError, OSError, SyntaxError, KeyError, TypeError) as error:
        write_receipt(args.output, {"schema": "vedic.daily-command-discovery.v1",
                                    "utc_date": day.isoformat(), "source": PIN,
                                    "status": "error", "candidate": None, "exceptions": [type(error).__name__]})
        raise
    write_receipt(args.output, result)


if __name__ == "__main__":
    main()