GLOBALGRID2050 / EXPLORE CODE

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

VEDIC Modular Features and 4 more files

A Python command-line tool in the tools folder that works with atomic write (`atomic_write`) and path rank (`path_rank`), using SHA-256.

673 lines of Python from vedic-, in 5 files. Topic: AI agents and coordination. Section 1677 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 Modular Features storage · vedic- / tools/modular_features.py lines 1–285
  2. VEDIC Modular Snapshot storage · vedic- / tools/modular_snapshot.py lines 1–101
  3. VEDIC Package Modular Intelligence storage · vedic- / tools/package_modular_intelligence.py lines 1–89
  4. VEDIC Prose Smoke test · vedic- / tools/prose_smoke.py lines 1–109
  5. VEDIC Replay Orient Archive storage · vedic- / tools/replay_orient_archive.py lines 1–89

VEDIC Modular Features

A Python command-line tool in the tools folder that works with atomic write (`atomic_write`) and path rank (`path_rank`), using SHA-256.

storagevedic- / tools/modular_features.py · lines 1–285 of 285 · Entry point · pattern feature_row (shared by 2 files)

What it does
It loads data. Defines 12 functions or classes, including atomic_write, connect, init_worker, digest, path_rank. Uses libraries argparse, ast, collections, contextlib, concurrent.futures. 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: SQLite database; command-line arguments.
Downstream impact
Used directly by 5 files: VEDIC Canonical Intelligence (vedic-); VEDIC Canonical Sources (vedic-); VEDIC Daily Accelerator (vedic-); VEDIC Package Modular Intelligence (vedic-); and 1 more. Reached from 5 other entry points, including VEDIC Anatomy Workflow (vedic-); VEDIC Modular Consumer Workflow (vedic-); VEDIC Daily Operations (vedic-).
What it achieves
It is built from the connect step (`connect`), the init worker helper (`init_worker`) and the digest step (`digest`). Project deterministic CPU features from the existing immutable Modular Star inventory. It accepts `--workers`, `--limit` and `--reuse`.
Why it matters
Imported by 4 files, including VEDIC Canonical Intelligence, VEDIC Canonical Sources and VEDIC Daily Accelerator. Checked by VEDIC Test Modular Features.
Application
vedic- · tools · Python CLI
Uses
argparse, ast, collections, contextlib, concurrent.futures, hashlib, json, pathlib
Used by
imported by VEDIC Canonical Intelligence (import), imported by VEDIC Canonical Sources (import), imported by VEDIC Daily Accelerator (import), imported by VEDIC Package Modular Intelligence (import), imported by VEDIC Test Modular Features (import)
Produces
atomic_write, connect, init_worker, digest, path_rank, plan, utf16_slice, selected_text, feature_row, process_tablet, extract, main
Defines here
atomic_write, connect, init_worker, digest, path_rank, plan, utf16_slice, selected_text, feature_row, process_tablet, extract, 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/modular_features.py:1-285 · blob f19978fc8cbb37879890e8c85e5c2b9b52a224f8 · 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
"""Project deterministic CPU features from the existing immutable Modular Star inventory."""

import argparse
import ast
from collections import Counter, defaultdict
from contextlib import closing
from concurrent.futures import ProcessPoolExecutor
import hashlib
import json
from pathlib import Path
import re
import sqlite3
import struct
import tempfile
import textwrap
from time import perf_counter, process_time

import pyarrow as pa
import pyarrow.parquet as pq


VERSION = "modular-feature-v1"
TOKEN = re.compile(
    r'//[^\n]*|/\*[\s\S]*?\*/|"(?:\\.|[^"\\])*"|\'(?:\\.|[^\'\\])*\'|'
    r'[A-Za-z_$][\w$]*|\d+(?:\.\d+)?|===|!==|=>|==|!=|<=|>=|&&|\|\||\?\?|'
    r'\?\.|\*\*|[-+*/%&|^!<>?:=.,;{}()\[\]]'
)
NON_PRODUCTION = re.compile(r"(?:^|/)(?:vendor|node_modules|fixtures|tests?|generated|attic|archive)(?:/|$)")
GENERATED = re.compile(r"(?:\.min\.|/generated/|(?:^|/)bundle\.)")
WORD_SPLIT = re.compile(r"(?<=[a-z0-9])(?=[A-Z])|[_\W]+")
STRINGS = ("repository", "commit", "blob", "path", "symbol", "kind", "lang", "element_sha256",
           "family_sha256", "path_role", "signature", "docstring", "feature_status", "lexer")
NUMBERS = ("element_id", "family_id", "tablet_id", "first_line", "last_line", "col0", "col1")
SCHEMA = pa.schema([(name, pa.int64()) for name in NUMBERS]
                   + [(name, pa.string()) for name in STRINGS]
                   + [("tokens", pa.list_(pa.string())), ("needs", pa.list_(pa.string())),
                      ("refusal_markers", pa.list_(pa.string())), ("constants", pa.list_(pa.string())),
                      ("standalone_candidate", pa.bool_()), ("tokens_truncated", pa.bool_())])
