GLOBALGRID2050 / EXPLORE CODE

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

VEDIC Source Evidence and 6 more files

A Python module in the tools folder that verifies blob (`verify_blob`), masks JavaScript (`mask_javascript`) and verifies JavaScript syntax (`verify_javascript_syntax`).

682 lines of Python from vedic-, in 7 files. Topic: AI agents and coordination. Section 1679 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 Source Evidence other · vedic- / tools/source_evidence.py lines 1–197
  2. VEDIC Stage Demo storage · vedic- / tools/stage_demo.py lines 1–23
  3. VEDIC Stage Pages storage · vedic- / tools/stage_pages.py lines 1–118
  4. VEDIC Test Anatomy test · vedic- / tools/test_anatomy.py lines 1–28
  5. VEDIC Test Daily Accelerator test · vedic- / tools/test_daily_accelerator.py lines 1–71
  6. VEDIC Test Daily Intelligence test · vedic- / tools/test_daily_intelligence.py lines 1–51
  7. VEDIC Test Daily Operations test · vedic- / tools/test_daily_operations.py lines 1–194

VEDIC Source Evidence

A Python module in the tools folder that verifies blob (`verify_blob`), masks JavaScript (`mask_javascript`) and verifies JavaScript syntax (`verify_javascript_syntax`).

othervedic- / tools/source_evidence.py · lines 1–197 of 197

What it does
Defines 10 functions or classes, including source_link, verify_blob, python_spans, mask_javascript, matching_delimiter. Uses libraries ast, hashlib, re, subprocess, pathlib. 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).
Downstream impact
Used directly by 4 files: VEDIC Daily Source Policy (vedic-); VEDIC Source Admissions (vedic-); VEDIC Test Source Admissions (vedic-); VEDIC Validate Dictionary (vedic-). Reached from 11 other entry points, including VEDIC Anatomy Workflow (vedic-); VEDIC Modular Consumer Workflow (vedic-); VEDIC Allocate Commands (vedic-).
What it achieves
It verifies lightning initializer (`verify_lightning_initializer`) and is built from the source link helper (`source_link`) and the python spans helper (`python_spans`). Verify immutable source bytes and conservative function boundaries without executing code.
Why it matters
Imported by VEDIC Daily Source Policy, VEDIC Source Admissions and VEDIC Validate Dictionary. Checked by VEDIC Test Source Admissions.
Application
vedic- · tools · Python module
Uses
ast, hashlib, re, subprocess, pathlib, urllib.parse
Used by
imported by VEDIC Daily Source Policy (import), imported by VEDIC Source Admissions (import), imported by VEDIC Test Source Admissions (import), imported by VEDIC Validate Dictionary (import)
Produces
source_link, verify_blob, python_spans, mask_javascript, matching_delimiter, verify_javascript_syntax, javascript_text, verify_lightning_initializer, javascript_spans, verify_exact_span
Defines here
source_link, verify_blob, python_spans, mask_javascript, matching_delimiter, verify_javascript_syntax, javascript_text, verify_lightning_initializer, javascript_spans, verify_exact_span
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/source_evidence.py:1-197 · blob e8b6308c287508ada6b59fa47876b98e7c926ef6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Verify immutable source bytes and conservative function boundaries without executing code."""
import ast
import hashlib
import re
import subprocess
from pathlib import PurePosixPath
from urllib.parse import quote

MAX_SOURCE_BYTES = 1_000_000
POLICY = "vedic.static-source.v1"
POLICY_SCHEMA = "vedic.static-policy-receipt.v1"
POLICY_STATE = "STATIC_POLICY_REPRODUCED"
LIGHTNING_LAYER_SOURCE = {
    "repo": "Ventusltd/gridatlas",
    "commit": "afffa9781f6130529ae93052604cd3d98d172a35",
    "blob": "9268a1c4aeac981dea019e3ec63ad8e8384ae227",
    "path": "atlas/cartridges/202610221600-sld-sandbox-v9-8.js",
    "first": 8680,
    "last": 8698,
}
LIGHTNING_LAYER_SYMBOL = "addPublicLightningLayer"
LIGHTNING_INITIALIZER = re.compile(
    r"^[ \t]*window\.initVentusMap[ \t]*=[ \t]*function[ \t]+"
    + LIGHTNING_LAYER_SYMBOL + r"[ \t]*(?=\()", re.MULTILINE
)
JS_FUNCTION = re.compile(
    r"^[ \t]*(?:export[ \t]+)?(?:async[ \t]+)?function[ \t]+"
    r"([A-Za-z_$][A-Za-z0-9_$]*)[ \t]*(?=\()", re.MULTILINE
)
JS_NON_CODE = re.compile(
    r"""/\*[\s\S]*?\*/|//[^\r\n]*|'(?:\\[^\r\n]|[^'\\\r\n])*'|"(?:\\[^\r\n]|[^"\\\r\n])*"|[/`'"]"""
)


def source_link(source):
    path = quote(source["path"], safe="/")
    return (f"https://github.com/{source['repo']}/blob/{source['commit']}/{path}"
            f"#L{source['first']}-L{source['last']}")


def verify_blob(source, raw):
    if not isinstance(raw, bytes) or len(raw) > MAX_SOURCE_BYTES:
        raise ValueError("source bytes invalid or too large")
    blob = hashlib.sha1(f"blob {len(raw)}\0".encode() + raw).hexdigest()
    if blob != source["blob"]:
        raise ValueError("source blob differs from pinned evidence")


def python_spans(raw, symbol):
    try:
        tree = ast.parse(raw)
    except (SyntaxError, ValueError) as error:
        raise ValueError("unsupported Python source") from error
    return [
        (min([node.lineno, *(decorator.lineno for decorator in node.decorator_list)]), node.end_lineno)
        for node in tree.body
        if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.name == symbol
    ]


