GLOBALGRID2050 / EXPLORE CODE

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

VEDIC Source Admissions and 1 more file

A Python command-line tool in the tools folder that fetches dictionary, command candidates, admitted queue archive and translation geodesy, using SHA-256.

511 lines of Python from vedic-, in 2 files. Topic: AI agents and coordination. Section 1678 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 Semantic Compiler storage · vedic- / tools/semantic_compiler.py lines 1–233
  2. VEDIC Source Admissions ingest · vedic- / tools/source_admissions.py lines 1–278

VEDIC Semantic Compiler

A Python command-line tool in the tools folder that works with small read (`small_read`) and pinned git file (`pinned_git_file`), covering dictionary, command execution bindings, request and build receipt, using SHA-256.

storagevedic- / tools/semantic_compiler.py · lines 1–233 of 233 · Entry point · pattern strict_json (shared by 2 files)

What it does
Defines 16 functions or classes, including Refusal, __init__, need, sha256, strict_json. Uses libraries __future__, argparse, hashlib, json, math. 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 dictionary.json; JSON file command-execution-bindings.json; JSON file request.json; JSON file build-receipt.json; command-line arguments.
Downstream impact
Used directly by 4 files: VEDIC Replay Faraday Orient (vedic-); VEDIC Replay Orient Archive (vedic-); VEDIC Test Find Capability Admission (vedic-); VEDIC Test Semantic Compiler (vedic-). Reached from 1 other entry point, including VEDIC Anatomy Workflow (vedic-).
What it achieves
It is built from the refusal class (`Refusal`), the need step (`need`) and the sha256 step (`sha256`). Resolve the existing VEDIC dictionary and invoke reviewed package bindings. It accepts `--sense-id`, `--input` and `--archive`.
Why it matters
Imported by VEDIC Replay Faraday Orient and VEDIC Replay Orient Archive. Checked by 2 tests, including VEDIC Test Find Capability Admission.
Application
vedic- · tools · Python CLI
Uses
__future__, argparse, hashlib, json, math, os, pathlib, re
Used by
imported by VEDIC Replay Faraday Orient (import), imported by VEDIC Replay Orient Archive (import), imported by VEDIC Test Find Capability Admission (import), imported by VEDIC Test Semantic Compiler (import)
Produces
Refusal, need, sha256, strict_json, json_bytes, small_read, phrase_key, resolve, pinned_git_file, stage_factory, execute, main
Defines here
Refusal, __init__, need, sha256, strict_json, unique, finite_number, nonfinite, json_bytes, small_read, phrase_key, resolve, pinned_git_file, stage_factory, execute, 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/semantic_compiler.py:1-233 · blob 189f695b243ba0e67af15b89d72f0a153555df67 · 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
"""Resolve the existing VEDIC dictionary and invoke reviewed package bindings."""
from __future__ import annotations

import argparse
import hashlib
import json
import math
import os
from pathlib import Path
import re
import subprocess
import sys
import tempfile

ROOT = Path(__file__).resolve().parents[1]
DICTIONARY = ROOT / "data" / "dictionary.json"
BINDINGS = ROOT / "data" / "command-execution-bindings.json"
RECEIPT_SCHEMA = "vedic.command-execution.v1"
PHRASE = re.compile(r"[a-z]+(?: [a-z]+){0,4}")


class Refusal(ValueError):
    def __init__(self, code, **details):
        super().__init__(code)
        self.details = details


def need(condition, code, **details):
    if not condition:
        raise Refusal(code, **details)


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


def strict_json(raw):
    def unique(pairs):
        fields = {}
        for key, value in pairs:
            need(key not in fields, "DUPLICATE_JSON_KEY")
            fields[key] = value
        return fields

    def finite_number(literal):
        value = float(literal)
        need(math.isfinite(value), "NONFINITE_INPUT")
        return value

    def nonfinite(_literal):
        raise Refusal("NONFINITE_INPUT")

    try:
        return json.loads(raw, object_pairs_hook=unique, parse_float=finite_number,
                          parse_constant=nonfinite)
    except Refusal:
        raise
    except (UnicodeError, ValueError, RecursionError) as exc:
        raise Refusal("INVALID_JSON") from exc


