In this section
- VEDIC Test Daily Source Policy test · vedic- / tools/test_daily_source_policy.py lines 1–56
- VEDIC Test Dictionary test · vedic- / tools/test_dictionary.py lines 1–49
- VEDIC Test Dictionary Shards test · vedic- / tools/test_dictionary_shards.py lines 1–49
- VEDIC Test Family Pulse test · vedic- / tools/test_family_pulse.py lines 1–66
- VEDIC Test Find Capability Admission test · vedic- / tools/test_find_capability_admission.py lines 1–26
- VEDIC Test Graph test · vedic- / tools/test_graph.py lines 1–37
- VEDIC Test Modular Features test · vedic- / tools/test_modular_features.py lines 1–61
- VEDIC Test Modular Snapshot test · vedic- / tools/test_modular_snapshot.py lines 1–45
- VEDIC Test Semantic Compiler test · vedic- / tools/test_semantic_compiler.py lines 1–72
- VEDIC Test Source Admissions test · vedic- / tools/test_source_admissions.py lines 1–201
VEDIC Test Daily Source Policy
A test in the tools folder that checks VEDIC Daily Source Policy and VEDIC Source Admissions. It sets up (`setUp`) and is built from the source policy tests class (`SourcePolicyTests`).
testvedic- / tools/test_daily_source_policy.py · lines 1–56 of 56 · Entry point
- What it does
- It tests its inputs. Defines SourcePolicyTests, setUp, test_candidate_is_reproducible_and_emitted_once_after_admission, test_pin_and_complete_span_are_required, test_explicit_contract_requires_reviewed_blob_and_span. Uses libraries hashlib, unittest, unittest.mock.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Downstream impact
- Used directly by 1 file: VEDIC Anatomy Workflow (vedic-).
- What it achieves
- Defines `SourcePolicyTests`, `setUp`, `test_candidate_is_reproducible_and_emitted_once_after_admission` and 2 more.
- Why it matters
- Run by VEDIC Anatomy Workflow.
- Application
- vedic- · tools · test
- Uses
- VEDIC Daily Source Policy (import), VEDIC Source Admissions (import), hashlib, unittest, unittest.mock
- Used by
- run by VEDIC Anatomy Workflow (workflow run)
- Produces
- SourcePolicyTests
- Defines here
- SourcePolicyTests, setUp, test_candidate_is_reproducible_and_emitted_once_after_admission, test_pin_and_complete_span_are_required, test_explicit_contract_requires_reviewed_blob_and_span
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/test_daily_source_policy.py:1-56 · blob c722720ff0a85601bcb777b36165c800194bbe62 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
import hashlib
import unittest
from unittest.mock import patch
from daily_source_policy import discover_candidates, pinned_functions, reproduce_candidate
from source_admissions import candidate_id, verify_policy_candidate
RAW = b"def validate_fixture(rows):\n return len(rows)\n"
PIN = {
"repo": "Ventusltd/fixture",
"commit": "a" * 40,
"path": "unit.py",
"blob": hashlib.sha1(f"blob {len(RAW)}\0".encode() + RAW).hexdigest(),
}
CONTRACT = {
"word": "COUNT FIXTURE ROWS",
"purpose": "Count supplied fixture rows.",
"inputs": ["fixture rows"],
"output": "Number of supplied rows.",
"limits": "Requires a sized collection.",
}
class SourcePolicyTests(unittest.TestCase):
def setUp(self):
self.enterContext(patch("daily_source_policy.PIN", PIN))
self.enterContext(patch("daily_source_policy.CONTRACTS", {"validate_fixture": CONTRACT}))
def test_candidate_is_reproducible_and_emitted_once_after_admission(self):
draft = discover_candidates(RAW, {"records": []})
candidate, = draft["records"]
self.assertEqual(verify_policy_candidate(candidate, RAW),
verify_policy_candidate(candidate, RAW))
self.assertEqual(reproduce_candidate(candidate["source"], RAW)["word"], CONTRACT["word"])
archive = {"records": [{"candidate_id": candidate_id(candidate)}]}
self.assertEqual(discover_candidates(RAW, archive)["records"], [])
def test_pin_and_complete_span_are_required(self):
anchor, _ = next(pinned_functions(RAW))
with self.assertRaisesRegex(ValueError, "reviewed pin"):
reproduce_candidate(anchor, RAW + b"\n")
with self.assertRaisesRegex(ValueError, "Source span"):
reproduce_candidate({**anchor, "last": anchor["last"] - 1}, RAW)
with self.assertRaisesRegex(ValueError, "outside the reviewed"):
reproduce_candidate({**anchor, "commit": "b" * 40}, RAW)
def test_explicit_contract_requires_reviewed_blob_and_span(self):
anchor = {**PIN, "repo": "Ventusltd/explicit-fixture", "first": 1, "last": 2}
candidate = {**CONTRACT, "source": anchor, "symbol": "validate_fixture"}
with patch("daily_source_policy.EXPLICIT_CONTRACTS", (candidate,)):
self.assertEqual(reproduce_candidate(anchor, RAW), candidate)
with self.assertRaisesRegex(ValueError, "blob differs"):
reproduce_candidate(anchor, RAW + b"\n")
with self.assertRaisesRegex(ValueError, "outside the reviewed"):
reproduce_candidate({**anchor, "last": 1}, RAW)VEDIC Test Dictionary
A test in the tools folder that checks VEDIC Validate Dictionary. It is built from the dictionary tests class (`DictionaryTests`).
testvedic- / tools/test_dictionary.py · lines 1–49 of 49 · Entry point · pattern test_cycle (shared by 2 files)
- What it does
- It tests its inputs. Defines 13 functions or classes, including DictionaryTests, test_valid, test_identity, test_missing_demo, test_incompatible_inputs. Uses libraries copy, json, unittest, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file dictionary.json; JSON file translation-geodesy.json.
- Downstream impact
- Used directly by 1 file: VEDIC Anatomy Workflow (vedic-).
- What it achieves
- Defines `DictionaryTests`, `test_valid`, `test_identity` and 10 more.
- Why it matters
- Run by VEDIC Anatomy Workflow.
- Application
- vedic- · tools · test
- Uses
- VEDIC Validate Dictionary (import), copy, json, unittest, pathlib
- Used by
- run by VEDIC Anatomy Workflow (workflow run)
- Produces
- DictionaryTests
- Defines here
- DictionaryTests, test_valid, test_identity, test_missing_demo, test_incompatible_inputs, test_cycle, test_duplicate, test_same_word_distinct_meaning, test_duplicate_meaning, test_creation_time_immutable, test_source_only_cannot_claim_demo, test_source_only_requires_reason, test_source_only_requires_source_pin
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/test_dictionary.py:1-49 · blob 1467ec07f02cbda67c02df6d2b7bbdd550375994 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import copy,json,unittest
from pathlib import Path
from validate_dictionary import validate
ROOT=Path(__file__).resolve().parents[1]
D=json.loads((ROOT/"data/dictionary.json").read_text())
T=json.loads((ROOT/"data/translation-geodesy.json").read_text())
class DictionaryTests(unittest.TestCase):
def test_valid(self):
self.assertEqual(validate(D,T),len(D["entries"]))
def test_identity(self):
d=copy.deepcopy(D); d["entries"][0]["word"]="OTHER"
with self.assertRaises(ValueError): validate(d,T,D)
def test_missing_demo(self):
d=copy.deepcopy(D); d["entries"][0]["demo"]="unknown"
with self.assertRaises(ValueError): validate(d,T)
def test_incompatible_inputs(self):
d=copy.deepcopy(D); d["entries"][5]["inputs"]=["kilovolt_list"]
with self.assertRaises(ValueError): validate(d,T)
def test_cycle(self):
d=copy.deepcopy(D); d["entries"][5]["components"][0]=d["entries"][5]["gg_id"]
with self.assertRaises(ValueError): validate(d,T)
def test_duplicate(self):
d=copy.deepcopy(D); d["entries"].append(d["entries"][0])
with self.assertRaises(ValueError): validate(d,T)
def test_same_word_distinct_meaning(self):
d=copy.deepcopy(D); t=copy.deepcopy(T)
e=copy.deepcopy(d["entries"][0])
e.update(number=d["next_number"],gg_id=f'GG2050-VEDIC-{d["next_number"]:06d}',translation_ref="fixture:distinct_meaning",sense_key="function:fixture:distinct_meaning")
t["records"].append({"id":"fixture:distinct_meaning"})
d["entries"].append(e); d["next_number"]+=1
self.assertEqual(validate(d,t,D),len(D["entries"])+1)
def test_duplicate_meaning(self):
d=copy.deepcopy(D)
e=copy.deepcopy(d["entries"][0]); e.update(number=d["next_number"],gg_id=f'GG2050-VEDIC-{d["next_number"]:06d}',word="OTHER")
d["entries"].append(e); d["next_number"]+=1
with self.assertRaises(ValueError): validate(d,T,D)
def test_creation_time_immutable(self):
d=copy.deepcopy(D); d["entries"][0]["created_utc"]="2026-11-26T02:00:00Z"
with self.assertRaises(ValueError): validate(d,T,D)
def test_source_only_cannot_claim_demo(self):
d=copy.deepcopy(D); d["entries"][6]["demo"]="distance"
with self.assertRaises(ValueError): validate(d,T)
def test_source_only_requires_reason(self):
d=copy.deepcopy(D); d["entries"][6].pop("demo_unavailable_reason")
with self.assertRaises(ValueError): validate(d,T)
def test_source_only_requires_source_pin(self):
d=copy.deepcopy(D); d["entries"][6]["source"]["blob"]="invalid"
with self.assertRaises(ValueError): validate(d,T)VEDIC Test Dictionary Shards
A test in the tools folder that checks VEDIC Dictionary Shards using data from the GridAtlas repository. It is built from the shards tests class (`ShardsTests`).
testvedic- / tools/test_dictionary_shards.py · lines 1–49 of 49 · Entry point
- What it does
- It tests its inputs. Defines ShardsTests, test_full_catalogue, test_satnav_application_and_precise_code_are_separate, test_101_rows. Uses libraries json, pathlib, unittest. 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: data source: gridatlas data; JSON file dictionary.json; JSON file translation-geodesy.json; JSON file 000001.json; JSON file 000002.json.
- Downstream impact
- Used directly by 1 file: VEDIC Anatomy Workflow (vedic-).
- What it achieves
- Defines `ShardsTests`, `test_full_catalogue`, `test_satnav_application_and_precise_code_are_separate` and 1 more.
- Why it matters
- Run by VEDIC Anatomy Workflow.
- Application
- vedic- · tools · test
- Uses
- VEDIC Dictionary Shards (import), json, pathlib, unittest
- Used by
- run by VEDIC Anatomy Workflow (workflow run)
- Produces
- ShardsTests
- Defines here
- ShardsTests, test_full_catalogue, test_satnav_application_and_precise_code_are_separate, test_101_rows
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/test_dictionary_shards.py:1-49 · blob 74c75135be23d4247ff5ea433ef629127bd435d4 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import json
from pathlib import Path
import unittest
from dictionary_shards import build, INDEX, PREFIX, SIZE
ROOT=Path(__file__).resolve().parents[1]
class ShardsTests(unittest.TestCase):
def test_full_catalogue(self):
d=json.loads((ROOT/"data/dictionary.json").read_bytes())
t=json.loads((ROOT/"data/translation-geodesy.json").read_bytes())
files=build(d,t);idx=json.loads(files[INDEX])
self.assertEqual(idx["count"],len(d["entries"]))
self.assertEqual(idx["entries"],sorted(idx["entries"],key=lambda e:(e["word"].casefold(),e["number"])))
rows=[]
for name,raw in files.items():
if name.startswith(PREFIX):
page=json.loads(raw)["entries"]
self.assertLessEqual(len(page),SIZE)
rows.extend(page)
self.assertEqual({e["gg_id"] for e in rows},{e["gg_id"] for e in d["entries"]})
self.assertTrue(all("source" not in e and "application" not in e for e in idx["entries"]))
self.assertTrue(any("Measure and calculate" in e["patterns"] for e in idx["entries"]))
self.assertTrue(all(e["code_sources"] for e in idx["entries"]))
self.assertEqual(len(next(e for e in idx["entries"] if e["word"]=="ORIENT")["code_sources"]),2)
for entry in idx["entries"]:
for record in entry["code_sources"]:
self.assertEqual(set(record["source"]),{"repo","commit","path","first","last"})
def test_satnav_application_and_precise_code_are_separate(self):
d=json.loads((ROOT/"data/dictionary.json").read_bytes())
t=json.loads((ROOT/"data/translation-geodesy.json").read_bytes())
files=build(d,t)
idx=json.loads(files[INDEX])
satnav=[e for e in idx["entries"] if e["estate_group"]=="SatNav"]
self.assertEqual(len(satnav),11)
for row in satnav:
self.assertEqual(row["launch"],["SatNav","https://ventusltd.github.io/gridatlas/atlas/v/satnav-road-to-field-202611281800/"])
self.assertTrue(row["code_sources"])
detail=next(e for e in json.loads(files[row["page"]])["entries"] if e["gg_id"]==row["gg_id"])
self.assertIn("teleprint/satnav-source-20261129.txt",detail["application"]["teleprint_url"])
self.assertEqual(detail["application"]["state"],"RELATED_APPLICATION_RUNTIME_UNVERIFIED")
self.assertEqual({e["number"] for e in satnav},{62,63,64,65,*range(96,103)})
def test_101_rows(self):
d=json.loads((ROOT/"data/dictionary.json").read_bytes())
t=json.loads((ROOT/"data/translation-geodesy.json").read_bytes())
d["entries"]=[dict(d["entries"][0],number=i+1,gg_id=f"fixture-{i+1}",word=f"COMMAND {i+1:03d}") for i in range(101)]
files=build(d,t)
self.assertEqual(len(json.loads(files[PREFIX+"000001.json"])["entries"]),100)
self.assertEqual(len(json.loads(files[PREFIX+"000002.json"])["entries"]),1)
self.assertEqual(json.loads(files[INDEX])["entries"][-1]["gg_id"],"fixture-101")VEDIC Test Family Pulse
A test in the tools folder that checks VEDIC Family Pulse. It sets up (`setUp`) and is built from the daily tests class (`DailyTests`).
testvedic- / tools/test_family_pulse.py · lines 1–66 of 66 · Entry point · pattern queue (shared by 4 files)
- What it does
- It tests its inputs. Defines 13 functions or classes, including row, queue, DailyTests, setUp, test_normalisation. Uses libraries copy, tempfile, unittest, pathlib, duckdb. 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 pulse.parquet; DuckDB queries.
- Downstream impact
- Used directly by 2 files: VEDIC Anatomy Workflow (vedic-); VEDIC Modular Consumer Workflow (vedic-).
- What it achieves
- Defines `row`, `queue`, `DailyTests` and 10 more.
- Why it matters
- Run by VEDIC Anatomy Workflow and VEDIC Modular Consumer Workflow.
- Application
- vedic- · tools · test
- Uses
- VEDIC Family Pulse (import), copy, tempfile, unittest, pathlib, duckdb
- Used by
- run by VEDIC Anatomy Workflow (workflow run), run by VEDIC Modular Consumer Workflow (workflow run)
- Produces
- row, queue, DailyTests
- Defines here
- row, queue, DailyTests, setUp, test_normalisation, test_append_and_replay, test_family_collision, test_existing_symbol, test_unreviewed, test_cursor_and_family, test_bounded_labels, test_parquet, test_review_replay
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/test_family_pulse.py:1-66 · blob e42ad0c74af6a14be15e515352e8bfb3ec0c300d · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
import copy
import tempfile
import unittest
from pathlib import Path
from family_pulse import allocate, checkpoint_cursor, family_identities, family_rows, key, export_pulse, verify_extension
def row(word="FILTER ASSETS", sym="filterAssets"):
return {"decision":"REVIEWED_FOR_ADMISSION","family_refs":[7],"entry":{
"word":word,"translation_ref":"daily:"+sym,"sense_key":"function:daily:"+sym,
"kind":"FUNCTION","state":"STATIC_SOURCE_REVIEW","demo":None,"purpose":"Filter assets",
"application":{"url":"https://github.com/Ventusltd/gridatlas"} }}
def queue(*records):
return {"schema":"vedic.daily-command-queue.v1","records":list(records)}
class DailyTests(unittest.TestCase):
def setUp(self):
self.d={"entries":[],"next_number":1}
def test_normalisation(self):
self.assertEqual(key("Filter Assets"),key("filter_assets"))
def test_append_and_replay(self):
c=row()
self.assertEqual(len(allocate(self.d,queue(c))[0]),1)
before=copy.deepcopy(self.d)
self.assertEqual(allocate(self.d,queue(c))[0],[])
self.assertEqual(self.d,before)
def test_family_collision(self):
allocate(self.d,queue(row()))
self.assertEqual(allocate(self.d,queue(row("OTHER","other")))[0],[])
def test_existing_symbol(self):
self.d["entries"]=[{"word":"FILTER","translation_ref":"old:filterAssets","sense_key":"old"}]
self.assertEqual(allocate(self.d,queue(row()))[0],[])
def test_unreviewed(self):
c=row();c["decision"]="CANDIDATE"
with self.assertRaises(ValueError): allocate(self.d,queue(c))
def test_cursor_and_family(self):
catalogue={"family_by_hash":{"a"*64:7,"b"*64:8,"c"*64:9},
"families":{"7":{"names":["filterAssets"],"repos":2},"8":{"names":["other"],"repos":1}}}
identities=family_identities(catalogue)
allocate(self.d,queue(row()))
rows,cursor=family_rows(catalogue,identities,self.d["entries"],0)
self.assertEqual((rows[0][4],rows[-1][4],cursor),("MAPPED_FAMILY","NO_CURRENT_PLACEMENT",9))
self.assertEqual(family_rows(catalogue,identities,[],9),([],9))
checkpoint={"schema":"vedic.daily-family-pulse.v2","next_cursor":9,"cursor_family_hash":"c"*64}
self.assertEqual(checkpoint_cursor(checkpoint,identities),9)
checkpoint["cursor_family_hash"]="e"*64
with self.assertRaises(ValueError): checkpoint_cursor(checkpoint,identities)
def test_bounded_labels(self):
with self.assertRaisesRegex(ValueError, "command not compact"):
allocate(self.d,queue(row("ONE TWO THREE FOUR FIVE SIX")))
def test_parquet(self):
import duckdb
with tempfile.TemporaryDirectory() as d:
p=Path(d)/"pulse.parquet"
export_pulse([(1,"[]",1,"[]","REVIEW_REQUIRED","[]","[]","[]")],p)
self.assertGreater(p.stat().st_size,0)
export_pulse([],p)
self.assertGreater(p.stat().st_size,0)
def test_review_replay(self):
historic=copy.deepcopy(self.d)
c=row()
allocate(self.d,queue(c))
verify_extension(historic,self.d,queue(c))
self.d["entries"][0]["word"]="ALTERED"
with self.assertRaises(ValueError):
verify_extension(historic,self.d,queue(c))VEDIC Test Find Capability Admission
A test in the tools folder that checks VEDIC Semantic Compiler. It finds capability admission tests (`FindCapabilityAdmissionTests`) and sets up (`setUp`).
testvedic- / tools/test_find_capability_admission.py · lines 1–26 of 26 · Entry point
- What it does
- It tests its inputs. Defines FindCapabilityAdmissionTests, setUp, test_reviewed_source_row_resolves_without_claiming_a_runtime_binding, test_executor_refuses_static_row_before_accessing_package_material. Uses libraries unittest.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Downstream impact
- Used directly by 1 file: VEDIC Anatomy Workflow (vedic-).
- What it achieves
- Defines `FindCapabilityAdmissionTests`, `setUp`, `test_reviewed_source_row_resolves_without_claiming_a_runtime_binding` and 1 more.
- Why it matters
- Run by VEDIC Anatomy Workflow.
- Application
- vedic- · tools · test
- Uses
- VEDIC Semantic Compiler (import), unittest
- Used by
- run by VEDIC Anatomy Workflow (workflow run)
- Produces
- FindCapabilityAdmissionTests
- Defines here
- FindCapabilityAdmissionTests, setUp, test_reviewed_source_row_resolves_without_claiming_a_runtime_binding, test_executor_refuses_static_row_before_accessing_package_material
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/test_find_capability_admission.py:1-26 · blob 1ce1071ccac1af59d12f6dfec474344d12c45db5 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
import unittest
from semantic_compiler import BINDINGS, DICTIONARY, Refusal, execute, resolve, strict_json
class FindCapabilityAdmissionTests(unittest.TestCase):
def setUp(self):
self.dictionary = strict_json(DICTIONARY.read_bytes())
self.bindings = strict_json(BINDINGS.read_bytes())
def test_reviewed_source_row_resolves_without_claiming_a_runtime_binding(self):
plan = resolve(" find\tcapability ", self.dictionary, self.bindings)
self.assertEqual(plan["command_id"], "GG2050-VEDIC-000095")
self.assertEqual(plan["canonical"], "FIND CAPABILITY")
self.assertEqual(plan["dictionary_status"], "STATIC_POLICY_REPRODUCED")
self.assertEqual(plan["execution_readiness"], "NO_REVIEWED_PACKAGE_BINDING")
self.assertNotIn(plan["command_id"], self.bindings["bindings"])
def test_executor_refuses_static_row_before_accessing_package_material(self):
plan = resolve("FIND CAPABILITY", self.dictionary, self.bindings)
with self.assertRaisesRegex(Refusal, "^PACKAGE_NOT_ADMITTED$"):
execute(plan, {"objective": "audit a captured component"}, None, None, None)
if __name__ == "__main__":
unittest.main()VEDIC Test Graph
A test in the tools folder that checks VEDIC Validate Graph. It is built from the graph tests class (`GraphTests`).
testvedic- / tools/test_graph.py · lines 1–37 of 37 · Entry point · pattern test_valid (shared by 4 files)
- What it does
- It tests its inputs. Defines 8 functions or classes, including GraphTests, test_valid, test_bad_endpoint, test_live_promotion, test_no_caveat. Uses libraries copy, json, unittest, pathlib. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: JSON file nearest-spider.json; JSON file translation-geodesy.json.
- Downstream impact
- Used directly by 1 file: VEDIC Anatomy Workflow (vedic-).
- What it achieves
- Defines `GraphTests`, `test_valid`, `test_bad_endpoint` and 5 more.
- Why it matters
- Run by VEDIC Anatomy Workflow.
- Application
- vedic- · tools · test
- Uses
- VEDIC Validate Graph (import), copy, json, unittest, pathlib
- Used by
- run by VEDIC Anatomy Workflow (workflow run)
- Produces
- GraphTests
- Defines here
- GraphTests, test_valid, test_bad_endpoint, test_live_promotion, test_no_caveat, test_bad_evidence, test_shared_occurrence_alias, test_alias_cannot_change_identity
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/test_graph.py:1-37 · blob 0a61dbee0cdf5fc43c9d80c4b582a9529c17d808 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import copy
import json
import unittest
from pathlib import Path
from validate_graph import validate, validate_aliases
G = json.loads((Path(__file__).resolve().parents[1] / "data/nearest-spider.json").read_text())
class GraphTests(unittest.TestCase):
def test_valid(self):
self.assertEqual(validate(G), (4, 3))
def test_bad_endpoint(self):
g = copy.deepcopy(G)
g["edges"][0]["to"] = "invented"
with self.assertRaises(ValueError): validate(g)
def test_live_promotion(self):
g = copy.deepcopy(G)
g["nodes"][0]["rag"] = "green"
with self.assertRaises(ValueError): validate(g)
def test_no_caveat(self):
g = copy.deepcopy(G)
g["scope"] = "Active"
with self.assertRaises(ValueError): validate(g)
def test_bad_evidence(self):
g = copy.deepcopy(G)
g["edges"][0]["evidence"]["contains"] = ""
with self.assertRaises(ValueError): validate(g)
def test_shared_occurrence_alias(self):
catalogue = json.loads((Path(__file__).resolve().parents[1] / "data/translation-geodesy.json").read_text())
self.assertEqual(validate_aliases(G, catalogue), 8)
g = copy.deepcopy(G)
next(n for n in g["nodes"] if n["id"] == "vedic:distanceKm").pop("catalogue_ref")
with self.assertRaises(ValueError): validate_aliases(g, catalogue)
def test_alias_cannot_change_identity(self):
catalogue = json.loads((Path(__file__).resolve().parents[1] / "data/translation-geodesy.json").read_text())
g = copy.deepcopy(G)
next(n for n in g["nodes"] if n["id"] == "vedic:distanceKm")["catalogue_ref"] = "geodesy:initialBearingDeg"
with self.assertRaises(ValueError): validate_aliases(g, catalogue)VEDIC Test Modular Features
A test in the tools folder that checks VEDIC Modular Features. It is built from the test modular features class (`TestModularFeatures`).
testvedic- / tools/test_modular_features.py · lines 1–61 of 61 · Entry point
- What it does
- It tests its inputs. Defines TestModularFeatures, test_acorn_utf16_single_and_multi_line_columns, test_index_identity_and_incremental_reuse. Uses libraries contextlib, json, sqlite3, struct, pathlib. 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 first.parquet; Parquet file second.parquet; Parquet file rejected.parquet; SQLite database.
- Downstream impact
- Used directly by 1 file: VEDIC Anatomy Workflow (vedic-).
- What it achieves
- Regression checks for producer coordinates and immutable incremental feature reuse.
- Why it matters
- Run by VEDIC Anatomy Workflow.
- Application
- vedic- · tools · test
- Uses
- VEDIC Modular Features (import), contextlib, json, sqlite3, struct, pathlib, tempfile, unittest, pyarrow.parquet
- Used by
- run by VEDIC Anatomy Workflow (workflow run)
- Produces
- TestModularFeatures
- Defines here
- TestModularFeatures, test_acorn_utf16_single_and_multi_line_columns, test_index_identity_and_incremental_reuse
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/test_modular_features.py:1-61 · blob 453759a64902ed5b1226332ae585868d865e4c2f · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Regression checks for producer coordinates and immutable incremental feature reuse."""
from contextlib import closing
import json
import sqlite3
import struct
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
import pyarrow.parquet as pq
from modular_features import digest, extract, selected_text
class TestModularFeatures(unittest.TestCase):
def test_acorn_utf16_single_and_multi_line_columns(self):
first = b"before " + "\U0001f600".encode() + b" body\r\n"
last = b"finish after\n"
self.assertEqual(selected_text([first], 7, 9), "\U0001f600")
self.assertEqual(selected_text([first, last], 10, 6), "body\r\nfinish")
def test_index_identity_and_incremental_reuse(self):
with TemporaryDirectory() as directory:
root = Path(directory)
db = root / "modular.sqlite"
source = b"function ping(){\n return 1;\n}\n"
lines = source.splitlines(keepends=True)
with closing(sqlite3.connect(db)) as cx:
cx.executescript("""
CREATE TABLE line(n INTEGER, text BLOB);
CREATE TABLE tablet(n INTEGER, git_blob TEXT, lines BLOB);
CREATE TABLE family(n INTEGER, sha BLOB, lang TEXT);
CREATE TABLE element(n INTEGER, family INTEGER, sha BLOB, kind TEXT,
needs TEXT, standalone INTEGER);
CREATE TABLE tablet_element(tablet INTEGER, element INTEGER, first INTEGER,
last INTEGER, col0 INTEGER, col1 INTEGER, name TEXT);
CREATE TABLE occurrence(tablet INTEGER, repo TEXT, commit_sha TEXT, path TEXT);
CREATE TABLE scan(repo TEXT, commit_sha TEXT);
""")
cx.executemany("INSERT INTO line VALUES (?,?)", enumerate(lines, start=1))
cx.execute("INSERT INTO tablet VALUES (?,?,?)", (123, "a"*40, struct.pack("<III", 1, 2, 3)))
cx.execute("INSERT INTO family VALUES (?,?,?)", (81, bytes.fromhex("1"*64), "js"))
cx.execute("INSERT INTO element VALUES (?,?,?,?,?,?)",
(321, 81, bytes.fromhex(digest(source)), "function", "[]", 1))
cx.execute("INSERT INTO tablet_element VALUES (?,?,?,?,?,?,?)",
(123, 321, 1, 3, 0, 1, "ping"))
cx.execute("INSERT INTO occurrence VALUES (?,?,?,?)",
(123, "Ventusltd/test", "b"*40, "src/utils.js"))
cx.execute("INSERT INTO scan VALUES (?,?)", ("Ventusltd/test", "b"*40))
cx.commit()
first, second = root/"first.parquet", root/"second.parquet"
extract(db, first, 1, None)
report = extract(db, second, 1, None, first)
self.assertEqual(report["reused_elements"], 1)
entry = pq.read_table(second).to_pylist()[0]
self.assertEqual((entry["family_id"], entry["element_id"]), (81, 321))
self.assertIn("literal:number", entry["tokens"])
first.with_suffix(".json").write_text(json.dumps({"parquet_sha256": "0"*64}))
with self.assertRaises(ValueError):
extract(db, root/"rejected.parquet", 1, None, first)VEDIC Test Modular Snapshot
A test in the tools folder that checks VEDIC Modular Snapshot, using SHA-256. It is built from the snapshot tests class (`SnapshotTests`).
testvedic- / tools/test_modular_snapshot.py · lines 1–45 of 45 · Entry point
- What it does
- It tests its inputs. Defines SnapshotTests, test_read_only_inventory, test_missing_schema, test_snapshot_pin_and_hash. Uses libraries gzip, hashlib, sqlite3, tempfile, unittest. 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.
- Downstream impact
- Used directly by 3 files: VEDIC Anatomy Workflow (vedic-); VEDIC Modular Consumer Workflow (vedic-); VEDIC Release Rehearsal Workflow (vedic-).
- What it achieves
- Defines `SnapshotTests`, `test_read_only_inventory`, `test_missing_schema` and 1 more.
- Why it matters
- Run by VEDIC Anatomy Workflow, VEDIC Modular Consumer Workflow and VEDIC Release Rehearsal Workflow.
- Application
- vedic- · tools · test
- Uses
- VEDIC Modular Snapshot (import), gzip, hashlib, sqlite3, tempfile, unittest, contextlib, pathlib
- Used by
- run by VEDIC Anatomy Workflow (workflow run), run by VEDIC Modular Consumer Workflow (workflow run), run by VEDIC Release Rehearsal Workflow (workflow run)
- Produces
- SnapshotTests
- Defines here
- SnapshotTests, test_read_only_inventory, test_missing_schema, test_snapshot_pin_and_hash
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/test_modular_snapshot.py:1-45 · blob f33598557486b2f6006fe1ef9e1ee0833795f9ff · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
import gzip
import hashlib
import sqlite3
import tempfile
import unittest
from contextlib import closing
from pathlib import Path
from modular_snapshot import inventory, unpack_snapshot, TABLES
class SnapshotTests(unittest.TestCase):
def test_read_only_inventory(self):
with tempfile.TemporaryDirectory() as d:
p = Path(d) / "test.sqlite"
with closing(sqlite3.connect(p)) as db, db:
for t in TABLES:
db.execute(f'CREATE TABLE "{t}" (repo TEXT)')
db.execute("INSERT INTO line VALUES ('x')")
db.execute("INSERT INTO tablet VALUES ('x')")
db.execute("INSERT INTO occurrence VALUES ('test')")
before = p.read_bytes()
result = inventory(p)
self.assertEqual(result["producer_inventory"]["line"], 1)
self.assertIsNone(result["translated_unique_lines"])
self.assertEqual(p.read_bytes(), before)
def test_missing_schema(self):
with tempfile.TemporaryDirectory() as d:
p = Path(d) / "empty.sqlite"
with closing(sqlite3.connect(p)) as db, db:
db.execute("CREATE TABLE other (n INT)")
with self.assertRaises(ValueError):
inventory(p)
def test_snapshot_pin_and_hash(self):
with tempfile.TemporaryDirectory() as d:
p = Path(d) / "snapshot.gz"
payload = b"test bytes"
p.write_bytes(gzip.compress(payload, mtime=0))
meta = {"size": p.stat().st_size, "digest": "sha256:" + hashlib.sha256(p.read_bytes()).hexdigest(), "asset_id": 1}
result = unpack_snapshot(p, Path(d) / "out", meta, dict(meta))
self.assertEqual(result["database_sha256"], hashlib.sha256(payload).hexdigest())
with self.assertRaises(ValueError):
unpack_snapshot(p, Path(d) / "race", meta, dict(meta, asset_id=2))
with self.assertRaises(ValueError):
wrong = dict(meta, digest="sha256:" + "0"*64)
unpack_snapshot(p, Path(d) / "bad", wrong, wrong)
self.assertFalse((Path(d) / "race").exists())VEDIC Test Semantic Compiler
A test in the tools folder that checks VEDIC Semantic Compiler.
testvedic- / tools/test_semantic_compiler.py · lines 1–72 of 72 · Entry point · pattern setUpClass (shared by 19 files)
- What it does
- It tests its inputs. Defines 10 functions or classes, including CommandCompilerTests, setUpClass, plan, test_every_dictionary_name_resolves_by_its_existing_id, test_alias_keeps_the_existing_composition_identity. Uses libraries copy, pathlib, tempfile, unittest. 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).
- Downstream impact
- Used directly by 1 file: VEDIC Anatomy Workflow (vedic-).
- What it achieves
- It sets up class (`setUpClass`) and is built from the command compiler tests class (`CommandCompilerTests`) and the plan step (`plan`). Regression checks for exact command lookup and the package admission boundary.
- Why it matters
- Run by VEDIC Anatomy Workflow.
- Application
- vedic- · tools · test
- Uses
- VEDIC Semantic Compiler (import), copy, pathlib, tempfile, unittest
- Used by
- run by VEDIC Anatomy Workflow (workflow run)
- Produces
- CommandCompilerTests
- Defines here
- CommandCompilerTests, setUpClass, plan, test_every_dictionary_name_resolves_by_its_existing_id, test_alias_keeps_the_existing_composition_identity, test_homonym_requires_an_explicit_existing_sense, test_refuses_dictionary_binding_drift_and_alias_collision, test_discards_unrecognised_free_text_and_nonfinite_input, test_unadmitted_meaning_refuses_before_reading_artifacts, test_tampered_archive_refuses_before_staging_code
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/test_semantic_compiler.py:1-72 · blob 0c46a361b0b3ad19999a47e0a17710cfb81ec292 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Regression checks for exact command lookup and the package admission boundary."""
from copy import deepcopy
from pathlib import Path
import tempfile
import unittest
from semantic_compiler import (BINDINGS, DICTIONARY, Refusal, execute, resolve,
strict_json)
class CommandCompilerTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.dictionary = strict_json(DICTIONARY.read_bytes())
cls.registry = strict_json(BINDINGS.read_bytes())
def plan(self, phrase, sense_id=None):
return resolve(phrase, self.dictionary, self.registry, sense_id)
def test_every_dictionary_name_resolves_by_its_existing_id(self):
for row in self.dictionary["entries"]:
with self.subTest(command=row["gg_id"]):
self.assertEqual(self.plan(row["word"], row["gg_id"])["command_id"], row["gg_id"])
def test_alias_keeps_the_existing_composition_identity(self):
canonical = self.plan("ORIENT")
self.assertEqual(canonical, self.plan(" Measure distance and bearing "))
self.assertEqual(canonical["components"], [row["vedic_id"] for row in canonical["operations"]])
self.assertEqual(canonical["execution_readiness"], "PRIVATE_FACTORY_PACKAGE")
self.assertFalse(canonical["independent_package_acceptance"])
def test_homonym_requires_an_explicit_existing_sense(self):
with self.assertRaisesRegex(Refusal, "AMBIGUOUS_COMMAND") as caught:
self.plan("AREA")
self.assertEqual(caught.exception.details["candidates"],
["GG2050-VEDIC-000017", "GG2050-VEDIC-000019"])
self.assertEqual(self.plan("AREA", "GG2050-VEDIC-000019")["command_id"], "GG2050-VEDIC-000019")
def test_refuses_dictionary_binding_drift_and_alias_collision(self):
changed = deepcopy(self.dictionary)
next(row for row in changed["entries"] if row["word"] == "ORIENT")["components"].reverse()
with self.assertRaisesRegex(Refusal, "DICTIONARY_BINDING_DRIFT"):
resolve("ORIENT", changed, self.registry)
other = deepcopy(self.dictionary)
other["entries"][0]["aliases"] = ["Measure Distance and Bearing"]
with self.assertRaisesRegex(Refusal, "AMBIGUOUS_COMMAND"):
resolve("measure distance and bearing", other, self.registry)
def test_discards_unrecognised_free_text_and_nonfinite_input(self):
for text in ("guess the voltage", "measure voltage; orient", "Orıent", "please could you measure the distance"):
with self.subTest(text=text), self.assertRaises(Refusal):
self.plan(text)
for raw, expected in ((b'{"a":1,"a":2}', "DUPLICATE_JSON_KEY"),
(b'{"a":1e400}', "NONFINITE_INPUT"),
(b'{"a":NaN}', "NONFINITE_INPUT")):
with self.subTest(raw=raw), self.assertRaisesRegex(Refusal, expected):
strict_json(raw)
def test_unadmitted_meaning_refuses_before_reading_artifacts(self):
with self.assertRaisesRegex(Refusal, "PACKAGE_NOT_ADMITTED"):
execute(self.plan("CHECK POWER CAP"), {}, None, None, None)
def test_tampered_archive_refuses_before_staging_code(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "tampered"
path.write_bytes(b"tampered evidence")
with self.assertRaisesRegex(Refusal, "PACKAGE_EVIDENCE_MISMATCH"):
execute(self.plan("ORIENT"), {}, None, path, path)
if __name__ == "__main__":
unittest.main()VEDIC Test Source Admissions
A test in the tools folder that checks VEDIC Family Pulse and VEDIC Source Admissions.
testvedic- / tools/test_source_admissions.py · lines 1–201 of 201 · Entry point · pattern archive (shared by 3 files)
- What it does
- It tests its inputs. Defines 23 functions or classes, including source, candidate, dictionary, archive, queue. Uses libraries copy, hashlib, sys, tempfile, unittest. 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 admitted-queue-archive.json; JSON file dictionary.json.
- Downstream impact
- Used directly by 1 file: VEDIC Anatomy Workflow (vedic-).
- What it achieves
- It writes one (`write_one`) and is built from the archive step (`archive`) and the queue step (`queue`). Defines `source`, `candidate`, `dictionary` and 20 more.
- Why it matters
- Run by VEDIC Anatomy Workflow.
- Application
- vedic- · tools · test
- Uses
- VEDIC Family Pulse (import), VEDIC Source Admissions (import), VEDIC Source Evidence (import), copy, hashlib, sys, tempfile, unittest, pathlib, shutil, types
- Used by
- run by VEDIC Anatomy Workflow (workflow run)
- Produces
- source, candidate, dictionary, archive, queue, policy_modules, AdmissionTests, SourceBoundaryTests
- Defines here
- source, candidate, dictionary, archive, queue, policy_modules, AdmissionTests, test_bad_record_does_not_consume_id, test_bounded_drain_and_exact_replay, test_duplicate_symbol_and_source, test_check_failure_rolls_back, check, test_archive_tamper, test_legacy_prefix_is_immutable, test_new_candidates_refuse_dangling_human_review, test_policy_reproduction_rejects_changed_contract_even_with_recomputed_receipt, test_stage_proposal_does_not_expose_incomplete_pair, write_one, SourceBoundaryTests, test_python_requires_exact_top_level_span_including_decorator, test_javascript_masks_strings_and_refuses_inner_brace_as_end, test_javascript_refuses_unbalanced_and_unsupported_source, test_reviewed_initializer_requires_complete_unique_assignment
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/test_source_admissions.py:1-201 · blob e68058bd7e7a7f36c3b7e43e3b92f3ad6acdb111 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import copy
import hashlib
import sys
import tempfile
import unittest
from pathlib import Path
from shutil import which
from types import SimpleNamespace
from unittest.mock import patch
from family_pulse import write
from source_admissions import (
BASE, POLICY, SCHEMA, make_policy_receipt, prepare, replay, stage_proposal,
verify_policy_candidate, verify_policy_receipt,
)
from source_evidence import source_link, verify_exact_span, verify_lightning_initializer
MANIFEST = "a" * 40
TIME = "2026-11-26T00:00:00Z"
PYTHON = b"@dec\ndef firstCommand(x):\n if x:\n return 10\n return 0\n"
JAVASCRIPT = b"export function firstCommand(x) {\n if (x) {\n return '}';\n }\n return 0;\n}\n"
def source(raw, path="engine/test.py", first=1, last=5):
blob = hashlib.sha1(f"blob {len(raw)}\0".encode() + raw).hexdigest()
return {"repo": "Ventusltd/test", "commit": "b" * 40, "blob": blob,
"path": path, "first": first, "last": last}
def candidate(word="FIRST COMMAND", symbol="firstCommand", first=10):
src = source(PYTHON, first=first, last=first + 2)
row = {
"word": word, "symbol": symbol, "purpose": "Purpose of " + word,
"limits": "Source contract only", "inputs": ["x"], "output": "result",
"estate_group": "Test", "discipline": "Test", "periodic_category": "Test",
"vedic_class_candidate": "Computation", "aliases": [],
"source": src, "receipt": source_link(src),
}
row["policy_receipt"] = make_policy_receipt(row, PYTHON)
return row
def dictionary():
return {"entries": [], "next_number": 1}
def archive():
return {"schema": SCHEMA, "baseline_commit": BASE, "records": []}
def queue(*records):
return {"schema": "vedic.source-candidates.v1", "records": list(records)}
def policy_modules(canonical):
module = SimpleNamespace(POLICY=POLICY, reproduce_candidate=lambda source, raw: canonical)
return patch.dict(sys.modules, {"daily_source_policy": module})
class AdmissionTests(unittest.TestCase):
def test_bad_record_does_not_consume_id(self):
d, a = dictionary(), archive()
good = candidate()
bad = candidate("lowercase", "bad", 20)
added, held = prepare(d, a, queue(bad, good), MANIFEST, TIME, lambda candidate: None)
self.assertEqual((added, len(held), d["next_number"]), (["GG2050-VEDIC-000001"], 1, 2))
def test_bounded_drain_and_exact_replay(self):
d, a = dictionary(), archive()
q = queue(*(candidate(f"COMMAND {i}", f"cmd{i}", 10 + i * 4) for i in range(21)))
self.assertEqual(len(prepare(d, a, q, MANIFEST, TIME, lambda candidate: None)[0]), 20)
self.assertEqual(len(prepare(d, a, q, MANIFEST, TIME, lambda candidate: None)[0]), 1)
self.assertEqual(prepare(d, a, q, MANIFEST, TIME, lambda candidate: None)[0], [])
expected = replay(dictionary(), a, lambda manifest, path: q, lambda manifest: TIME)
self.assertEqual(expected, d)
self.assertEqual([e["number"] for e in d["entries"]], list(range(1, 22)))
def test_duplicate_symbol_and_source(self):
d, a = dictionary(), archive()
q = queue(candidate(), candidate("SECOND", "firstCommand", 20), candidate("THIRD", "third", 11))
added, held = prepare(d, a, q, MANIFEST, TIME, lambda candidate: None)
self.assertEqual((len(added), len(held)), (1, 2))
def test_check_failure_rolls_back(self):
d, a = dictionary(), archive()
q = queue(candidate(), candidate("SECOND", "second", 20))
def check(candidate):
if candidate["word"] == "FIRST COMMAND":
raise ValueError("source mismatch")
added, held = prepare(d, a, q, MANIFEST, TIME, check)
self.assertEqual((len(added), len(held), d["entries"][0]["number"]), (1, 1, 1))
def test_archive_tamper(self):
d, a = dictionary(), archive()
q = queue(candidate())
prepare(d, a, q, MANIFEST, TIME, lambda candidate: None)
a["records"][0]["candidate"] = copy.deepcopy(a["records"][0]["candidate"])
a["records"][0]["candidate"]["purpose"] = "tampered"
with self.assertRaisesRegex(ValueError, "archive evidence mismatch"):
replay(dictionary(), a, lambda manifest, path: q, lambda manifest: TIME)
def test_legacy_prefix_is_immutable(self):
legacy = [{"candidate_id": "historic"}]
with self.assertRaisesRegex(ValueError, "legacy source-admission archive prefix"):
replay(dictionary(), archive(), legacy_records=legacy)
def test_new_candidates_refuse_dangling_human_review(self):
proposed = candidate()
proposed["receipt"] = "https://github.com/Ventusltd/neural-link-between-agents/issues/87#issuecomment-"
proposed["policy_receipt"] = make_policy_receipt(proposed, PYTHON)
with self.assertRaisesRegex(ValueError, "exact pinned source"):
verify_policy_receipt(proposed)
proposed.pop("policy_receipt")
_, held = prepare(dictionary(), archive(), queue(proposed), MANIFEST, TIME,
lambda candidate: self.fail("unreviewed candidate must not reach the checker"))
self.assertIn("strict policy receipt", held[0]["reason"])
def test_policy_reproduction_rejects_changed_contract_even_with_recomputed_receipt(self):
accepted = candidate(first=1)
accepted["source"]["last"] = 5
accepted["receipt"] = source_link(accepted["source"])
accepted["policy_receipt"] = make_policy_receipt(accepted, PYTHON)
canonical = {key: value for key, value in accepted.items() if key != "policy_receipt"}
with policy_modules(canonical):
verify_policy_candidate(accepted, PYTHON)
for field in ("purpose", "output"):
changed = dict(accepted, **{field: "Different value"})
with self.assertRaisesRegex(ValueError, "does not bind candidate contract"):
verify_policy_candidate(changed, PYTHON)
changed["policy_receipt"] = make_policy_receipt(changed, PYTHON)
with self.assertRaisesRegex(ValueError, "differs from exact policy reproduction"):
verify_policy_candidate(changed, PYTHON)
def test_stage_proposal_does_not_expose_incomplete_pair(self):
with tempfile.TemporaryDirectory() as directory:
parent = Path(directory)
dest = parent / "proposal"
def write_one(path, value):
if path.name == "admitted-queue-archive.json":
raise OSError("simulated failed second write")
write(path, value)
with patch("source_admissions.write", side_effect=write_one):
with self.assertRaisesRegex(OSError, "second write"):
stage_proposal(dest, dictionary(), archive())
self.assertFalse(dest.exists())
self.assertFalse(list(parent.iterdir()))
stage_proposal(dest, dictionary(), archive())
self.assertEqual(sorted(p.name for p in (dest / "data").iterdir()),
["admitted-queue-archive.json", "dictionary.json"])
with self.assertRaisesRegex(ValueError, "destination already exists"):
stage_proposal(dest, dictionary(), archive())
class SourceBoundaryTests(unittest.TestCase):
def test_python_requires_exact_top_level_span_including_decorator(self):
pin = source(PYTHON)
verify_exact_span(pin, "firstCommand", PYTHON)
for mismatched in (dict(pin, first=2), dict(pin, last=4)):
with self.assertRaisesRegex(ValueError, "unique complete top-level function"):
verify_exact_span(mismatched, "firstCommand", PYTHON)
with self.assertRaisesRegex(ValueError, "pinned evidence"):
verify_exact_span(pin, "firstCommand", PYTHON + b"\n")
nested = b"def outer():\n def firstCommand():\n pass\n"
with self.assertRaisesRegex(ValueError, "unique complete top-level function"):
verify_exact_span(source(nested, first=2, last=3), "firstCommand", nested)
@unittest.skipUnless(which("node"), "JavaScript syntax checking requires Node")
def test_javascript_masks_strings_and_refuses_inner_brace_as_end(self):
pin = source(JAVASCRIPT, "engine/test.js", last=6)
verify_exact_span(pin, "firstCommand", JAVASCRIPT)
with self.assertRaisesRegex(ValueError, "unique complete top-level function"):
verify_exact_span(dict(pin, last=4), "firstCommand", JAVASCRIPT)
@unittest.skipUnless(which("node"), "JavaScript syntax checking requires Node")
def test_javascript_refuses_unbalanced_and_unsupported_source(self):
for body, error in ((JAVASCRIPT[:-2], "invalid JavaScript source"),
(JAVASCRIPT.replace(b"'}'", b"/}/"), "lexical construct")):
with self.assertRaisesRegex(ValueError, error):
verify_exact_span(source(body, "engine/test.js", last=6), "firstCommand", body)
@unittest.skipUnless(which("node"), "JavaScript syntax checking requires Node")
def test_reviewed_initializer_requires_complete_unique_assignment(self):
sample = (
b"(() => {\n"
b" const label = `Lightning`;\n"
b" window.initVentusMap = function addPublicLightningLayer(options) {\n"
b" return originalInit.call(this, options);\n"
b" };\n"
b"})();\n"
)
verify_lightning_initializer(sample, 3, 5)
with self.assertRaisesRegex(ValueError, "unclosed"):
verify_lightning_initializer(sample, 3, 4)
with self.assertRaisesRegex(ValueError, "complete assignment"):
verify_lightning_initializer(sample, 3, 6)
with self.assertRaisesRegex(ValueError, "reviewed assignment"):
verify_lightning_initializer(sample + sample, 3, 5)