def mask_javascript(match):
    value = match[0]
    if len(value) == 1:
        raise ValueError("JavaScript lexical construct outside supported boundary-check subset")
    return re.sub(r"[^\r\n]", " ", value)


def matching_delimiter(text, start, opening, closing):
    depth = 0
    for offset in range(start, len(text)):
        char = text[offset]
        if char == opening:
            depth += 1
        elif char == closing:
            depth -= 1
            if depth == 0:
                return offset
    raise ValueError("unclosed JavaScript function delimiter")


def verify_javascript_syntax(raw):
    try:
        syntax = subprocess.run(
            ["node", "--check", "--input-type=module"], input=raw,
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=10,
        )
    except (OSError, subprocess.TimeoutExpired) as error:
        raise ValueError("JavaScript syntax verifier unavailable") from error
    if syntax.returncode != 0:
        raise ValueError("invalid JavaScript source")


def javascript_text(raw):
    text = raw.decode("utf-8").replace("\r\n", "\n")
    if any(separator in text for separator in ("\r", "\u2028", "\u2029")):
        raise ValueError("unsupported JavaScript line endings")
    return text


def verify_lightning_initializer(raw, first, last):
    """Check the complete assignment in the independently reviewed cartridge."""
    text = javascript_text(raw)
    matches = list(LIGHTNING_INITIALIZER.finditer(text))
    if len(matches) != 1 or text.count("\n", 0, matches[0].start()) + 1 != first:
        raise ValueError("lightning initializer differs from the reviewed assignment")
    snippet = "\n".join(text.split("\n")[first - 1:last])
    masked = JS_NON_CODE.sub(mask_javascript, snippet)
    match = LIGHTNING_INITIALIZER.match(masked)
    params_end = matching_delimiter(masked, match.end(), "(", ")")
    body = re.match(r"\s*\{", masked[params_end + 1:])
    if not body:
        raise ValueError("lightning initializer has no function body")
    close = matching_delimiter(masked, params_end + body.end(), "{", "}")
    if masked[close + 1:].strip() != ";" or masked.count("\n", 0, close) + first != last:
        raise ValueError("lightning initializer span must end at the complete assignment")
    verify_javascript_syntax(raw)


def javascript_spans(raw, symbol):
    masked = JS_NON_CODE.sub(mask_javascript, javascript_text(raw))
    verify_javascript_syntax(raw)

    spans = []
    for match in JS_FUNCTION.finditer(masked):
        if match[1] != symbol:
            continue
        prefix = masked[:match.start()]
        if any(prefix.count(a) != prefix.count(b) for a, b in ("()", "[]", "{}")):
            continue
        # Reject named continuation expressions even when top-level delimiters
        # are balanced. Only plain declarations in this subset are supported.
        if prefix.strip() and prefix.rstrip()[-1] not in ";}":
            continue
        params_end = matching_delimiter(masked, match.end(), "(", ")")
        body = re.match(r"\s*\{", masked[params_end + 1:])
        if not body:
            continue
        body_start = params_end + body.end()
        close = matching_delimiter(masked, body_start, "{", "}")
        if masked[close + 1:].split("\n", 1)[0].strip():
            raise ValueError("JavaScript function end shares a line with another statement")
        spans.append((prefix.count("\n") + 1, masked.count("\n", 0, close) + 1))
    return spans


# Narrow immutable exception: this reviewed exported function has a regex literal,
# and its module contains an HTML template literal. Do not relax the generic checker.
SATNAV_OFFLINE_SOURCE = {
    "repo": "Ventusltd/gridatlas",
    "commit": "2cc9238caaeeac87de71187e9eae3c7823277d38",
    "blob": "47497dbdc4416d4b90905372f466f72da3164a74",
    "path": "tools/satnav/field-reliability/offline-plan.mjs",
    "first": 137,
    "last": 179
}

# The pinned gate module contains division expressions unsupported by the generic
# conservative lexical checker. Its reviewed function is the unique final declaration.
SATNAV_GATE_SOURCE = {
    "repo": "Ventusltd/gridatlas",
    "commit": "2cc9238caaeeac87de71187e9eae3c7823277d38",
    "blob": "d10d92161c141e360eccf25e3d3221c476fb9503",
    "path": "tools/satnav/walk/gate/handoff.mjs",
    "first": 10,
    "last": 122
}

def verify_exact_span(source, symbol, raw):
    verify_blob(source, raw)
    if source == LIGHTNING_LAYER_SOURCE and symbol == LIGHTNING_LAYER_SYMBOL:
        verify_lightning_initializer(raw, source["first"], source["last"])
        return
    if source == SATNAV_OFFLINE_SOURCE and symbol == "mountOfflinePlan":
        lines = javascript_text(raw).splitlines()
        declaration = "export function mountOfflinePlan({container, getPins, maths}) {"
        if (len(lines) != source["last"] or lines[source["first"] - 1] != declaration
                or lines[-1] != "}" or lines.count(declaration) != 1):
            raise ValueError("offline plan span differs from reviewed immutable declaration")
        verify_javascript_syntax(raw)
        return
    if source == SATNAV_GATE_SOURCE and symbol == "createGateHandoff":
        lines = javascript_text(raw).splitlines()
        declaration = "export function createGateHandoff(plan, maths, compass) {"
        if (len(lines) != source["last"] or lines[source["first"] - 1] != declaration
                or lines[-1] != "}" or lines.count(declaration) != 1):
            raise ValueError("gate handoff span differs from reviewed immutable declaration")
        verify_javascript_syntax(raw)
        return
    extension = PurePosixPath(source["path"]).suffix
    if extension == ".py":
        spans = python_spans(raw, symbol)
    elif extension in {".js", ".mjs"}:
        spans = javascript_spans(raw, symbol)
    else:
        raise ValueError("unsupported source language")
    if spans != [(source["first"], source["last"])]:
        raise ValueError("source span differs from unique complete top-level function")

VEDIC Stage Demo

A Python command-line tool in the tools folder.