DB = None


def atomic_write(path, write):
    path.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as handle:
        temporary = Path(handle.name)
    try:
        write(temporary)
        temporary.replace(path)
    finally:
        temporary.unlink(missing_ok=True)


def connect(db):
    return sqlite3.connect(Path(db).resolve().as_uri() + "?mode=ro&immutable=1", uri=True)


def init_worker(db):
    global DB
    DB = connect(db)


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


def path_rank(repo, path, is_current):
    lower = path.lower()
    if GENERATED.search(lower):
        return (8, "generated_path_hint")
    if NON_PRODUCTION.search(lower):
        return (7, "vendor_test_archive_path_hint")
    if "/releases/" in lower or lower.startswith(("editions/", "history/")):
        return (6, "historical_path_hint")
    if repo.lower().endswith("ventus-grid-engine") and is_current and lower.startswith("engine/"):
        return (0, "canonical_engine_path_candidate")
    if is_current:
        return (1, "current_snapshot_path_candidate")
    return (3, "indexed_snapshot_path_candidate")


def plan(conn, limit):
    eligible = conn.execute(
        """SELECT e.n, e.family, hex(e.sha), hex(f.sha), e.kind, e.needs, e.standalone, f.lang
           FROM element e JOIN family f ON e.family=f.n ORDER BY e.n LIMIT ?""",
        (limit or -1,),
    )
    elements = {row[0]: row for row in eligible}
    locations = {}
    # One representative path per unchanged file version; all other occurrences
    # remain addressable by tablet_id in the original Modular Star database.
    for tablet, repo, revision, path, is_current in conn.execute(
        """SELECT o.tablet,o.repo,o.commit_sha,o.path,o.commit_sha=s.commit_sha
           FROM occurrence o LEFT JOIN scan s ON o.repo=s.repo"""
    ):
        priority, role = path_rank(repo, path, is_current)
        choice = (priority, repo, path, revision, role)
        if tablet not in locations or choice < locations[tablet]:
            locations[tablet] = choice
    choices = {}
    for tablet, element, first, last, col0, col1, name in conn.execute(
        """SELECT tablet,element,first,last,col0,col1,name FROM tablet_element"""
    ):
        if element not in elements or tablet not in locations:
            continue
        rank = (locations[tablet], tablet, first, last, -1 if col0 is None else col0, name or "")
        if element not in choices or rank < choices[element][0]:
            choices[element] = (rank, tablet, first, last, col0, col1, name)
    if choices.keys() != elements.keys():
        raise ValueError("Some existing elements have no indexed source occurrence")
    groups = defaultdict(list)
    for element, (rank, tablet, first, last, col0, col1, name) in choices.items():
        _, repo, path, revision, role = rank[0]
        _, family, element_hash, family_hash, kind, needs, standalone, lang = elements[element]
        groups[tablet].append({
            "element_id": element, "family_id": family, "tablet_id": tablet,
            "first_line": first, "last_line": last, "col0": col0, "col1": col1,
            "repository": repo, "commit": revision, "path": path, "symbol": name,
            "path_role": role, "element_sha256": element_hash.lower(),
            "family_sha256": family_hash.lower(), "kind": kind, "lang": lang,
            "needs": json.loads(needs) if needs else None, "standalone_candidate": bool(standalone),
        })
    return groups


def utf16_slice(text, start=None, stop=None):
    return text.encode("utf-16-le")[slice(None if start is None else start * 2,
                                             None if stop is None else stop * 2)].decode("utf-16-le")


def selected_text(lines, start, stop):
    parts = [line.decode("utf-8", errors="replace") for line in lines]
    if start is None or stop is None:
        return "".join(parts)
    if len(parts) == 1:
        return utf16_slice(parts[0], start, stop)
    return utf16_slice(parts[0], start) + "".join(parts[1:-1]) + utf16_slice(parts[-1], stop=stop)


