GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Automation and CI / cvaa / tools

Seed Regression and 6 more files

A Python command-line tool in the tools folder of CVAA that reads capture and routes, using SHA-256. It makes capture (`make_capture`), makes database (`make_database`) and sets up (`setUp`).

666 lines of Python and JavaScript from cvaa, in 7 files. Topic: Automation and CI. Section 1692 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. CVAA GPU Reuse Test test · cvaa / tools/gpu-reuse.test.mjs lines 1–58
  2. CVAA Grid First Critical Path Test test · cvaa / tools/grid-first-critical-path.test.mjs lines 1–86
  3. CVAA Replay other · cvaa / tools/replay.mjs lines 1–15
  4. CVAA Runtime Endpoints Test test · cvaa / tools/runtime-endpoints.test.mjs lines 1–21
  5. CVAA Score ingest · cvaa / tools/score.mjs lines 1–25
  6. Seed Regression storage · cvaa / tools/seed-regression/seed_regression.py lines 1–355
  7. State Regression storage · cvaa / tools/seed-regression/state_regression.py lines 1–106

CVAA GPU Reuse Test

A test in the tools folder.

testcvaa / tools/gpu-reuse.test.mjs · lines 1–58 of 58 · Not reached from any entry point (candidate for review) · pattern healthy (shared by 2 files)

What it does
It tests its inputs. Defines healthy. Uses libraries node:fs, node:test, node:assert/strict. 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 'cvaa'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file receipt.json.
What it achieves
Defines `healthy`.
Why it matters
No other file in the estate was found to import it.
Application
cvaa · tools · test
Uses
node:fs, node:test, node:assert/strict
Used by
none found
Produces
healthy
Defines here
healthy
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cvaa@dc04524c4df79e90642b8b7c00729e67cdf52855 tools/gpu-reuse.test.mjs:1-58 · blob 8aef6b0990ceadd897f2a4272b9c4a708fcef3b2 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import assert from 'node:assert/strict';

const vaccine = readFileSync(new URL('../vaccines/202609250037-gpu-reuse-before-new-infrastructure.md', import.meta.url), 'utf8').replace(/\r\n/g, '\n');
const code = vaccine.match(/```js\n([\s\S]*?)\n```/)[1];
const antibody = (await import('data:text/javascript;base64,' + Buffer.from(code).toString('base64'))).default;
const canonical = 'https://github.com/Ventusltd/cvaa/blob/main/vaccines/202609250037-gpu-reuse-before-new-infrastructure.md';
const healthy = () => ({
  present: true,
  document: {
    schema: 'cvaa.gpu-reuse.v1',
    inventory_sources: ['docs/GPU-INVENTORY.md'],
    implementations: [{ script: 'https://example.org/script.py', receipt: 'https://example.org/receipt.json' }],
    workload_scope: 'Existing array workload; does not measure browser rendering.',
    decision: { mode: 'reuse', reason: 'Reuse existing numerical batches; browser rendering remains separate.' },
    runner_status: { checked_at: '2026-09-25T00:37:00Z', source: 'docs/GPU-INVENTORY.md', status: 'Offline at the recorded observation.' },
  },
  localFiles: { 'docs/GPU-INVENTORY.md': true },
  readmeHeader: ['# fixture', '<!-- CVAA:GPU-REUSE:START -->',
    `[Vaccine](${canonical})`, '[Metadata](.cvaa/gpu-reuse.json)',
    '[Inventory and runner status](docs/GPU-INVENTORY.md)',
    '[Script](https://example.org/script.py)', '[Receipt](https://example.org/receipt.json)',
    '<!-- CVAA:GPU-REUSE:END -->'].join('\n'),
});
test('healthy trail passes with an explicitly offline observation', () => assert.deepEqual(antibody({ gpuReuse: healthy() }), []));
test('workload can be explicitly inapplicable to GPU', () => {
  const value = healthy(); value.document.decision = { mode: 'inapplicable', reason: 'The requested work is browser DOM rendering.' };
  assert.deepEqual(antibody({ gpuReuse: value }), []);
});
test('no opt-in and old runner are explicitly not evaluated', () => {
  assert.ok(antibody({ gpuReuse: { present: false, readmeHeader: '# other' } }).skip);
  assert.ok(antibody({}).skip);
});
const diseases = {
  'missing metadata while README still opts in': value => { value.present = false; },
  'malformed JSON snapshot': value => { value.error = 'invalid JSON'; },
  'wrong schema': value => { value.document.schema = 'wrong'; },
  'missing README block': value => { value.readmeHeader = '# fixture'; },
  'block cut off at header limit': value => { value.readmeHeader = value.readmeHeader.replace('<!-- CVAA:GPU-REUSE:END -->', ''); },
  'missing canonical vaccine link': value => { value.readmeHeader = value.readmeHeader.replace(canonical, 'https://example.org/note'); },
  'missing implementation link': value => { value.readmeHeader = value.readmeHeader.replace('[Script](https://example.org/script.py)', 'script exists'); },
  'missing inventory file': value => { value.localFiles = {}; },
  'remote inventory instead of local document': value => { value.document.inventory_sources = ['https://example.org/inventory.md']; },
  'unpaired script': value => { delete value.document.implementations[0].receipt; },
  'non-HTTPS implementation': value => { value.document.implementations[0].script = 'http://example.org/script.py'; },
  'empty scope': value => { value.document.workload_scope = ' '; },
  'missing reuse decision': value => { delete value.document.decision; },
  'unexplained extension': value => { value.document.decision = { mode: 'extend', reason: '' }; },
  'missing runner observation': value => { value.document.runner_status = {}; },
  'impossible observation date': value => { value.document.runner_status.checked_at = '2026-02-30T00:00:00Z'; },
  'read-proof flag in place of evidence': value => { value.document = { schema: 'cvaa.gpu-reuse.v1', agent_read: true }; },
};
for (const [name, mutate] of Object.entries(diseases)) test(name + ' fails', () => {
  const value = healthy(); mutate(value);
  const result = antibody({ gpuReuse: value });
  assert.ok(Array.isArray(result) && result.length > 0);
});

CVAA Grid First Critical Path Test