storagevedic- / tools/stage_demo.py · lines 1–23 of 23 · Entry point

What it does
It fetches data. Defines main. Uses libraries hashlib, 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).
Downstream impact
Used directly by 1 file: VEDIC Anatomy Workflow (vedic-).
What it achieves
Stage byte-exact upstream maths for VEDIC demos, never rewrite the engine.
Why it matters
Run by VEDIC Anatomy Workflow.
Application
vedic- · tools · Python CLI
Uses
VEDIC Validate Translation (import), hashlib, pathlib
Used by
run by VEDIC Anatomy Workflow (workflow run)
Produces
main
Defines here
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/stage_demo.py:1-23 · blob fd82e42f73f56d0affae178557ef07ccd11911d7 · 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
"""Stage byte-exact upstream maths for VEDIC demos, never rewrite the engine."""
import hashlib
from pathlib import Path
from validate_translation import fetch
ROOT = Path(__file__).resolve().parents[1]
PIN = "487ec7bd38dfa5aecb1c75da53b4a866ab2101cb"
FILES = {
    "engine/v9-geodesy.js": ("14023f06d4ef2ea806437863bd35dee954c46b11", "geodesy.mjs"),
    "LICENSE": ("d645695673349e3947e8e5ae42332d0ac3164cd7", "LICENSE"),
    "NOTICE": ("fc080f562deed00d61e2b3e0fe39346cc6c2987e", "NOTICE"),
}
def main():
    target = ROOT / "demo-engine"
    target.mkdir(exist_ok=True)
    for source, (expected, output) in FILES.items():
        data = fetch("Ventusltd/ventus-grid-engine", PIN, source)
        actual = hashlib.sha1(b"blob " + str(len(data)).encode() + b"\0" + data).hexdigest()
        if actual != expected:
            raise ValueError("Upstream Git blob mismatch: " + source)
        (target / output).write_bytes(data)
        print("Verified and staged", source, actual)
if __name__ == "__main__":
    main()

VEDIC Stage Pages

A Python command-line tool in the tools folder that validates publication (`validate_publication`) and writes bundle (`write_bundle`), covering anatomy, translation geodesy, nearest spider and dictionary, using SHA-256.

storagevedic- / tools/stage_pages.py · lines 1–118 of 118 · Entry point · pattern write_bundle (shared by 2 files)

What it does
Defines git_bytes, digest, validate_publication, write_bundle, stage. Uses libraries argparse, hashlib, json, subprocess, pathlib. 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 anatomy.json; JSON file translation-geodesy.json; JSON file nearest-spider.json; JSON file dictionary.json; JSON file prose-catalogue.json; JSON file prose-publication.json; JSON file accelerator-loop-193906.json; JSON file accelerator-loop-193907.json. Out: JSON file release.json.
Downstream impact
Used directly by 3 files: VEDIC Browser Smoke (vedic-); VEDIC Check Pages Candidate (vedic-); VEDIC Anatomy Workflow (vedic-). Reached from 1 other entry point, including VEDIC Release Rehearsal Workflow (vedic-).
What it achieves
It is built from the git bytes helper (`git_bytes`), the digest step (`digest`) and the stage step (`stage`). Stage Git-exact current and historical VEDIC Pages payloads with file digests.
Why it matters
Imported by VEDIC Check Pages Candidate. Run by VEDIC Anatomy Workflow. Checked by VEDIC Browser Smoke.
Application
vedic- · tools · Python CLI
Uses
VEDIC Dictionary Shards (import), argparse, hashlib, json, subprocess, pathlib
Used by
imported by VEDIC Browser Smoke (import), imported by VEDIC Check Pages Candidate (import), run by VEDIC Anatomy Workflow (workflow run)
Produces
git_bytes, digest, validate_publication, write_bundle, stage
Defines here
git_bytes, digest, validate_publication, write_bundle, stage
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/stage_pages.py:1-118 · blob 4e8a5a9f263222efa90375793942ff8f4f96e371 · 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
"""Stage Git-exact current and historical VEDIC Pages payloads with file digests."""
import argparse
import hashlib
import json
import subprocess
from pathlib import Path
from dictionary_shards import build as build_command_shards

ROOT = Path(__file__).resolve().parents[1]
LEGACY_PUBLIC_FILES = (
    "index.html",
    "data/anatomy.json",
    "data/translation-geodesy.json",
    "data/nearest-spider.json",
    "data/dictionary.json",
)
CATALOGUE = "data/prose-catalogue.json"
PUBLICATION = "data/prose-publication.json"
CURRENT_PUBLIC_FILES = (
    *LEGACY_PUBLIC_FILES,
    "data/accelerator-loop-193906.json",
    "data/accelerator-loop-193907.json",
)
PROSE_ARCHIVE_FILES = (*LEGACY_PUBLIC_FILES, CATALOGUE, PUBLICATION)
V1_COMMIT = "b17a153a6c0698902bfa89516a34ec8a956c11e7"
V1_ROUTE = "releases/202611260135-v1"
V2_ROUTE = "releases/202611261351"
V2_COMMIT = "55ff568b378acff4adae02fb5c758b4f4f8c6bcd"
V3_ROUTE = "releases/20261126-v3"
V3_COMMIT = "9d6a3a35b12fc4709f4b65965ca1f17a87277a2d"
FIRST_PROSE_ROUTE = "releases/20261126-prose-reader"
FIRST_PROSE_COMMIT = "7ca32d66e96ce8f453a99363ffaf04de265f2f6a"
TELEPRINTER_PROSE_ROUTE = "releases/20261126-prose-teleprinter"
TELEPRINTER_PROSE_COMMIT = "205bbd8f9be2f38d1b6f514022a494474fac79a6"

def git_bytes(ref, name):
    return subprocess.check_output(["git","show",f"{ref}:{name}"],cwd=ROOT)
def digest(data):
    return hashlib.sha256(data).hexdigest()