def json_bytes(value):
    return (json.dumps(value, sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n").encode("utf-8")


def small_read(path, limit=2 * 1024 * 1024):
    with path.open("rb") as stream:
        raw = stream.read(limit + 1)
    need(len(raw) <= limit, "PAYLOAD_TOO_LARGE")
    return raw


def phrase_key(phrase):
    key = " ".join(phrase.strip().lower().split())
    need(phrase.isascii() and PHRASE.fullmatch(key), "COMMAND_SYNTAX")
    return key


def resolve(phrase, dictionary, registry, sense_id=None):
    key = phrase_key(phrase)
    entries = dictionary["entries"]
    bindings = registry["bindings"]
    matching = []
    for entry in entries:
        binding = bindings.get(entry["gg_id"], {})
        names = [entry["word"], *entry.get("aliases", []), *binding.get("aliases", [])]
        if any(" ".join(name.lower().split()) == key for name in names):
            if sense_id is None or sense_id == entry["gg_id"]:
                matching.append(entry)
    need(matching, "UNKNOWN_COMMAND")
    need(len(matching) == 1, "AMBIGUOUS_COMMAND",
         candidates=[entry["gg_id"] for entry in matching])
    command = matching[0]
    command_id = command["gg_id"]
    plan = {
        "command_id": command_id,
        "canonical": command["word"],
        "intent": command.get("purpose"),
        "dictionary_status": command["state"],
        "inputs": command["inputs"],
        "output": command["output"],
        "execution_readiness": "NO_REVIEWED_PACKAGE_BINDING",
    }
    binding = bindings.get(command_id)
    if binding:
        need(binding["sense_key"] == command["sense_key"]
             and binding["components"] == command["components"]
             and command["composition_mode"] == "shared_inputs", "DICTIONARY_BINDING_DRIFT")
        plan["execution_readiness"] = "PRIVATE_FACTORY_PACKAGE"
        for field in ("aliases", "components", "operations", "ports", "refusals",
                      "scope", "package", "source_receipt_sha256", "independent_package_acceptance"):
            plan[field] = binding[field]
    return plan


def pinned_git_file(repo, commit, path, expected_sha256=None):
    environment = {**os.environ, "GIT_NO_LAZY_FETCH": "1", "GIT_NO_REPLACE_OBJECTS": "1"}
    try:
        result = subprocess.run(["git", "-C", str(repo), "show", f"{commit}:{path}"],
                                check=True, capture_output=True, timeout=15, env=environment)
    except (OSError, subprocess.SubprocessError) as exc:
        raise Refusal("PINNED_GIT_OBJECT_UNAVAILABLE", path=path) from exc
    raw = result.stdout
    if expected_sha256 is not None:
        need(sha256(raw) == expected_sha256, "GIT_BYTES_MISMATCH", path=path)
    return raw


def stage_factory(repo, factory, package):
    for relative, digest in package["factory_files"].items():
        path = factory / relative
        path.parent.mkdir(parents=True, exist_ok=True)
        path.write_bytes(pinned_git_file(repo, package["factory_commit"], relative, digest))


def execute(plan, values, repo, archive, build_receipt):
    need(plan["execution_readiness"] == "PRIVATE_FACTORY_PACKAGE", "PACKAGE_NOT_ADMITTED")
    package = plan["package"]
    evidence = {field: small_read(path) for path, field in
                ((archive, "archive_sha256"), (build_receipt, "build_receipt_sha256"))}
    for field, raw in evidence.items():
        need(sha256(raw) == package[field], "PACKAGE_EVIDENCE_MISMATCH", evidence=field)
    request = {
        "schema": "vedic.typed-package-request.v1",
        "family": package["family"],
        "export": package["export"],
        "archive_sha256": package["archive_sha256"],
        "descriptor_sha256": package["descriptor_sha256"],
        "ports": plan["ports"],
        "input": values,
    }
    with tempfile.TemporaryDirectory(prefix="vedic-command-") as tmp:
        factory = Path(tmp)
        stage_factory(repo, factory, package)
        runner = factory / "tools/typed_package_execution.py"
        runner_bytes = runner.read_bytes()
        runtime_compatibility = "PINNED_FACTORY_RUNNER"
        if os.name == "nt":
            # Windows Node's system crypto initialization requires SYSTEMROOT.
            # Preserve the Factory's minimal environment and its exact checks.
            original = b'env={"PATH":os.environ["PATH"]}'
            replacement = b'env={k:os.environ[k] for k in ("PATH","SYSTEMROOT")}'
            need(runner_bytes.count(original) == 1 and "SYSTEMROOT" in os.environ,
                 "WINDOWS_RUNNER_SHAPE")
            runner_bytes = runner_bytes.replace(original, replacement)
            runner.write_bytes(runner_bytes)
            runtime_compatibility = "WINDOWS_SYSTEMROOT_ONLY"
        request_path = factory / "request.json"
        request_path.write_bytes(json_bytes(request))
        archive_path = factory / "orient.zip"
        archive_path.write_bytes(evidence["archive_sha256"])
        receipt_path = factory / "build-receipt.json"
        receipt_path.write_bytes(evidence["build_receipt_sha256"])
        command = [sys.executable, "-E", "-s", str(runner), "--request", str(request_path),
                   "--archive", str(archive_path), "--receipt", str(receipt_path)]
        try:
            result = subprocess.run(command, capture_output=True, timeout=30, cwd=factory)
        except (OSError, subprocess.SubprocessError) as exc:
            raise Refusal("PACKAGE_RUN_ERROR") from exc
    outcome = strict_json(result.stdout) if result.stdout.strip() else {}
    if result.returncode != 0:
        raise Refusal("PACKAGE_REFUSED", package_reason=outcome.get("reason", "PACKAGE_RUN_ERROR"))
    need(outcome.get("state") == "EXECUTED_ADMITTED_ORIENT_ONLY", "PACKAGE_RESULT_MISMATCH")
    pattern = outcome.get("pattern", {})
    need(pattern.get("request") == request
         and pattern.get("source_receipt_sha256") == plan["source_receipt_sha256"]
         and pattern.get("independent_acceptance") is False, "PACKAGE_RESULT_MISMATCH")
    return {
        "schema": RECEIPT_SCHEMA,
        "state": "EXECUTED_PRIVATE_PACKAGE",
        "plan": plan,
        "plan_sha256": sha256(json_bytes(plan)),
        "runtime_compatibility": runtime_compatibility,
        "runner_sha256": sha256(runner_bytes),
        "package_execution": outcome,
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("command")
    parser.add_argument("--sense-id", help="Select an existing ID for a command with several meanings")
    parser.add_argument("--input", type=Path, help="Execute with this exact JSON input")
    parser.add_argument("--archive", type=Path)
    parser.add_argument("--build-receipt", type=Path)
    parser.add_argument("--factory-repo", type=Path, default=ROOT)
    args = parser.parse_args()
    try:
        registry = strict_json(small_read(BINDINGS))
        need(registry.get("schema") == "vedic.execution-bindings.v1", "BINDINGS_SCHEMA")
        plan = resolve(args.command, strict_json(DICTIONARY.read_bytes()), registry, args.sense_id)
        if args.input:
            need(plan["execution_readiness"] == "PRIVATE_FACTORY_PACKAGE", "PACKAGE_NOT_ADMITTED")
            need(args.archive and args.build_receipt, "PACKAGE_EVIDENCE_REQUIRED")
            result = execute(plan, strict_json(small_read(args.input)), args.factory_repo,
                             args.archive, args.build_receipt)
        else:
            need(not (args.archive or args.build_receipt), "INPUT_REQUIRED")
            result = {"state": "RESOLVED", "plan": plan, "plan_sha256": sha256(json_bytes(plan))}
    except Refusal as exc:
        result = {"schema": RECEIPT_SCHEMA, "state": "REFUSED", "reason": str(exc), **exc.details}
        sys.stdout.buffer.write(json_bytes(result))
        return 2
    except OSError:
        sys.stdout.buffer.write(json_bytes({"schema": RECEIPT_SCHEMA, "state": "REFUSED",
                                           "reason": "EVIDENCE_IO_ERROR"}))
        return 2
    sys.stdout.buffer.write(json_bytes(result))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

VEDIC Source Admissions

A Python command-line tool in the tools folder that fetches dictionary, command candidates, admitted queue archive and translation geodesy, using SHA-256.

ingestvedic- / tools/source_admissions.py · lines 1–278 of 278 · Entry point · pattern pinned (shared by 7 files)

What it does
It fetches dictionary, command candidates, admitted queue archive and translation geodesy. Defines 19 functions or classes, including git, pinned, stamp, contract, candidate_id. Uses libraries argparse, copy, hashlib, json, re. Side effects: reads or writes files; makes network requests; 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 dictionary.json; JSON file source-command-candidates.json; JSON file admitted-queue-archive.json; JSON file translation-geodesy.json; command-line arguments.
Downstream impact
Used directly by 6 files: VEDIC Allocate Commands (vedic-); VEDIC Daily Operations (vedic-); VEDIC Daily Source Policy (vedic-); VEDIC Test Daily Source Policy (vedic-); and 2 more. Reached from 2 other entry points, including VEDIC Modular Consumer Workflow (vedic-); VEDIC Test Daily Operations (vedic-).
What it achieves
It makes policy receipt (`make_policy_receipt`), verifies policy receipt (`verify_policy_receipt`) and reads policy source (`read_policy_source`). Bounded, append-only admission of source-reviewed VEDIC contracts. It reads `data/translation-geodesy.json`. It accepts `--check`, `--prepare` and `--limit`.
Why it matters
Imported by VEDIC Allocate Commands, VEDIC Daily Operations and VEDIC Daily Source Policy. Run by VEDIC Anatomy Workflow. Checked by 2 tests, including VEDIC Test Daily Source Policy.
Application
vedic- · tools · Python CLI
Uses
VEDIC Family Pulse (import), VEDIC Source Evidence (import), VEDIC Validate Dictionary (import), VEDIC Validate Translation (import), VEDIC Daily Source Policy (import), argparse, copy, hashlib, json, re, subprocess, tempfile, datetime
Used by
imported by VEDIC Allocate Commands (import), imported by VEDIC Daily Operations (import), imported by VEDIC Daily Source Policy (import), imported by VEDIC Test Daily Source Policy (import), imported by VEDIC Test Source Admissions (import), run by VEDIC Anatomy Workflow (workflow run)
Produces
git, pinned, stamp, contract, candidate_id, contract_payload, policy_contract_digest, make_policy_receipt, verify_policy_receipt, read_policy_source, verify_policy_candidate, allocate_one
Defines here
git, pinned, stamp, contract, candidate_id, contract_payload, policy_contract_digest, make_policy_receipt, verify_policy_receipt, read_policy_source, verify_policy_candidate, allocate_one, replay, replay_published, prepare, stage_proposal, main, check_policy, check
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_admissions.py:1-278 · blob a3ff07ee589f684a5205740035edc0f581f28bc7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Bounded, append-only admission of source-reviewed VEDIC contracts.

No source execution, model API, or renumbering. The source manifest is a
durable input queue; its entries are not automatically semantic proof.
"""
import argparse
import copy
import hashlib
import json
import re
import subprocess
import tempfile
from datetime import datetime, timezone
from pathlib import Path
from urllib.parse import quote
from family_pulse import key, read, write, require
from source_evidence import POLICY, POLICY_SCHEMA, POLICY_STATE, source_link, verify_exact_span
from validate_dictionary import validate
from validate_translation import fetch

ROOT = Path(__file__).resolve().parents[1]
BASE = "bfc4924495dfe14ab9c074bc7a2af36c32281680"
LEGACY = "a888ef8f20da773d4056cc64a0821495f9dd7631"
DICT = "data/dictionary.json"
QUEUE = "data/source-command-candidates.json"
ARCHIVE = "data/admitted-queue-archive.json"
SCHEMA = "vedic.source-admission-archive.v1"
LIMIT = 20
DEFAULT_OUTPUT = ROOT / "receipts" / "source-admissions"

def git(*args):
    return subprocess.check_output(["git", *args], cwd=ROOT, timeout=30)

def pinned(commit, path):
    require(bool(re.fullmatch(r"[0-9a-f]{40}", commit)), "invalid manifest commit")
    return json.loads(git("show", f"{commit}:{path}"))

def stamp(commit):
    epoch = int(git("show", "-s", "--format=%ct", commit).strip())
    return datetime.fromtimestamp(epoch, timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")

def contract(c):
    return hashlib.sha256(json.dumps([key(c["purpose"]), [key(x) for x in c["inputs"]],
        key(c["output"]), key(c["limits"])], separators=(",", ":")).encode()).hexdigest()

def candidate_id(c):
    return hashlib.sha256(json.dumps(c["source"], sort_keys=True, separators=(",", ":")).encode()).hexdigest()

def contract_payload(candidate):
    return {key: value for key, value in candidate.items() if key != "policy_receipt"}


def policy_contract_digest(candidate):
    body = json.dumps(contract_payload(candidate), ensure_ascii=False, sort_keys=True,
                      separators=(",", ":"), allow_nan=False)
    return hashlib.sha256(body.encode("utf-8")).hexdigest()


def make_policy_receipt(candidate, raw):
    return {
        "schema": POLICY_SCHEMA,
        "policy": POLICY,
        "source_sha256": hashlib.sha256(raw).hexdigest(),
        "contract_sha256": policy_contract_digest(candidate),
    }


def verify_policy_receipt(candidate):
    receipt = candidate.get("policy_receipt")
    require(isinstance(receipt, dict) and set(receipt) == {
        "schema", "policy", "source_sha256", "contract_sha256"
    }, "missing strict policy receipt")
    require(receipt["schema"] == POLICY_SCHEMA and receipt["policy"] == POLICY,
            "unsupported source policy")
    require(isinstance(receipt["source_sha256"], str) and
            re.fullmatch(r"[0-9a-f]{64}", receipt["source_sha256"]),
            "invalid policy source digest")
    require(receipt["contract_sha256"] == policy_contract_digest(candidate),
            "policy receipt does not bind candidate contract")
    source = candidate.get("source")
    require(isinstance(source, dict) and set(source) == {
        "repo", "commit", "blob", "path", "first", "last"
    }, "invalid policy source fields")
    require(candidate.get("receipt") == source_link(source),
            "policy evidence must link to the exact pinned source")


def read_policy_source(repo, commit, path):
    return fetch(repo, commit, quote(path, safe="/"))


def verify_policy_candidate(candidate, raw):
    verify_policy_receipt(candidate)
    from daily_source_policy import POLICY as REPRODUCER_POLICY, reproduce_candidate

    require(REPRODUCER_POLICY == POLICY, "unexpected source policy implementation")
    verify_exact_span(candidate["source"], candidate["symbol"], raw)
    require(candidate["policy_receipt"] == make_policy_receipt(candidate, raw),
            "policy receipt does not bind pinned source bytes")
    require(reproduce_candidate(candidate["source"], raw) == contract_payload(candidate),
            "candidate differs from exact policy reproduction")


def allocate_one(d, c, manifest, timestamp):
    require(isinstance(c, dict), "invalid candidate")
    w, sym = c["word"], c["symbol"]
    require(bool(re.fullmatch(r"[A-Z][A-Z0-9]*(?: [A-Z0-9]+){0,4}", w)) and len(w)<=64, "invalid canonical label")
    require(bool(re.fullmatch(r"[A-Za-z_$][A-Za-z0-9_$]*", sym)), "invalid symbol")
    require(isinstance(c["purpose"],str) and 0<len(c["purpose"])<=240, "purpose")
    require(isinstance(c["limits"],str) and 0<len(c["limits"])<=600, "limits")
    require(isinstance(c["output"],str) and 0<len(c["output"])<=300, "output")
    require(isinstance(c["inputs"],list) and all(isinstance(x,str) and x for x in c["inputs"]), "inputs")
    aliases=c.get("aliases",[])
    require(isinstance(aliases,list) and all(isinstance(x,str) and key(x) for x in aliases), "aliases")
    labels={key(w),*map(key,aliases)}
    require(len(labels)==1+len(aliases), "duplicate aliases")
    s=c["source"]
    require(bool(re.fullmatch(r"Ventusltd/[A-Za-z0-9][A-Za-z0-9_.-]*",s["repo"])), "source repository")
    require(all(re.fullmatch(r"[0-9a-f]{40}",s[k]) for k in ("commit","blob")), "source pin")
    require(bool(re.fullmatch(r"[A-Za-z0-9_. /-]+",s["path"])) and
            not {"", ".", ".."}.intersection(s["path"].split("/")), "source path")
    require(type(s["first"]) is int and type(s["last"]) is int and 1<=s["first"]<=s["last"], "source span")
    ref=f"source-command:{s['repo']}:{sym}"
    fingerprint = contract(c)
    for old in d["entries"]:
        old_labels={key(old["word"]),*map(key,old.get("aliases",[]))}
        old_sym=key((old.get("translation_ref") or "").rsplit(":",1)[-1])
        require(not labels.intersection(old_labels|{old_sym}) and key(sym) not in old_labels|{old_sym}, "duplicate label or symbol")
        require(old["sense_key"]!="function:"+ref, "duplicate sense")
        t=old.get("source") or {}
        if all(s[k]==t.get(k) for k in ("repo","path","blob")):
            require(s["last"]<t["first"] or s["first"]>t["last"], "overlapping source occurrence")
        if old.get("contract_fingerprint"):
            require(old["contract_fingerprint"]!=fingerprint, "duplicate contract")
    n=d["next_number"]
    row={k:copy.deepcopy(c[k]) for k in ("word","purpose","limits","inputs","output",
        "estate_group","discipline","periodic_category","vedic_class_candidate","source","receipt")}
    row.update(number=n,gg_id=f"GG2050-VEDIC-{n:06d}",kind="FUNCTION",
        translation_ref=ref,sense_key="function:"+ref,aliases=aliases,
        fixture_status="Static source reviewed; runtime not verified",
        demo=None,demo_unavailable_reason="No independently admitted executable package.",
        state="STATIC_SOURCE_REVIEW",classification_state="CURATED_CANDIDATE",
        periodic_block_candidate="Unresolved",created_utc=timestamp,
        creation_evidence=f"https://github.com/Ventusltd/vedic-/commit/{manifest}",
        priority=2,family_id=None,element_id=None,tablet_id=None,line_ids=None,proof=None,
        contract_fingerprint=fingerprint,admission_policy="source-reviewed-v1",
        application={"name":c["estate_group"],"url":f"https://github.com/{s['repo']}/blob/{s['commit']}/{quote(s['path'])}#L{s['first']}-L{s['last']}",
            "instructions":"Inspect the pinned source and input contract.","state":"RELATED_APPLICATION_RUNTIME_UNVERIFIED"})
    if "policy_receipt" in c:
        row["admission_policy"] = POLICY
        row["state"] = POLICY_STATE
        row["policy_receipt"] = copy.deepcopy(c["policy_receipt"])
        row["fixture_status"] = "Static source contract reproduced by policy; runtime not verified"
    d["entries"].append(row)
    d["next_number"]+=1
    return row

def replay(base, archive, load=pinned, date=stamp, *, legacy_records=(), checker=None):
    require(archive["schema"]==SCHEMA and archive["baseline_commit"]==BASE,"archive schema")
    d=copy.deepcopy(base)
    records = archive["records"]
    require(isinstance(records, list) and records[:len(legacy_records)] == list(legacy_records),
            "immutable legacy source-admission archive prefix changed")
    cache={}
    seen=set()
    for position, a in enumerate(records):
        m=a["manifest_commit"]
        if m not in cache:
            q=load(m,QUEUE)
            require(q["schema"]=="vedic.source-candidates.v1","manifest schema")
            cache[m]=(q["records"],date(m))
        manifest_records,timestamp=cache[m]
        i=a["index"]
        require(type(i) is int and 0<=i<len(manifest_records),"manifest index")
        c=manifest_records[i]
        require(a["candidate"]==c and a["candidate_id"]==candidate_id(c),"archive evidence mismatch")
        require(a["candidate_id"] not in seen,"duplicate archived source")
        seen.add(a["candidate_id"])
        strict = position >= len(legacy_records)
        if strict:
            verify_policy_receipt(c)
        allocate_one(d,c,m,timestamp)
        if strict and checker is not None:
            checker(c)
    return d

def replay_published(base, archive, *, checker=None):
    legacy = pinned(LEGACY, ARCHIVE)
    manifests = {item["manifest_commit"] for item in archive["records"][len(legacy["records"]):]}
    for manifest in manifests:
        require(bool(re.fullmatch(r"[0-9a-f]{40}", manifest)), "invalid manifest commit")
        is_ancestor = subprocess.run(
            ["git", "merge-base", "--is-ancestor", manifest, "HEAD"], cwd=ROOT, timeout=30,
            check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
        ).returncode == 0
        require(is_ancestor, "policy manifest must remain in Git history; use a merge commit")
    return replay(base, archive, legacy_records=legacy["records"], checker=checker)


def prepare(d, archive, queue, manifest, timestamp, checker, limit=LIMIT):
    require(queue["schema"]=="vedic.source-candidates.v1","queue schema")
    require(type(limit) is int and 0<=limit<=LIMIT,"admission budget")
    known={a["candidate_id"] for a in archive["records"]}
    held=[];added=[]
    for i,c in enumerate(queue["records"]):
        if len(added)>=limit: break
        before=len(d["entries"])
        try:
            cid=candidate_id(c)
            if cid in known: continue
            verify_policy_receipt(c)
            row=allocate_one(d,c,manifest,timestamp)
            checker(c)
        except (ValueError,KeyError,TypeError,AttributeError,IndexError) as exc:
            if len(d["entries"])>before:
                d["entries"].pop();d["next_number"]-=1
            held.append({"index":i,"reason":str(exc)[:240]})
            continue
        archive["records"].append({"manifest_commit":manifest,"index":i,"candidate_id":cid,"candidate":c})
        known.add(cid);added.append(row["gg_id"])
    return added,held

def stage_proposal(destination, dictionary, archive):
    destination = destination.resolve()
    require(not destination.exists(), "proposal destination already exists")
    destination.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix=".admission-", dir=destination.parent) as temporary:
        snapshot = Path(temporary) / "snapshot"
        write(snapshot / DICT, dictionary)
        write(snapshot / ARCHIVE, archive)
        snapshot.rename(destination)


def main():
    p=argparse.ArgumentParser()
    p.add_argument("--check",action="store_true")
    p.add_argument("--prepare",action="store_true")
    p.add_argument("--limit",type=int,default=LIMIT)
    p.add_argument("--online", action="store_true", help="independently reproduce archived policy contracts")
    p.add_argument("--output-dir", type=Path, help="stage proposed dictionary and archive together")
    args=p.parse_args()
    require(args.check!=args.prepare,"choose exactly one mode")
    require(not args.check or args.output_dir is None, "--output-dir requires --prepare")

    source_cache = {}

    def check_policy(candidate):
        source = candidate["source"]
        key = source["repo"], source["commit"], source["path"]
        if key not in source_cache:
            source_cache[key] = read_policy_source(*key)
        verify_policy_candidate(candidate, source_cache[key])

    base=pinned(BASE,DICT)
    current=read(ROOT/DICT)
    archive=read(ROOT/ARCHIVE)
    require(replay_published(base, archive, checker=check_policy if args.online else None) == current,
            "dictionary differs from exact source-admission replay")
    if args.check:
        print("Exact source-admission replay:",len(current["entries"]))
        return
    manifest=git("log","-1","--format=%H","--",QUEUE).decode().strip()
    queue=pinned(manifest,QUEUE)
    require(queue==read(ROOT/QUEUE),"uncommitted candidate manifest")
    translations=read(ROOT/"data/translation-geodesy.json")
    def check(candidate):
        validate(current,translations,base)
        check_policy(candidate)
    added,held=prepare(current,archive,queue,manifest,stamp(manifest),check,args.limit)
    require(replay_published(base, archive) == current,"proposal replay mismatch")
    destination = args.output_dir or DEFAULT_OUTPUT
    if added:
        stage_proposal(destination, current, archive)
    print(json.dumps({"added":added,"held":held,"count":len(current["entries"]),
                      "output_dir": str(destination.resolve()) if added else None}))

if __name__=="__main__":
    main()