In this section
- Test Extract test · vedic- / fingerprints/test_extract.py lines 1–272
- Test Modular Join test · vedic- / fingerprints/test_modular_join.py lines 1–133
- VEDIC — Index Page render · vedic- / index.html lines 1–172
- VEDIC Allocate Commands storage · vedic- / tools/allocate_commands.py lines 1–116
Test Extract
A test in the fingerprints folder of VEDIC that checks Extract, using haversine.
testvedic- / fingerprints/test_extract.py · lines 1–272 of 272 · Entry point · pattern by_name (shared by 4 files)
- What it does
- It tests cables. Defines 28 functions or classes, including haversine_km, Cable, __init__, save, Meter. Uses libraries os, sys, textwrap, unittest, collections. Side effects: changes the web page (DOM); reads or writes files; makes network requests.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). Domain terms in the code: cables, 11kV. README: "Better evidence from extraction: add `unit_terms` or side-effect patterns in `extract.py` together with a test in `test_extract.py`"
- Inputs & outputs
- In: JSON file r.json. Voltage levels named: 11kV.
- Downstream impact
- Used directly by 1 file: VEDIC Fingerprints Workflow (vedic-).
- What it achieves
- It sets up (`setUp`) and is built from the haversine km helper (`haversine_km`) and the cable class (`Cable`). Unit tests for `fingerprints/extract.py`. No network, no clones. Its code works with 11 kV.
- Why it matters
- Run by VEDIC Fingerprints Workflow.
- Application
- vedic- · fingerprints · test
- Uses
- Extract (import), os, sys, textwrap, unittest, collections
- Used by
- run by VEDIC Fingerprints Workflow (workflow run)
- Produces
- by_name, PythonUnits, JavaScriptUnits, MinHash, Terms
- Defines here
- haversine_km, Cable, __init__, save, Meter, by_name, PythonUnits, setUp, test_detection_and_ranges, test_terms_effects_calls, test_renamed_copy, test_whitespace_comment_only, test_fstring_is_one_str, JavaScriptUnits, setUp, test_detection_and_ranges, test_templates_and_regex_do_not_break_braces, test_renamed_copy_and_whitespace, test_html_script_offsets, test_tokenizer_failure_skips_file, test_process_files_counts_failures, MinHash, test_deterministic_and_known, test_near_copy_high_unrelated_low, test_finish_rows, Terms, test_terms, test_single_letters_need_context
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 fingerprints/test_extract.py:1-272 · blob 4c77fea081e6d837a03bfcc0b84c6c02975eb7cf · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Unit tests for fingerprints/extract.py. No network, no clones.
Run from the repo root: python -m unittest discover -s fingerprints -p 'test_*.py'
"""
import os
import sys
import textwrap
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import extract as X # noqa: E402
PY = textwrap.dedent('''\
import os
def haversine_km(lat1, lon1, lat2, lon2):
"""Great-circle distance in km."""
r = 6371.0
d = (lat2 - lat1) ** 2 + (lon2 - lon1) ** 2
return r * d ** 0.5
# a cable
class Cable:
def __init__(self, voltage_kv, length_m):
self.voltage_kv = voltage_kv
self.length_m = length_m
async def save(self, path):
with open(path, "w") as fh:
fh.write(f"{self.voltage_kv} kV {self.length_m}")
print("saved", path)
''')
JS = textwrap.dedent('''\
// Add two numbers
function add(a, b) {
const s = a + b;
return s;
}
class Meter {
constructor(kw) {
this.kw = kw;
this.x = 1;
}
static async read(url, opts) {
const r = await fetch(url, opts);
return r.json();
}
}
const scale = (x, k) => {
const y = x * k;
return y;
};
const tidy = s =>
s.trim().toLowerCase()
.replace(/\\s+/g, " ");
''')
LONG_JS = textwrap.dedent('''\
function cableLoss(currentA, resistanceOhm, lengthKm, cores, temp) {
let total = 0;
for (let i = 0; i < cores; i++) {
const r = resistanceOhm * lengthKm * (1 + 0.004 * (temp - 20));
const loss = currentA * currentA * r;
total += loss;
if (total > 1000) {
total = total / 2;
}
}
const out = { total: total, perCore: total / cores, lengthKm: lengthKm };
if (out.perCore < 0) {
return null;
}
return out;
}
''')
def by_name(rows):
return {(r['kind'], r['name']): r for r in rows}
class PythonUnits(unittest.TestCase):
def setUp(self):
self.rows = by_name(X.py_rows(PY))
def test_detection_and_ranges(self):
f = self.rows[('function', 'haversine_km')]
self.assertEqual((f['line_from'], f['line_to']), (4, 8))
self.assertEqual(f['params'], ['lat1', 'lon1', 'lat2', 'lon2'])
self.assertEqual(f['doc'], 'Great-circle distance in km.')
c = self.rows[('class', 'Cable')]
self.assertEqual((c['line_from'], c['line_to']), (12, 20))
self.assertEqual(c['doc'], 'a cable')
m = self.rows[('method', 'save')]
self.assertEqual((m['line_from'], m['line_to']), (17, 20))
self.assertIn(('method', '__init__'), self.rows)
def test_terms_effects_calls(self):
f = self.rows[('function', 'haversine_km')]
for t in ('lat', 'lon', 'km', 'haversine'):
self.assertIn(t, f['unit_terms'])
self.assertEqual(f['side_effects'], [])
m = self.rows[('method', 'save')]
self.assertEqual(m['side_effects'], ['console', 'filesystem'])
self.assertIn('kv', m['unit_terms'])
self.assertIn('fh.write', m['calls'])
self.assertIn('open', m['calls'])
def test_renamed_copy(self):
a = X.py_rows('def f(x, y):\n t = x * y + 1\n return t - x\n')[0]
b = X.py_rows('def g(p, q):\n z = p * q + 1\n return z - p\n')[0]
self.assertEqual(a['struct'], b['struct'])
self.assertNotEqual(a['exact_hash'], b['exact_hash'])
def test_whitespace_comment_only(self):
a = X.py_rows('def f(x, y):\n t = x*y + 1\n return t - x\n')[0]
b = X.py_rows('def f(x, y): # hi\n # note\n t = x * y+1\n\n return t - x\n')[0]
self.assertEqual(a['exact_hash'], b['exact_hash'])
def test_fstring_is_one_str(self):
r = X.py_rows('def f(a):\n s = f"{a:>{3}} x {a!r}"\n return s + "k"\n')[0]
self.assertEqual(r['struct'].count('STR'), 2)
class JavaScriptUnits(unittest.TestCase):
def setUp(self):
self.rows = by_name(X.js_rows(JS))
def test_detection_and_ranges(self):
f = self.rows[('function', 'add')]
self.assertEqual((f['line_from'], f['line_to'], f['params']), (2, 5, ['a', 'b']))
self.assertEqual(f['doc'], 'Add two numbers')
c = self.rows[('class', 'Meter')]
self.assertEqual((c['line_from'], c['line_to']), (7, 16))
m = self.rows[('method', 'read')]
self.assertEqual((m['line_from'], m['line_to'], m['params']), (12, 15, ['url', 'opts']))
self.assertEqual(m['side_effects'], ['network'])
self.assertIn('fetch', m['calls'])
self.assertIn('r.json', m['calls'])
k = self.rows[('method', 'constructor')]
self.assertEqual((k['line_from'], k['line_to']), (8, 11))
a = self.rows[('arrow', 'scale')]
self.assertEqual((a['line_from'], a['line_to'], a['params']), (18, 21, ['x', 'k']))
e = self.rows[('arrow', 'tidy')]
self.assertEqual((e['line_from'], e['line_to'], e['params']), (23, 25, ['s']))
self.assertIn('kw', c['unit_terms'])
def test_templates_and_regex_do_not_break_braces(self):
src = textwrap.dedent('''\
function tricky(a) {
const t = `x ${a + "}"} y ${ {k: `}${1}`}.k } }`;
const r = /[}{]+\\/}/g;
const d = a / 2 / 3;
return t.replace(r, "{") + d;
}
function after(b) {
return b + 1 + 2 + 3 + 4;
}
''')
rows = by_name(X.js_rows(src))
self.assertEqual((rows[('function', 'tricky')]['line_from'], rows[('function', 'tricky')]['line_to']), (1, 6))
self.assertEqual((rows[('function', 'after')]['line_from'], rows[('function', 'after')]['line_to']), (7, 9))
def test_renamed_copy_and_whitespace(self):
a = X.js_rows('function f(x, y) {\n const t = x * y + 1;\n return t - x;\n}\n')[0]
b = X.js_rows('function g(p, q) {\n const z = p * q + 1;\n return z - p;\n}\n')[0]
c = X.js_rows('function f(x,y){ /* c */\n const t = x*y+1; // n\n\n return t-x;\n}\n')[0]
self.assertEqual(a['struct'], b['struct'])
self.assertNotEqual(a['exact_hash'], b['exact_hash'])
self.assertEqual(a['exact_hash'], c['exact_hash'])
def test_html_script_offsets(self):
html = textwrap.dedent('''\
<!doctype html>
<html><head>
<script type="application/ld+json">{"a": 1}</script>
<script src="x.js"></script>
</head><body>
<script>
function boot(el) {
document.getElementById(el).innerHTML = "hi";
return Date.now();
}
</script></body></html>
''')
rows, n = X.html_rows(html)
self.assertEqual(n, 1)
r = by_name(rows)[('function', 'boot')]
self.assertEqual((r['line_from'], r['line_to']), (7, 10))
self.assertEqual(r['side_effects'], ['dom', 'time'])
def test_tokenizer_failure_skips_file(self):
for bad in ('function f() {\n const s = "unterminated;\n}\n', 'function f() { /* never closed\n',
'const t = `open ${ x\n'):
with self.assertRaises(X.TokenizeFailure):
X.js_rows(bad)
rows, kind = None, None
try:
rows, kind = X.file_rows('a.js', bad)
except X.TokenizeFailure:
pass # main() counts this and moves on
self.assertIsNone(rows)
def test_process_files_counts_failures(self):
import collections
skipped = collections.Counter()
files = [{'repo': 'r', 'commit': '0' * 40, 'blob': '1' * 40, 'path': p, 'lines': t.split('\n')}
for p, t in (('bad.js', 'x = "oops\nfunction g() {'), ('bad.py', 'def f(:\n pass'),
('good.js', JS), ('good.py', PY))]
rows, kinds, n_lines = X.process_files(files, skipped)
self.assertEqual(skipped['javascript tokenizer failure'], 1)
self.assertEqual(skipped['python syntax or tokenize error'], 1)
self.assertEqual(sorted({r['path'] for r in rows}), ['good.js', 'good.py'])
class MinHash(unittest.TestCase):
def test_deterministic_and_known(self):
s = ['function', 'ID', '(', 'ID', ')', '{', 'return', 'ID', ';', '}']
a, b = X.minhash(s), X.minhash(list(s))
self.assertEqual(len(a), 64)
self.assertEqual(a.dtype.name, 'uint32')
self.assertEqual(a.tolist(), b.tolist())
self.assertEqual(X.minhash(['a', 'b']).tolist(), X.minhash(['a', 'b']).tolist())
def test_near_copy_high_unrelated_low(self):
base = X.js_rows(LONG_JS)[0]
near_src = LONG_JS.replace(' total = total / 2;\n', ' total = total / 2;\n console.log(total);\n')
near = X.js_rows(near_src)[0]
other = by_name(X.py_rows(PY))[('class', 'Cable')]
ja = X.jaccard(X.minhash(base['struct']), X.minhash(near['struct']))
jb = X.jaccard(X.minhash(base['struct']), X.minhash(other['struct']))
self.assertGreaterEqual(ja, 0.7)
self.assertLess(jb, 0.3)
def test_finish_rows(self):
f = {'repo': 'r', 'commit': '0' * 40, 'path': 'a.js', 'blob': '1' * 40}
rows = X.finish_rows(X.js_rows(JS), f)
self.assertTrue(rows)
for r in rows:
self.assertEqual(len(r['unit_id']), 16)
self.assertEqual(r['pure'], not r['side_effects'])
self.assertGreaterEqual(r['n_lines'], 3)
self.assertGreaterEqual(r['n_tokens'], 12)
t = X.to_table(rows)
self.assertEqual(t.schema, X.ARROW_SCHEMA)
class Terms(unittest.TestCase):
def test_terms(self):
self.assertEqual(X.unit_terms(['cableLengthM', 'totalKWh', 'a', 'm'], ['11 kV feeder', 'name']),
['cable', 'feeder', 'kv', 'kwh', 'm'])
def test_single_letters_need_context(self):
# Non-first pieces without a number or unit context no longer count (v2 gap a).
self.assertEqual(X.unit_terms(['dataA', 'itemM', 'getV', 'rowS'], []), [])
self.assertEqual(X.unit_terms(['voltageV'], []), ['v', 'voltage'])
self.assertEqual(X.unit_terms(['span50M'], []), ['m'])
# Whole parameter names count only when the unit already carries a domain term.
self.assertEqual(X.unit_terms(['add', 'a', 'b'], [], params=['a', 'b']), [])
self.assertEqual(X.unit_terms(['dropKv', 'v'], [], params=['v']), ['kv', 'v'])
# Strings keep the number rule.
self.assertEqual(X.unit_terms([], ['a b m', '5 m']), ['m'])
if __name__ == '__main__':
unittest.main()Test Modular Join
A test in the fingerprints folder of VEDIC that checks Modular Join and Testcode — Wafer Development Environment Page. It makes db (`make_db`) and sets up (`setUp`).
testvedic- / fingerprints/test_modular_join.py · lines 1–133 of 133 · Entry point · pattern tearDown (shared by 38 files)
- What it does
- It tests its inputs. Defines 11 functions or classes, including pack, make_db, ModularJoinTests, setUp, tearDown. Uses libraries os, sqlite3, sys, tempfile, unittest. Side effects: uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: Parquet file units.parquet; Parquet file candidates.parquet; Parquet file units-modular.parquet; SQLite database.
- Downstream impact
- Used directly by 1 file: VEDIC Fingerprints Workflow (vedic-).
- What it achieves
- Units meet Modular Star's permanent numbers exactly, never by guess.
- Why it matters
- Run by VEDIC Fingerprints Workflow.
- Application
- vedic- · fingerprints · test
- Uses
- Modular Join (import), Testcode — Wafer Development Environment Page (estate URL), os, sqlite3, sys, tempfile, unittest, pyarrow, pyarrow.parquet
- Used by
- run by VEDIC Fingerprints Workflow (workflow run)
- Produces
- pack, make_db, ModularJoinTests
- Defines here
- pack, make_db, ModularJoinTests, setUp, tearDown, test_join, test_line_keys, test_at_most_five_lines, test_rerun_is_idempotent, test_low_overlap_is_not_a_match, test_without_database_nothing_is_joined
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 fingerprints/test_modular_join.py:1-133 · blob 7ad9766bf4e0f15da9df894252f0002b9e3fbb16 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""modular_join.py: units meet Modular Star's permanent numbers exactly, never by guess."""
import os
import sqlite3
import sys
import tempfile
import unittest
import pyarrow as pa
import pyarrow.parquet as pq
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import modular_join as mj # noqa: E402
def pack(nums):
"""Byte-for-byte what lib.mjs `pack` writes: Buffer.alloc(n * 4), writeUInt32LE(n, i * 4)."""
b = bytearray(len(nums) * 4)
for i, n in enumerate(nums):
b[i * 4:i * 4 + 4] = n.to_bytes(4, 'little')
return bytes(b)
B1_LINES = [1000 + i for i in range(50)] # 50 physical lines
B2_LINES = [70000 + 3 * i for i in range(120)] # 120 physical lines, not contiguous
B2_LINES[99] = 2**32 - 2 # a large permanent number survives unsigned
def make_db(path):
con = sqlite3.connect(path)
con.executescript('''
CREATE TABLE tablet(n INTEGER PRIMARY KEY AUTOINCREMENT, git_blob TEXT UNIQUE NOT NULL, lang TEXT, lines BLOB NOT NULL, issue TEXT);
CREATE TABLE family(n INTEGER PRIMARY KEY AUTOINCREMENT, sha BLOB UNIQUE NOT NULL, lang TEXT NOT NULL);
CREATE TABLE element(n INTEGER PRIMARY KEY AUTOINCREMENT, sha BLOB UNIQUE NOT NULL, family INTEGER NOT NULL, kind TEXT, needs TEXT, standalone INTEGER);
CREATE TABLE tablet_element(tablet INTEGER NOT NULL, element INTEGER NOT NULL, first INTEGER NOT NULL, last INTEGER NOT NULL, col0 INTEGER, col1 INTEGER, name TEXT, PRIMARY KEY(tablet, element, first));
INSERT INTO tablet(n, git_blob, lang, lines) VALUES (1, 'b1', 'js', x''), (2, 'b2', 'js', x'');
INSERT INTO family(n, sha, lang) VALUES (511, x'01', 'js'), (8770, x'02', 'js');
INSERT INTO element(n, sha, family) VALUES (10, x'0a', 511), (11, x'0b', 8770), (12, x'0c', 511);
INSERT INTO tablet_element VALUES (1, 10, 5, 20, 0, 0, 'distanceKm'), (1, 11, 30, 40, 0, 0, 'initialBearingDeg'),
(2, 12, 100, 115, 0, 0, 'distanceKm');
''')
con.execute('UPDATE tablet SET lines = ? WHERE git_blob = ?', (pack(B1_LINES), 'b1'))
con.execute('UPDATE tablet SET lines = ? WHERE git_blob = ?', (pack(B2_LINES), 'b2'))
con.commit()
con.close()
class ModularJoinTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.out = self.tmp.name
pq.write_table(pa.Table.from_pylist([
{'unit_id': 'u1', 'blob': 'b1', 'line_from': 5, 'line_to': 20, # exact start
'repo': 'r1', 'path': 'p1.js', 'name': 'distanceKm'},
{'unit_id': 'u2', 'blob': 'b1', 'line_from': 31, 'line_to': 40, # overlap 10/11
'repo': 'r1', 'path': 'p1.js', 'name': 'initialBearingDeg'},
{'unit_id': 'u3', 'blob': 'b2', 'line_from': 100, 'line_to': 115, # exact, other blob, same family
'repo': 'r2', 'path': 'p2.js', 'name': 'distanceKm'},
{'unit_id': 'u4', 'blob': 'b1', 'line_from': 60, 'line_to': 70, # nothing there, past the tablet
'repo': 'r1', 'path': 'p1.js', 'name': 'x'},
{'unit_id': 'u5', 'blob': 'zz', 'line_from': 1, 'line_to': 9, # blob unknown to Modular Star
'repo': 'r5', 'path': 'p.js', 'name': 'x'},
]), os.path.join(self.out, 'units.parquet'))
pq.write_table(pa.Table.from_pylist([
{'cluster_id': 'c1', 'members': ['u1', 'u3', 'u4'], 'import_hint': 'r2/p2.js::distanceKm'},
{'cluster_id': 'c2', 'members': ['u5'], 'import_hint': 'r5/p.js::x'},
]), os.path.join(self.out, 'candidates.parquet'))
self.db = os.path.join(self.out, 'modular.sqlite')
make_db(self.db)
def tearDown(self):
self.tmp.cleanup()
def test_join(self):
s = mj.run(self.db, self.out)
self.assertEqual((s['exact'], s['overlap'], s['unmatched']), (2, 1, 2))
rows = {r['unit_id']: r for r in pq.read_table(os.path.join(self.out, 'units-modular.parquet')).to_pylist()}
self.assertEqual((rows['u1']['ms_element'], rows['u1']['ms_family'], rows['u1']['ms_match']), (10, 511, 'exact'))
self.assertEqual((rows['u2']['ms_family'], rows['u2']['ms_match']), (8770, 'overlap'))
self.assertIsNone(rows['u4']['ms_family'])
cand = {r['cluster_id']: r for r in pq.read_table(os.path.join(self.out, 'candidates.parquet')).to_pylist()}
self.assertEqual(cand['c1']['ms_families'], [511])
self.assertEqual(cand['c1']['ms_family_main'], 511)
self.assertEqual(cand['c2']['ms_families'], [])
self.assertIsNone(cand['c2']['ms_family_main'])
def test_line_keys(self):
self.assertEqual(mj.unpack(pack([1, 2**32 - 1, 7])), [1, 2**32 - 1, 7])
self.assertEqual(mj.unpack(b''), [])
s = mj.run(self.db, self.out)
rows = {r['unit_id']: r for r in pq.read_table(os.path.join(self.out, 'units-modular.parquet')).to_pylist()}
self.assertEqual(rows['u1']['ms_line'], 1004) # file line 5 -> index 4
self.assertEqual(rows['u2']['ms_line'], 1030)
self.assertEqual(rows['u3']['ms_line'], 2**32 - 2) # file line 100 -> index 99
self.assertIsNone(rows['u4']['ms_line']) # line 60 of a 50-line tablet
self.assertIsNone(rows['u5']['ms_line'])
self.assertEqual(s['units_with_line'], 3)
cand = {r['cluster_id']: r for r in pq.read_table(os.path.join(self.out, 'candidates.parquet')).to_pylist()}
self.assertEqual(cand['c1']['ms_lines'], [1004, 2**32 - 2])
# The import_hint member (u3) is the top member.
self.assertTrue(cand['c1']['underground_url'].endswith('202609180205-underground/?line=%d' % (2**32 - 2)))
self.assertTrue(cand['c1']['underground_url'].startswith(
'https://globalgrid2050.com/testcode/wafer-development-environment/'))
self.assertEqual(cand['c2']['ms_lines'], [])
self.assertEqual(cand['c2']['underground_url'], '')
def test_at_most_five_lines(self):
pq.write_table(pa.Table.from_pylist([
{'unit_id': 'v%d' % i, 'blob': 'b2', 'line_from': i + 1, 'line_to': i + 9} for i in range(8)]),
os.path.join(self.out, 'units.parquet'))
pq.write_table(pa.Table.from_pylist([{'cluster_id': 'c', 'members': ['v%d' % i for i in range(8)]}]),
os.path.join(self.out, 'candidates.parquet'))
mj.run(self.db, self.out)
c = pq.read_table(os.path.join(self.out, 'candidates.parquet')).to_pylist()[0]
self.assertEqual(c['ms_lines'], B2_LINES[:5])
self.assertTrue(c['underground_url'].endswith('?line=%d' % B2_LINES[0]))
def test_rerun_is_idempotent(self):
mj.run(self.db, self.out)
first = pq.read_table(os.path.join(self.out, 'candidates.parquet')).to_pylist()
mj.run(self.db, self.out)
self.assertEqual(first, pq.read_table(os.path.join(self.out, 'candidates.parquet')).to_pylist())
def test_low_overlap_is_not_a_match(self):
self.assertEqual(mj.match(1, 100, [(90, 200, 1, 1)], 0.8), (None, None, 'none'))
def test_without_database_nothing_is_joined(self):
s = mj.run(None, self.out)
self.assertEqual(s['joined'], 0)
self.assertNotIn('ms_families', pq.read_table(os.path.join(self.out, 'candidates.parquet')).column_names)
if __name__ == '__main__':
unittest.main()VEDIC — Index Page
A web page that draws command, nearest spider, anatomy and translation geodesy, using SHA-256, and uses data from the stars and kuiper-belt repositories. Published at https://ventusltd.github.io/vedic-/.
rendervedic- / index.html · lines 1–172 of 172 · Entry point · pattern pending (shared by 2 files)
- What it does
- It draws command, nearest spider, anatomy and translation geodesy. Defines 13 functions or classes, including $, el, link, queryTerms, loadPage. Side effects: changes the web page (DOM); makes network requests.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: data source: stars data; data source: kuiper-belt data; JSON file command-index.json; JSON file nearest-spider.json; JSON file anatomy.json; JSON file translation-geodesy.json; form fields (user input). Out: web page.
- Downstream impact
- Used directly by 5 files: Registry of All Content in Repos and Dependencies — Index Page (registry_of_all_content_in_repos_and_dependencies, https://ventusltd.github.io/registry_of_all_content_in_repos_and_dependencies/); GlobalGrid2050 Verify VEDIC Homepage Release (globalgrid2050); Test VEDIC Entry (globalgrid2050-homepage); VEDIC Browser Smoke (vedic-); and 1 more. Reached from 136 other entry points, including Iterations — 43 Registry Growth Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/43-registry-growth/); Iterations — 47 Federation Honesty Page (galaxies-wafers, https://ventusltd.github.io/galaxies-wafers/iterations/47-federation-honesty/); GlobalGrid2050 Historical Builds (globalgrid2050, https://globalgrid2050.com/historical_builds.html). It is itself an entry point, published at https://ventusltd.github.io/vedic-/.
- What it achieves
- It queries terms (`queryTerms`), loads page (`loadPage`) and loads command (`loadCommand`). Defines `link`, `queryTerms`, `loadPage` and 8 more. It reads `./data/command-index.json`. It responds to toggle and input events.
- Why it matters
- Loaded by the Registry of All Content in Repos and Dependencies page in Registry of All Content in Repos and Dependencies at https://ventusltd.github.io/registry_of_all_content_in_repos_and_dependencies/. Also imported by GlobalGrid2050 Verify VEDIC Homepage Release and GlobalGrid2050 VEDIC Homepage Promotion Workflow, from GlobalGrid2050. Checked by 2 tests, including Test VEDIC Entry.
- Application
- vedic- · / · page
- Uses
- Code (estate URL)
- Used by
- linked from Registry of All Content in Repos and Dependencies — Index Page (link), named by URL in GlobalGrid2050 Verify VEDIC Homepage Release (estate URL), named by URL in Test VEDIC Entry (estate URL), named by URL in VEDIC Browser Smoke (estate URL), named by URL in GlobalGrid2050 VEDIC Homepage Promotion Workflow (estate URL)
- Produces
- $, el, link, queryTerms, loadPage, pending, loadCommand, codeSources, codeCell, drawCommandRow, load, drawDictionary
- Defines here
- $, el, link, queryTerms, loadPage, pending, loadCommand, codeSources, codeCell, drawCommandRow, load, drawDictionary, drawApps
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 index.html:1-172 · blob 2a17ed7e266c480451cc182a0a8b11016b6075d5 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: unknown
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>VEDIC | GlobalGrid2050</title>
<style>
:root{--bg:#000;--panel:#0b0e14;--line:#2f343d;--text:#fff;--muted:#a6adbb;--accent:#00ffff;--ok:#00ff88;--amber:#ffae00;--news:#ff3038}
*{box-sizing:border-box}html,body{margin:0;background:var(--bg);color:var(--text);font:14px/1.55 'Courier New',monospace}a{color:var(--accent);overflow-wrap:anywhere}button,input{font:inherit}button{background:#0a0a0a;color:var(--accent);border:1px solid var(--line);min-height:44px;padding:8px 12px;cursor:pointer}button[aria-pressed=true]{border-color:var(--accent);box-shadow:inset 0 -2px var(--ac … [line shortened here: 2,297 characters; full line on GitHub]
.dict-filters{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,150px),1fr));gap:8px}.dict-filters label{min-width:0;color:var(--muted);font-size:11px}.dict-filters select{width:100%;min-height:44px;background:#050505;color:var(--text);border:1px solid var(--line);font:inherit}.dict-scroll{max-width:100%;overflow:auto;overscroll-behavior-x:contain}.dict-table{border-collapse:colla … [line shortened here: 3,069 characters; full line on GitHub]
</style></head><body>
<div class="news"><a href="https://globalgrid2050.com/">GLOBALGRID2050 / PIPELINE NEWS</a> · VEDIC / Computational Commands</div><div class="shell"><header class="header"><a class="brand" href="https://globalgrid2050.com/">GLOBALGRID2050<small>VENTUS | ELECTRICITY INFRASTRUCTURE</small></a><span class="hud">VEDIC / FUNCTIONAL DICTIONARY</span></header>
<main><section class="panel" id="dictionary"><h1>VEDIC COMMAND DICTIONARY</h1><p class="muted">Permanent references · plain-English functions · reusable combinations. Expand a meaning to see its inputs, limits and source. Search by command, family or permanent ID.</p><div class="dict-filters"><label>SEARCH<input id="dictSearch" class="search" type="search" placeholder="Search all commands, pattern … [line shortened here: 2,794 characters; full line on GitHub]
<div class="layout"><section class="panel"><h2>01 / Capabilities</h2><label for="search">Find a capability</label><input class="search" id="search" type="search" placeholder="Search in plain English"><div id="capabilities"></div></section><section class="panel" id="detail" aria-live="polite"><h2>02 / Composition</h2><p class="muted">Choose a capability.</p></section></div>
<section class="panel"><h2>05 / Connected knowledge</h2><div id="links" class="links"></div><p class="muted">Spider Printer and Teleprinter are existing external resources; local browser printing is separate.</p><button class="print" id="print" type="button">Print page</button></section></details><section class="panel" id="package-evidence"><h2>VEDIC V3 / Package capability register</h2><p class=" … [line shortened here: 3,010 characters; full line on GitHub]
<script type="module">
const $=id=>document.getElementById(id);
const el=(tag,text,cls)=>{const e=document.createElement(tag);if(text!==undefined)e.textContent=text;if(cls)e.className=cls;return e};
const link=(text,url)=>{const a=el('a',text);a.href=url;return a};
let data,app,selected,translation=null,nearestGraph=null;const bodyBy=new Map();
let dictionary=null,dictPage=0,indexById=new Map();const pageSize=100,loadedPages=new Map();
const queryTerms=value=>String(value).replace(/([a-z0-9])([A-Z])/g,"$1 $2").toLowerCase().match(/[\p{L}\p{N}]+/gu)||[];
function loadPage(path){
if(!/^data\/command-pages\/\d{6}\.json$/.test(path))throw Error("Invalid command page");
if(!loadedPages.has(path)){
const pending=(async()=>{
const response=await fetch("./"+path,{cache:"no-cache"});
if(!response.ok)throw Error("Command page unavailable");
const page=await response.json();
if(page.schema!=="vedic.command-page.v1"||!Array.isArray(page.entries)||page.entries.length>pageSize)throw Error("Invalid command page");
const rows=new Map(page.entries.map(row=>[row.gg_id,row]));
if(rows.size!==page.entries.length||page.entries.some(row=>indexById.get(row.gg_id)?.page!==path))throw Error("Invalid command page identities");
return rows;
})();
loadedPages.set(path,pending);
pending.catch(()=>loadedPages.delete(path));
}
return loadedPages.get(path);
}
async function loadCommand(summary){
const pending=[summary.gg_id],details=new Map();
while(pending.length){
const id=pending.pop();
if(details.has(id))continue;
const ref=indexById.get(id);
if(!ref)throw Error("Missing command identity");
const row=(await loadPage(ref.page)).get(id);
if(!row)throw Error("Missing command record");
details.set(id,row);
pending.push(...(row.components||[]));
}
return details;
}
function codeSources(entry,records,details,seen=new Set()){
if(seen.has(entry.gg_id))return [];
seen.add(entry.gg_id);
const t=records.get(entry.translation_ref),s=t?.source||entry.source;
if(s)return [{source:s,symbol:t?.name||entry.translation_ref?.split(':').at(-1)||entry.word}];
return (entry.components||[]).flatMap(id=>{
const component=details.get(id);
return component?codeSources(component,records,details,seen):[];
});
}
function codeCell(entry,records,details){
const cell=el('td',undefined,'code-cell'),sources=entry.code_sources??codeSources(entry,records,details);
if(!sources.length){cell.append(el('span','Not mapped','muted'));return cell;}
const reuse=el('details'),summary=el('summary','Reuse / dependencies');
reuse.append(summary);
for(const {source:s,symbol} of sources){
const path=s.path.split('/').map(encodeURIComponent).join('/');
const exact='https://github.com/'+s.repo+'/blob/'+s.commit+'/'+path+'#L'+s.first+'-L'+s.last;
const a=link(sources.length===1?'View code':symbol,exact);
a.className='code-source';a.title=symbol+' · lines '+s.first+'–'+s.last;
cell.append(a);
reuse.append(el('small',symbol+' · L'+s.first+'–'+s.last),link('Raw source file','https://raw.githubusercontent.com/'+s.repo+'/'+s.commit+'/'+path));
// Search the actual producer report until a verified occurrence-to-family join is supplied.
reuse.append(link('Modular Star code report','https://ventusltd.github.io/stars/code.html'),el('small','Search '+symbol+'; verify the occurrence before copying or importing.'),link('Kuiper repository view','https://ventusltd.github.io/kuiper-belt/see-through/202611020012/#repo='+encodeURIComponent(s.repo.split('/')[1])));
}
reuse.append(el('small','Exact source is copyable; standalone execution is not established. Follow module imports, dependencies, data requirements and the source licence.'));
cell.append(reuse);return cell;
}
function drawCommandRow(summary,records){
const tr=el('tr'),demo=el('td'),code=el('td',undefined,'code-cell'),meaning=el('td'),detail=el('details');
if(summary.launch)demo.append(link(...summary.launch));else demo.append(el('span','Not mapped','muted'));
detail.append(el('summary',summary.purpose||summary.word));
const evidence=el('button','View code');
evidence.type='button';
evidence.onclick=()=>{detail.open=true;load();};
// Source links are available from the initial index; only prose is lazy-loaded.
if(Array.isArray(summary.code_sources)){
code.append(...codeCell(summary,records,new Map()).childNodes);
}else{
code.append(evidence); // Compatibility with an older cached index.
}
let loading=false,loaded=false;
async function load(){
if(loading||loaded)return;
loading=true;
const status=el('p','Loading command details?','muted');
status.setAttribute('role','status');
detail.querySelector('[role="status"]')?.remove();
detail.append(status);
try{
const details=await loadCommand(summary),row=details.get(summary.gg_id),translation=records.get(row.translation_ref);
status.remove();
detail.append(
el('p','How to see it: '+(row.application?.instructions||'Application mapping pending')),
el('p','Application evidence: '+(row.application?.state||'NOT MAPPED'),'muted'),
el('p','Input: '+row.inputs.join(', ')),
el('p','Output: '+row.output),
...(row.aliases?.length?[el('p','Also called: '+row.aliases.join(', '))]:[]),
el('p','Limits: '+(translation?.limits||row.limits)),
el('p','State: '+row.state+' ? '+row.classification_state,'muted'),
el('p','Functional groups: '+(row.patterns.join(' / ')||'Not classified'),'muted'),
el('p','Modular Star family IDs: '+(row.modular_family_refs?.join(', ')||translation?.family_id||row.family_id||'Not yet resolved'),'muted'),
el('p','Periodic Table: '+row.periodic_category+' / '+row.periodic_block_candidate+' (candidate); VEDIC class: '+row.vedic_class_candidate,'muted')
);
if(row.application?.teleprint_url)detail.append(link('Full application source (TXT)',row.application.teleprint_url));
if(row.receipt)detail.append(link(row.policy_receipt?'Source evidence':'Review evidence',row.receipt));
const source=translation?.source||row.source;
if(source)detail.append(link('Exact source','https://github.com/'+source.repo+'/blob/'+source.commit+'/'+source.path.split('/').map(encodeURIComponent).join('/')+'#L'+source.first+'-L'+source.last));
for(const id of row.components||[])detail.append(el('p',details.get(id).word+' / '+id));
const related=dictionary.entries.filter(other=>other.gg_id!==summary.gg_id&&other.patterns.some(pattern=>summary.patterns.includes(pattern))).slice(0,6);
if(related.length){
detail.append(el('p','Related commands by search group','muted'));
const list=el('ul');
for(const other of related){
const item=el('li'),button=el('button',other.word);
button.type='button';
button.onclick=()=>{$('dictClear').click();$('dictSearch').value=other.gg_id;$('dictSearch').focus();drawDictionary();};
item.append(button);list.append(item);
}
detail.append(list);
}
if(!Array.isArray(summary.code_sources)){
const sourceCell=codeCell(row,records,details);
const returnFocus=document.activeElement===evidence;
code.replaceChildren(...sourceCell.childNodes);
if(returnFocus)(code.querySelector('a.code-source')||detail.querySelector('summary')).focus();
}
loaded=true;
}catch(error){
status.textContent='Command details unavailable: '+error.message;
}finally{loading=false;}
}
detail.addEventListener('toggle',()=>{if(detail.open)load();});
meaning.append(detail);
tr.append(el('td',summary.word),demo,code,meaning,el('td',summary.estate_group),el('td',summary.discipline),el('td',summary.gg_id),el('td',summary.created_utc));
return tr;
}
function drawDictionary(){
const root=$('dictRows');root.replaceChildren();
if(!dictionary){$('dictStatus').textContent='Dictionary unavailable';return;}
const raw=$('dictSearch').value.trim(),query=queryTerms(raw),exactId=dictionary.entries.find(row=>row.gg_id.toLowerCase()===raw.toLowerCase())?.gg_id;
const pattern=$('patternFilter').value,estate=$('estateFilter').value,discipline=$('disciplineFilter').value,klass=$('classFilter').value,sort=$('dictSort').value;
const records=new Map((translation?.records||[]).map(row=>[row.id,row]));
const rows=dictionary.entries.filter(row=>(!estate||row.estate_group===estate)&&(!discipline||row.discipline===discipline)&&(!klass||row.vedic_class_candidate===klass)&&(!pattern||row.patterns.includes(pattern))&&(exactId?row.gg_id===exactId:query.every(term=>row.search.includes(term))));
rows.sort((a,b)=>sort==='priority'?(a.priority??9)-(b.priority??9)||a.number-b.number:sort==='number'?a.number-b.number:sort==='word_desc'?b.word.localeCompare(a.word):String(a[sort]).localeCompare(String(b[sort]))||a.word.localeCompare(b.word));
$('dictStatus').textContent=rows.length+' of '+dictionary.entries.length+' commands';
const pages=Math.max(1,Math.ceil(rows.length/pageSize));
dictPage=Math.min(dictPage,pages-1);
$('dictPage').textContent='Page '+(dictPage+1)+' / '+pages;
$('dictPrev').disabled=dictPage===0;
$('dictNext').disabled=dictPage>=pages-1;
root.append(...rows.slice(dictPage*pageSize,(dictPage+1)*pageSize).map(row=>drawCommandRow(row,records)));
root.setAttribute('aria-busy','false');
}
async function initDictionary(){try{const r=await fetch('./data/command-index.json',{cache:'no-cache'});if(!r.ok)throw Error('Dictionary unavailable');dictionary=await r.json();if(dictionary.schema!=='vedic.command-index.v1'||dictionary.count!==dictionary.entries.length||dictionary.page_size!==pageSize)throw Error('Unsupported dictionary schema');indexById=new Map(dictionary.entries.map(e=>[e.gg_i … [line shortened here: 1,748 characters; full line on GitHub]
function drawApps(){ $('apps').replaceChildren();for(const a of data.apps){const b=el('button',a.name);b.type='button';b.setAttribute('aria-pressed',String(a===app));b.onclick=()=>{app=a;selected=a.capabilities[0]||null;$('search').value='';drawApps();drawCaps();drawDetail()};$('apps').append(b)}}
function drawCaps(){const q=$('search').value.trim().toLowerCase();const list=app.capabilities.filter(c=>(c.name+' '+c.purpose).toLowerCase().includes(q));$('capabilities').replaceChildren();if(!list.length)$('capabilities').append(el('p',app.capabilities.length?'No matching capabilities.':'Not mapped yet. No capability or completeness claim.','muted'));for(const c of list){const b=el('button',c.n … [line shortened here: 559 characters; full line on GitHub]
function drawTranslation(root){if(!translation||app.id!==translation.app||selected.id!==translation.capability)return;const section=el('section',undefined,'card');section.append(el('h2','03 / VEDIC functional language'),el('p',translation.relationship,'notice muted'));for(const t of translation.records){const card=el('article',undefined,'card');card.append(el('h3',t.purpose),el('p','STATIC SOURCE … [line shortened here: 1,027 characters; full line on GitHub]
function drawGraph(root){if(!nearestGraph||app.id!=='gridatlas'||selected.id!=='measure')return;const section=el('section',undefined,'card');section.append(el('h2','04 / Source dependency diagram'),el('p',nearestGraph.scope,'notice muted'));const nodes=new Map(nearestGraph.nodes.map(n=>[n.id,n]));for(const e of nearestGraph.edges){const box=el('div',undefined,'card');const from=nodes.get(e.from),t … [line shortened here: 653 characters; full line on GitHub]
function drawDetail(){const root=$('detail');root.replaceChildren(el('h2','02 / Composition'));if(!selected){root.append(el('p','No mapped capability.','muted'));return}root.append(el('h3',selected.name),el('p',selected.purpose),el('p',selected.limit,'notice muted'),el('p',selected.body_ids.length+' manifest-linked bodies · unique lines: not measured','metric'),link('Open '+app.name,app.url));for( … [line shortened here: 1,070 characters; full line on GitHub]
$('search').addEventListener('input',()=>{if(app)drawCaps()});$('print').onclick=()=>window.print();
try{const r=await fetch('./data/anatomy.json');if(!r.ok)throw Error('Data unavailable');data=await r.json();try{const tr=await fetch('./data/translation-geodesy.json');if(tr.ok){const candidate=await tr.json();if(candidate.schema==='vedic.translation.v1'&&Array.isArray(candidate.records))translation=candidate}}catch(e){console.warn('Translation data unavailable',e)}try{const gr=await fetch('./data … [line shortened here: 1,272 characters; full line on GitHub]
</script></body></html>VEDIC Allocate Commands
A Python command-line tool in the tools folder covering dictionary, command distillation review, command distillation allocation and translation geodesy.
storagevedic- / tools/allocate_commands.py · lines 1–116 of 116 · Entry point · pattern normalized (shared by 4 files)
- What it does
- Defines normalized, labels, allocate, main. Uses libraries argparse, datetime, json, pathlib, re. 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-distillation-review.json; JSON file command-distillation-allocation.json; JSON file translation-geodesy.json; JSON file daily-command-queue.json; command-line arguments.
- Downstream impact
- Used directly by 2 files: VEDIC Daily Operations (vedic-); VEDIC Anatomy Workflow (vedic-). Reached from 2 other entry points, including VEDIC Modular Consumer Workflow (vedic-); VEDIC Test Daily Operations (vedic-).
- What it achieves
- It is built from the normalized step (`normalized`), the labels step (`labels`) and the allocate step (`allocate`). Replay reviewed append-only dictionary admissions against the frozen baseline. It accepts `--allocate-from`, `--check` and `--online`.
- Why it matters
- Run by VEDIC Daily Operations and VEDIC Anatomy Workflow.
- Application
- vedic- · tools · Python CLI
- Uses
- VEDIC Validate Dictionary (import), VEDIC Validate V2 Allocation (import), VEDIC Family Pulse (import), VEDIC Source Admissions (import), argparse, datetime, json, pathlib, re, urllib.parse, subprocess
- Used by
- run by VEDIC Daily Operations (script call), run by VEDIC Anatomy Workflow (workflow run)
- Produces
- normalized, labels, allocate, main
- Defines here
- normalized, labels, allocate, 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/allocate_commands.py:1-116 · blob 47fce727530aa3c712596a1e4911f1ddc8835b84 · 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
"""Replay reviewed append-only dictionary admissions against the frozen baseline."""
import argparse
from datetime import datetime, timezone
import json
from pathlib import Path
import re
from urllib.parse import urlsplit
from validate_dictionary import require, validate, verify_source_entries
from validate_v2_allocation import git_blob, git_bytes
ROOT = Path(__file__).resolve().parents[1]
DICTIONARY = "data/dictionary.json"
DECISIONS = "data/command-distillation-review.json"
BASE = "205bbd8f9be2f38d1b6f514022a494474fac79a6"
def normalized(value):
return " ".join(re.findall(r"[a-z0-9]+", value.casefold()))
def labels(entry):
return {normalized(text) for text in (entry["word"], *entry.get("aliases", []))}
def allocate(base, batches, commit, timestamp):
result = json.loads(json.dumps(base))
known = set().union(*(labels(row) for row in result["entries"]))
for batch in batches:
require(batch["schema_version"] == 1 and batch["baseline_count"] == len(base["entries"]),
"Wrong reviewed-batch version or baseline")
for c in batch["records"]:
require(c["review_status"] == "STATIC_SOURCE_REVIEW" and c["verified_executable_package"] is False,
"Unsupported command admission status")
require(normalized(c["word"]) and c["word"] == c["word"].upper(), "Invalid canonical label")
aliases = c.get("aliases", [])
require(isinstance(aliases, list) and all(isinstance(alias, str) and normalized(alias) for alias in aliases),
"Invalid alias")
names = labels(c)
require(len(names) == len(aliases)+1 and not known.intersection(names), "Duplicate command or alias")
known.update(names)
app_url = urlsplit(c["application"]["url"])
require(app_url.scheme == "https" and app_url.hostname and not app_url.username, "Invalid application URL")
s = c["source"]
for old in result["entries"]:
t = old.get("source") or {}
same_origin = all(s[key] == t.get(key) for key in ("repo", "commit", "path", "blob"))
require(not same_origin or s["first"] > t["last"] or t["first"] > s["last"],
"Overlapping command evidence")
number = result["next_number"]
result["next_number"] += 1
reference = f"msi-command:{s['repo']}:{c['symbol']}"
row = {key: c[key] for key in ("word", "purpose", "limits", "inputs", "output", "estate_group",
"discipline", "periodic_category", "vedic_class_candidate",
"application", "source", "receipt")}
row.update(number=number, gg_id=f"GG2050-VEDIC-{number:06d}", kind="FUNCTION",
translation_ref=reference, sense_key="function:" + reference,
aliases=aliases, fixture_status=c["fixture_status"], demo=None,
demo_unavailable_reason="No independently admitted executable package for this command.",
state="STATIC_SOURCE_REVIEW", classification_state="CURATED_CANDIDATE",
periodic_block_candidate="Unresolved", created_utc=timestamp,
creation_evidence=f"https://github.com/Ventusltd/vedic-/commit/{commit}",
priority=2, family_id=None, element_id=None, tablet_id=None, line_ids=None, proof=None)
result["entries"].append(row)
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--allocate-from")
parser.add_argument("--check", action="store_true")
parser.add_argument("--online", action="store_true")
args = parser.parse_args()
if bool(args.allocate_from) == args.check:
parser.error("Provide --allocate-from or --check")
import subprocess
base = json.loads(git_bytes(BASE, DICTIONARY))
manifest_path = ROOT / "data/command-distillation-allocation.json"
if args.allocate_from:
commit = args.allocate_from
else:
commit = json.loads(manifest_path.read_bytes())["review_commit"]
epoch = subprocess.check_output(["git", "show", "-s", "--format=%ct", commit], cwd=ROOT, text=True)
timestamp = datetime.fromtimestamp(int(epoch), timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
receipt = git_bytes(commit, DECISIONS)
working_blob = subprocess.check_output(
["git", "hash-object", "--path", DECISIONS, DECISIONS], cwd=ROOT, text=True
).strip()
require(git_blob(receipt) == working_blob, "Review receipt differs from committed bytes")
current = allocate(base, json.loads(receipt)["batches"], commit, timestamp)
translations = json.loads((ROOT / "data/translation-geodesy.json").read_bytes())
validate(current, translations, base)
if args.online:
verify_source_entries(current)
target = ROOT / DICTIONARY
if args.allocate_from:
target.write_bytes((json.dumps(current, ensure_ascii=False, indent=2) + "\n").encode())
manifest_path.write_bytes((json.dumps({"review_commit": commit, "baseline_commit": BASE,
"new_commands": len(current["entries"])-len(base["entries"])}, indent=2)+"\n").encode())
else:
from family_pulse import verify_extension
queue = json.loads((ROOT / "data/daily-command-queue.json").read_bytes())
published = json.loads(target.read_bytes())
from source_admissions import ARCHIVE, BASE as SOURCE_BASE, pinned, replay_published
historical = pinned(SOURCE_BASE, DICTIONARY)
verify_extension(current, historical, queue)
archive = json.loads((ROOT / ARCHIVE).read_bytes())
require(replay_published(historical, archive) == published, "exact source-admission replay mismatch")
validate(published, translations, current)
current = published
print("Reviewed dictionary entries:", len(current["entries"]))
if __name__ == "__main__":
main()