def validate_publication(payload):
    raw = payload[CATALOGUE]
    if len(raw) > 8 * 1024 * 1024:
        raise ValueError("Public prose requires a bounded catalogue")
    catalogue = json.loads(raw)
    publication = json.loads(payload[PUBLICATION])
    records = catalogue["records"]
    if catalogue["schema"] != "vedic.prose.catalogue.v1" or not isinstance(records, list) or not records:
        raise ValueError("Missing published prose")
    if publication["schema"] != "vedic.prose.publication-batch.v1" or publication["catalogue"] != {
        "path": "prose-catalogue.json", "rows": len(records), "sha256": digest(raw)
    }:
        raise ValueError("Prose catalogue differs from approved batch")
    ids = set()
    hashes = []
    for row in records:
        for field in ("id", "software", "prose", "status", "provenance", "evidence"):
            if not isinstance(row[field], str) or not row[field].strip():
                raise ValueError("Invalid public prose field: " + field)
        if row["id"] in ids:
            raise ValueError("Duplicate public prose reference: " + row["id"])
        ids.add(row["id"])
        hashes.append({"id": row["id"], "sha256": digest(row["prose"].encode("utf-8"))})
    if hashes != publication["records"]:
        raise ValueError("Public prose text or reading order differs from approved batch")
    return len(records)

def write_bundle(destination, payload, version, ref):
    prose_count = validate_publication(payload) if CATALOGUE in payload else None
    for name, data in payload.items():
        target=destination/name
        target.parent.mkdir(parents=True,exist_ok=True)
        target.write_bytes(data)
        if target.read_bytes()!=data:
            raise ValueError("staged mismatch: "+name)
    manifest={"schema":"vedic.pages.release.v1","version":version,"source_commit":ref,
        "row_count":len(json.loads(payload["data/dictionary.json"])["entries"]),
        "files":{name:digest(data) for name,data in payload.items()}}
    if prose_count is not None:
        manifest["prose_count"] = prose_count
    (destination/"release.json").write_bytes((json.dumps(manifest,sort_keys=True,indent=2)+"\n").encode("utf-8"))
    for name,h in manifest["files"].items():
        if digest((destination/name).read_bytes())!=h:
            raise ValueError("digest mismatch "+name)
        print(f"{h}  {destination/name}",flush=True)
def stage(destination):
    head=subprocess.check_output(["git","rev-parse","HEAD"],cwd=ROOT,text=True).strip()
    current={name:git_bytes(head,name) for name in CURRENT_PUBLIC_FILES}
    v3={name:git_bytes(V3_COMMIT,name) for name in LEGACY_PUBLIC_FILES}
    v2={name:git_bytes(V2_COMMIT,name) for name in LEGACY_PUBLIC_FILES}
    for name,data in current.items():
        if (ROOT/name).read_bytes()!=data:
            raise ValueError("working tree differs from committed bytes: "+name)
    prior={name:git_bytes(V1_COMMIT,name) for name in LEGACY_PUBLIC_FILES}
    destination.mkdir(parents=True,exist_ok=False)
    first_prose = {name:git_bytes(FIRST_PROSE_COMMIT,name) for name in PROSE_ARCHIVE_FILES}
    teleprinter_prose = {name:git_bytes(TELEPRINTER_PROSE_COMMIT,name) for name in PROSE_ARCHIVE_FILES}
    generated = build_command_shards(json.loads(current["data/dictionary.json"]), json.loads(current["data/translation-geodesy.json"]))
    current.update(generated)
    write_bundle(destination,current,"20261126-commands",head)
    write_bundle(destination/TELEPRINTER_PROSE_ROUTE,teleprinter_prose,"20261126-prose-teleprinter",TELEPRINTER_PROSE_COMMIT)
    write_bundle(destination/FIRST_PROSE_ROUTE,first_prose,"20261126-prose-reader",FIRST_PROSE_COMMIT)
    write_bundle(destination/V1_ROUTE,prior,"202611260135-v1",V1_COMMIT)
    write_bundle(destination/V2_ROUTE,v2,"202611261351",V2_COMMIT)
    write_bundle(destination/V3_ROUTE,v3,"20261126-v3",V3_COMMIT)
    (destination/".nojekyll").touch()
    expected = {".nojekyll", "release.json", *CURRENT_PUBLIC_FILES, *generated}
    expected.update(f"{route}/{name}" for route in (V1_ROUTE, V2_ROUTE, V3_ROUTE)
                    for name in (*LEGACY_PUBLIC_FILES, "release.json"))
    actual={p.relative_to(destination).as_posix() for p in destination.rglob("*") if p.is_file()}
    expected.update(f"{route}/{name}" for route in (FIRST_PROSE_ROUTE, TELEPRINTER_PROSE_ROUTE)
                    for name in (*PROSE_ARCHIVE_FILES, "release.json"))
    if actual!=expected:
        raise ValueError("public file-set mismatch")
if __name__=="__main__":
    p=argparse.ArgumentParser(description=__doc__)
    p.add_argument("destination",type=Path)
    stage(p.parse_args().destination)

VEDIC Test Anatomy

A test in the tools folder that checks VEDIC Validate Anatomy. It is built from the anatomy tests class (`AnatomyTests`).

testvedic- / tools/test_anatomy.py · lines 1–28 of 28 · Entry point · pattern test_duplicate (shared by 3 files)

What it does
It tests its inputs. Defines 6 functions or classes, including AnatomyTests, test_valid, test_dangling, test_invented_count, test_duplicate. Uses libraries copy, json, unittest, 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: JSON file anatomy.json.
Downstream impact
Used directly by 1 file: VEDIC Anatomy Workflow (vedic-).
What it achieves
Defines `AnatomyTests`, `test_valid`, `test_dangling` and 3 more.
Why it matters
Run by VEDIC Anatomy Workflow.
Application
vedic- · tools · test
Uses
VEDIC Validate Anatomy (import), copy, json, unittest, pathlib
Used by
run by VEDIC Anatomy Workflow (workflow run)
Produces
AnatomyTests
Defines here
AnatomyTests, test_valid, test_dangling, test_invented_count, test_duplicate, test_unverified_proof
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/test_anatomy.py:1-28 · blob 94ba22b09a2ec8cba14c465bfb5cbec0ec203fa0 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import copy
import json
import unittest
from pathlib import Path
from validate_anatomy import validate