A test in the tools folder that uses SHA-256. It is built from the healthy step (`healthy`), the seen step (`seen`) and the doc step (`doc`).

testcvaa / tools/grid-first-critical-path.test.mjs · lines 1–86 of 86 · Not reached from any entry point (candidate for review) · pattern healthy (shared by 2 files)

What it does
It tests its inputs. Defines healthy, seen, doc, test. Uses libraries node:fs, node:url, node:path, node:vm, node:assert/strict. 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 'cvaa'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file grid-first-critical-path.json; JSON file neso-connection-sites.lean.json; GeoJSON file grid_substations.geojson; JSON file 202609132340-grid-first-observed.json; DuckDB queries.
What it achieves
Unit fixtures are synthetic, not browser results or evidence of a product cure.
Why it matters
No other file in the estate was found to import it.
Application
cvaa · tools · test
Uses
node:fs, node:url, node:path, node:vm, node:assert/strict
Used by
none found
Produces
healthy, seen, doc, test
Defines here
healthy, seen, doc, test
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cvaa@dc04524c4df79e90642b8b7c00729e67cdf52855 tools/grid-first-critical-path.test.mjs:1-86 · blob 5c3ce4e08cbd86ca16b05ff4ff622aa83801fe31 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, storage · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// Unit fixtures are synthetic, not browser results or evidence of a product cure.
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import vm from 'node:vm';
import assert from 'node:assert/strict';
const root = dirname(dirname(fileURLToPath(import.meta.url)));
const file = '202609132340-grid-first-critical-path.md';
const source = readFileSync(join(root, 'vaccines', file), 'utf8').replace(/\r\n/g, '\n');
assert.match(source, /^---\nvaccine: grid-first-critical-path\ngeneration: "202609132340"\ndose: every-deploy\n---/);
for (const section of ['Disease', 'Symptom', 'Antibody', 'Dose', 'Provenance']) assert.match(source, new RegExp('^' + section + '$','m'));
const code = source.match(/```js\n([\s\S]*?)\n```/)[1];
const antibody = vm.runInNewContext('(' + code.replace(/^export default\s*/, '').replace(/;\s*$/, '') + ')', {}, { timeout: 1000 });
const H = 'a'.repeat(64);
const name = 'grid-first-critical-path.json';
function healthy() {
  const cartridges = [{ id: 'synthetic', path: './cartridges/synthetic.js', sha256: H }];
  const seen = t => ({ t_ms: t, substations: 10, links: 5, source_features: 5, rendered_features: 14, answered: true, engine: 'onshore', identity_status: 'PENDING', status_message: null, status_visible: false, pending_dependency: null });
  const cases = ['control','delay-identity','delay-neso','delay-substations'].map(id => ({
    id, response_bodies_replaced: false, source_sha256: H, evidence: 'SYNTHETIC UNIT FIXTURE', cache: 'cold', errors: [],
    held: id === 'control' ? [] : [{ url: 'https://fixture.invalid/' + ({ 'delay-identity':'duckdb-wasm', 'delay-neso':'neso-connection-sites.lean.json', 'delay-substations':'grid_substations.geojson' })[id], start_ms: 500, end_ms: 20500 }],
    before: seen(8000), after: seen(28000)
  }));
  Object.assign(cases[3].before, { substations: 0, links: 0, source_features: 0, rendered_features: 0, answered: null, engine: null, status_visible: true, status_message: 'Loading mapped substation geometry', pending_dependency: 'substation-geometry' });
  const d = { schema:'cvaa.grid-first-critical-path.v1', generation:'202609132340', release_id:'fixture-shell', repd_ref:'12588', technology:'solar', longitude:-1.3489728, latitude:51.8132088, expected_links:5,
    url:'https://fixture.invalid/?repd_ref=12588&latitude=51.8132088&longitude=-1.3489728', measured_at:'SYNTHETIC', browser:'fixture', environment:'SYNTHETIC UNIT FIXTURE', evidence:'fixture', artifact_sha256:H, physical_ios:false, cartridges, cases };
  return { pointer: {schema:'gridatlas.current.v2',generation:d.generation,release_id:d.release_id,cartridges}, cartridgeHashes:{'./cartridges/synthetic.js':{sha256:H}}, controlContracts:[{file:name,document:d,error:null}] };
}
const doc = ctx => ctx.controlContracts[0].document;
let count = 0;
function test(label, mutate, pattern) {
  const ctx = healthy(); mutate(ctx); const result = antibody(ctx);
  assert.ok(Array.isArray(result), label);
  if (pattern) assert.match(result.join('\n'), pattern, label);
  else assert.equal(result.length, 0, label + ': ' + result.join('; '));
  count++; console.log('PASS grid-first: ' + label);
}
test('healthy visible onshore result while optional data is held',()=>{});
assert.equal(antibody({}).length,0);count++;
test('missing receipt is incomplete on an Atlas target',x=>x.controlContracts=[],/INCOMPLETE/);
test('malformed JSON receipt is not ignored',x=>x.controlContracts[0].error='invalid JSON',/invalid JSON/);
test('null document',x=>x.controlContracts[0].document=null,/unsupported/);
test('empty declaration',x=>x.controlContracts[0].document={},/unsupported/);
test('duplicate contract',x=>x.controlContracts.push(x.controlContracts[0]),/exactly one/);
test('different generation',x=>doc(x).generation='other',/composition/);
test('different release',x=>doc(x).release_id='other',/composition/);
test('wrong locally observed bytes',x=>x.cartridgeHashes['./cartridges/synthetic.js'].sha256='b'.repeat(64),/stale or unverified/);
test('absent local bytes',x=>x.cartridgeHashes={},/stale or unverified/);
test('missing cartridge',x=>doc(x).cartridges=[],/cartridge coverage/);
test('duplicate case replaces missing case',x=>doc(x).cases[3]=doc(x).cases[2],/missing or duplicate/);
test('empty test set',x=>doc(x).cases=[],/four distinct/);
test('wrong canary',x=>doc(x).repd_ref='9873',/canary/);
test('wrong supplied coordinate',x=>doc(x).latitude=0,/canary/);
test('different URL',x=>doc(x).url='https://fixture.invalid',/tested URL/);
test('missing trace digest',x=>doc(x).cases[1].source_sha256='',/provenance/);
test('response substitution is not a causal hold',x=>doc(x).cases[1].response_bodies_replaced=true,/unchanged-response/);
test('warm cache is not cold proof',x=>doc(x).cases[1].cache='warm',/cold/);
test('unrecorded errors',x=>delete doc(x).cases[1].errors,/error record/);
test('runtime errors stay visible',x=>doc(x).cases[1].errors=['exception'],/BLOCKED_RUNTIME/);
test('held NESO blocks despite geometry available',x=>Object.assign(doc(x).cases[2].before,{links:0,source_features:0,rendered_features:0,answered:null,engine:null}),/PRODUCT: delay-neso optional enrichment blocks/);
test('held identity blocks',x=>doc(x).cases[1].before.links=0,/optional enrichment blocks/);
test('telemetry success without rendered features',x=>doc(x).cases[2].before.rendered_features=0,/optional enrichment blocks/);
test('no essential geometry is dependency, not optional-gate evidence',x=>doc(x).cases[2].before.substations=0,/BLOCKED_DEPENDENCY/);
test('geometry wait needs visible status',x=>doc(x).cases[3].before.status_visible=false,/visible, dependency-specific/);
test('geometry wait must name dependency',x=>doc(x).cases[3].before.pending_dependency='identity',/dependency-specific/);
test('generic empty message is not a status',x=>doc(x).cases[3].before.status_message='',/waiting state/);
test('missing geometry cannot return an answer',x=>doc(x).cases[3].before.answered=true,/fabricated/);
test('empty recovery',x=>doc(x).cases[3].after.links=0,/did not recover/);
test('duplicate recovered links',x=>doc(x).cases[2].after.source_features=10,/duplicating/);
test('no actual hold',x=>doc(x).cases[2].held=[],/BLOCKED_HARNESS/);
test('wrong dependency held',x=>doc(x).cases[2].held[0].url='https://fixture.invalid/tiles',/named dependency/);
test('hold too short',x=>doc(x).cases[2].held[0].end_ms=3000,/BLOCKED_HARNESS/);
test('late observation after release',x=>doc(x).cases[2].before.t_ms=25000,/before\/after/);
test('excessively late recovery',x=>doc(x).cases[2].after.t_ms=40000,/observed too late/);
test('identity already resolved during supposed hold',x=>doc(x).cases[1].before.identity_status='VERIFIED',/BLOCKED_HARNESS/);
test('headless is not physical iOS',x=>doc(x).physical_ios=true,/physical iOS/);
const record=JSON.parse(readFileSync(join(root,'studies/202609132340-grid-first-observed.json'),'utf8'));
assert.equal(record.record_type,'PRESERVED_FAILING_OBSERVATIONS_NOT_ACCEPTANCE');
const d=record.receipt;
const observed={pointer:{schema:'gridatlas.current.v2',generation:d.generation,release_id:d.release_id,cartridges:d.cartridges},cartridgeHashes:Object.fromEntries(d.cartridges.map(c=>[c.path,{sha256:c.sha256}])),controlContracts:[{file:name,document:d,error:null}]};
const findings=antibody(observed);
assert.ok(findings.some(s=>s.includes('delay-neso optional enrichment blocks')));
assert.ok(findings.some(s=>s.includes('geometry-wait visibility and dependency were not measured')));
assert.equal(findings.length,2,findings.join('\n')); count++;
console.log('PASS grid-first: historical observations retain a product finding and an incomplete measurement, not a cure');
console.log(JSON.stringify({schema:'cvaa.grid-first-selftest.v1',tests:count,pass:true,product_fixed:false,historical_findings:findings}));

