GLOBALGRID2050 / EXPLORE CODE

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

VEDIC Browser Smoke and 2 more files

A Python command-line tool in the tools folder that tests dictionary, translation geodesy, command and prose catalogue, and uses data from the stars, kuiper-belt and GridAtlas repositories.

516 lines of Python and JavaScript from vedic-, in 3 files. Topic: AI agents and coordination. Section 1671 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 Browser Smoke test · vedic- / tools/browser_smoke.py lines 1–323
  2. VEDIC Canonical Acorn ingest · vedic- / tools/canonical_acorn.mjs lines 1–112
  3. VEDIC Canonical Intelligence storage · vedic- / tools/canonical_intelligence.py lines 1–81

VEDIC Browser Smoke

A Python command-line tool in the tools folder that tests dictionary, translation geodesy, command and prose catalogue, and uses data from the stars, kuiper-belt and GridAtlas repositories.

testvedic- / tools/browser_smoke.py · lines 1–323 of 323 · Entry point · pattern expected (shared by 5 files)

What it does
It tests dictionary, translation geodesy, command and prose catalogue. Defines 10 functions or classes, including audit_all_code_rows, audit_live, live_json, sources, expected. Uses libraries json, math, urllib.parse, functools, http.server. 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: data source: stars data; data source: kuiper-belt data; data source: gridatlas data; JSON file release.json; JSON file dictionary.json; JSON file translation-geodesy.json; JSON file command-index.json; JSON file prose-catalogue.json.
Downstream impact
Used directly by 2 files: 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 audits code rows (`audit_all_code_rows`) and audits live (`audit_live`). Offline UI smoke against the exact checked-out VEDIC candidate.
Why it matters
Imported by VEDIC Check Pages Candidate. Run by VEDIC Anatomy Workflow.
Application
vedic- · tools · Python CLI
Uses
VEDIC Prose Smoke (import), VEDIC Dictionary Shards (import), VEDIC Stage Pages (import), Code (estate URL), Kuiper Belt — Index Page (estate URL), VEDIC — Index Page (estate URL), json, math, urllib.parse, functools, http.server, pathlib, threading, playwright.sync_api
Used by
imported by VEDIC Check Pages Candidate (import), run by VEDIC Anatomy Workflow (workflow run)
Produces
audit_all_code_rows, audit_live, main
Defines here
audit_all_code_rows, audit_live, live_json, sources, expected, main, source_records, expected_links, wait_dictionary, close
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/browser_smoke.py:1-323 · blob 47eee61fe8e1b309e1d975c7edb6f43c0a7c5231 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Offline UI smoke against the exact checked-out VEDIC candidate."""
import json
import math
from urllib.parse import parse_qs, urlparse, quote
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from threading import Thread
from playwright.sync_api import sync_playwright

from prose_smoke import exercise_published, exercise_local
from dictionary_shards import write_bundle as write_command_shards
from stage_pages import FIRST_PROSE_ROUTE, TELEPRINTER_PROSE_ROUTE

ROOT = Path(__file__).resolve().parents[1]

def audit_all_code_rows(page, entries, expected_links):
    """Exercise every lazy-loaded source control, not just sample rows."""
    for entry in entries:
        identity = entry["gg_id"]
        page.locator("#dictSearch").fill(identity)
        row = page.locator("#dictRows tr")
        assert row.count() == 1, identity
        assert row.locator("td").first.inner_text() == entry["word"], identity
        button = row.locator(".code-cell button")
        if button.count():
            button.click()
        try:
            row.locator("a.code-source").first.wait_for(timeout=8000)
        except Exception as exc:
            raise AssertionError(f"{identity} {entry['word']}: {row.inner_text()}") from exc
        selectors = ['a.code-source', 'a[href^="https://raw.githubusercontent.com/"]',
                     'a[href^="https://ventusltd.github.io/stars/code.html"]',
                     'a[href^="https://ventusltd.github.io/kuiper-belt/"]']
        actual = [row.locator(".code-cell").locator(sel).evaluate_all(
            "(links) => links.map(link => link.href)") for sel in selectors]
        assert actual == expected_links(entry), (identity, actual, expected_links(entry))
        assert not row.get_by_text("Command details unavailable", exact=False).count(), identity
    print(f"PASS all {len(entries)} command code controls and source targets", flush=True)


def audit_live():
    """Read-only audit of the deployed website, independent of the checkout."""
    url = "https://ventusltd.github.io/vedic-/"
    with sync_playwright() as p:
        for engine in (p.chromium, p.webkit):
            browser = engine.launch(headless=True)
            try:
                page = browser.new_page(viewport={"width": 390, "height": 844}, is_mobile=True,
                                        has_touch=True, device_scale_factor=3)
                errors, failed = [], []
                page.on("pageerror", lambda err: errors.append(str(err)))
                page.on("response", lambda response: failed.append((response.status, response.url))
                        if response.url.startswith(url) and response.status >= 400 else None)
                page.on("requestfailed", lambda req: failed.append((req.failure, req.url))
                        if req.url.startswith(url) else None)
                page.goto(url, wait_until="domcontentloaded", timeout=45000)
                page.locator("#dictRows tr").first.wait_for(timeout=30000)
                def live_json(path):
                    response = page.request.get(url + path, headers={"Cache-Control": "no-cache"}, timeout=30000)
                    assert response.ok, (path, response.status)
                    return response.json()
                release = live_json("release.json")
                entries = live_json("data/dictionary.json")["entries"]
                translations = {r["id"]: r for r in live_json("data/translation-geodesy.json")["records"]}
                identities = {e["gg_id"]: e for e in entries}
                def sources(entry, seen=None):
                    if seen is None:
                        seen = set()
                    if entry["gg_id"] in seen:
                        return []
                    seen.add(entry["gg_id"])
                    src = translations.get(entry.get("translation_ref"), {}).get("source") or entry.get("source")
                    if src:
                        return [src]
                    return [s for identity in entry.get("components", []) for s in sources(identities[identity], seen)]
                def expected(entry):
                    ss = sources(entry)
                    return [
                        ["https://github.com/"+s["repo"]+"/blob/"+s["commit"]+"/"+quote(s["path"], safe="/")+"#L"+str(s["first"])+"-L"+str(s["last"]) for s in ss],
                        ["https://raw.githubusercontent.com/"+s["repo"]+"/"+s["commit"]+"/"+quote(s["path"], safe="/") for s in ss],
                        ["https://ventusltd.github.io/stars/code.html" for s in ss],
                        ["https://ventusltd.github.io/kuiper-belt/see-through/202611020012/#repo="+quote(s["repo"].split("/")[1], safe="") for s in ss],
                    ]
                assert release["row_count"] == len(entries), release
                print(f"LIVE {engine.name}: {release['source_commit']} / {len(entries)} commands", flush=True)
                audit_all_code_rows(page, entries, expected)
                assert not errors, errors
                assert not failed, failed
                page.reload(wait_until="domcontentloaded", timeout=45000)
                page.locator("#dictRows tr").first.wait_for(timeout=30000)
                audit_all_code_rows(page, entries[:3], expected)
                assert not errors, errors
                assert not failed, failed
                page.close()
            finally:
                browser.close()


def main(root=ROOT, *, run_demos=True, offline=False, base_path=''):
    data_root = root / base_path
    server = ThreadingHTTPServer(("127.0.0.1", 0), partial(SimpleHTTPRequestHandler, directory=str(root)))
    thread = Thread(target=server.serve_forever, daemon=True)
    thread.start()
    url = f"http://127.0.0.1:{server.server_port}/" + (base_path.rstrip("/") + "/" if base_path else "")
    paged = 'data/command-index.json' in (data_root/'index.html').read_text(encoding='utf-8')
    if paged and not (data_root/'data/command-index.json').exists():
        write_command_shards(data_root)
    entries = json.loads((data_root / 'data/dictionary.json').read_text(encoding='utf-8'))['entries']
    translations = {r["id"]: r for r in json.loads((data_root / "data/translation-geodesy.json").read_text(encoding="utf-8"))["records"]}
    identities = {e["gg_id"]: e for e in entries}
    def source_records(entry, seen=None):
        if seen is None:
            seen = set()
        if entry["gg_id"] in seen:
            return []
        seen.add(entry["gg_id"])
        t = translations.get(entry.get("translation_ref"), {})
        source = t.get("source") or entry.get("source")
        if source:
            return [source]
        return [s for identity in entry.get("components", []) for s in source_records(identities[identity], seen)]
    def expected_links(entry):
        sources = source_records(entry)
        return [
            ["https://github.com/"+s["repo"]+"/blob/"+s["commit"]+"/"+quote(s["path"], safe="/")+"#L"+str(s["first"])+"-L"+str(s["last"]) for s in sources],
            ["https://raw.githubusercontent.com/"+s["repo"]+"/"+s["commit"]+"/"+quote(s["path"], safe="/") for s in sources],
            ["https://ventusltd.github.io/stars/code.html" for s in sources],
            ["https://ventusltd.github.io/kuiper-belt/see-through/202611020012/#repo="+quote(s["repo"].split("/")[1], safe="") for s in sources]
        ]
    catalogue_path = data_root / "data/prose-catalogue.json"
    catalogue = (json.loads(catalogue_path.read_bytes())
                 if base_path in (FIRST_PROSE_ROUTE, TELEPRINTER_PROSE_ROUTE) else None)
    expected_count = min(100, len(entries))
    expected_pages = max(1, math.ceil(len(entries) / 100))
    passed = 0
    try:
        with sync_playwright() as p:
            for engine in (p.chromium, p.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 err: errors.append(str(err)))
                        if offline:
                            page.route("**/*", lambda route: route.continue_()
                                       if route.request.url.startswith(url) else route.abort())
                        requests = []
                        page.on("request", lambda request: requests.append(request.url))
                        page.goto(url)
                        def wait_dictionary():
                            if paged:
                                page.locator("#dictRows[aria-busy=false]").wait_for(state="attached")
                        page.locator("#anatomy > summary").click()
                        page.get_by_text("9 recorded cartridges", exact=False).wait_for()
                        page.get_by_role("button", name="Find nearby grid infrastructure").click()
                        page.get_by_text("03 / VEDIC functional language", exact=True).wait_for()
                        page.get_by_text("04 / Source dependency diagram", exact=True).wait_for()
                        assert page.locator("#detail").get_by_text("Measure distance between two geographic points", exact=True).count() == 1
                        assert page.get_by_text("not loaded by the live Atlas", exact=False).count() == 1
                        assert page.get_by_role("link", name="Static dependency graph JSON").count() == 1
                        page.locator("#search").fill("vicinity")
                        assert page.get_by_role("button", name="Explore Vicinity").count() == 1
                        assert page.get_by_role("button", name="Find nearby grid infrastructure").count() == 0
                        page.get_by_role("button", name="Explore Vicinity").click()
                        assert page.get_by_text("03 / VEDIC functional language", exact=True).count() == 0
                        page.get_by_role("button", name="Pipeline News", exact=True).click()
                        assert page.get_by_text("Not mapped yet.", exact=False).count() == 1
                        assert page.evaluate("document.documentElement.scrollWidth <= innerWidth + 1"), "horizontal overflow"
                        page.get_by_role("button", name="GridAtlas", exact=True).click()
                        assert page.get_by_role("button", name="Find a place", exact=True).count() == 1
                        page.locator("#dictRows tr").first.wait_for()
                        wait_dictionary()
                        if paged:
                            assert any("/data/command-index.json" in x for x in requests)
                            assert not any("/data/dictionary.json" in x or "/data/prose-catalogue.json" in x for x in requests)
                            assert not any("/data/command-pages/" in x for x in requests)
                        assert page.locator("#dictRows tr").count() == expected_count
                        assert page.locator("#dictPage").inner_text() == f"Page 1 / {expected_pages}"
                        ordering = page.locator("#dictSort").input_value()
                        if ordering != "word":
                            assert page.locator("#dictRows tr").first.locator("td").first.inner_text() == min(entries, key=lambda e: (e.get("priority", 9), e["number"]))["word"]
                        else:
                            first_label = page.evaluate("words => words.sort((a, b) => a.localeCompare(b))[0]", [entry["word"] for entry in entries])
                            assert page.locator("#dictRows tr td").first.inner_text() == first_label
                        page.locator("#dictSort").select_option("number")
                        wait_dictionary()
                        assert page.locator("#dictRows tr").first.locator("td").first.inner_text() == "MEASURE"
                        page.locator("#dictSearch").fill("ORIENT")
                        wait_dictionary()
                        assert page.locator("#dictRows tr").count() == 1
                        if paged:
                            code_link = page.locator("#dictRows .code-cell a.code-source").first
                            code_link.wait_for()
                            code_link.focus()
                            assert code_link.evaluate("(element) => element === document.activeElement")
                            assert not any("/data/command-pages/" in x for x in requests)
                        assert page.locator("#dictRows .code-cell a.code-source").count() == 2
                        assert "2026-11-26T01:35:15Z" in page.locator("#dictRows").inner_text()
                        page.get_by_role("button",name="CLEAR FILTERS").click()
                        wait_dictionary()
                        assert page.locator("#dictRows tr").count() == expected_count
                        page.locator("#dictSort").select_option("priority")
                        wait_dictionary()
                        assert page.locator("#dictRows tr").first.locator("td").first.inner_text() == "LINK"
                        assert page.locator("#dictRows tr td:nth-child(2) a").count() == expected_count
                        assert page.locator("#dictRows a[href^='./demo.html']").count() == 0
                        if not paged:
                            assert page.locator("#dictRows tr").first.get_by_text("How to see it:", exact=False).count() == 1
                        # SatNav intentionally launches the working field application, not the source file.
                        # Keep independent exact-source checks below for every row.
                        expected = {
                            e["gg_id"]: (
                                "https://ventusltd.github.io/gridatlas/atlas/v/satnav-road-to-field-202611281800/"
                                if paged and e["estate_group"] == "SatNav" else e["application"]["url"]
                            )
                            for e in entries
                        }
                        for i in range(expected_pages):
                            rows = page.locator("#dictRows tr").evaluate_all("""(rs) => rs.map(r => [r.cells[6].textContent, r.cells[1].querySelector('a').getAttribute('href'), ['a.code-source','a[href^="https://raw.githubusercontent.com/"]','a[href^="https://ventusltd.github.io/stars/code.html"]','a[href^="https://ventusltd.github.io/kuiper-belt/"]'].map(sel => Array.from(r.cells[2].querySelector  … [line shortened here: 443 characters; full line on GitHub]
                            assert len(rows) == min(100, len(entries) - 100*i)
                            for identity, href, links in rows:
                                assert expected.pop(identity) == href
                                assert links == expected_links(identities[identity]), (identity, links)
                            if i+1 < expected_pages:
                                page.locator("#dictNext").click()
                                wait_dictionary()
                        assert not expected
                        page.locator("#dictSearch").fill("AREA")
                        wait_dictionary()
                        assert page.locator("#dictRows tr").count() >= 2
                        page.get_by_role("button",name="CLEAR FILTERS").click()
                        wait_dictionary()
                        links = [url + "demo.html?id=GG2050-VEDIC-" + str(i).zfill(6) for i in range(1,7)] if run_demos else []
                        for demo_url in links:
                            demo = browser.new_page(viewport={"width":width,"height":height})
                            demo.goto(demo_url)
                            demo.get_by_role("button",name="RUN DEMONSTRATION").wait_for()
                            demo.get_by_role("button",name="RUN DEMONSTRATION").click(timeout=10000)
                            result = demo.locator("#result").inner_text()
                            assert result not in ("Ready","Loading…") and not result.startswith(("Cannot run","Demonstration unavailable")), result
                            actual = json.loads(result)
                            identity = parse_qs(urlparse(demo_url).query)["id"][0]
                            # Independent known-answer checks for the seeded examples.
                            expected = {
                                "GG2050-VEDIC-000001": 111.31949079327357,
                                "GG2050-VEDIC-000002": [1, 0.5],
                                "GG2050-VEDIC-000003": [132, 33, 0.75],
                                "GG2050-VEDIC-000004": [0.8983152841195214, 0],
                                "GG2050-VEDIC-000005": 90,
                                "GG2050-VEDIC-000006": {"distance_km":111.31949079327357,"initial_bearing_deg":90}
                            }[identity]
                            def close(a, b):
                                if isinstance(b, dict):
                                    return isinstance(a, dict) and a.keys() == b.keys() and all(close(a[k], b[k]) for k in b)
                                if isinstance(b, list):
                                    return isinstance(a, list) and len(a) == len(b) and all(close(x,y) for x,y in zip(a,b))
                                return isinstance(a,(int,float)) and math.isclose(a,b,rel_tol=1e-9,abs_tol=1e-9)
                            assert close(actual, expected), (identity,actual,expected)
                            demo.locator("#args").fill("not JSON")
                            demo.get_by_role("button",name="RUN DEMONSTRATION").click()
                            assert demo.locator("#result").inner_text().startswith("Cannot run:")
                            demo.close()
                        if catalogue:
                            exercise_published(page, catalogue)
                            exercise_local(page, url)
                        if not catalogue:
                            if paged:
                                page.locator("#patternFilter").select_option("Measure and calculate")
                                wait_dictionary()
                                assert page.locator("#dictRows tr").count()>0
                                assert "MEASURE" in page.locator("#dictRows").inner_text()
                                page.get_by_role("button",name="CLEAR FILTERS").click()
                                wait_dictionary()
                            assert not page.locator("#prose-library, #proseSearch, #proseImport").count()
                            assert "CONTINUOUS ENGLISH LIBRARY" not in page.locator("body").inner_text()
                            assert all("prose-catalogue.json" not in url for url in requests)
                            last = entries[-1]
                            page.locator("#dictSearch").fill(last["gg_id"])
                            wait_dictionary()
                            assert page.locator("#dictRows tr").count() == 1
                            assert page.locator("#dictRows tr td").first.text_content() == last["word"]
                            if paged:
                                before = [request for request in requests if "/data/command-pages/" in request]
                                row = page.locator("#dictRows tr").first
                                row.locator(".code-cell a.code-source").first.wait_for()
                                assert row.locator(".code-cell button").count() == 0
                                row.locator("td:nth-child(4) summary").click()
                                row.get_by_text("How to see it:", exact=False).wait_for()
                                assert row.locator("a.code-source").evaluate_all("(links) => links.map(link => link.href)") == expected_links(last)[0]
                                after = [request for request in requests if "/data/command-pages/" in request]
                                assert len(after) >= len(before)
                                if expected_pages > 1:
                                    index = json.loads((data_root/"data/command-index.json").read_bytes())
                                    second = next(entry for entry in index["entries"] if entry["page"].endswith("000002.json"))
                                    page.locator("#dictSearch").fill(second["gg_id"])
                                    wait_dictionary()
                                    assert page.locator("#dictRows tr").count() == 1
                                    page.locator("#dictRows .code-cell a.code-source").first.wait_for()
                                    page.locator("#dictRows td:nth-child(4) summary").click()
                                    page.locator("#dictRows").get_by_text("How to see it:", exact=False).wait_for()
                                    assert any("/"+second["page"] in request for request in requests)
                            assert not page.locator("#dictRows img").count()
                            assert all("fixture-should-never-request" not in url for url in requests)
                        if paged and not catalogue:
                            page.locator("#dictClear").click()
                            audit_all_code_rows(page, entries, expected_links)
                        assert not errors, errors
                        page.close()
                        passed += 1
                        print(f"PASS {engine.name} {width}x{height}", flush=True)
                finally:
                    browser.close()
    finally:
        server.shutdown()
        server.server_close()
    assert passed == 6
    print("6/6 browser/viewport cases passed; no live handset claim")

if __name__ == "__main__":
    main()
    audit_live()

VEDIC Canonical Acorn

A JavaScript module in the tools folder that parses unit (`parseUnit`). It parses unit (`parseUnit`) and is built from the groups step (`groups`) and the declared names helper (`declaredNames`).

ingestvedic- / tools/canonical_acorn.mjs · lines 1–112 of 112 · Not reached from any entry point (candidate for review)

What it does
It loads data. Defines groups, declaredNames, parseUnit, line, spelling. Uses libraries node:module, node:fs, node:path. 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: command-line arguments.
What it achieves
Static Acorn enrichment for pinned canonical files.
Why it matters
No other file in the estate was found to import it.
Application
vedic- · tools · JavaScript module
Uses
node:module, node:fs, node:path
Used by
none found
Produces
groups, declaredNames, parseUnit, line, spelling
Defines here
groups, declaredNames, parseUnit, line, spelling
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/canonical_acorn.mjs:1-112 · blob f49904b2e7f9bee4f27ba0ecaea03064b74392cc · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
/** Static Acorn enrichment for pinned canonical files. Input source is never evaluated. */
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';

const requires = createRequire(resolve(process.argv[2], 'package.json'));
const acorn = requires('acorn');
const walk = requires('acorn-walk');
const files = JSON.parse(readFileSync(0, 'utf8'));

function groups(file) {
  if (!file.path.endsWith('.html')) return [{ code: file.text, line: 0 }];
  const units = [];
  for (const block of file.text.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script\s*>/gi)) {
    if (/\bsrc\s*=/i.test(block[1])) continue;
    const mime = block[1].match(/\btype\s*=\s*["']?([^"'\s>]+)/i)?.[1];
    if (mime && !/^(module|text\/javascript|application\/javascript)$/i.test(mime)) continue;
    const start = block.index + block[0].indexOf('>') + 1;
    units.push({ code: block[2], line: file.text.slice(0, start).split('\n').length - 1 });
  }
  return units;
}

function declaredNames(node) {
  if (node?.id?.name) return [node.id.name];
  if (node?.type !== 'VariableDeclaration') return [];
  return node.declarations.map(item => item.id.name).filter(Boolean);
}

function parseUnit(unit, result) {
  let tree;
  const comments = [];
  for (const sourceType of ['module', 'script']) {
    try {
      comments.length = 0;
      tree = acorn.parse(unit.code, {
        ecmaVersion: 'latest', sourceType, locations: true, onComment: comments,
        allowHashBang: true, allowReturnOutsideFunction: true, allowAwaitOutsideFunction: true,
      });
      break;
    } catch (error) {
      if (sourceType === 'script') result.issues.push({ line: unit.line + 1, type: error.name });
    }
  }
  if (!tree) return;

  const exported = new Set();
  const line = node => node.loc.start.line + unit.line;
  const spelling = node => unit.code.slice(node.start, node.end);
  for (const statement of tree.body) {
    const isExport = statement.type === 'ExportNamedDeclaration' || statement.type === 'ExportDefaultDeclaration';
    if (isExport) {
      declaredNames(statement.declaration).forEach(name => exported.add(name));
      for (const item of statement.specifiers ?? []) {
        if (item.local?.name) exported.add(item.local.name);
        result.exports.push(item.exported?.name ?? item.exported?.value);
      }
      if (statement.type === 'ExportDefaultDeclaration') result.exports.push('default');
      else result.exports.push(...declaredNames(statement.declaration));
    }
    if (statement.source?.value && /^(Import|Export)/.test(statement.type)) {
      result.imports.push({ module: statement.source.value, line: line(statement) });
    }
    const declaration = isExport ? statement.declaration : statement;
    if (declaration?.type === 'VariableDeclaration' && declaration.kind === 'const') {
      for (const item of declaration.declarations) {
        if (item.id.type !== 'Identifier') continue;
        result.constants.push({ name: item.id.name, line: line(item), exported: isExport,
          initializer_kind: item.init?.type ?? null,
          literal_json: item.init?.type === 'Literal' && !item.init.regex && !item.init.bigint
            ? JSON.stringify(item.init.value) : null });
      }
    }
  }

  walk.fullAncestor(tree, (node, _state, ancestors) => {
    const parent = ancestors.at(-2);
    if (node.type === 'ThrowStatement') {
      const context = ancestors.slice(0, -1).reverse().find(item => item.type === 'IfStatement');
      result.refusals.push({ line: line(node),
        condition_hint: context ? spelling(context.test).slice(0, 240) : null,
        directly_guarded: context?.consequent === node || context?.consequent?.body?.length === 1 &&
          context.consequent.body[0] === node,
        error_kind: node.argument?.callee?.name ?? null });
    }
    if (!['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression', 'ClassDeclaration', 'ClassExpression'].includes(node.type)) return;
    const functionName = node.id?.name ?? parent?.id?.name ?? parent?.key?.name ?? null;
    const scope = parent?.type.startsWith('Export') || parent?.type === 'Program'
      ? 'top_level' : (parent?.type === 'VariableDeclarator' && ancestors.at(-4)?.type === 'Program')
        ? 'top_level' : 'nested_or_member';
    const anchor = parent?.type.startsWith('Export') ? parent.start : node.start;
    const closest = comments.findLast(c => c.end <= anchor && !unit.code.slice(c.end, anchor).trim());
    result.symbols.push({
      name: functionName, kind: node.type, first_line: line(node),
      last_line: node.loc.end.line + unit.line, scope,
      exported_binding: scope === 'top_level' && (exported.has(functionName) || parent?.type.startsWith('Export')),
      parameters: (node.params ?? []).map(param => spelling(param)),
      doc_comment: closest?.type === 'Block' ? closest.value.trim().slice(0, 900) : null,
      async: node.async ?? false,
    });
  });
}

const output = [];
for (const file of files) {
  const record = { repository: file.repository, path: file.path, commit: file.commit, blob: file.blob,
    symbols: [], imports: [], constants: [], refusals: [], exports: [], issues: [] };
  for (const unit of groups(file)) parseUnit(unit, record);
  record.exports = [...new Set(record.exports.filter(Boolean))].sort();
  output.push(record);
}
process.stdout.write(JSON.stringify({ acorn_version: acorn.version, files: output }));

VEDIC Canonical Intelligence

A Python command-line tool in the tools folder that reads canonical bindings, canonical metadata, canonical symbols and canonical acorn. It is built from the build step (`build`).

storagevedic- / tools/canonical_intelligence.py · lines 1–81 of 81 · Entry point

What it does
It loads canonical bindings, canonical metadata, canonical symbols and canonical acorn. Defines build, main. Uses libraries argparse, collections, json, pathlib, subprocess. 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: Parquet file canonical-bindings.parquet; Parquet file canonical-file-metadata.parquet; Parquet file canonical-symbols.parquet; JSON file canonical-acorn-manifest.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Produce private Acorn metadata for canonical bound modules, reusing local Acorn. It reads `canonical-bindings.parquet` and writes `canonical-acorn-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, collections, json, pathlib, subprocess, time, 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/canonical_intelligence.py:1-81 · blob cc80ef17645c0e0ffcaace61e9f4b9217f9ae631 · 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
"""Produce private Acorn metadata for canonical bound modules, reusing local Acorn."""

import argparse
from collections import Counter
import json
from pathlib import Path
import subprocess
from time import perf_counter

import pyarrow.parquet as pq

from canonical_sources import blob, output_table
from modular_features import atomic_write


def build(t1, engine, grid, acorn_root):
    start = perf_counter()
    bindings = pq.read_table(t1/"canonical-bindings.parquet").to_pylist()
    provenance = {}
    indexed_slots = {}
    for row in bindings:
        source_key = tuple(row[key] for key in ("repository", "commit", "path", "blob"))
        if row["path"].endswith((".js", ".mjs", ".html")):
            provenance[source_key] = source_key
            indexed_slots.setdefault(source_key + (row["first_line"], row["last_line"]), []).append(row)
    sources = []
    for repository, commit, path, expected in sorted(provenance):
        repo = engine if repository == "Ventusltd/ventus-grid-engine" else grid
        oid, raw = blob(repo, commit, path)
        if oid != expected:
            raise ValueError(f"Canonical source pin mismatch: {path}")
        sources.append({"repository": repository, "commit": commit, "path": path,
                        "blob": oid, "text": raw.decode("utf-8")})
    runner = Path(__file__).with_name("canonical_acorn.mjs")
    received = subprocess.check_output(["node", str(runner), str(acorn_root)],
                                       input=json.dumps(sources).encode("utf-8"))
    report = json.loads(received)
    metadata, symbols = [], []
    for row in report["files"]:
        identity = {key: row[key] for key in ("repository", "commit", "path", "blob")}
        source_key = tuple(identity.values())
        metadata.append({**identity, **{key + "_json": json.dumps(row[key], ensure_ascii=False)
                                          for key in ("imports", "constants", "refusals", "exports", "issues")}})
        for symbol in row["symbols"]:
            anchors = indexed_slots.get(source_key + (symbol["first_line"], symbol["last_line"]), [])
            # Use the name if possible. With ambiguous/anonymous spans retain all
            # possible anchors explicitly, rather than assigning an identity.
            named = [candidate for candidate in anchors if candidate["symbol"] == symbol["name"]]
            exact = named or anchors
            identifiers = sorted({candidate["element_id"] for candidate in exact})
            families = sorted({candidate["family_id"] for candidate in exact})
            symbols.append({**identity, **symbol, "matched_element_ids": identifiers,
                            "matched_family_ids": families,
                            "match_status": "unambiguous_name_and_lines" if len(named)==1
                            else "line_range_candidates" if exact else "outside_indexed_spans"})
    tables = [output_table(t1/"canonical-file-metadata.parquet", metadata),
              output_table(t1/"canonical-symbols.parquet", symbols)]
    summary = {"acorn_version": report["acorn_version"], "files": len(metadata), "symbols": len(symbols),
               "matches": dict(Counter(row["match_status"] for row in symbols)),
               "static_imports": sum(len(row["imports"]) for row in report["files"]),
               "export_bindings": sum(len(row["exports"]) for row in report["files"]),
               "top_level_constants": sum(len(row["constants"]) for row in report["files"]),
               "refusal_markers": sum(len(row["refusals"]) for row in report["files"]),
               "parse_issues": sum(len(row["issues"]) for row in report["files"]),
               "elapsed_seconds": perf_counter() - start, "tables": tables,
               "notes": "Static imports are source syntax; browser global bindings and dynamic dependencies are not fully resolved. Refusal markers are source cues."}
    atomic_write(t1/"canonical-acorn-manifest.json",
                 lambda p: p.write_text(json.dumps(summary, indent=2)+"\n", encoding="utf-8"))
    return summary


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


if __name__ == "__main__":
    main()