DATA = json.loads((Path(__file__).resolve().parents[1] / "data/anatomy.json").read_text())
class AnatomyTests(unittest.TestCase):
    def test_valid(self):
        self.assertEqual(validate(DATA), (3, 4, 9))
    def test_dangling(self):
        d = copy.deepcopy(DATA)
        d["apps"][0]["capabilities"][0]["body_ids"] = ["missing"]
        with self.assertRaises(ValueError): validate(d)
    def test_invented_count(self):
        d = copy.deepcopy(DATA)
        d["bodies"][0]["unique_lines"] = 42
        with self.assertRaises(ValueError): validate(d)
    def test_duplicate(self):
        d = copy.deepcopy(DATA)
        d["bodies"].append(d["bodies"][0])
        with self.assertRaises(ValueError): validate(d)
    def test_unverified_proof(self):
        d = copy.deepcopy(DATA)
        d["apps"][0]["capabilities"][0]["proof"] = "PASS"
        with self.assertRaises(ValueError): validate(d)
if __name__ == "__main__":
    unittest.main()

VEDIC Test Daily Accelerator

A test in the tools folder that checks VEDIC Daily Accelerator and VEDIC Estate Crib Search. It is built from the daily accelerator tests class (`DailyAcceleratorTests`).

testvedic- / tools/test_daily_accelerator.py · lines 1–71 of 71 · Entry point · pattern progress (shared by 7 files)

What it does
It tests cables. Defines 6 functions or classes, including DailyAcceleratorTests, progress, test_seeded_rotation_covers_every_crib_before_repeating, test_progress_rejects_skips_changed_universes_and_missing_state, test_cpu_element_scores_matching_tied_and_ungrounded_clues. Uses libraries random, sqlite3, unittest, numpy. Side effects: 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). Domain terms in the code: cables.
Inputs & outputs
In: SQLite database.
Downstream impact
Used directly by 2 files: VEDIC Anatomy Workflow (vedic-); VEDIC Modular Consumer Workflow (vedic-).
What it achieves
Defines `DailyAcceleratorTests`, `progress`, `test_seeded_rotation_covers_every_crib_before_repeating` and 3 more.
Why it matters
Run by VEDIC Anatomy Workflow and VEDIC Modular Consumer Workflow.
Application
vedic- · tools · test
Uses
VEDIC Daily Accelerator (import), VEDIC Estate Crib Search (import), VEDIC Estate Domain Scan (import), random, sqlite3, unittest, numpy
Used by
run by VEDIC Anatomy Workflow (workflow run), run by VEDIC Modular Consumer Workflow (workflow run)
Produces
DailyAcceleratorTests
Defines here
DailyAcceleratorTests, progress, test_seeded_rotation_covers_every_crib_before_repeating, test_progress_rejects_skips_changed_universes_and_missing_state, test_cpu_element_scores_matching_tied_and_ungrounded_clues, test_cpu_domain_scan_uses_existing_action_and_object_rule
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/test_daily_accelerator.py:1-71 · blob 9746794009b0559d8797a1a25380988bdd840e18 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
import random
import sqlite3
import unittest

import numpy as np

import daily_accelerator
from estate_crib_search import GROUPS, scheduled_cribs, select_groups_numpy
from estate_domain_scan import scan


class DailyAcceleratorTests(unittest.TestCase):
    def progress(self, rounds, database="a", method="b", total=37):
        return daily_accelerator.validate({
            "schema": daily_accelerator.SCHEMA,
            "database_sha256": database * 64,
            "method_sha256": method * 64,
            "completed_rounds": rounds,
            "probe_coverage": {"MEASURE EXAMPLE": {"tested": min(total, rounds * 16), "total": total}},
        })

    def test_seeded_rotation_covers_every_crib_before_repeating(self):
        choices = list(range(37))
        unique = []
        for round_index in range(4):
            selected, covered = scheduled_cribs(choices, 16, random.Random(91 + round_index), 123, round_index)
            self.assertEqual(selected, scheduled_cribs(choices, 16, random.Random(91 + round_index), 123, round_index)[0])
            self.assertEqual(len(set(selected)), 16)
            fresh = covered - len(unique)
            self.assertFalse(set(selected[:fresh]).intersection(unique))
            self.assertTrue(set(selected[fresh:]).issubset(unique))
            unique.extend(selected[:fresh])
        self.assertEqual(set(unique), set(choices))

    def test_progress_rejects_skips_changed_universes_and_missing_state(self):
        old = self.progress(1)
        daily_accelerator.verify_advance(old, old)
        daily_accelerator.verify_advance(old, self.progress(2))
        daily_accelerator.verify_advance(old, self.progress(2, database="c"))
        daily_accelerator.verify_advance(old, self.progress(1, method="c"))
        with self.assertRaisesRegex(ValueError, "skipped a round"):
            daily_accelerator.verify_advance(old, self.progress(3))
        with self.assertRaisesRegex(ValueError, "changed its probe universe"):
            daily_accelerator.verify_advance(old, self.progress(2, total=38))
        with self.assertRaisesRegex(ValueError, "first round"):
            daily_accelerator.verify_advance(old, self.progress(2, method="c"))
        with self.assertRaisesRegex(ValueError, "Missing existing"):
            daily_accelerator.verify_advance(old, None)

    def test_cpu_element_scores_matching_tied_and_ungrounded_clues(self):
        rows = np.array([[6, 6, 0, 0], [6, 6, 6, 6], [6, 0, 0, 0]], dtype=np.float32)
        base = np.zeros((4, len(GROUPS) * 2), dtype=np.float32)
        base[:, :4] = np.eye(4, dtype=np.float32)
        scores = np.zeros((4, len(GROUPS)), dtype=np.float32)
        scores[:2, 0] = scores[2:, 1] = 1
        result, _ = select_groups_numpy(rows, base, scores, 1)
        self.assertEqual(result.tolist(), [[0, 18, 0], [-1, 18, 0], [-1, 0, 0]])

    def test_cpu_domain_scan_uses_existing_action_and_object_rule(self):
        columns = {"draw": 0, "cable": 1, "route": 2}
        cues = np.array([[1, 0], [0, 1], [0, 1]], dtype=np.float32)
        with sqlite3.connect(":memory:") as database:
            database.execute("CREATE TABLE line(n INTEGER, text BLOB)")
            database.executemany("INSERT INTO line VALUES(?, ?)", [(1, b"draw cable route"), (3, b"draw cable"), (9, b"cable route")])
            ids, masks, truncated, benchmark = scan(database, columns, cues, backend="numpy")
        self.assertEqual((ids.tolist(), masks.tolist(), truncated), ([1, 3, 9], [1, 0, 0], 0))
        self.assertIsNone(benchmark["cupy_seconds_including_transfers"])