CVAA Replay

A JavaScript module in the tools folder.

othercvaa / tools/replay.mjs · lines 1–15 of 15 · Not reached from any entry point (candidate for review)

What it does
It lists and searches its content. Defines sh. Uses libraries node:child_process. Side effects: starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'cvaa'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: command-line arguments.
What it achieves
No statement of purpose was found in the file, a README line naming it, or its name.
Why it matters
No other file in the estate was found to import it.
Application
cvaa · tools · JavaScript module
Uses
CVAA Inoculate (script call), node:child_process
Used by
none found
Produces
sh
Defines here
sh
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cvaa@dc04524c4df79e90642b8b7c00729e67cdf52855 tools/replay.mjs:1-15 · blob 4a43558d4280d9bf3d2d58e0222d79833173b1cb · GitHub at these lines
State
achieves: name · context: readme_derived · stage: unknown · effects: process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// tools/replay.mjs <repo> [since-ref]  — JSONL: one line per commit per vaccine, findings count. Detached checkouts, restored at end.
import { execSync } from 'node:child_process';
const [repo, since = 'HEAD~15'] = process.argv.slice(2);
const sh = c => execSync(c, { cwd: repo, stdio: 'pipe' }).toString().trim();
const head = sh('git rev-parse --abbrev-ref HEAD');
const commits = sh(`git log --format=%H%x09%s ${since}..HEAD`).split('\n').filter(Boolean).reverse();
for (const line of commits) {
  const [sha, subject] = line.split('\t');
  sh(`git checkout -q ${sha}`);
  let out = ''; try { out = execSync(`node ${new URL('../inoculate.mjs', import.meta.url).pathname} . --no-write --no-lock`, { cwd: repo, stdio: 'pipe' }).toString(); } catch (e) { out = e.stdout.toString(); }
  let cur = null; const counts = {};
  for (const l of out.split('\n')) { const m = l.match(/^(FAIL|WARN|immune)\s+(\S+)/); if (m) { cur = m[2]; counts[cur] = counts[cur] || 0; } else if (/^\s+- /.test(l) && cur) counts[cur]++; }
  for (const [vaccine, findings] of Object.entries(counts)) console.log(JSON.stringify({ sha: sha.slice(0, 7), subject: subject.slice(0, 60), vaccine, findings }));
}
sh(`git checkout -q ${head}`);

CVAA Runtime Endpoints Test

A test in the tools folder.

testcvaa / tools/runtime-endpoints.test.mjs · lines 1–21 of 21 · Not reached from any entry point (candidate for review)