def feature_row(row, text):
    kind = row["kind"] or "unknown"
    features = ["kind:" + kind, "lang:" + row["lang"]]
    signature = next((line.strip()[:240] for line in text.splitlines() if line.strip()), "")
    markers = sorted(set(re.findall(r"\b(?:throw|raise|assert)\b|return\s+(?:null|None)\b", text)))
    constants = []
    doc = None
    if row["lang"] == "py":
        try:
            tree = ast.parse(textwrap.dedent(text))
            first = tree.body[0] if tree.body else None
            if isinstance(first, (ast.FunctionDef, ast.AsyncFunctionDef)):
                signature = f"{first.name}({ast.unparse(first.args)})"
            if isinstance(first, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
                doc = (ast.get_docstring(first) or "")[:1024] or None
            features.extend("ast:" + type(node).__name__ for node in ast.walk(tree))
        except (SyntaxError, ValueError, RecursionError):
            pass
    for value in (row["symbol"] or "", *(row["needs"] or [])):
        features.extend("symbol:" + word.lower() for word in WORD_SPLIT.split(value) if word)
    sequence = []
    for token in TOKEN.findall(text):
        if token.startswith(("//", "/*")):
            continue
        if token[0] in "\"'":
            sequence.append("literal:string")
        elif token[0].isdigit():
            sequence.append("literal:number")
            if len(constants) < 20 and token not in constants:
                constants.append(token)
        elif token[0].isalpha() or token[0] in "_$":
            sequence.append("id:" + token.lower())
        else:
            sequence.append("op:" + token)
    truncated = len(sequence) > 512 or len(features) > 512
    sequence = sequence[:512]
    features = features[:512] + sequence
    features.extend("pair:" + a + "|" + b for a, b in zip(sequence, sequence[1:]))
    return {**row, "tokens": features, "signature": signature, "docstring": doc,
            "constants": constants, "refusal_markers": markers,
            "tokens_truncated": truncated, "lexer": "bounded_lexical_ngrams_with_indexed_structure",
            "feature_status": "source_span_reconstructed"}


def process_tablet(task):
    tablet, rows = task
    started = process_time()
    blob, packed = DB.execute("SELECT git_blob,lines FROM tablet WHERE n=?", (tablet,)).fetchone()
    numbers = [item[0] for item in struct.iter_unpack("<I", packed)]
    wanted = sorted({number for row in rows for number in numbers[row["first_line"]-1:row["last_line"]]})
    lines = {}
    for offset in range(0, len(wanted), 500):
        batch = wanted[offset:offset + 500]
        placeholders = ",".join("?" for _ in batch)
        lines.update(DB.execute(f"SELECT n,text FROM line WHERE n IN ({placeholders})", batch))
    out = []
    for row in rows:
        raw = [lines[n] for n in numbers[row["first_line"]-1:row["last_line"]]]
        if not raw or digest(b"".join(raw)) != row["element_sha256"]:
            raise ValueError(f"Indexed source hash mismatch for element {row['element_id']}")
        body = selected_text(raw, row["col0"], row["col1"])
        out.append(feature_row({**row, "blob": blob}, body))
    return out, process_time() - started


KEYS = ("element_id", "family_id", "element_sha256", "family_sha256", "repository",
        "commit", "path", "first_line", "last_line", "col0", "col1", "symbol",
        "path_role", "kind", "lang", "needs", "standalone_candidate")


def extract(db, output, workers, limit, prior=None):
    if output.exists():
        raise ValueError("Refusing to replace frozen output")
    start = perf_counter()
    with closing(connect(db)) as conn:
        groups = plan(conn, limit)
    plan_seconds = perf_counter() - start
    cached = {}
    if prior is not None:
        receipt = json.loads(prior.with_suffix(".json").read_text(encoding="utf-8"))
        if receipt.get("parquet_sha256") != digest(prior.read_bytes()):
            raise ValueError("Incremental feature input differs from its frozen manifest")
        table = pq.read_table(prior)
        if (table.schema.metadata or {}).get(b"feature_version", b"").decode() != VERSION:
            raise ValueError("Cannot reuse features from a different schema version")
        cached = {row["element_id"]: row for row in table.to_pylist()}
    result = []
    remaining = []
    cached_count = 0
    for tablet, rows in sorted(groups.items()):
        needs_work = []
        for row in rows:
            hit = cached.get(row["element_id"])
            if hit is not None and all(hit.get(key) == row.get(key) for key in KEYS):
                result.append(hit)
                cached_count += 1
            else:
                needs_work.append(row)
        if needs_work:
            remaining.append((tablet, needs_work))
    cpu = 0
    if remaining:
        if workers == 1:
            init_worker(db)
            try:
                for rows, seconds in map(process_tablet, remaining):
                    result.extend(rows)
                    cpu += seconds
            finally:
                DB.close()
        else:
            with ProcessPoolExecutor(max_workers=workers, initializer=init_worker, initargs=(db,)) as pool:
                for rows, seconds in pool.map(process_tablet, remaining, chunksize=12):
                    result.extend(rows)
                    cpu += seconds
    result.sort(key=lambda row: row["element_id"])
    table = pa.Table.from_pylist(result, schema=SCHEMA).replace_schema_metadata({b"feature_version": VERSION.encode()})
    atomic_write(output, lambda temporary: pq.write_table(table, temporary, compression="zstd"))
    report = {
        "feature_version": VERSION, "workers": workers, "planning_wall_seconds": plan_seconds,
        "cpu_worker_seconds": cpu, "wall_seconds": perf_counter() - start,
        "elements": len(result), "families": len({row["family_id"] for row in result}),
        "selected_tablets": len(groups), "reused_elements": cached_count,
        "lexically_truncated_elements": sum(row["tokens_truncated"] for row in result),
        "roles": dict(Counter(row["path_role"] for row in result)),
        "parquet_sha256": digest(output.read_bytes()), "parquet_bytes": output.stat().st_size,
        "identity_basis": "Existing Modular Star element and family IDs; reconstructed span bytes verified against element SHA-256.",
    }
    atomic_write(output.with_suffix(".json"), lambda t: t.write_text(json.dumps(report, indent=2)+"\n", encoding="utf-8"))
    return report


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("sqlite", type=Path)
    parser.add_argument("parquet", type=Path)
    parser.add_argument("--workers", type=int, default=1)
    parser.add_argument("--limit", type=int)
    parser.add_argument("--reuse", type=Path)
    args = parser.parse_args()
    if args.workers < 1 or (args.limit is not None and args.limit < 1):
        parser.error("Worker and sample limits must be positive")
    print(json.dumps(extract(args.sqlite, args.parquet, args.workers, args.limit, args.reuse), indent=2))


if __name__ == "__main__":
    main()

VEDIC Modular Snapshot

A Python command-line tool in the tools folder that works with unpack snapshot (`unpack_snapshot`), using SHA-256.

storagevedic- / tools/modular_snapshot.py · lines 1–101 of 101 · Entry point · pattern metadata (shared by 2 files)

What it does
It loads data. Defines 8 functions or classes, including require, gh, metadata, sha256, unpack_snapshot. Uses libraries argparse, datetime, gzip, hashlib, json. 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: SQLite database; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 3 files: VEDIC Daily Accelerator (vedic-); VEDIC Test Modular Snapshot (vedic-); VEDIC Modular Consumer Workflow (vedic-). Reached from 5 other entry points, including VEDIC Anatomy Workflow (vedic-); VEDIC Release Rehearsal Workflow (vedic-); VEDIC Daily Operations (vedic-).
What it achieves
It downloads snapshot (`download_snapshot`) and is built from the require step (`require`) and the metadata step (`metadata`). Read-only Modular Star consumer. No producer writes and no ID allocation. It accepts `--output`.
Why it matters
Imported by VEDIC Daily Accelerator. Run by VEDIC Modular Consumer Workflow. Checked by VEDIC Test Modular Snapshot.
Application
vedic- · tools · Python CLI
Uses
argparse, datetime, gzip, hashlib, json, sqlite3, subprocess, tempfile
Used by
imported by VEDIC Daily Accelerator (import), imported by VEDIC Test Modular Snapshot (import), run by VEDIC Modular Consumer Workflow (workflow run)
Produces
require, gh, metadata, sha256, unpack_snapshot, inventory, download_snapshot, acquire
Defines here
require, gh, metadata, sha256, unpack_snapshot, inventory, download_snapshot, acquire
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/modular_snapshot.py:1-101 · blob b513c57f8e94ec87c541686c5baafb37d14a6e1e · 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
"""Read-only Modular Star consumer. No producer writes and no ID allocation."""
import argparse
import datetime as dt
import gzip
import hashlib
import json
import sqlite3
import subprocess
import tempfile
from contextlib import closing
from pathlib import Path

PRODUCER = "Ventusltd/stars"
TAG = "modular-star"
ASSET = "modular.sqlite.gz"
MAX_BYTES = 4 * 1024**3
TABLES = ("line", "tablet", "family", "element", "tablet_element", "occurrence", "scan")

def require(ok, message):
    if not ok:
        raise ValueError(message)

def gh(*args):
    return subprocess.check_output(["gh", *args], timeout=300)

def metadata():
    release = json.loads(gh("api", f"repos/{PRODUCER}/releases/tags/{TAG}"))
    assets = [a for a in release["assets"] if a["name"] == ASSET and a["state"] == "uploaded"]
    require(len(assets) == 1, "expected exactly one completed database asset")
    a = assets[0]
    return {"release_id": release["id"], "asset_id": a["id"], "size": a["size"],
            "updated_at": a["updated_at"], "digest": a.get("digest")}

def sha256(path):
    with path.open("rb") as f:
        return hashlib.file_digest(f, "sha256").hexdigest()

def unpack_snapshot(compressed, database, before, after):
    require(before == after, "producer asset changed during download; retry later")
    require(compressed.stat().st_size == before["size"], "asset size mismatch")
    require(0 < before["size"] <= MAX_BYTES, "compressed size outside bound")
    compressed_hash = sha256(compressed)
    if before["digest"] is not None:
        require(before["digest"] == "sha256:" + compressed_hash, "asset digest mismatch")
    written = 0
    with gzip.open(compressed, "rb") as src, database.open("xb") as dst:
        while chunk := src.read(1024 * 1024):
            written += len(chunk)
            require(written <= MAX_BYTES, "uncompressed database exceeds bound")
            dst.write(chunk)
    return {"compressed_sha256": compressed_hash, "database_sha256": sha256(database),
            "database_bytes": written, "asset_digest_verified": before["digest"] is not None}

def inventory(database):
    uri = database.resolve().as_uri() + "?mode=ro"
    with closing(sqlite3.connect(uri, uri=True)) as db:
        db.execute("PRAGMA query_only=ON")
        require(db.execute("PRAGMA quick_check").fetchall() == [("ok",)], "SQLite integrity check failed")
        names = {r[0] for r in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
        require(set(TABLES) <= names, "producer schema incompatible")
        counts = {table: db.execute(f'SELECT count(*) FROM "{table}"').fetchone()[0] for table in TABLES}
        require(counts["line"] > 0 and counts["tablet"] > 0, "empty producer inventory")
        repos = db.execute("SELECT count(DISTINCT repo) FROM occurrence").fetchone()[0]
        return {"producer_inventory": counts, "repositories_with_occurrences": repos,
                "translated_unique_lines": None, "active_application_unique_lines": None,
                "scope": "Producer database inventory, including historical occurrences; not VEDIC translation coverage."}

def download_snapshot(directory, require_digest=False):
    before = metadata()
    require(0 < before["size"] <= MAX_BYTES, "asset size outside bound")
    if require_digest:
        require(isinstance(before["digest"], str) and before["digest"].startswith("sha256:"),
                "producer asset is missing its digest")
    compressed = directory / ASSET
    with compressed.open("xb") as stream:
        subprocess.run(["gh", "api", f"repos/{PRODUCER}/releases/assets/{before['asset_id']}",
                        "-H", "Accept: application/octet-stream"], stdout=stream, check=True, timeout=300)
    database = directory / "modular.sqlite"
    hashes = unpack_snapshot(compressed, database, before, metadata())
    return database, before, hashes


def acquire(output):
    output = output.resolve()
    output.parent.mkdir(parents=True, exist_ok=True)
    require(not output.exists(), "refuse to overwrite existing receipt")
    with tempfile.TemporaryDirectory(prefix="vedic-stars-") as directory:
        database, before, hashes = download_snapshot(Path(directory))
        report = {"schema": "vedic.modular-snapshot.v1", "producer": PRODUCER, "release_tag": TAG,
                  "asset": ASSET, "metadata": before, "snapshot": hashes,
                  "observed_utc": dt.datetime.now(dt.timezone.utc).isoformat(), **inventory(database)}
        with output.open("x", encoding="utf-8") as f:
            json.dump(report, f, sort_keys=True, indent=2)
            f.write("\n")
        return report

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()
    print(json.dumps(acquire(args.output), indent=2))

VEDIC Package Modular Intelligence

A Python command-line tool in the tools folder that reads element features, compiled members, family coverage and engine nodes. It is built from the build step (`build`).

storagevedic- / tools/package_modular_intelligence.py · lines 1–89 of 89 · Entry point

What it does
It loads element features, compiled members, family coverage and engine nodes. Defines build, main. Uses libraries argparse, json, pathlib, re, sqlite3. 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: Parquet file element-features.parquet; Parquet file compiled-members.parquet; Parquet file family-coverage.parquet; Parquet file engine-nodes.parquet; Parquet file engine-edges.parquet; Parquet file gridatlas-composition.parquet; Parquet file canonical-bindings.parquet; Parquet file canonical-symbols.parquet.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Package local factor tables without modifying the shared catalogue. It reads `element-features.parquet` and writes `t1-intelligence-manifest.json`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
vedic- · tools · Python CLI
Uses
VEDIC Canonical Sources (import), VEDIC Modular Features (import), argparse, json, pathlib, re, sqlite3, time, duckdb, pyarrow.parquet
Used by
none found
Produces
build, main
Defines here
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/package_modular_intelligence.py:1-89 · blob b7c0f32c9079a55edf5fb633be0d79a5778b7f5f · 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
"""Package local factor tables without modifying the shared catalogue."""

import argparse
import json
from pathlib import Path
import re
import sqlite3
from time import perf_counter

import duckdb
import pyarrow.parquet as pq

from canonical_sources import blob, digest, output_table
from modular_features import atomic_write

STARS = "1cf9c7530c7d287ccf9b3cffd70f693fb83c8402"


def build(db, t1, stars):
    started = perf_counter()
    library_blob, raw = blob(stars, STARS, "library/standalone.mjs")
    compiled = re.findall(
        rb"(?m)^// Family #(\d+) [^\n]*?element #(\d+) [^\n]*? (https://github\.com/\S+)\n"
        rb"export const (f[0-9]+_[A-Za-z0-9_$]+)\s*=", raw)
    compiled_rows = [
        {"family_id": int(family), "element_id": int(element), "recorded_source": url.decode(),
         "export_name": name.decode(), "producer_commit": STARS, "library_blob": library_blob,
         "status": "compiled_candidate_no_admission"}
        for family, element, url, name in compiled
    ]
    if len(compiled_rows) != 766 or len({row["family_id"] for row in compiled_rows}) != len(compiled_rows):
        raise ValueError("Compiled library exports disagree with this pinned inventory")
    features = pq.read_table(t1/"element-features.parquet", columns=["family_id", "element_id"])
    exported_families = {row["family_id"] for row in compiled_rows}
    with sqlite3.connect(db.resolve().as_uri() + "?mode=ro&immutable=1", uri=True) as conn:
        coverage = [
            {"family_id": family, "family_sha256": sha.lower(), "language": lang,
             "indexed_element_count": elements, "has_feature_row": elements > 0,
             "compiled_candidate": family in exported_families}
            for family, sha, lang, elements in conn.execute(
                "SELECT f.n,hex(f.sha),f.lang,count(e.n) FROM family f LEFT JOIN element e "
                "ON f.n=e.family GROUP BY f.n ORDER BY f.n")
        ]
    assert sum(row["indexed_element_count"] for row in coverage) == features.num_rows
    tables = [output_table(t1/"compiled-members.parquet", compiled_rows),
              output_table(t1/"family-coverage.parquet", coverage)]
    files = {
        "element_features": "element-features.parquet",
        "family_coverage": "family-coverage.parquet",
        "compiled_members": "compiled-members.parquet",
        "engine_nodes": "engine-nodes.parquet",
        "engine_edges": "engine-edges.parquet",
        "gridatlas_composition": "gridatlas-composition.parquet",
        "canonical_bindings": "canonical-bindings.parquet",
        "canonical_symbols": "canonical-symbols.parquet",
        "canonical_file_metadata": "canonical-file-metadata.parquet",
    }
    target = t1/"canonical-intelligence.duckdb"
    scratch = target.with_suffix(".part")
    if target.exists() or scratch.exists():
        raise ValueError("Refusing to replace existing intelligence file")
    with duckdb.connect(str(scratch)) as local:
        for name, file in files.items():
            local.execute(f"CREATE TABLE {name} AS SELECT * FROM read_parquet(?)", [str(t1/file)])
        totals = local.execute("SELECT count(*), count(DISTINCT family_id) FROM element_features").fetchone()
        assert totals == (features.num_rows, sum(row["has_feature_row"] for row in coverage))
        local.execute("CHECKPOINT")
    scratch.rename(target)
    manifest = {
        "tables": tables, "compiled_candidates": len(compiled_rows), "duckdb": target.name,
        "duckdb_sha256": digest(target.read_bytes()), "duckdb_size_bytes": target.stat().st_size,
        "database_tables": files, "processing_seconds": perf_counter() - started,
        "families_without_linked_elements": sum(not row["has_feature_row"] for row in coverage),
    }
    atomic_write(t1/"t1-intelligence-manifest.json",
                 lambda p: p.write_text(json.dumps(manifest, indent=2)+"\n", encoding="utf-8"))
    return manifest


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


if __name__ == "__main__":
    main()

VEDIC Prose Smoke

A Python command-line tool in the tools folder that tests prose catalogue and only.

testvedic- / tools/prose_smoke.py · lines 1–109 of 109 · Entry point · pattern unavailable (shared by 6 files)

What it does
It tests prose catalogue and only. Defines fixture_file, exercise_published, exercise_local, unavailable, main. Uses libraries argparse, json, pathlib, playwright.sync_api. Side effects: changes the web page (DOM); 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 prose-catalogue.json; JSON file test-only.json; command-line arguments.
Downstream impact
Used directly by 1 file: VEDIC Browser Smoke (vedic-). Reached from 3 other entry points, including VEDIC Anatomy Workflow (vedic-); VEDIC Release Rehearsal Workflow (vedic-); VEDIC Check Pages Candidate (vedic-).
What it achieves
It is built from the fixture file helper (`fixture_file`), the exercise published helper (`exercise_published`) and the exercise local helper (`exercise_local`). Check the real released prose and browser-only catalogue handling.
Why it matters
Checked by VEDIC Browser Smoke.
Application
vedic- · tools · Python CLI
Uses
argparse, json, pathlib, playwright.sync_api
Used by
imported by VEDIC Browser Smoke (import)
Produces
fixture_file, exercise_published, exercise_local, main
Defines here
fixture_file, exercise_published, exercise_local, unavailable, 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/prose_smoke.py:1-109 · blob a1972e2ccb4e7ef3c4829b932cf316e9c1cfb36d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Check the real released prose and browser-only catalogue handling."""
import argparse
import json
from pathlib import Path

from playwright.sync_api import expect, sync_playwright

CATALOGUE_URL = "**/data/prose-catalogue.json"


def fixture_file(records):
    data = {"schema": "vedic.prose.catalogue.v1", "records": records}
    return {"name": "test-only.json", "mimeType": "application/json",
            "buffer": json.dumps(data, ensure_ascii=False).encode("utf-8")}


def exercise_published(page, catalogue):
    expected = catalogue["records"]
    expect(page.locator("#proseStatus")).to_contain_text("Published catalogue")
    rows = page.locator("#proseRows tr")
    assert rows.count() == min(100, len(expected))
    for position, record in enumerate(expected[:100]):
        row = rows.nth(position)
        assert row.locator("strong").text_content() == record["id"]
        assert row.locator(".prose-text").first.text_content() == record["prose"]
        row.locator("summary").click()
        assert row.locator("details p").all_text_contents() == [record["provenance"], record["evidence"]]
    assert page.evaluate("document.documentElement.scrollWidth <= innerWidth + 1")
    final = expected[-1]
    page.locator("#proseSearch").fill(final["id"])
    assert rows.count() == 1
    assert rows.first.locator(".prose-text").first.text_content() == final["prose"]
    page.locator("#proseSearch").fill("")
    page.locator("#proseApp").select_option(final["software"])
    assert rows.count() == min(100, sum(r["software"] == final["software"] for r in expected))
    page.locator("#proseFull").click()
    expect(page.locator("#proseFull")).to_have_attribute("aria-pressed", "true")
    assert page.evaluate("document.documentElement.scrollWidth <= innerWidth + 1")
    page.keyboard.press("Escape")
    expect(page.locator("#proseFull")).to_have_attribute("aria-pressed", "false")


def exercise_local(page, url):
    long_text = "An exact long paragraph \u2014 long enough to wrap. " * 200 + "\n\nA second paragraph and \u00a9."
    attack = '<img src="/should-never-send-local-import" onerror="window.importExecuted=true">'
    records = [{"id": f"LOCAL-{i:03}", "software": "Synthetic fixture",
                "prose": long_text if i == 0 else attack if i == 100 else f"Test passage {i}"}
               for i in range(101)]
    page.wait_for_load_state("networkidle")
    sent = []
    page.on("request", lambda request: sent.append(request.url))
    page.locator("#proseImport").set_input_files(fixture_file(records))
    expect(page.locator("#proseStatus")).to_contain_text("Local file")
    rows = page.locator("#proseRows tr")
    assert rows.count() == 100
    assert rows.first.locator(".prose-text").first.text_content() == long_text
    page.locator("#proseNext").click()
    assert rows.count() == 1
    assert rows.first.locator(".prose-text").first.text_content() == attack
    assert page.locator("#proseRows img").count() == 0
    assert not page.evaluate("Boolean(window.importExecuted)")
    page.locator("#proseSearch").fill("A second paragraph")
    assert rows.count() == 1
    assert rows.first.locator("strong").text_content() == "LOCAL-000"
    page.locator("#proseImport").set_input_files(fixture_file([records[0], records[0]]))
    expect(page.locator("#proseStatus")).to_contain_text("Import rejected")
    assert not sent, sent

    for code, body in ((404, ""), (200, '{"schema":"invalid","records":[]}')):
        def unavailable(route):
            route.fulfill(status=code, body=body, content_type="application/json")

        page.route(CATALOGUE_URL, unavailable)
        page.goto(url)
        page.wait_for_load_state("networkidle")
        expect(page.locator("#proseStatus")).to_contain_text("No published catalogue available")
        assert rows.count() == 0
        page.locator("#proseImport").set_input_files(fixture_file(records[:1]))
        expect(page.locator("#proseStatus")).to_contain_text("Local file")
        assert rows.first.locator(".prose-text").first.text_content() == long_text
        page.unroute(CATALOGUE_URL, unavailable)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("url")
    parser.add_argument("catalogue", type=Path)
    args = parser.parse_args()
    catalogue = json.loads(args.catalogue.read_bytes())
    with sync_playwright() as playwright:
        for engine in (playwright.chromium, playwright.webkit):
            browser = engine.launch(headless=True)
            try:
                for width, height in ((1280, 800), (390, 844), (844, 390)):
                    page = browser.new_page(viewport={"width": width, "height": height})
                    errors = []
                    page.on("pageerror", lambda error: errors.append(str(error)))
                    page.goto(args.url)
                    exercise_published(page, catalogue)
                    exercise_local(page, args.url)
                    assert not errors, errors
                    page.close()
                    print(f"Prose PASS {engine.name} {width}x{height}", flush=True)
            finally:
                browser.close()


if __name__ == "__main__":
    main()

VEDIC Replay Orient Archive

A Python command-line tool in the tools folder covering build receipt, using SHA-256. It is built from the member step (`member`) and the reassemble step (`reassemble`).

storagevedic- / tools/replay_orient_archive.py · lines 1–89 of 89 · Entry point · pattern member (shared by 2 files)

What it does
Defines member, reassemble, main. Uses libraries argparse, importlib.util, json, pathlib, shutil. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage experimental (path word 'archive'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
Inputs & outputs
In: JSON file receipt.json; JSON file build-receipt.json; JSON file orient.json; command-line arguments. Out: JSON file build-receipt.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Recover the exact private ORIENT archive from its existing build evidence. It reads `packages/factory/admissions/orient.json`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
vedic- · tools · Python CLI
Uses
VEDIC Semantic Compiler (import), argparse, importlib.util, json, pathlib, shutil, tempfile, unittest.mock, zipfile
Used by
none found
Produces
member, reassemble, main
Defines here
member, reassemble, 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/replay_orient_archive.py:1-89 · blob 2d24e7dbfe0df5b4c99609942500320b1edade28 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: ai_agent · canonical: supporting_data
"""Recover the exact private ORIENT archive from its existing build evidence."""
import argparse
import importlib.util
import json
from pathlib import Path
import shutil
import tempfile
from unittest.mock import patch
import zipfile

from semantic_compiler import (BINDINGS, Refusal, need, pinned_git_file, sha256,
                               small_read, stage_factory, strict_json)

SOURCE_MEMBERS = {
    "module.mjs": "source-receipt/v9-geodesy.mjs",
    "receipt.json": "source-receipt/receipt.json",
}
MANIFEST_SHA256 = "67b6f9f39e30449e1a965d1e06334925ee002a5fd3b4429f892fe61f83a3af78"


def member(archive, name):
    matches = [entry for entry in archive.infolist() if entry.filename == name]
    need(len(matches) == 1 and matches[0].file_size <= 2 * 1024 * 1024,
         "ARTIFACT_MEMBER_MISMATCH", member=name)
    return archive.read(matches[0])


def reassemble(vedic, engine, source_artifact, build_artifact):
    binding = strict_json(small_read(BINDINGS))["bindings"]["GG2050-VEDIC-000006"]
    package = binding["package"]
    with zipfile.ZipFile(source_artifact) as source:
        inputs = {name: member(source, path) for name, path in SOURCE_MEMBERS.items()}
    with zipfile.ZipFile(build_artifact) as build:
        manifest = member(build, "manifest.json")
        receipt = member(build, "build-receipt.json")
    need(sha256(manifest) == MANIFEST_SHA256
         and sha256(receipt) == package["build_receipt_sha256"], "BUILD_EVIDENCE_MISMATCH")
    need(inputs["module.mjs"] == pinned_git_file(
        engine, "487ec7bd38dfa5aecb1c75da53b4a866ab2101cb", "engine/v9-geodesy.js"),
        "SOURCE_ARTIFACT_GIT_MISMATCH")
    with tempfile.TemporaryDirectory(prefix="vedic-package-recovery-") as tmp:
        root = Path(tmp)
        stage_factory(vedic, root, package)
        spec = importlib.util.spec_from_file_location("pinned_factory", root / "tools/package_factory.py")
        factory = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(factory)
        descriptor = strict_json(small_read(root / "packages/factory/admissions/orient.json"))
        repos = {"Ventusltd/vedic-": vedic, "Ventusltd/ventus-grid-engine": engine}
        for item in descriptor["inputs"]:
            if item["filename"] not in inputs:
                inputs[item["filename"]] = pinned_git_file(
                    repos[item["repo"]], item["commit"], item["path"])
        # The published build opens files using Linux-only flags. Supply immutable
        # in-memory bytes while retaining the original Factory digest checks.
        with patch.object(factory, "read_file", side_effect=lambda _, name: inputs[name]):
            payload, _ = factory.assemble(descriptor, None)
        raw = factory.archive(payload)
        factory.verify(raw, payload)
    need(payload["manifest.json"] == manifest and sha256(raw) == package["archive_sha256"],
         "REASSEMBLED_ARCHIVE_MISMATCH")
    return raw, receipt


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    for name in ("vedic", "engine", "source-artifact", "build-artifact", "out"):
        parser.add_argument("--" + name, required=True, type=Path)
    args = parser.parse_args()
    try:
        need(not args.out.exists(), "OUTPUT_EXISTS")
        archive, receipt = reassemble(args.vedic, args.engine, args.source_artifact, args.build_artifact)
        staging = Path(tempfile.mkdtemp(prefix=".vedic-orient-", dir=args.out.parent))
        try:
            (staging / "orient.zip").write_bytes(archive)
            (staging / "build-receipt.json").write_bytes(receipt)
            staging.rename(args.out)
        finally:
            if staging.exists():
                shutil.rmtree(staging)
    except (ValueError, OSError, zipfile.BadZipFile) as exc:
        print(json.dumps({"state": "REFUSED", "reason": str(exc)}))
        return 2
    print(json.dumps({"state": "EXACT_ARCHIVE_RECOVERED", "archive_bytes": len(archive),
                      "archive_sha256": sha256(archive), "build_receipt_sha256": sha256(receipt)}))
    return 0


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