if __name__ == "__main__":
    unittest.main()

VEDIC Test Daily Intelligence

A test in the tools folder that checks VEDIC Daily Intelligence. It is built from the daily command tests class (`DailyCommandTests`).

testvedic- / tools/test_daily_intelligence.py · lines 1–51 of 51 · Entry point

What it does
It tests its inputs. Defines 6 functions or classes, including DailyCommandTests, run_case, test_replays_and_reports_function_range, test_existing_alias_and_span_produce_no_change, test_rejects_modified_oversized_and_ambiguous_sources. Uses libraries datetime, hashlib, unittest.
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).
Downstream impact
Used directly by 2 files: VEDIC Anatomy Workflow (vedic-); VEDIC Modular Consumer Workflow (vedic-).
What it achieves
Defines `DailyCommandTests`, `run_case`, `test_replays_and_reports_function_range` and 3 more.
Why it matters
Run by VEDIC Anatomy Workflow and VEDIC Modular Consumer Workflow.
Application
vedic- · tools · test
Uses
VEDIC Daily Intelligence (import), datetime, hashlib, unittest
Used by
run by VEDIC Anatomy Workflow (workflow run), run by VEDIC Modular Consumer Workflow (workflow run)
Produces
DailyCommandTests
Defines here
DailyCommandTests, run_case, test_replays_and_reports_function_range, test_existing_alias_and_span_produce_no_change, test_rejects_modified_oversized_and_ambiguous_sources, test_one_pass_plan_does_not_repeat
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/test_daily_intelligence.py:1-51 · blob c17cf7074958ccf1437908c0c1b5ed8c087664f0 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
import datetime as dt
import hashlib
import unittest

from daily_intelligence import MAX_BYTES, discover

SOURCE = b"def count_sites(rows) -> int:\n    return len(rows)\n"
PIN = {"repo": "Ventusltd/fixture", "commit": "a" * 40, "path": "unit.py",
       "blob": hashlib.sha1(f"blob {len(SOURCE)}\0".encode() + SOURCE).hexdigest()}
DAY = dt.date(2026, 11, 26)


class DailyCommandTests(unittest.TestCase):
    def run_case(self, rows=(), raw=SOURCE, pin=PIN):
        return discover(raw, {"schema": "vedic.dictionary.v1", "entries": list(rows)},
                        DAY, pin, ("count_sites",))

    def test_replays_and_reports_function_range(self):
        result = self.run_case()
        self.assertEqual(result, self.run_case())
        self.assertEqual(result["candidate"]["parameters"], ["rows"])
        self.assertEqual(result["candidate"]["output_annotation"], "int")
        self.assertEqual((result["source"]["first"], result["source"]["last"]), (1, 2))

    def test_existing_alias_and_span_produce_no_change(self):
        for row in (
            {"word": "SITE TOTAL", "aliases": ["Count Sites"], "gg_id": "ID"},
            {"word": "ROW TOTAL", "source": {**PIN,"first":1,"last":2}, "gg_id": "ID"},
        ):
            result = self.run_case([row])
            self.assertEqual(result["status"], "no_change")
            self.assertIsNone(result["candidate"])
            self.assertEqual(result["existing_matches"], ["ID"])

    def test_rejects_modified_oversized_and_ambiguous_sources(self):
        with self.assertRaisesRegex(ValueError, "differs"):
            self.run_case(raw=SOURCE + b"\n")
        with self.assertRaisesRegex(ValueError, "byte budget"):
            self.run_case(raw=b"x" * (MAX_BYTES + 1))
        raw = SOURCE * 2
        pin = {**PIN, "blob": hashlib.sha1(f"blob {len(raw)}\0".encode() + raw).hexdigest()}
        with self.assertRaisesRegex(ValueError, "ambiguous"):
            self.run_case(raw=raw, pin=pin)

    def test_one_pass_plan_does_not_repeat(self):
        future = DAY + dt.timedelta(days=1)
        result = discover(SOURCE, {"schema": "vedic.dictionary.v1", "entries": []},
                          future, PIN, ("count_sites",))
        self.assertEqual(result["status"], "no_change")
        self.assertIsNone(result["candidate"])
        self.assertEqual(result["checkpoint"], "pinned-plan-exhausted")

VEDIC Test Daily Operations

A test in the tools folder that checks VEDIC Daily Operations and VEDIC Daily Source Policy.

testvedic- / tools/test_daily_operations.py · lines 1–194 of 194 · Entry point · pattern queue (shared by 4 files)

