In this section
- Route Screen ingest · seed-data / experiments/economical-seeds/next-invention/cable-screen/route-screen.mjs lines 1–128
- Route Screen Test test · seed-data / experiments/economical-seeds/next-invention/cable-screen/route-screen.test.mjs lines 1–86
- Explain ingest · seed-data / experiments/explain-cable-screen-change/followup/explain.mjs lines 1–87
- Session ingest · seed-data / experiments/explain-cable-screen-change/followup/session.mjs lines 1–57
- Trial storage · seed-data / experiments/explain-cable-screen-change/followup/trial.mjs lines 1–104
- Worker storage · seed-data / experiments/explain-cable-screen-change/followup/worker.py lines 1–110
- Check storage · seed-data / experiments/explain-cable-screen-change/original/check.mjs lines 1–38
- Evidence Adapter storage · seed-data / experiments/explain-cable-screen-change/original/evidence_adapter.py lines 1–51
Route Screen
A JavaScript module in the cable screen folder of Seed Data that reads cables.
ingestseed-data / experiments/economical-seeds/next-invention/cable-screen/route-screen.mjs · lines 1–128 of 128 · pattern nonnegative (shared by 2 files)
- What it does
- It loads cables. Defines loadInstruments, positive, nonnegative, has, screen. Uses libraries node:child_process, node:crypto, node:fs, node:path, node:url. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 6 files: Benchmark (seed-data); Route Screen Test (seed-data); Invoke (seed-data); Measure (seed-data); and 2 more. Reached from 1 other entry point, including Seed Regressions Workflow (seed-data).
- What it achieves
- It loads instruments (`loadInstruments`) and is built from the has step (`has`) and the screen step (`screen`). Defines `loadInstruments`, `positive`, `nonnegative` and 2 more.
- Why it matters
- Imported by Invoke, Parity and Projected. Run by Benchmark and Measure. Checked by Route Screen Test.
- Application
- seed-data · experiments/economical-seeds/next-invention/cable-screen · JavaScript module
- Uses
- node:child_process, node:crypto, node:fs, node:path, node:url
- Used by
- run by Benchmark (script call), imported by Route Screen Test (import), imported by Invoke (import), run by Measure (script call), imported by Parity (import), imported by Projected (import)
- Produces
- REVISION, SOURCES, loadInstruments, screen
- Defines here
- loadInstruments, positive, nonnegative, has, screen
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-invention/cable-screen/route-screen.mjs:1-128 · blob 7ff3f1271243dcc06162883d49834dbf8b118862 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: experimental · users: none · canonical: supporting_data
/** Compare declared cable-route options using three pinned SEED dependencies. */
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
export const REVISION = '00c5df92cf0c714f3e7e9824dcd170c634ce7d76';
export const SOURCES = [
{ path: 'engine/route-obstacles.js', tablet: 2689, blob: '36ab4d0b96d35c92691a048705dde56a27679f38' },
{ path: 'engine/corridor-estimate.js', tablet: 2675, blob: '6951c9652cdb7ab2a3b3e5c29450f0c97adc5395' },
{ path: 'engine/voltage-drop.js', tablet: 2692, blob: '85f48ecf7effabb47973b0a056f90e82b8196ef2' }
];
export async function loadInstruments(repo) {
const request = SOURCES.map(({path}) => REVISION + ':' + path).join('\n') + '\n';
const bodies = execFileSync('git', ['--no-lazy-fetch', '-C', repo, 'cat-file', '--batch'],
{ input: request, maxBuffer: 131072 });
let offset = 0;
const pending = SOURCES.map(({path, blob}) => {
const end = bodies.indexOf(10, offset);
if (end === -1) throw new Error('Incomplete pinned Git response');
const [id, type, sizeString] = bodies.toString('ascii', offset, end).split(' ');
const size = Number(sizeString);
const bytes = bodies.subarray(end + 1, end + 1 + size);
if (id !== blob || type !== 'blob' || !Number.isSafeInteger(size) ||
size <= 0 || size !== bytes.length || bodies[end + 1 + size] !== 10 ||
createHash('sha1').update('blob ' + size + '\0').update(bytes).digest('hex') !== blob) {
throw new Error('Missing or altered dependency: ' + path);
}
offset = end + size + 2;
return bytes;
});
if (offset !== bodies.length) throw new Error('Unexpected trailing source bytes');
// Evaluate only the three verified blobs. No mutable module path enters the loader.
const [obstacles, corridor, voltage] = await Promise.all(pending.map(bytes =>
import('data:text/javascript;base64,' + bytes.toString('base64'))));
return { obstacles, corridor, voltage, logicalSourceBytes: pending.reduce((n, body) => n + body.length, 0) };
}
const positive = value => Number.isFinite(value) && value > 0;
const nonnegative = value => Number.isFinite(value) && value >= 0;
const has = (row, key) => Object.hasOwn(row, key);
export function screen(input, { obstacles, corridor, voltage }) {
const { electrical: e, options } = input || {};
if (!e || !positive(e.currentA) || !positive(e.nominalVolts) || !positive(e.resistanceOhmPerKm) ||
!nonnegative(e.reactanceOhmPerKm) || !positive(e.powerFactor) || e.powerFactor > 1 ||
!['single', 'three'].includes(e.phases) || !Array.isArray(options) || !options.length) {
throw new TypeError('Expected a complete electrical contract and at least one route option');
}
const seen = new Set();
const rows = options.map(route => {
if (!route || typeof route.id !== 'string' || !route.id.trim() || seen.has(route.id) ||
!positive(route.straightLineKm) || !Number.isFinite(route.straightLineKm * 1000) ||
!Array.isArray(route.crossings)) throw new TypeError('Invalid or duplicate route option');
seen.add(route.id);
const declared = has(route, 'installedLengthM');
if (declared && (!positive(route.installedLengthM) ||
route.installedLengthM < route.straightLineKm * 1000)) {
throw new RangeError('Installed length must cover the stated straight-line distance');
}
for (const entry of route.crossings) {
if (!entry || typeof entry.type !== 'string' || !Object.hasOwn(obstacles.OBSTACLES, entry.type) ||
(has(entry, 'count') && (!Number.isSafeInteger(entry.count) || entry.count < 1)) ||
has(entry, 'widthM') !== has(entry, 'setbackM') ||
(has(entry, 'widthM') && (!positive(entry.widthM) || !positive(entry.setbackM))) ||
(has(entry, 'depthM') && (!has(entry, 'widthM') || !nonnegative(entry.depthM)))) {
throw new TypeError('Invalid crossing declaration');
}
}
const schedule = obstacles.crossingSchedule({ crossings: route.crossings });
if (!Number.isSafeInteger(schedule.crossingCount) || !Number.isFinite(schedule.addedLengthM)) {
throw new RangeError('Crossing totals exceed the supported range');
}
const estimate = schedule.corridorApplicable ? corridor.forCable(route.straightLineKm) : null;
if (estimate?.km !== null && estimate?.km !== undefined && !Number.isFinite(estimate.km)) {
throw new RangeError('Corridor estimate exceeds the supported range');
}
let electrical = { status: 'needs_installed_length' };
if (declared) {
const lengthM = route.installedLengthM;
const dropV = voltage.voltageDropVolts({ ...e, lengthM }).value;
const dropPct = voltage.dropPercent({ dropVolts: dropV, nominalVolts: e.nominalVolts }).value;
const lossW = voltage.lossesWatts({ ...e, lengthM }).value;
if (![dropV, dropPct, lossW].every(positive)) throw new RangeError('Electrical result exceeds the supported range');
electrical = { status: 'computed', lengthM, dropV, dropPct, lossW };
}
return {
id: route.id,
corridor: { status: !estimate ? 'blocked' : estimate.km === null ? 'below_minimum' : 'indicative',
km: estimate?.km ?? null },
crossings: { count: schedule.crossingCount, trenchless: schedule.trenchlessCount,
openCut: schedule.openCutCount, declaredLengthM: schedule.addedLengthM,
undeclaredCount: schedule.items.reduce((n, entry) => n + (entry.lengthDeclared ? 0 : entry.count), 0) },
electrical
};
});
const lowest = rows.reduce((minimum, row) => Math.min(minimum, row.electrical.lossW ?? Infinity), Infinity);
return { options: rows, lowestLossIds: rows.filter(row => row.electrical.lossW === lowest)
.map(row => row.id).sort() };
}
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
const [input, repo, ...extra] = process.argv.slice(2);
if (!input || !repo || extra.length) {
console.error('Usage: node route-screen.mjs <declared-input.json> <engine-git-checkout>');
process.exitCode = 2;
} else {
try {
const request = JSON.parse(readFileSync(input, 'utf8'));
const runtime = await loadInstruments(repo);
console.log(JSON.stringify({ ...screen(request, runtime), provenance: {
repository: 'Ventusltd/ventus-grid-engine', revision: REVISION, sources: SOURCES }
}, null, 2));
} catch (error) {
console.error(error.message);
process.exitCode = 1;
}
}
}
Route Screen Test
A test in the cable screen folder of Seed Data that checks Route Screen and Baseline.
testseed-data / experiments/economical-seeds/next-invention/cable-screen/route-screen.test.mjs · lines 1–86 of 86 · Entry point · pattern composed (shared by 4 files)
- What it does
- It tests its inputs. Defines composed, equivalent. Uses libraries node:fs, node:test. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: JSON file fixture.json.
- Downstream impact
- Used directly by 1 file: Seed Regressions Workflow (seed-data).
- What it achieves
- Defines `composed` and `equivalent`. It reads `./fixture.json`.
- Why it matters
- Run by Seed Regressions Workflow.
- Application
- seed-data · experiments/economical-seeds/next-invention/cable-screen · test
- Uses
- Route Screen (import), Baseline (import), node:fs, node:test
- Used by
- run by Seed Regressions Workflow (workflow run)
- Produces
- composed, equivalent
- Defines here
- composed, equivalent
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/economical-seeds/next-invention/cable-screen/route-screen.test.mjs:1-86 · blob 529424b90096673d754d5ee9dc4a1691c2386f8b · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: supporting_data
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { test } from 'node:test';
import { loadInstruments, screen } from './route-screen.mjs';
import { screen as conventional } from './baseline.mjs';
const repo = process.env.VENTUS_ENGINE_REPO;
assert(repo, 'Set VENTUS_ENGINE_REPO to a checkout containing the pinned Git commit');
const dependencies = await loadInstruments(repo);
const fixture = JSON.parse(readFileSync(new URL('./fixture.json', import.meta.url), 'utf8'));
const composed = input => screen(input, dependencies);
function equivalent(actual, expected, at = 'result') {
if (typeof expected === 'number') {
assert(Math.abs(actual - expected) <= 1e-10 * Math.max(1, Math.abs(expected)), at);
} else if (expected && typeof expected === 'object') {
assert.deepEqual(Object.keys(actual).sort(), Object.keys(expected).sort(), at);
for (const key of Object.keys(expected)) equivalent(actual[key], expected[key], at + '.' + key);
} else {
assert.equal(actual, expected, at);
}
}
test('model produces hand-checked voltage, loss and crossing length', () => {
const answer = composed(fixture);
const first = answer.options[0];
equivalent(first.electrical, { status: 'computed', lengthM: 1000, dropV: 44, dropPct: 4.4, lossW: 4000 });
assert.equal(first.crossings.declaredLengthM, 60);
assert.equal(first.corridor.km, 1.245);
assert.deepEqual(answer.lowestLossIds, ['alternative-land', 'land']);
});
test('marine refusal affects only the corridor and keeps declared-length arithmetic', () => {
const water = composed(fixture).options[1];
assert.deepEqual(water.corridor, { status: 'blocked', km: null });
assert.equal(water.crossings.undeclaredCount, 2);
assert.equal(water.electrical.lossW, 6000);
});
test('straight-line and indicative corridor lengths never become electrical inputs', () => {
const row = composed(fixture).options[2];
assert.deepEqual(row.corridor, { status: 'below_minimum', km: null });
assert.deepEqual(row.electrical, { status: 'needs_installed_length' });
const noMeasurements = structuredClone(fixture);
for (const item of noMeasurements.options) delete item.installedLengthM;
assert.deepEqual(composed(noMeasurements).lowestLossIds, []);
});
test('independently authored comparator matches both phase modes and deep crossing quantities', () => {
equivalent(composed(fixture), conventional(fixture));
const varied = structuredClone(fixture);
varied.electrical.phases = 'three';
varied.options[0].crossings[0].depthM = 8;
varied.options[0].crossings[0].count = 2;
const output = composed(varied);
equivalent(output, conventional(varied));
equivalent(output.options[0].crossings.declaredLengthM, 4 * Math.sqrt(30 ** 2 + 8 ** 2));
equivalent(output.options[0].electrical.lossW, 6000);
equivalent(output.options[0].electrical.dropV, Math.sqrt(3) * 22);
});
test('both paths refuse incomplete, contradictory or unsupported declarations', () => {
const edits = [
a => { delete a.electrical.reactanceOhmPerKm; },
a => { a.electrical.powerFactor = 80; },
a => { a.electrical.currentA = Number.MAX_VALUE; },
a => { a.options[1].id = 'land'; },
a => { a.options[0].installedLengthM = 999; },
a => { a.options[0].crossings[0].type = '__proto__'; },
a => { delete a.options[0].crossings[0].setbackM; },
a => { a.options[0].crossings[0].count = 0; },
a => { a.options[0].crossings[0].count = Number.MAX_SAFE_INTEGER + 1; },
a => { a.options[0].crossings[0].widthM = Number.MAX_VALUE;
a.options[0].crossings[0].setbackM = Number.MAX_VALUE; }
];
for (const edit of edits) {
const sample = structuredClone(fixture);
edit(sample);
assert.throws(() => composed(sample));
assert.throws(() => conventional(sample));
}
});
test('expected source is unavailable in an unrelated checkout', async () => {
await assert.rejects(() => loadInstruments(process.cwd()), /Missing or altered dependency|git/i);
});
Explain
A JavaScript module in the followup folder of Seed Data that reads cables, using SHA-256.
ingestseed-data / experiments/explain-cable-screen-change/followup/explain.mjs · lines 1–87 of 87 · Not reached from any entry point (candidate for review) · pattern explain (shared by 7 files)
- What it does
- It loads cables. Defines 8 functions or classes, including num, bounds, validate, result, describe. Uses libraries node:crypto, node:fs. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables.
- Downstream impact
- Used directly by 1 file: Trial (seed-data).
- What it achieves
- It is built from the result step (`result`), the describe step (`describe`) and the exact step (`exact`). Defines `num`, `bounds`, `validate` and 5 more.
- Why it matters
- Run by Trial.
- Application
- seed-data · experiments/explain-cable-screen-change/followup · JavaScript module
- Uses
- Session (import), node:crypto, node:fs
- Used by
- run by Trial (script call), mentioned in Standalone (comment link)
- Produces
- explain
- Defines here
- num, bounds, validate, result, describe, exact, explain, metres
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/explain-cable-screen-change/followup/explain.mjs:1-87 · blob 83da918efd047fb93a8be82641dda211ad170bf7 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
import { packet } from './session.mjs';
import { createHash } from 'node:crypto';
import { readFileSync } from 'node:fs';
const root = new URL('../../economical-seeds/next-invention/', import.meta.url);
const pinned = {
'reduction/projected.mjs': 'e3ac6314fcefc1351c6c6b3c569e630bf96f6160d66f8392c7a3f7ad36615c3f',
'cable-screen/route-screen.mjs': '315ab43679156e2ba19516e7d76526bbd305dc78bf2a02ed8094cb760139f7b8',
};
for (const [rel, digest] of Object.entries(pinned)) {
const actual = createHash('sha256').update(readFileSync(new URL(rel, root))).digest('hex');
if (actual !== digest) throw new Error('Screener source differs from pin');
}
const { prepareProjectedScreen } = await import(new URL('reduction/projected.mjs', root));
const screen = await prepareProjectedScreen(process.env.EXPLAIN_ENGINE || 'ventus-grid-engine');
const num = v => Number(v.toFixed(6));
const bounds = (n, low, high) => Number.isFinite(n) && n >= low && n <= high;
function validate(input) {
if (!input || typeof input !== 'object' || Object.keys(input).sort().join() !== 'after,before') {
throw new Error('Expected before and after scenarios');
}
for (const side of [input.before, input.after]) {
if (!side || typeof side !== 'object' ||
Object.keys(side).some(key => key !== 'currentA' && key !== 'lengthM') ||
!bounds(side.currentA, 1, 1000) || (Object.hasOwn(side, 'lengthM') && !bounds(side.lengthM, 1000, 10000))) {
throw new Error('Invalid current or declared installed length');
}
}
}
function result(side) {
const route = { id: 'fictional', straightLineKm: 1, crossings: [] };
if (Object.hasOwn(side, 'lengthM')) route.installedLengthM = side.lengthM;
return screen({
electrical: { currentA: side.currentA, nominalVolts: 1000, resistanceOhmPerKm: 0.2,
reactanceOhmPerKm: 0.1, powerFactor: 0.8, phases: 'single' },
options: [route],
}).options[0].electrical;
}
const describe = r => r.status === 'computed' ? num(r.dropV) + ' V and ' + num(r.lossW) + ' W' : 'unavailable';
const exact = (a,b) => a.dropV === b.dropV && a.lossW === b.lossW;
export async function explain(input, session, version = 'v1') {
validate(input);
const {before, after} = input, changes = [];
const length = before.lengthM !== after.lengthM, current = before.currentA !== after.currentA;
const metres = v => v === undefined ? 'unknown' : num(v) + ' m';
if (length) changes.push('Installed length ' + metres(before.lengthM) + ' to ' + metres(after.lengthM));
if (current) changes.push((length ? 'current ' : 'Current ') + num(before.currentA) + ' A to ' + num(after.currentA) + ' A');
const scope = JSON.stringify([before.currentA, before.lengthM, after.currentA, after.lengthM]);
const work = await session.exchange(packet({
before_length: Object.hasOwn(before, 'lengthM'),
after_length: Object.hasOwn(after, 'lengthM')
}, version, scope));
if (work.status !== 'ok') throw new Error(work.reason);
const { coverage } = work;
const a = result(before), b = result(after);
if (coverage.before_length !== (a.status === 'computed') || coverage.after_length !== (b.status === 'computed')) {
throw new Error('Evidence and screener disagree');
}
let difference, reason;
if (!coverage.before_length || !coverage.after_length) {
difference = 'Before: ' + describe(a) + '. After: ' + describe(b) + '.';
const missing = !coverage.before_length && !coverage.after_length ? 'Both cases need'
: coverage.before_length ? 'The after case needs' : 'The before case needs';
reason = missing + ' a declared installed length. The change cannot be explained.';
} else {
difference = 'Voltage drop ' + num(a.dropV) + ' V to ' + num(b.dropV)
+ ' V; loss ' + num(a.lossW) + ' W to ' + num(b.lossW) + ' W.';
if (!length && !current) {
if (!exact(a,b)) throw new Error('Identical inputs produced different results');
reason = 'The model returned the same result. There is no change to explain.';
} else if (length && current) {
const l = result({...before, lengthM: after.lengthM}), c = result({...before, currentA: after.currentA});
reason = 'With the before case as the baseline, length alone produced ' + describe(l)
+ '; current alone produced ' + describe(c) + '. These replays do not establish a unique split of the joint change.';
} else {
const replay = result(length ? {...before, lengthM: after.lengthM} : {...before, currentA: after.currentA});
if (!exact(replay,b)) throw new Error('Controlled replay failed to reproduce result');
reason = 'Changing only ' + (length ? 'installed length' : 'current') + ' in the model reproduced the result.';
}
}
const text = 'Inputs: ' + (changes.length ? changes.join('; ') + '.' : 'No changes.')
+ '\nResult: ' + difference + '\nEvidence: ' + reason;
return { text, work };
}Session
A JavaScript module in the followup folder of Seed Data that reads cables, using SHA-256. It is built from the open step (`open`) and the next step (`next`).
ingestseed-data / experiments/explain-cable-screen-change/followup/session.mjs · lines 1–57 of 57 · Not reached from any entry point (candidate for review)
- What it does
- It loads cables. Defines here, hash, packet, open, next. Uses libraries node:child_process, node:crypto, node:events, node:readline, node:url. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables.
- Downstream impact
- Used directly by 2 files: Explain (seed-data); Trial (seed-data).
- What it achieves
- Defines `here`, `hash`, `packet` and 2 more.
- Why it matters
- Imported by Explain. Run by Trial.
- Application
- seed-data · experiments/explain-cable-screen-change/followup · JavaScript module
- Uses
- Identify Missing Evidence (script call), node:child_process, node:crypto, node:events, node:readline, node:url
- Used by
- imported by Explain (import), run by Trial (script call)
- Produces
- packet, open
- Defines here
- here, hash, packet, open, next
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/explain-cable-screen-change/followup/session.mjs:1-57 · blob 467a948f95fb06db6e4928c5d249be670a2778d6 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
import { spawn } from 'node:child_process';
import { createHash } from 'node:crypto';
import { once } from 'node:events';
import { createInterface } from 'node:readline';
import { fileURLToPath } from 'node:url';
const here = rel => fileURLToPath(new URL(rel, import.meta.url));
const metrics = ['before_length', 'after_length'];
const hash = value => createHash('sha256').update(value).digest('hex');
export function packet(flags, version = 'v1', scope = '') {
const payloads = {}, subject = 'fictional-cable', time = '2026-11-28T00:00:00Z';
const evidence = metrics.map(metric => {
const row = { id: metric, metric, source: 'validated_case_input:' + hash(scope), state: 'missing' };
if (!flags[metric]) return row;
const path = metric + '.json';
const raw = JSON.stringify({ subject, metric, observed_at: time, value: 1, unit: 'flag' });
payloads[path] = raw;
return { ...row, state: 'observed', path, observed_at: time, sha256: hash(raw), bytes: Buffer.byteLength(raw) };
});
const manifest = JSON.stringify({ schema: 'seed.synthetic-bench-evidence.v1', subject, evidence });
return { version, manifest, digest: hash(manifest), payloads };
}
export async function open(mode) {
const child = spawn(process.env.EXPLAIN_PYTHON || 'python', [
'-u', here('worker.py'),
here('../../economical-seeds/next-invention/reduction/sufficiency/identify_missing_evidence.py'), mode,
], { stdio: ['pipe', 'pipe', 'inherit'] });
const reader = createInterface({ input: child.stdout });
const replies = reader[Symbol.asyncIterator]();
const exited = once(child, 'close');
exited.catch(() => {});
async function next() {
const reply = await Promise.race([replies.next(), exited.then(() => ({ done: true }))]);
if (reply.done) throw new Error('Persistent evidence adapter ended before replying');
return JSON.parse(reply.value);
}
try {
const ready = await next();
if (ready.status !== 'ready' || ready.mode !== mode) throw new Error('Unexpected evidence adapter handshake');
} catch (error) {
child.kill();
throw error;
}
return {
async exchange(value) {
child.stdin.write(JSON.stringify(value) + '\n');
return next();
},
async close() {
child.stdin.end();
await exited;
reader.close();
},
};
}Trial
A JavaScript module in the followup folder of Seed Data that reads acceptance and after length, using SHA-256.
storageseed-data / experiments/explain-cable-screen-change/followup/trial.mjs · lines 1–104 of 104 · Not reached from any entry point (candidate for review)
- What it does
- It loads acceptance and after length. Defines acceptance, work, measurement. Uses libraries node:child_process, node:crypto, node:fs, node:url, node:perf_hooks. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: JSON file acceptance.json; JSON file after_length.json; command-line arguments.
- What it achieves
- Defines `acceptance`, `work` and `measurement`. It reads `../original/acceptance.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- seed-data · experiments/explain-cable-screen-change/followup · JavaScript module
- Uses
- Session (script call), Explain (script call), node:child_process, node:crypto, node:fs, node:url, node:perf_hooks
- Used by
- none found
- Produces
- acceptance, work, measurement
- Defines here
- acceptance, work, measurement
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/explain-cable-screen-change/followup/trial.mjs:1-104 · blob bd1befdeab64f5961845b53a033fbe303a656f25 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { performance } from 'node:perf_hooks';
import { open, packet } from './session.mjs';
const contract = readFileSync(new URL('../original/acceptance.json', import.meta.url));
assert.equal(createHash('sha256').update(contract).digest('hex'),
'0dc63a1b98d1606eaf642b681f153e660d9adfb0075c2327cc34c4c742adfcbf');
const cases = JSON.parse(contract);
const joint = cases.cases.find(row => row.id === 'joint');
async function acceptance(mode) {
const { explain } = await import('./explain.mjs');
const session = await open(mode);
try {
for (const {input, expected} of cases.cases) assert.equal((await explain(input, session)).text, expected);
for (const input of cases.refusals) await assert.rejects(() => explain(input, session));
const flags = { before_length: true, after_length: true };
const v1 = packet(flags, 'v1', 'changed-evidence-control');
const v2 = packet(flags, 'v2', 'changed-evidence-control');
assert.equal(v1.digest, v2.digest);
const first = await session.exchange(v1);
assert.equal(first.full_verifications, 1);
const repeat = await session.exchange(v1);
assert.equal(repeat.cache_hit, mode === 'reuse');
const differentVersion = await session.exchange(v2);
assert.equal(differentVersion.full_verifications, 1);
assert.equal(differentVersion.cache_hit, false);
const changed = structuredClone(v1);
const key = 'after_length.json';
changed.payloads[key] = changed.payloads[key].replace('"value":1', '"value":0');
assert.notEqual(changed.payloads[key], v1.payloads[key]);
assert.equal(Buffer.byteLength(changed.payloads[key]), Buffer.byteLength(v1.payloads[key]));
const refusal = await session.exchange(changed);
assert.deepEqual(refusal, { status: 'refused', reason: 'Changed evidence payload' });
const afterRefusal = await session.exchange(v1);
assert.equal(afterRefusal.cache_hit, mode === 'reuse');
assert.deepEqual(afterRefusal.coverage, first.coverage);
return { golden: cases.cases.length, refusedInputs: cases.refusals.length,
repeatWasHit: repeat.cache_hit, sameDigestNewVersionWasReverified: true,
unchangedManifestSameSizeTamper: refusal, originalResultRecoveredAfterRefusal: true };
} finally {
await session.close();
}
}
function work(rows) {
const keys = ['full_verifications', 'manifest_bytes', 'payload_bytes_hashed', 'prototype_payload_bytes'];
return Object.fromEntries(keys.map(k => [k, rows.reduce((sum, row) => sum + row[k], 0)]));
}
async function measurement(mode) {
const init = performance.now();
const { explain } = await import('./explain.mjs');
const session = await open(mode);
const startupMs = performance.now() - init;
try {
const start = performance.now();
const first = await explain(joint.input, session);
const firstMs = performance.now() - start;
assert.equal(first.text, joint.expected);
assert.equal(first.work.full_verifications, 1);
const repeated = [], repeatStart = performance.now();
for (let i = 0; i < 8; i++) {
const result = await explain(joint.input, session);
assert.equal(result.text, joint.expected);
assert.equal(result.work.cache_hit, mode === 'reuse');
repeated.push(result.work);
}
return { mode, startupMs, firstMs, repeatedMs: performance.now()-repeatStart,
first: work([first.work]), repeated: work(repeated) };
} finally {
await session.close();
}
}
const [, , arg, mode] = process.argv;
if (arg === '--worker') {
console.log(JSON.stringify(await measurement(mode)));
} else {
assert(arg, 'Usage: node trial.mjs <new-receipt.json>');
const checks = { verify: await acceptance('verify'), reuse: await acceptance('reuse') };
const samples = [];
for (let i = 0; i < 5; i++) {
for (const nextMode of i % 2 ? ['reuse','verify'] : ['verify','reuse']) {
const result = execFileSync(process.execPath, [fileURLToPath(import.meta.url), '--worker', nextMode],
{ encoding: 'utf8', timeout: 20000 });
samples.push(JSON.parse(result));
}
}
const medians = {};
for (const k of ['verify','reuse']) {
const subset = samples.filter(row => row.mode === k);
medians[k] = Object.fromEntries(['startupMs', 'firstMs', 'repeatedMs'].map(field =>
[field, subset.map(row => row[field]).sort((a,b)=>a-b)[2]]));
}
const receipt = { checks, medians, samples, platform:process.platform,node:process.version,
scope: 'Five interleaved Node workers per mode. Startup ends at persistent adapter ready, including screener imports and exact Git blob checks, excluding Node process launch. First explanation starts on a cold evidence cache. Repeat is eight calls on the same fixture. Every request verifies manifest hash and actual body hashes before lookup. The cache is process-local with fixed policy, date, … [line shortened here: 424 characters; full line on GitHub]
writeFileSync(arg, JSON.stringify(receipt,null,2)+'\n',{flag:'wx'});
console.log(JSON.stringify({checks,medians},null,2));
}
Worker
A Python command-line tool in the followup folder of Seed Data covering cables, using SHA-256. It is built from the adapter class (`Adapter`) and the reply step (`reply`).
storageseed-data / experiments/explain-cable-screen-change/followup/worker.py · lines 1–110 of 110 · Entry point · pattern reply (shared by 2 files)
- What it does
- Defines 6 functions or classes, including sha, emit, Adapter, __init__, reply. Uses libraries collections, hashlib, json, pathlib, sys. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Defines `sha`, `emit`, `Adapter` and 1 more.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- seed-data · experiments/explain-cable-screen-change/followup · Python CLI
- Uses
- collections, hashlib, json, pathlib, sys, tempfile
- Used by
- none found
- Produces
- sha, emit, Adapter, main
- Defines here
- sha, emit, Adapter, __init__, reply, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/explain-cable-screen-change/followup/worker.py:1-110 · blob 5b6c7e137407dca918b93560cb109c2bd2698be4 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: supporting_data
"""Verify a bounded evidence packet; share work only for the same digest and version."""
from collections import OrderedDict
import hashlib
import json
from pathlib import Path
import sys
import tempfile
PIN = "4e1460f1064550367492463e907ce4e0d7e9b6af630783ebfcb3426e3e551a2b"
QUESTION = "explain-cable-declared-length-v1"
WHEN = "2026-11-28T00:00:00Z"
METRICS = ("before_length", "after_length")
CAP = 512
def sha(data):
return hashlib.sha256(data).hexdigest()
def emit(data):
print(json.dumps(data, separators=(",", ":")), flush=True)
class Adapter:
def __init__(self, source, reuse):
if sha(source) != PIN:
raise ValueError("Evidence implementation differs from its pin")
module = {}
exec(compile(source, "pinned-lei04", "exec"), module)
module["QUESTION"] = QUESTION
module["PREDICATES"] = {m: {"unit": "flag", "op": ">=", "threshold": 1} for m in METRICS}
self.assess = module["assess"]
self.decode = module["decode"]
self.reuse = reuse
self.cache = OrderedDict()
def reply(self, packet):
if (not isinstance(packet, dict) or set(packet) != {"version", "manifest", "digest", "payloads"}
or packet["version"] not in ("v1", "v2") or not isinstance(packet["manifest"], str)
or not isinstance(packet["digest"], str) or not isinstance(packet["payloads"], dict)):
raise ValueError("Invalid packet or unsupported version")
manifest = packet["manifest"].encode()
if sha(manifest) != packet["digest"]:
raise ValueError("Changed manifest")
data = self.decode(manifest)
if not isinstance(data, dict) or data.get("subject") != "fictional-cable":
raise ValueError("Invalid manifest subject")
rows = data.get("evidence")
if not isinstance(rows, list) or len(rows) != len(METRICS):
raise ValueError("Expected two indexed facts")
bodies = {}
for metric, row in zip(METRICS, rows):
if not isinstance(row, dict) or row.get("metric") != metric:
raise ValueError("Unexpected metric")
state = row.get("state")
if state == "missing":
continue
path = metric + ".json"
if state != "observed" or row.get("path") != path:
raise ValueError("Unexpected evidence locator or state")
supplied = packet["payloads"].get(path)
if not isinstance(supplied, str):
raise ValueError("Missing indexed evidence")
raw = supplied.encode()
if len(raw) != row.get("bytes") or sha(raw) != row.get("sha256"):
raise ValueError("Changed evidence payload")
bodies[path] = raw
count = sum(map(len, bodies.values()))
if set(bodies) != set(packet["payloads"]) or count > CAP:
raise ValueError("Unexpected evidence or exhausted byte budget")
# Manifest binds the body hashes. Each body is hashed before the lookup.
# Code pin, policy, subject, as-of time and budget are fixed for this worker.
key = (packet["version"], packet["digest"])
work = dict(manifest_bytes=len(manifest), payload_bytes_hashed=count)
if self.reuse and key in self.cache:
self.cache.move_to_end(key)
return dict(status="ok", coverage=self.cache[key], cache_hit=True,
full_verifications=0, prototype_payload_bytes=0, **work)
with tempfile.TemporaryDirectory() as folder:
path = Path(folder)
for name, raw in bodies.items():
(path / name).write_bytes(raw)
req = dict(question=QUESTION, subject="fictional-cable", as_of=WHEN, max_age_seconds=0,
max_payload_bytes=CAP, manifest_sha256=packet["digest"])
verified = self.assess(req, manifest, path)
coverage = {p["metric"]: p["status"] == "supported" for p in verified["predicates"]}
if self.reuse:
self.cache[key] = coverage
if len(self.cache) > 16:
self.cache.popitem(last=False)
return dict(status="ok", coverage=coverage, cache_hit=False, full_verifications=1,
prototype_payload_bytes=verified["resources"]["payload_bytes"], **work)
def main():
source, mode = sys.argv[1:]
if mode not in ("verify", "reuse"):
raise ValueError("Invalid adapter mode")
engine = Adapter(Path(source).read_bytes(), mode == "reuse")
emit({"status": "ready", "mode": mode})
for line in sys.stdin:
try:
emit(engine.reply(engine.decode(line)))
except (ValueError, OSError) as error:
emit({"status": "refused", "reason": str(error)})
if __name__ == "__main__":
main()
Check
A JavaScript module in the original folder of Seed Data that reads acceptance and request, using SHA-256.
storageseed-data / experiments/explain-cable-screen-change/original/check.mjs · lines 1–38 of 38 · Not reached from any entry point (candidate for review)
- What it does
- It loads acceptance and request. Uses libraries node:child_process, node:crypto, node:fs, node:os, node:path. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow.
- Inputs & outputs
- In: JSON file acceptance.json; JSON file request.json; command-line arguments.
- What it achieves
- It reads `acceptance.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- seed-data · experiments/explain-cable-screen-change/original · JavaScript module
- Uses
- node:child_process, node:crypto, node:fs, node:os, node:path, node:url
- Used by
- none found
- Produces
- none declared
- Defines here
- none
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/explain-cable-screen-change/original/check.mjs:1-38 · blob 5a801aff48997ab097200692fd41df2a3e496947 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: experimental · users: none · canonical: unreached_review
import assert from 'node:assert/strict';
import { execFileSync, spawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
const raw = readFileSync(new URL('acceptance.json', import.meta.url));
assert.equal(createHash('sha256').update(raw).digest('hex'),
'0dc63a1b98d1606eaf642b681f153e660d9adfb0075c2327cc34c4c742adfcbf');
const spec = JSON.parse(raw);
const arms = process.argv.slice(2);
assert(arms.length, 'Give one or more arm filenames');
const scratch = mkdtempSync(join(tmpdir(), 'explain-change-'));
const results = {};
try {
for (const arm of arms) {
const url = new URL(arm, import.meta.url);
const { explain } = await import(url);
for (const row of spec.cases) assert.equal(explain(row.input), row.expected, arm + ': ' + row.id);
for (const input of spec.refusals) assert.throws(() => explain(input), arm);
const file = join(scratch, 'request.json');
const joint = spec.cases.find(row => row.id === 'joint');
writeFileSync(file, JSON.stringify(joint.input));
const args = [fileURLToPath(url), file];
assert.equal(execFileSync(process.execPath, args, { encoding:'utf8' }).trimEnd(), joint.expected);
writeFileSync(file, JSON.stringify(spec.refusals[0]));
const rejection = spawnSync(process.execPath, args, { encoding:'utf8' });
assert.notEqual(rejection.status, 0);
assert.equal(rejection.stdout, '');
results[arm] = { successfulFixtures: spec.cases.length, refusals: spec.refusals.length,
identicalCliWitness: joint.id, invalidCliWithoutSuccessfulOutput: true };
}
} finally {
rmSync(scratch, { recursive: true });
}
console.log(JSON.stringify(results, null, 2));
Evidence Adapter
A Python module in the original folder of Seed Data covering cables, using SHA-256.
storageseed-data / experiments/explain-cable-screen-change/original/evidence_adapter.py · lines 1–51 of 51 · Not reached from any entry point (candidate for review) · pattern encode (shared by 21 files)
- What it does
- Defines encode, sha. Uses libraries hashlib, json, pathlib, sys, tempfile. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage experimental (path word 'experiments'): work its own path marks as experimental (sandbox, prototype, archive or similar words); by this evidence it is not part of a production workflow. Domain terms in the code: cables.
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- Used directly by 1 file: Reuse (seed-data).
- What it achieves
- Defines `encode` and `sha`.
- Why it matters
- Run by Reuse.
- Application
- seed-data · experiments/explain-cable-screen-change/original · Python module
- Uses
- hashlib, json, pathlib, sys, tempfile
- Used by
- run by Reuse (script call)
- Produces
- encode, sha
- Defines here
- encode, sha
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- seed-data@e4af7ee340a38d94f21ddbba147395b569ccce11 experiments/explain-cable-screen-change/original/evidence_adapter.py:1-51 · blob ead6180488f6e54ef487721212d2fd80663e543c · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: experimental · users: none · canonical: unreached_review
"""Reuse LEI-04 for fixture length-presence facts, without changing its source."""
import hashlib
import json
from pathlib import Path
import sys
import tempfile
PIN = "4e1460f1064550367492463e907ce4e0d7e9b6af630783ebfcb3426e3e551a2b"
QUESTION = "explain-cable-declared-length-v1"
WHEN = "2026-11-28T00:00:00Z"
def encode(value):
return json.dumps(value, separators=(",", ":")).encode()
def sha(raw):
return hashlib.sha256(raw).hexdigest()
source = Path(sys.argv[1]).read_bytes()
if sha(source) != PIN:
raise SystemExit("Evidence implementation differs from its pin")
module = {}
exec(compile(source, "pinned-lei04", "exec"), module)
present = json.loads(sys.stdin.buffer.read())
metrics = ("before_length", "after_length")
if set(present) != set(metrics) or any(type(v) is not bool for v in present.values()):
raise SystemExit("Expected two declared presence flags")
module["QUESTION"] = QUESTION
module["PREDICATES"] = {metric: {"unit": "flag", "op": ">=", "threshold": 1} for metric in metrics}
subject = "fictional-cable"
with tempfile.TemporaryDirectory() as scratch:
path = Path(scratch)
rows = []
for metric in metrics:
row = {"id": metric, "metric": metric, "source": "validated_case_input", "state": "missing"}
if present[metric]:
payload = encode({"subject": subject, "metric": metric, "observed_at": WHEN,
"value": 1, "unit": "flag"})
filename = metric + ".json"
(path / filename).write_bytes(payload)
row.update(state="observed", observed_at=WHEN, path=filename, sha256=sha(payload),
bytes=len(payload))
rows.append(row)
manifest = encode({"schema": "seed.synthetic-bench-evidence.v1", "subject": subject, "evidence": rows})
request = dict(question=QUESTION, subject=subject, as_of=WHEN, max_age_seconds=0,
max_payload_bytes=512, manifest_sha256=sha(manifest))
result = module["assess"](request, manifest, path)
print(json.dumps({p["metric"]: p["status"] == "supported" for p in result["predicates"]}))