What it does
It tests its inputs. Defines good, run. Uses libraries node:test, node:assert/strict, node:fs. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'cvaa'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file probe.json; JSON file runtime-endpoints.json.
What it achieves
Defines `good` and `run`.
Why it matters
No other file in the estate was found to import it.
Application
cvaa · tools · test
Uses
node:test, node:assert/strict, node:fs
Used by
none found
Produces
good, run
Defines here
good, run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cvaa@dc04524c4df79e90642b8b7c00729e67cdf52855 tools/runtime-endpoints.test.mjs:1-21 · blob 377abea3923811a9b95ab9aa54994f1728fa4ae6 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
const text = readFileSync(new URL('../vaccines/202609051828-runtime-endpoint-contract.md', import.meta.url), 'utf8');
const code = text.split('```js')[1].split('```')[0];
const { default: antibody } = await import('data:text/javascript;base64,' + Buffer.from(code).toString('base64'));
const good = () => ({schema:'cvaa.runtime-endpoints.v1',build:'build-a',environment:'local',
 required:[{method:'GET',path:'/receipt',status:200},{method:'POST',path:'/receipt',status:201}],
 probes:[['GET',200],['POST',201]].map(([method,status])=>({method,status,path:'/receipt',build:'build-a',environment:'local',bodyValidated:true,measuredAt:'2026-09-05T18:28:00Z',evidence:'offline/probe.json'}))});
const run = document => antibody({controlContracts:[{file:'runtime-endpoints.json',document}]});
test('measured GET and persisted POST pass',()=>assert.deepEqual(run(good()),[]));
for (const [name, mutate] of [
 ['static-server GET404',d=>d.probes[0].status=404],
 ['static-server POST501',d=>d.probes[1].status=501],
 ['HTTP200 with wrong body',d=>d.probes[0].bodyValidated=false],
 ['missing POST probe',d=>d.probes.pop()],
 ['different build',d=>d.probes[0].build='old'],
 ['different environment',d=>d.probes[0].environment='production'],
 ['empty coverage',d=>d.required=[]],
 ['no evidence',d=>delete d.probes[0].evidence]
]) test(name,()=>{const d=good(); mutate(d); assert.ok(run(d).length);});

CVAA Score

A JavaScript module in the tools folder.

ingestcvaa / tools/score.mjs · lines 1–25 of 25 · Not reached from any entry point (candidate for review)

What it does
It loads data. Defines agg. Uses libraries node:fs. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'cvaa'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: command-line arguments.
What it achieves
Defines `agg`.
Why it matters
No other file in the estate was found to import it.
Application
cvaa · tools · JavaScript module
Uses
node:fs
Used by
none found
Produces
agg
Defines here
agg
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cvaa@dc04524c4df79e90642b8b7c00729e67cdf52855 tools/score.mjs:1-25 · blob fcf626d855b02c669e600892e18ed6ca1c70c4ea · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// tools/score.mjs <replay.jsonl> <labels.json> [labels2.json]  — precision/recall per vaccine; kappa if two label files
import { readFileSync, existsSync } from 'node:fs';
const [replay, labelsA, labelsB] = process.argv.slice(2);
const rows = readFileSync(replay, 'utf8').split('\n').filter(Boolean).map(JSON.parse);
const A = JSON.parse(readFileSync(labelsA, 'utf8'));
const commits = [...new Set(rows.map(r => r.sha))];
const fired = {}; for (const r of rows) (fired[r.sha] ||= new Set()); for (const r of rows) if (r.findings) fired[r.sha].add(r.vaccine);
const all = [...A.class.amnesia, ...A.class.hygiene];
console.log('vaccine'.padEnd(28) + 'class    TP FP FN  precision recall');
const summary = {};
for (const v of all) {
  let tp = 0, fp = 0, fn = 0;
  for (const c of commits) { const f = fired[c]?.has(v); const l = (A.labels[c] || []).includes(v); if (f && l) tp++; else if (f && !l) fp++; else if (!f && l) fn++; }
  if (!tp && !fp && !fn) continue;
  const p = tp + fp ? tp / (tp + fp) : null, r = tp + fn ? tp / (tp + fn) : null;
  summary[v] = { tp, fp, fn, p, r };
  console.log(v.padEnd(28) + (A.class.amnesia.includes(v) ? 'amnesia ' : 'hygiene ') + String(tp).padStart(3) + String(fp).padStart(3) + String(fn).padStart(3) + '  ' + (p === null ? '  n/a' : p.toFixed(2).padStart(5)) + '     ' + (r === null ? 'n/a' : r.toFixed(2)));
}
const agg = cls => { let tp = 0, fp = 0, fn = 0; for (const v of A.class[cls]) if (summary[v]) { tp += summary[v].tp; fp += summary[v].fp; fn += summary[v].fn; } const p = tp / (tp + fp || 1), r = tp / (tp + fn || 1); return { p, r, f1: 2 * p * r / (p + r || 1) }; };
for (const cls of ['amnesia', 'hygiene']) { const a = agg(cls); console.log(`${cls}: precision ${a.p.toFixed(2)} recall ${a.r.toFixed(2)} F1 ${a.f1.toFixed(2)}`); }
if (labelsB && existsSync(labelsB)) {
  const B = JSON.parse(readFileSync(labelsB, 'utf8')); let agree = 0, n = 0, pa = 0, pb = 0;
  for (const c of commits) for (const v of all) { const a = (A.labels[c] || []).includes(v), b = (B.labels[c] || []).includes(v); n++; if (a === b) agree++; if (a) pa++; if (b) pb++; }
  const po = agree / n, pe = (pa / n) * (pb / n) + (1 - pa / n) * (1 - pb / n); console.log(`kappa ${((po - pe) / (1 - pe)).toFixed(2)}`);
} else console.log('kappa: pending human labels');

Seed Regression

A Python command-line tool in the tools folder of CVAA that reads capture and routes, using SHA-256. It makes capture (`make_capture`), makes database (`make_database`) and sets up (`setUp`).

storagecvaa / tools/seed-regression/seed_regression.py · lines 1–355 of 355 · Entry point · pattern __enter__ (shared by 9 files)