What it does
It tests its inputs. Defines 20 functions or classes, including family, candidate, queue, DailyOperationsTests, setUp. Uses libraries json, tempfile, unittest, pathlib, unittest.mock. 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 family-research.json; JSON file state-update.json; JSON file proposal.json.
Downstream impact
Used directly by 2 files: VEDIC Anatomy Workflow (vedic-); VEDIC Modular Consumer Workflow (vedic-).
What it achieves
It sets up (`setUp`) and is built from the daily operations tests class (`DailyOperationsTests`) and the fixture update helper (`fixture_update`). Defines `family`, `candidate`, `queue` and 17 more. It reads `family-research.json` and writes `family-research.json`.
Why it matters
Run by VEDIC Anatomy Workflow and VEDIC Modular Consumer Workflow.
Application
vedic- · tools · test
Uses
VEDIC Daily Operations (import), VEDIC Daily Source Policy (script call), json, tempfile, unittest, pathlib, unittest.mock
Used by
run by VEDIC Anatomy Workflow (workflow run), run by VEDIC Modular Consumer Workflow (workflow run)
Produces
family, candidate, queue, DailyOperationsTests
Defines here
family, candidate, queue, DailyOperationsTests, setUp, fixture_update, test_durable_state_bootstrap_and_retry, test_accelerator_checkpoint_is_coupled_to_family_persistence, mocked_family, test_stale_and_discontinuous_progress_is_refused, test_migration_advances_legacy_receipt, mocked_family, test_unavailable_legacy_artifact_stops_without_state_update, test_malformed_remote_state_stops_instead_of_bootstrapping, test_conflicting_candidate_is_refused_and_exact_retry_is_idempotent, test_proposal_bundle_replays_exact_manifest_commit, mock_cli, test_empty_proposal_writes_receipt_without_bundle, mock_cli, test_proposal_refuses_existing_local_branch
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/test_daily_operations.py:1-194 · blob a2cf84691ae5797379e76811428feda7bf87beaf · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
import json
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch

import daily_operations as operations


def family(previous, current):
    return {"schema": operations.FAMILY_SCHEMA, "previous_cursor": previous, "next_cursor": current,
            "scanned_families": 1 if current > previous else 0,
            "cursor_family_hash": "a" * 40 if current else None,
            "status": "research_candidates" if current > previous else "no_change"}


def candidate(first):
    return {"source": {"path": "test.py", "first": first, "last": first + 1}, "word": "MEASURE TEST"}


def queue(*records):
    return {"schema": "vedic.source-candidates.v1", "records": list(records)}