What it does
It loads capture and routes. Defines 34 functions or classes, including SelectedReader, __init__, open, __enter__, __exit__. Uses libraries argparse, gc, hashlib, json, sqlite3. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'cvaa'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file capture-index.json; JSON file evidence.json; JSON file routes.json; JSON file universe.json; SQLite database; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
CVAA bounded regressions against the published SEED instruments. It reads `economy/routes.json`. It accepts `--seed-root` and `--with-planner`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
cvaa · tools/seed-regression · Python CLI
Uses
argparse, gc, hashlib, json, sqlite3, struct, sys, tempfile
Used by
none found
Produces
SelectedReader, make_capture, make_database, SeedRegression, PlannerRegression
Defines here
SelectedReader, __init__, open, __enter__, __exit__, seek, read, make_capture, make_database, SeedRegression, setUp, seed, initialise_fixture_catalogue, test_metadata_only_deterministic_search_and_expansion_budget, allowed_connect, test_registry_preserves_deterministic_contract_digest, test_missing_and_cyclic_dependencies_rollback_metadata_and_postings, test_refuses_evidence_outside_working_root, test_selected_byte_range_and_cryptographic_identity, test_refuses_corrupted_selected_bytes_and_offsets, test_refuses_incomplete_capture_index, test_index_closes_owned_read_only_connection, TrackingConnection, close, test_composition_reconstructs_exact_history_read_only, watched_connect, test_corrupted_historical_bytes_never_receive_identity, test_early_refusals_skip_the_historical_estate, PlannerRegression, setUpClass
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cvaa@dc04524c4df79e90642b8b7c00729e67cdf52855 tools/seed-regression/seed_regression.py:1-355 · blob dd691195221274580ca1a5e191e70574da07db8f · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""CVAA bounded regressions against the published SEED instruments."""
import argparse
import gc
import hashlib
import json
import sqlite3
import struct
import sys
import tempfile
import unittest
from contextlib import closing
from pathlib import Path
from unittest.mock import patch


LINE = "const rail = '\U0001f6e4';\n".encode()
TARGET = LINE * 2
URL = "https://fixture.invalid/rail-component.js"
DIGEST = "9fda1c9bae41562ad7972824077a02d08886a86ec095d77c25356426025e1be3"
BLOB = "e4cfc77fbb6b19979decc02df5b627281509c9d9"
READABLE = "code \u00b7 shown in full \u00b7 bounded CVAA fixture"
RULE = "=" * 78


class SelectedReader:
    """Count actual user-space reads and refuse an accidental full capture read."""

    def __init__(self, path, start, length):
        self.path = path
        self.start = start
        self.length = length
        self.opens = 0
        self.bytes_read = 0

    def open(self, mode):
        if mode != "rb":
            raise AssertionError(f"Capture opened with {mode}")
        self.opens += 1
        return self

    def __enter__(self):
        self.stream = self.path.open("rb")
        return self

    def __exit__(self, *args):
        self.stream.close()

    def seek(self, offset):
        if offset != self.start:
            raise AssertionError(f"Unexpected capture offset {offset}")
        self.stream.seek(offset)

    def read(self, size=-1):
        if size != self.length or self.bytes_read:
            raise AssertionError(f"Capture read outside one selected range: {size} bytes")
        data = self.stream.read(size)
        self.bytes_read += len(data)
        return data


def make_capture(path, bodies):
    lengths = [len(content.decode().encode("utf-16-le")) // 2 for _, content in bodies]
    index_role = READABLE.replace("shown in full", "in full")
    header = [
        RULE,
        "THE SCREEN THIS CAME FROM",
        RULE,
        '{"generation":"cvaa-fixture","capturedAt":"2026-11-27T00:00:00Z","viewport":{}}',
        "",
        RULE,
        f"CONTENTS -- {len(bodies)} file(s), {sum(lengths)} characters",
        RULE,
    ]
    for number, ((url, _), size) in enumerate(zip(bodies, lengths), 1):
        header.extend([f"{number}. {url}", f"     {size} chars \u00b7 {index_role}"])
    header.append("")
    parts = [("\n".join(header) + "\n").encode()]
    for (url, content), size in zip(bodies, lengths):
        parts.append(f"{RULE}\nFILE: {url}\n{size} chars \u00b7 {READABLE}\n{RULE}\n".encode())
        parts.extend([content, b"\n\n"])
    parts.append(f"{RULE}\nEND OF TELEPRINT\n{RULE}\n".encode())
    path.write_bytes(b"".join(parts))


def make_database(path):
    with closing(sqlite3.connect(path)) as db, db:
        db.executescript("""
            create table line (n integer primary key, text blob);
            create table tablet (n integer primary key, git_blob text unique, lines blob);
            create table occurrence (repo text, commit_sha text, path text, tablet integer);
            create table commit_info (repo text, sha text, date text);
        """)
        db.execute("insert into line values (41, ?)", (LINE,))
        db.execute("insert into tablet values (73, ?, ?)", (BLOB, struct.pack("<II", 41, 41)))
        db.execute("insert into occurrence values ('seed-fixture', 'commit-beta', 'rail.js', 73)")
        db.execute("insert into occurrence values ('seed-fixture', 'commit-alpha', 'rail.js', 73)")
        db.execute("insert into commit_info values ('seed-fixture', 'commit-alpha', '2026-11-27T00:00:00Z')")


class SeedRegression(unittest.TestCase):
    def setUp(self):
        temp = tempfile.TemporaryDirectory()
        self.addCleanup(temp.cleanup)
        self.addCleanup(gc.collect)
        self.root = Path(temp.name)
        self.database = self.root / "stars.sqlite"
        self.capture = self.root / "capture.txt"
        self.index_path = self.root / "capture-index.json"
        other = (b"padding " + "\N{SNOWMAN}".encode() + b"\n") * 2048
        make_capture(self.capture, [("https://fixture.invalid/unrelated", other), (URL, TARGET)])
        make_database(self.database)
        catalogue = teleprint_index.index(self.capture, self.database)
        self.record = catalogue["records"][1]
        self.index_path.write_text(json.dumps(catalogue), encoding="utf-8")
        self.evidence = self.root / "evidence.json"
        self.evidence.write_text('{"local_fixture":true}', encoding="utf-8")

    def seed(self, key, components=(), *, path="evidence.json", status="demonstrated"):
        return seed_discover.available_record(
            key, key, status, "conditional ordinal retrieval", path, "auditable rail",
            components)

    def initialise_fixture_catalogue(self, records):
        catalogue = self.root / "catalogue.sqlite"
        # Install the public schema, then use the normal registry API against a disposable workspace.
        seed_discover.initialize(catalogue, [])
        with closing(sqlite3.connect(catalogue)) as db:
            db.execute("pragma foreign_keys=on")
            seed_discover.install(db, records, workspace=self.root)
        return catalogue

    def test_metadata_only_deterministic_search_and_expansion_budget(self):
        catalogue = self.initialise_fixture_catalogue([
            self.seed("leaf"), self.seed("stage-a", ["leaf"]),
            self.seed("stage-b", ["leaf"]), self.seed("root", ["stage-a", "stage-b"]),
            self.seed("proposal", status="speculative"),
        ])
        connect = sqlite3.connect

        def allowed_connect(name, *args, **kwargs):
            self.assertEqual(name, catalogue.as_uri() + "?mode=ro")
            return connect(name, *args, **kwargs)

        with patch("io.open", side_effect=AssertionError("Opened evidence or estate file")), \
             patch.object(sqlite3, "connect", side_effect=allowed_connect):
            args = (catalogue, "conditional ordinal retrieval", 8)
            complete = seed_discover.discover(*args, depth=12, cap=9, verified_only=True)
            repeat = seed_discover.discover(*args, depth=12, cap=9, verified_only=True)
            limited = seed_discover.discover(*args, depth=12, cap=2, verified_only=True)
            unreachable = seed_discover.discover(catalogue, "volcano seismometer", 4)
        for key in ("hits", "expanded"):
            self.assertEqual(complete[key], repeat[key])
        self.assertEqual([row["id"] for row in complete["hits"]], ["leaf", "root", "stage-a", "stage-b"])
        self.assertEqual(len(complete["expanded"]), 4)
        self.assertFalse(complete["expansion_budget_exhausted"])
        self.assertEqual(len(limited["expanded"]), 2)
        self.assertTrue(limited["expansion_budget_exhausted"])
        self.assertEqual(unreachable["status"], "no_indexed_match")
        self.assertEqual(complete["metrics"]["inference_calls"], 0)

    def test_registry_preserves_deterministic_contract_digest(self):
        catalogue = self.initialise_fixture_catalogue([self.seed("stable")])
        with closing(sqlite3.connect(catalogue)) as db:
            (encoded,) = db.execute("select contract from record where id='stable'").fetchone()
        checkout = json.loads(encoded)
        expected = checkout.pop("digest")
        data = json.dumps(checkout, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
        self.assertEqual(hashlib.sha256(data.encode()).hexdigest(), expected)

    def test_missing_and_cyclic_dependencies_rollback_metadata_and_postings(self):
        cases = [
            ([self.seed("valid"), self.seed("broken", ["absent"])], sqlite3.IntegrityError),
            ([self.seed("left", ["right"]), self.seed("right", ["left"])], ValueError),
        ]
        catalogue = self.initialise_fixture_catalogue([self.seed("previous")])
        with closing(sqlite3.connect(catalogue)) as db:
            db.execute("pragma foreign_keys=on")
            for records, error in cases:
                with self.subTest(error=error), self.assertRaises(error):
                    seed_discover.install(db, records, workspace=self.root)
                self.assertEqual(db.execute("select id from record").fetchall(), [("previous",)])
                self.assertEqual(db.execute("select id from objective_fts").fetchall(), [("previous",)])
                self.assertEqual(db.execute("select * from dependency").fetchall(), [])

    def test_refuses_evidence_outside_working_root(self):
        contained = self.root / "nested"
        contained.mkdir()
        catalogue = self.initialise_fixture_catalogue([])
        with closing(sqlite3.connect(catalogue)) as db:
            db.execute("pragma foreign_keys=on")
            with self.assertRaisesRegex(ValueError, "outside-workspace"):
                seed_discover.install(db, [self.seed("escape", path="../evidence.json")],
                                      workspace=contained)
            self.assertEqual(db.execute("select * from record").fetchall(), [])

    def test_selected_byte_range_and_cryptographic_identity(self):
        reader = SelectedReader(self.capture, self.record["byte_start"], len(TARGET))
        self.assertEqual(teleprint_index.retrieve(reader, self.record), TARGET)
        self.assertEqual(self.record["utf16_units"], 38)
        self.assertEqual(self.record["byte_length"], 42)
        self.assertEqual(self.record["text_sha256"], DIGEST)
        self.assertEqual(self.record["git_blob"], BLOB)
        self.assertEqual(self.record["tablet"], 73)
        self.assertEqual((reader.opens, reader.bytes_read), (1, len(TARGET)))

    def test_refuses_corrupted_selected_bytes_and_offsets(self):
        with self.assertRaisesRegex(ValueError, "differs from the index"):
            teleprint_index.retrieve(self.capture, dict(self.record,
                byte_start=self.record["byte_start"] + 1))
        with self.capture.open("r+b") as stream:
            stream.seek(self.record["byte_start"])
            stream.write(b"X")
        with self.assertRaisesRegex(ValueError, "differs from the index"):
            teleprint_index.retrieve(self.capture, self.record)

    def test_refuses_incomplete_capture_index(self):
        data = self.capture.read_bytes().replace(b"END OF TELEPRINT", b"CUT OFF")
        self.capture.write_bytes(data)
        with self.assertRaisesRegex(ValueError, "Incomplete capture"):
            teleprint_index.index(self.capture, self.database)

    def test_index_closes_owned_read_only_connection(self):
        class TrackingConnection(sqlite3.Connection):
            was_closed = False

            def close(self):
                self.was_closed = True
                super().close()

        connection = sqlite3.connect(self.database.as_uri() + "?mode=ro", uri=True,
                                     factory=TrackingConnection)
        with closing(connection), patch.object(teleprint_index, "connect", return_value=connection):
            self.assertEqual(teleprint_index.index(self.capture, self.database)["records"][1]["tablet"], 73)
            self.assertTrue(connection.was_closed, "Capture indexing retains its SQLite handle")

    def test_composition_reconstructs_exact_history_read_only(self):
        before = hashlib.sha256(self.database.read_bytes()).digest()
        capture = SelectedReader(self.capture, self.record["byte_start"], len(TARGET))
        statements = []
        original = experiment_b.connect

        def watched_connect(path):
            connection = original(path)
            self.assertEqual(connection.execute("pragma query_only").fetchone(), (1,))
            connection.set_trace_callback(statements.append)
            return connection

        with patch.object(experiment_b, "connect", watched_connect):
            result, logical_bytes, queries = experiment_b.composed(
                capture, URL, self.database, self.index_path)
        self.assertEqual(result, {
            "status": "byte-identical", "url": URL, "sha256": DIGEST, "git_blob": BLOB,
            "tablet": 73, "occurrences": [
                ("seed-fixture", "commit-alpha", "rail.js", "2026-11-27T00:00:00Z"),
                ("seed-fixture", "commit-beta", "rail.js", None),
            ],
        })
        self.assertEqual((capture.opens, capture.bytes_read), (1, len(TARGET)))
        self.assertEqual(logical_bytes, len(TARGET) + self.index_path.stat().st_size)
        self.assertEqual((queries, len(statements)), (3, 3))
        self.assertEqual(hashlib.sha256(self.database.read_bytes()).digest(), before)

    def test_corrupted_historical_bytes_never_receive_identity(self):
        with closing(sqlite3.connect(self.database)) as db, db:
            db.execute("update line set text=? where n=41", (b"another source line\n",))
        with self.assertRaisesRegex(ValueError, "Historical tablet integrity mismatch"):
            experiment_b.composed(self.capture, URL, self.database, self.index_path)

    def test_early_refusals_skip_the_historical_estate(self):
        catalogue = json.loads(self.index_path.read_text(encoding="utf-8"))
        with patch.object(experiment_b, "connect", side_effect=AssertionError("Opened STARS")):
            missing, _, queries = experiment_b.composed(
                self.capture, URL + "-nonexistent", self.database, self.index_path)
            self.assertEqual((missing["status"], queries), ("absent", 0))
            self.index_path.write_text(json.dumps(dict(catalogue, records=[self.record, self.record])),
                                       encoding="utf-8")
            duplicated, _, queries = experiment_b.composed(
                self.capture, URL, self.database, self.index_path)
            self.assertEqual((duplicated["status"], queries), ("ambiguous", 0))
            bad_record = dict(self.record, git_blob="0" * 40)
            self.index_path.write_text(json.dumps(dict(catalogue, records=[bad_record])),
                                       encoding="utf-8")
            corrupt, _, queries = experiment_b.composed(
                self.capture, URL, self.database, self.index_path)
            self.assertEqual((corrupt["status"], queries), ("index-identity-drift", 0))


class PlannerRegression(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        directory = tempfile.TemporaryDirectory()
        cls.addClassCleanup(directory.cleanup)
        cls.catalogue = Path(directory.name) / "prior-28.sqlite"
        cls.routes = seed_discover.read_json(seed_root / "economy/routes.json")
        records = list(seed_discover.base_catalogue())
        if len(records) != 28:
            raise AssertionError("Expected the original 28 contracts in this fixture")
        seed_discover.initialize(cls.catalogue, records)

    def test_complete_pinned_cosmic_contract_proposes_one_command(self):
        inputs = {"ordinal": "17901", "cartridge": "universe.json"}
        with patch("io.open", side_effect=AssertionError("Planner read a payload file")):
            result = seed_plan.plan(self.catalogue, self.routes,
                                    "Locate ordinal 17901 in the hierarchy", inputs)
        self.assertEqual(result["status"], "ready_for_checked_invocation")
        self.assertEqual(result["argv"], ["node", "rare_cosmic.mjs", "17901", "universe.json"])
        self.assertEqual(result["missing"], [])
        self.assertEqual(result["ai_inference_calls"], 0)

    def test_missing_or_invalid_cosmic_arguments_produce_no_command(self):
        result = seed_plan.plan(self.catalogue, self.routes, "Locate the ordinal inside the sector",
                                {"ordinal": "-1"})
        self.assertEqual(result["status"], "supply_inputs")
        self.assertEqual(result["invalid"], ["ordinal"])
        self.assertEqual(result["missing"], ["cartridge"])
        self.assertNotIn("argv", result)

    def test_lexical_match_cannot_claim_executable_coverage(self):
        result = seed_plan.plan(self.catalogue, self.routes, "Explain ordinal arithmetic", {})
        self.assertEqual(result["status"], "investigate")
        self.assertIn("cosmic-ordinal-address", {r["id"] for r in result["candidates"]})
        self.assertNotIn("argv", result)

    def test_ambiguous_edits_refuse_before_opening_catalogue(self):
        with patch.object(sqlite3, "connect", side_effect=AssertionError("Opened catalogue")):
            result = seed_plan.plan(self.catalogue, self.routes,
                "Audit captured historical source at an ordinal in a sector", {})
        self.assertEqual(result["status"], "ambiguous")
        self.assertEqual(set(result["known_contracts"]),
                         {"audit-captured-source", "cosmic-ordinal-address"})
        self.assertNotIn("argv", result)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--seed-root", type=Path, required=True)
    parser.add_argument("--with-planner", action="store_true")
    args = parser.parse_args()
    sys.dont_write_bytecode = True
    seed_root = args.seed_root.resolve()
    sys.path.insert(0, str(seed_root))
    import experiment_b
    import seed_discover
    import teleprint_index

    suite = unittest.defaultTestLoader.loadTestsFromTestCase(SeedRegression)
    if args.with_planner:
        import seed_plan
        suite.addTests(unittest.defaultTestLoader.loadTestsFromTestCase(PlannerRegression))
    outcome = unittest.TextTestRunner(verbosity=2).run(suite)
    print(json.dumps({"tests": outcome.testsRun, "passed": outcome.wasSuccessful(),
                      "stage": "deterministic synthetic SEED regression",
                      "scope": "Selected reads and SQL work, without machine-timing gates"}))
    sys.exit(not outcome.wasSuccessful())

State Regression

A Python command-line tool in the seed regression folder of CVAA that reads same URL.

storagecvaa / tools/seed-regression/state_regression.py · lines 1–106 of 106 · Entry point · pattern compare (shared by 17 files)

What it does
It loads same URL. Defines 10 functions or classes, including StateRegression, setUp, compare, mutate_index, test_recursive_witness_provenance_and_exact_scope. Uses libraries argparse, json, sys, tempfile, unittest. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'cvaa'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file same-url.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It sets up (`setUp`) and is built from the state regression class (`StateRegression`) and the compare step (`compare`). CVAA cross-instrument checks for the next recursive SEED composition. It accepts `--seed-root` and `--composition-root`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
cvaa · tools/seed-regression · Python CLI
Uses
argparse, json, sys, tempfile, unittest, pathlib, unittest.mock, experiment_b
Used by
none found
Produces
StateRegression
Defines here
StateRegression, setUp, compare, mutate_index, test_recursive_witness_provenance_and_exact_scope, test_metadata_only_plan_opens_no_payload, test_mechanism_budget_fails_before_payload_read, test_refuses_duplicate_url_and_noncanonical_identity, test_refuses_inconsistent_stars_identity, test_refuses_selected_witness_corrupted_after_indexing
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cvaa@dc04524c4df79e90642b8b7c00729e67cdf52855 tools/seed-regression/state_regression.py:1-106 · blob 14bd54429e784e2970afe2781e22273334fc8572 · 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
"""CVAA cross-instrument checks for the next recursive SEED composition."""
import argparse
import json
import sys
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch


class StateRegression(unittest.TestCase):
    def setUp(self):
        directory = tempfile.TemporaryDirectory()
        self.addCleanup(directory.cleanup)
        self.inputs = make_fixture(Path(directory.name))
        self.before, self.before_index, self.after, self.after_index, self.database = self.inputs

    def compare(self, *, mechanism=None, limit=3, budget=500):
        return state_compare.compare(*self.inputs, SCOPE, mechanism, limit, budget)

    def mutate_index(self, path, operation):
        manifest = json.loads(path.read_text(encoding="utf-8"))
        operation(manifest)
        path.write_text(json.dumps(manifest), encoding="utf-8")

    def test_recursive_witness_provenance_and_exact_scope(self):
        before = self.database.read_bytes()
        result, usage = self.compare(mechanism=MECHANISM)
        self.assertEqual(result["counts"], dict(identical=1, changed=1, before_only=1,
                                               after_only=1, unread=1))
        self.assertEqual([row["status"] for row in result["changes"] if row["url"] == UNAVAILABLE],
                         ["unread"])
        self.assertNotIn(UNAVAILABLE, {w["url"] for w in result["witnesses"]})
        witness = result["mechanism"]
        self.assertTrue(witness["same_source"])
        for side in ("before", "after"):
            self.assertEqual(witness[side]["tablet"], 7740)
            self.assertTrue(witness[side]["scope_literal"])
        self.assertGreater(usage["payload_bytes"], 0)
        self.assertLessEqual(usage["payload_bytes"], 500)
        self.assertEqual(self.database.read_bytes(), before)

    def test_metadata_only_plan_opens_no_payload(self):
        error = AssertionError("Metadata-only plan opened a payload")
        with patch.object(state_compare, "retrieve", side_effect=error), \
             patch.object(state_compare, "selected_source", side_effect=error), \
             patch.object(state_compare, "composed", side_effect=error):
            result, usage = self.compare(mechanism=None, limit=0, budget=0)
        self.assertEqual(result["counts"]["changed"], 1)
        self.assertEqual(result["witnesses"], [])
        self.assertEqual(result["deferred_witnesses"], 3)
        self.assertEqual((usage["payload_bytes"], usage["sqlite_queries"]), (0, 0))

    def test_mechanism_budget_fails_before_payload_read(self):
        with patch.object(state_compare, "composed", side_effect=AssertionError("Opened STARS")):
            with self.assertRaisesRegex(ValueError, "budget"):
                self.compare(mechanism=MECHANISM, limit=3, budget=0)

    def test_refuses_duplicate_url_and_noncanonical_identity(self):
        original = self.after_index.read_bytes()
        mutations = [
            lambda m: m["records"].append(m["records"][0]),
            lambda m: m["records"][0].update(text_sha256="?" * 64),
            lambda m: m["records"][0].update(byte_start=-1),
        ]
        for mutation in mutations:
            with self.subTest(mutation=mutation):
                self.after_index.write_bytes(original)
                self.mutate_index(self.after_index, mutation)
                with self.assertRaisesRegex(ValueError, "Ambiguous or malformed"):
                    self.compare(mechanism=MECHANISM)

    def test_refuses_inconsistent_stars_identity(self):
        self.mutate_index(self.after_index, lambda m: m.update(database_sha256="0" * 64))
        with self.assertRaisesRegex(ValueError, "disagree on the recorded STARS"):
            self.compare(mechanism=MECHANISM)

    def test_refuses_selected_witness_corrupted_after_indexing(self):
        manifest = json.loads(self.after_index.read_text(encoding="utf-8"))
        selected = next(row for row in manifest["records"] if row["url"] == SCOPE + "same-url.json")
        with self.after.open("r+b") as payload:
            payload.seek(selected["byte_start"])
            payload.write(b"!")
        with self.assertRaisesRegex(ValueError, "differs from the index"):
            self.compare(mechanism=MECHANISM)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--seed-root", required=True, type=Path)
    parser.add_argument("--composition-root", type=Path)
    args = parser.parse_args()
    sys.dont_write_bytecode = True
    root = args.seed_root.resolve()
    sys.path[:0] = [str(root), str(args.composition_root or root / "next-compose")]
    import experiment_b  # Select supplied release modules before loading the higher-order seed.
    import teleprint_index
    import state_compare
    from fixture import MECHANISM, SCOPE, UNAVAILABLE, make_fixture

    result = unittest.TextTestRunner(verbosity=2).run(
        unittest.defaultTestLoader.loadTestsFromTestCase(StateRegression))
    print(json.dumps({"tests": result.testsRun, "passed": result.wasSuccessful(),
                      "stage": "deterministic recursive SEED regression"}))
    sys.exit(not result.wasSuccessful())