class DailyOperationsTests(unittest.TestCase):
    def setUp(self):
        self.temporary = tempfile.TemporaryDirectory()
        self.addCleanup(self.temporary.cleanup)
        self.directory = Path(self.temporary.name)
        self.remote = self.directory / "remote.git"
        self.repo = self.directory / "producer"
        self.repo.mkdir()
        operations.git(self.directory, "init", "--bare", str(self.remote))
        operations.git(self.repo, "init", "-b", "main")
        operations.git(self.repo, "config", "core.autocrlf", "false")
        operations.git(self.repo, "remote", "add", "origin", str(self.remote))
        operations.write_json(self.repo / operations.QUEUE, queue(candidate(10)))
        operations.write_json(self.repo / operations.DICTIONARY, {"entries": ["prior"]})
        operations.write_json(self.repo / operations.ARCHIVE, {"records": []})
        operations.git(self.repo, "add", "data")
        operations.git(self.repo, "-c", "commit.gpgSign=false", "commit", "-m", "Baseline", env=operations.IDENTITY)
        self.base = operations.git(self.repo, "rev-parse", "HEAD").decode().strip()
        operations.git(self.repo, "push", "origin", "main")

    def fixture_update(self, number, base, previous_cursor, next_cursor):
        return {"base": base, "checkpoint": {"schema": operations.STATE_SCHEMA, "source_commit": self.base,
                                             "run_id": number, "family": family(previous_cursor, next_cursor)}}

    def test_durable_state_bootstrap_and_retry(self):
        self.assertEqual(operations.load_state(self.repo), (None, None))
        initial = self.fixture_update(10, None, 0, 100)
        operations.persist(self.repo, initial, self.base, 10)
        state_commit, state = operations.load_state(self.repo)
        self.assertEqual(state, initial["checkpoint"])
        operations.persist(self.repo, initial, self.base, 10)
        self.assertEqual(operations.load_state(self.repo)[0], state_commit)
        output = self.directory / "retry"
        with patch.object(operations, "command") as command:
            operations.research(self.repo, output, self.base, 10)
            command.assert_not_called()
        self.assertEqual(operations.read_json(output / "family-research.json"), initial["checkpoint"]["family"])

    def test_accelerator_checkpoint_is_coupled_to_family_persistence(self):
        initial = self.fixture_update(10, None, 0, 100)
        operations.persist(self.repo, initial, self.base, 10)
        base, _ = operations.load_state(self.repo)
        progress = {"schema": operations.daily_accelerator.SCHEMA, "database_sha256": "a" * 64,
                    "method_sha256": "b" * 64, "completed_rounds": 1,
                    "probe_coverage": {"FIND EXAMPLE": {"tested": 16, "total": 20}}}
        output = self.directory / "accelerated"

        def mocked_family(root, *args):
            operations.write_json(output / "family-research.json", family(100, 200))
            return b""

        with patch.object(operations, "command", side_effect=mocked_family), \
                patch.object(operations.daily_accelerator, "research", return_value=progress) as accelerator:
            operations.research(self.repo, output, self.base, 11, accelerator=True)
            accelerator.assert_called_once_with(self.repo, output, None)
        update = operations.read_json(output / "state-update.json")
        self.assertEqual(update["base"], base)
        operations.persist(self.repo, update, self.base, 11)
        state_commit, state = operations.load_state(self.repo)
        self.assertEqual(state["accelerator"], progress)
        with patch.object(operations.daily_accelerator, "research") as accelerator:
            operations.research(self.repo, self.directory / "retry", self.base, 11, accelerator=True)
            accelerator.assert_not_called()
        with self.assertRaisesRegex(ValueError, "Missing existing accelerator progress"):
            operations.persist(self.repo, self.fixture_update(12, state_commit, 200, 300), self.base, 12)

    def test_stale_and_discontinuous_progress_is_refused(self):
        initial = self.fixture_update(10, None, 0, 100)
        operations.persist(self.repo, initial, self.base, 10)
        state_commit = operations.load_state(self.repo)[0]
        with self.assertRaisesRegex(ValueError, "changed while processing"):
            operations.persist(self.repo, self.fixture_update(11, None, 0, 101), self.base, 11)
        with self.assertRaisesRegex(ValueError, "does not continue"):
            operations.persist(self.repo, self.fixture_update(11, state_commit, 2, 101), self.base, 11)
        valid = self.fixture_update(11, state_commit, 100, 200)
        operations.persist(self.repo, valid, self.base, 11)
        self.assertEqual(operations.load_state(self.repo)[1], valid["checkpoint"])
        with self.assertRaisesRegex(ValueError, "later scheduled run"):
            operations.research(self.repo, self.directory / "old", self.base, 10)
        self.assertEqual(operations.remote_oid(self.repo, "refs/heads/main"), self.base)

    def test_migration_advances_legacy_receipt(self):
        output = self.directory / "migration"
        legacy = family(0, 100)

        def mocked_family(root, *args):
            checkpoint_path = Path(args[args.index("--checkpoint") + 1])
            self.assertEqual(operations.read_json(checkpoint_path), legacy)
            operations.write_json(output / "family-research.json", family(100, 200))
            return b""

        with patch.object(operations, "legacy_checkpoint", return_value=legacy), \
                patch.object(operations, "command", side_effect=mocked_family):
            operations.research(self.repo, output, self.base, 10)
        update = operations.read_json(output / "state-update.json")
        operations.persist(self.repo, update, self.base, 10)
        self.assertEqual(operations.load_state(self.repo)[1]["family"], family(100, 200))

    def test_unavailable_legacy_artifact_stops_without_state_update(self):
        output = self.directory / "unavailable"
        history = [{"databaseId": 9, "createdAt": "2026-11-27T03:37:00Z"}]
        responses = [{"createdAt": "2026-11-28T03:37:00Z"}, history, {"artifacts": []}, {"attempt": 1}]
        with patch.object(operations, "gh_json", side_effect=responses), \
                patch.dict(operations.os.environ, {"GITHUB_REPOSITORY": "Ventusltd/vedic-"}):
            with self.assertRaisesRegex(ValueError, "earlier family receipt expired"):
                operations.legacy_checkpoint(self.repo, 10, output)
        self.assertFalse((output / "family-research.json").exists())

    def test_malformed_remote_state_stops_instead_of_bootstrapping(self):
        operations.git(self.repo, "push", "origin", f"{self.base}:{operations.STATE_REF}")
        with self.assertRaises(operations.subprocess.CalledProcessError):
            operations.load_state(self.repo)

    def test_conflicting_candidate_is_refused_and_exact_retry_is_idempotent(self):
        current = queue(candidate(10))
        self.assertEqual(operations.merge_candidates(current, queue(candidate(10))), current)
        changed = {**candidate(10), "word": "DIFFERENT TEST"}
        with self.assertRaisesRegex(ValueError, "conflicts"):
            operations.merge_candidates(current, queue(changed))

    def test_proposal_bundle_replays_exact_manifest_commit(self):
        output = self.directory / "proposal"
        operations.git(self.repo, "checkout", "--detach", self.base)

        def mock_cli(root, tool, *args):
            if tool.endswith("daily_source_policy.py"):
                operations.write_json(Path(args[-1]), queue(candidate(20)))
            elif "--prepare" in args:
                staged = Path(args[-1])
                operations.write_json(staged / operations.DICTIONARY, {"entries": ["prior", "new"]})
                operations.write_json(staged / operations.ARCHIVE, {"records": ["new"]})
                return operations.json_bytes({"added": ["new"], "held": [], "count": 2})
            return b""

        with patch.object(operations, "command", side_effect=mock_cli):
            operations.proposal(self.repo, output)
        receipt = operations.read_json(output / "proposal.json")
        self.assertEqual(receipt["status"], "ready_for_review")
        self.assertEqual(receipt["base"], self.base)
        self.assertEqual(operations.remote_oid(self.repo, "refs/heads/main"), self.base)
        fresh = self.directory / "review"
        operations.git(self.directory, "clone", "--branch", "main", str(self.remote), str(fresh))
        ref = "refs/heads/review"
        operations.git(fresh, "fetch", str(output / "proposal.bundle"), f"{operations.BUNDLE_REF}:{ref}")
        self.assertEqual(operations.git(fresh, "rev-parse", ref).decode().strip(), receipt["head"])
        content = operations.git(fresh, "show", f"{receipt['manifest_commit']}:{operations.QUEUE}")
        self.assertEqual(json.loads(content), queue(candidate(10), candidate(20)))

    def test_empty_proposal_writes_receipt_without_bundle(self):
        output = self.directory / "no-change"
        operations.git(self.repo, "checkout", "--detach", self.base)

        def mock_cli(root, tool, *args):
            if tool.endswith("daily_source_policy.py"):
                operations.write_json(Path(args[-1]), queue())
                return b""
            return operations.json_bytes({"added": [], "held": [], "count": 1})

        with patch.object(operations, "command", side_effect=mock_cli):
            operations.proposal(self.repo, output)
        self.assertEqual(operations.read_json(output / "proposal.json")["status"], "no_change")
        self.assertFalse((output / "proposal.bundle").exists())

    def test_proposal_refuses_existing_local_branch(self):
        with self.assertRaisesRegex(ValueError, "detached checkout"):
            operations.proposal(self.repo, self.directory / "attached")


if __name__ == "__main__":
    unittest.main()