In this section
- Measure storage · seed-data / experiments/economical-seeds/next-invention/reduction/measure.mjs lines 1–53
- Transfer other · seed-data / experiments/economical-seeds/next-invention/reduction/ordinal/transfer.mjs lines 1–243
- Parity ingest · seed-data / experiments/economical-seeds/next-invention/reduction/parity.mjs lines 1–71
- Projected electrical · seed-data / experiments/economical-seeds/next-invention/reduction/projected.mjs lines 1–56
- Identify Missing Evidence ingest · seed-data / experiments/economical-seeds/next-invention/reduction/sufficiency/identify_missing_evidence.py lines 1–246
Measure
A JavaScript module in the reduction folder of Seed Data that reads fixture and cables.
storageseed-data / experiments/economical-seeds/next-invention/reduction/measure.mjs · lines 1–53 of 53 · Not reached from any entry point (candidate for review)
- What it does
- It loads fixture and cables. Uses libraries node:child_process, 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. Domain terms in the code: cables.
- Inputs & outputs
- In: JSON file fixture.json; command-line arguments.
- What it achieves
- It reads `../cable-screen/fixture.json`.
- Why it matters
- No other file in the estate was found to import it.
- Application
- seed-data · experiments/economical-seeds/next-invention/reduction · JavaScript module
- Uses
- Route Screen (script call), Projected (script call), node:child_process, node:fs, node:url, node:perf_hooks
- 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/economical-seeds/next-invention/reduction/measure.mjs:1-53 · blob 9d5ef4ca517c842dde86e61c1364ce7494a6ce4d · 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 { readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { performance } from 'node:perf_hooks';
import { loadInstruments, screen } from '../cable-screen/route-screen.mjs';
import { project } from './projected.mjs';
const fixture = JSON.parse(readFileSync(new URL('../cable-screen/fixture.json', import.meta.url)));
const n = 1024;
const here = fileURLToPath(import.meta.url);
if (process.argv[2] === '--worker') {
const mode = process.argv[3];
const t0 = performance.now();
const runtime = await loadInstruments(process.argv[4]);
const provider = mode === 'projected' ? project(runtime) : runtime;
const setupMs = performance.now() - t0;
const result = screen(fixture, provider);
for (let i = 0; i < 128; i++) screen(fixture, provider);
const cpu = process.cpuUsage();
const t1 = performance.now();
let witness = 0;
for (let i = 0; i < n; i++) witness += screen(fixture, provider).options[0].electrical.lossW;
const warmMs = performance.now() - t1;
const used = process.cpuUsage(cpu);
assert.equal(witness, result.options[0].electrical.lossW * n);
console.log(JSON.stringify({ mode, setupMs, warmMs, cpuUs: used.user + used.system,
peakProcessBytes: process.resourceUsage().maxRSS * 1024,
pinnedInputBytes: runtime.logicalSourceBytes, result }));
} else {
const [checkout, outfile] = process.argv.slice(2);
assert(checkout && outfile, 'Usage: node measure.mjs <engine-checkout> <new-receipt.json>');
const samples = [];
for (let i = 0; i < 5; i++) {
const order = i % 2 ? ['projected', 'reference'] : ['reference', 'projected'];
for (const mode of order) samples.push(JSON.parse(execFileSync(process.execPath,
[here, '--worker', mode, checkout], { encoding: 'utf8' })));
}
for (const row of samples) assert.deepEqual(row.result, samples[0].result);
const medians = {};
for (const mode of ['reference', 'projected']) {
const group = samples.filter(row => row.mode === mode);
medians[mode] = Object.fromEntries(['setupMs', 'warmMs', 'cpuUs', 'peakProcessBytes',
'pinnedInputBytes'].map(field => [field, group.map(x => x[field]).sort((a, b) => a - b)[2]]));
}
writeFileSync(outfile, JSON.stringify({
medians, batches: 5, invocationsPerWarmBatch: n, node: process.version, platform: process.platform,
limits: 'Interleaved fresh workers. Setup performs the same Git pin checks in both modes. Reported CPU and memory describe Node. Timing is host- and workload-dependent. Energy unmeasured.',
samples: samples.map(({result, ...row}) => row)
}, null, 2) + '\n', { flag: 'wx' });
console.log(JSON.stringify(medians, null, 2));
}
Transfer
A JavaScript module in the ordinal folder of Seed Data that finds chronology alias (`findChronologyAlias`), covering Kuiper and wafer meta, using SHA-256.
otherseed-data / experiments/economical-seeds/next-invention/reduction/ordinal/transfer.mjs · lines 1–243 of 243 · Not reached from any entry point (candidate for review) · pattern prefix (shared by 3 files)
- What it does
- It lists and searches Kuiper and wafer meta. Defines 12 functions or classes, including blob, sha256, table, prefix, locate. Uses libraries node:assert/strict, node:child_process, node:crypto, node:vm. Side effects: 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 universe.json; JSON file kuiper.json; JSON file wafer.json; JSON file wafer-meta.json; command-line arguments.
- What it achieves
- It finds chronology alias (`findChronologyAlias`) and is built from the prefix step (`prefix`) and the locate step (`locate`). Defines `blob`, `sha256`, `table` and 9 more.
- Why it matters
- No other file in the estate was found to import it.
- Application
- seed-data · experiments/economical-seeds/next-invention/reduction/ordinal · JavaScript module
- Uses
- node:assert/strict, node:child_process, node:crypto, node:vm
- Used by
- none found
- Produces
- blob, sha256, table, prefix, locate, widths, addressWidth, phase32, phase64, oracle, legacyWord, findChronologyAlias
- Defines here
- blob, sha256, table, prefix, locate, widths, addressWidth, phase32, phase64, oracle, legacyWord, findChronologyAlias
- 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/reduction/ordinal/transfer.mjs:1-243 · blob 0ca0112cffb38ddae83aa7a9377a1a31d1245936 · GitHub at these lines
- State
- achieves: name · context: readme_derived · stage: unknown · effects: 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 { runInNewContext } from 'node:vm';
const A32 = 1n << 32n;
const MASK = A32 - 1n;
const PINS = {
cosmic: 'dbe20b06c1ac107e902b93354f8e8a37b0462ad0',
kuiper: 'f7a4cb9e3a764a72b7133bb275bb5387ea083be2',
particle: '34153fcbd5e91e4aead765fba9e9d0cac1ebf5ec',
};
const PARTICLE_BLOB = '3de6ed7d81591ffa737656e229858acb278dae4f';
const PARTICLE_SHA = '867bb83466a9dbc35e86952b496b8f498fc0cc289f9d81cd1dcebdc21552db26';
const [, , cosmic, kuiper, particle, ...rest] = process.argv;
if (!cosmic || !kuiper || !particle || rest.length) {
throw new Error('Usage: node transfer.mjs <cosmic-checkout> <kuiper-belt-checkout> <particle-checkout>');
}
const checkouts = {cosmic, kuiper, particle};
const read = [];
function blob(project, path) {
const sha256 = bytes => createHash('sha256').update(bytes).digest('hex');
const bytes = execFileSync('git', ['-C', checkouts[project], 'show', PINS[project] + ':' + path],
{maxBuffer: 1_000_000, env: {...process.env, GIT_NO_LAZY_FETCH: '1'}});
const gitBlob = createHash('sha1').update('blob ' + bytes.length + '\0').update(bytes).digest('hex');
read.push({project, commit: PINS[project], path, gitBlob, sha256: sha256(bytes), bytes: bytes.length});
return bytes.toString('utf8');
}
function table(source) {
return source.trimEnd().split('\n').filter(row => row && !row.startsWith('#')).map(row => row.split('\t'));
}
function prefix(values, gaps = values.map(() => 0n)) {
let address = 0n;
return values.map((count, i) => {
const start = address + gaps[i];
address = start + count;
return {i, start, count, end: address};
});
}
function locate(records, k) {
if (k < 0n || k >= records.at(-1).end) return {status: 'outside'};
let lo = 0;
let hi = records.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (records[mid].start <= k) lo = mid + 1;
else hi = mid;
}
const row = records[lo - 1];
if (!row || k >= row.end) return {status: 'unissued'};
return {status: 'issued', row: row.i, offset: (k - row.start).toString()};
}
function widths(counts) {
const max = counts.reduce((a, b) => a > b ? a : b);
return {rows: counts.length, maxCount: max.toString(), rowsThatFitLocalUint32: counts.filter(x => x <= A32).length};
}
function addressWidth(count) {
return {units: count.toString(), largestAddress: (count - 1n).toString(),
bits: (count - 1n).toString(2).length, fitsUint32: count <= A32};
}
const cosmosSource = blob('cosmic', 'index.html');
const kuiperSource = blob('kuiper', 'index.html');
const kuiperKey = blob('kuiper', 'tools/key.py');
const cosmicConstant = Number(cosmosSource.match(/const GOLD32 = (\d+);/)?.[1]);
const kuiperConstant = Number(kuiperSource.match(/const G32 = (\d+),/)?.[1]);
assert(Number.isSafeInteger(cosmicConstant) && cosmicConstant === kuiperConstant);
assert(cosmosSource.includes('const k32 = (node.seed + m) >>> 0'));
assert(cosmosSource.includes('Math.sqrt((m + 0.5) / node.value)'));
assert(kuiperSource.includes('Math.imul((k % 4294967296) >>> 0, G32)'));
assert(kuiperSource.includes('Math.sqrt(k + 0.5)'));
assert(kuiperSource.includes('uint m = (u_k0lo + uint(gl_VertexID)) *'));
assert(kuiperKey.includes("if not c['k0'] <= k < c['k0'] + c['lines']:"));
assert(kuiperKey.includes('was never issued: it is silence between commits'));
const universe = JSON.parse(blob('cosmic', 'universe.json'));
const cosmicKuiper = JSON.parse(blob('cosmic', 'kuiper.json'));
const wafer = JSON.parse(blob('cosmic', 'wafer.json'));
const belt = table(blob('cosmic', 'belt.tsv'));
const repoCounts = belt.map(row => BigInt(row[1]));
const repositorySpans = prefix(repoCounts);
assert.equal(repositorySpans.at(-1).end, BigInt(universe.total));
assert.equal(universe.total, cosmicKuiper.total);
assert.equal(cosmicKuiper.levels[0].child, null);
const selected = belt.findIndex(([label]) => label === 'globalgrid2050');
assert(selected >= 0);
const selectedRepository = repositorySpans[selected];
const childPath = universe.levels[0].child.replace('{i2}', String(selected).padStart(2, '0'));
const cosmicCommitCounts = table(blob('cosmic', childPath)).map(row => BigInt(row[1]));
assert.equal(prefix(cosmicCommitCounts).at(-1).end, selectedRepository.count);
const dieCounts = table(blob('cosmic', 'wafer/dies.tsv')).map(row => BigInt(row[1]));
assert.equal(prefix(dieCounts).at(-1).end, BigInt(wafer.total));
assert.equal(wafer.levels[0].law, 'explicit');
const kuiperMeta = JSON.parse(blob('kuiper', 'cosmos/wafer-meta.json'));
const waferRows = table(blob('kuiper', 'cosmos/wafer.tsv'));
const commitCounts = waferRows.map(row => BigInt(row[1]));
const gaps = waferRows.map(row => BigInt(row[4]));
const issued = commitCounts.reduce((a, b) => a + b, 0n);
const unissued = gaps.reduce((a, b) => a + b, 0n);
const chronology = prefix(commitCounts, gaps);
assert.equal(issued, BigInt(kuiperMeta.issued_keys));
assert.equal(unissued, BigInt(kuiperMeta.unissued_keys));
assert.equal(chronology.at(-1).end, BigInt(kuiperMeta.address_space));
assert.equal(chronology.length, kuiperMeta.commits);
const particleSource = blob('particle', 'measurements/exactness.mjs');
assert.equal(read.at(-1).gitBlob, PARTICLE_BLOB);
assert.equal(read.at(-1).sha256, PARTICLE_SHA);
const closure = [19, 53, 54, 55].map(n => particleSource.split('\n')[n - 1]).join('\n');
const limb = runInNewContext(closure + '\n;({mulhi32, top32, C64, CHI, CLO})', {}, {
timeout: 500, contextCodeGeneration: {strings: false, wasm: false},
});
const MASK64 = (1n << 64n) - 1n;
function phase32(k) {
if (typeof k !== 'bigint' || k < 0n || k > MASK) throw new RangeError('Address exceeds the uint32 domain');
return limb.top32(Number(k));
}
function phase64(k) {
if (typeof k !== 'bigint' || k < 0n || k > MASK64) throw new RangeError('Address exceeds the uint64 domain');
const kLo = Number(k & MASK);
const kHi = Number(k >> 32n);
return (limb.mulhi32(kLo, limb.CLO) + Math.imul(kLo, limb.CHI) + Math.imul(kHi, limb.CLO)) >>> 0;
}
function oracle(k) {
return Number(((k * limb.C64) & MASK64) >> 32n);
}
function legacyWord(k) {
return Math.imul(Number(k & MASK), cosmicConstant) >>> 0;
}
const fitting = [
['COSMIC selected commit trailing offset', cosmicCommitCounts.reduce((a, b) => a > b ? a : b) - 1n],
['COSMIC largest die trailing offset', dieCounts.reduce((a, b) => a > b ? a : b) - 1n],
['KUIPER largest commit trailing offset', commitCounts.reduce((a, b) => a > b ? a : b) - 1n],
['uint32 last value', MASK],
];
const localChecks = fitting.map(([caseName, n]) => {
const expected = oracle(n);
assert.equal(phase32(n), expected);
assert.equal(phase64(n), expected);
return {case: caseName, offset: n.toString(), phaseWord: expected};
});
const bounds = [
['first address outside uint32', A32], ['COSMIC estate last', BigInt(universe.total) - 1n],
['COSMIC wafer last', BigInt(wafer.total) - 1n], ['KUIPER wafer last', chronology.at(-1).end - 1n],
];
const wideDomains = bounds.map(([caseName, key]) => {
assert.throws(() => phase32(key), /uint32 domain/);
assert.equal(phase64(key), oracle(key));
return {case: caseName, key: key.toString(), narrowRefused: true, widePhaseWord: phase64(key)};
});
assert.throws(() => phase32(-1n), /uint32 domain/);
assert.throws(() => phase64(MASK64 + 1n), /uint64 domain/);
assert.equal(phase64(MASK64), oracle(MASK64));
const targetA = 15n;
const targetB = A32 + targetA;
const globalA = selectedRepository.start + targetA;
const globalB = selectedRepository.start + targetB;
assert.deepEqual(locate(repositorySpans, globalA), {row: selected, status: 'issued', offset: '15'});
assert.deepEqual(locate(repositorySpans, globalB), {row: selected, status: 'issued', offset: targetB.toString()});
const seed = BigInt((selected * 2654435761) >>> 0);
assert.equal(legacyWord(seed + targetA), legacyWord(seed + targetB));
const cosmicRadial = [targetA, targetB].map(offset => Math.sqrt((Number(offset) + 0.5) / Number(selectedRepository.count)));
assert.notEqual(cosmicRadial[0], cosmicRadial[1]);
function findChronologyAlias(status) {
// Sample 64 evenly spaced actual published commit intervals, not 32-bit keys.
const step = Math.floor(chronology.length / 64);
for (let sample = 0; sample < 64; sample++) {
const row = chronology[sample * step];
for (const point of [row.start, row.start + (row.count - 1n) / 2n, row.end - 1n]) {
const other = point + A32;
const a = locate(chronology, point);
const b = locate(chronology, other);
if (a.status !== 'issued' || b.status !== status) continue;
assert.equal(legacyWord(point), legacyWord(other));
assert.notEqual(phase64(point), phase64(other));
assert.equal(phase64(point), oracle(point));
assert.equal(phase64(other), oracle(other));
if (status === 'issued') assert.notEqual(a.row, b.row);
return {addresses: [point.toString(), other.toString()], resolution: [a, b],
sharedLegacyPhaseWord: legacyWord(point), candidateWidePhaseWords: [phase64(point), phase64(other)]};
}
}
throw new Error('Expected a witness in the bounded chronological sample');
}
const kuiperAliases = {
separateCommitAddresses: findChronologyAlias('issued'),
issuedAndSilence: findChronologyAlias('unissued'),
};
const lawComparison = [0n, 1n, 2n, 3n, 17n, 65_535n].map(k => ({
offset: k.toString(), existingLowWord: legacyWord(k), proposedHighWord: phase32(k),
}));
assert(lawComparison.some(x => x.existingLowWord !== x.proposedHighWord));
console.log(JSON.stringify({
schema: 'seed.phase-transfer.v1',
status: 'arithmetical_proof_and_address_width_findings',
pins: PINS,
sources: read,
particleStars: {tablet: 6082, lines: [393288, 393317, 393318, 393319]},
domains: {
cosmic: {
estate: addressWidth(BigInt(universe.total)),
directKuiperView: addressWidth(BigInt(cosmicKuiper.total)),
allRepositoryRows: widths(repoCounts),
largestDirectLeaf: {label: 'globalgrid2050', ...addressWidth(selectedRepository.count)},
selectedRepositoryCommitRows: widths(cosmicCommitCounts),
wafer: addressWidth(BigInt(wafer.total)), allExplicitDieRows: widths(dieCounts),
},
kuiper: {
chronologicalWafer: addressWidth(chronology.at(-1).end),
issuedKeys: issued.toString(), deliberateUnissuedKeys: unissued.toString(),
allCommitRows: widths(commitCounts),
},
},
proof: {
knownLocalAddresses: localChecks, fullWidthRefusalsAndOracle: wideDomains,
cosmicSameLegacyPhaseDifferentAddress: {
bucket: 'globalgrid2050', globalAddresses: [globalA.toString(), globalB.toString()],
localOffsets: [targetA.toString(), targetB.toString()],
sharedLegacyPhaseWord: legacyWord(seed + targetA), normalizedRadii: cosmicRadial,
},
kuiperActualChronologyAlias: kuiperAliases,
phaseLawDifferenceWithinUint32: lawComparison,
uint64UpperBoundaryMatched: true,
},
resources: {
inputBlobs: read.length, gitBlobBytes: read.reduce((n, row) => n + row.bytes, 0),
particleSourceEvaluatedBytes: Buffer.byteLength(closure),
chronologicalIntervalsAvailableToWitnessSearch: 64, inferenceCalls: 0, gpuUsed: false,
},
bounds: 'Pinned CPU arithmetic and index witness only. Candidate phase mapping differs from legacy rendering. Existing address allocation, GPU rendering and inverse hit tests are outside scope.',
}, null, 2));Parity
A JavaScript module in the reduction folder of Seed Data that reads fixture and cables.
ingestseed-data / experiments/economical-seeds/next-invention/reduction/parity.mjs · lines 1–71 of 71 · Entry point · pattern compare (shared by 17 files)
- What it does
- It loads fixture and cables. Defines verify, compare. Uses libraries node:assert/strict, 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.
- Inputs & outputs
- In: JSON file fixture.json; command-line arguments.
- Downstream impact
- Used directly by 1 file: Seed Regressions Workflow (seed-data).
- What it achieves
- Defines `verify` and `compare`. It reads `../cable-screen/fixture.json`.
- Why it matters
- Run by Seed Regressions Workflow.
- Application
- seed-data · experiments/economical-seeds/next-invention/reduction · JavaScript module
- Uses
- Route Screen (import), Baseline (import), Projected (import), node:assert/strict, node:fs
- Used by
- run by Seed Regressions Workflow (workflow run)
- Produces
- fixture, verify
- Defines here
- verify, compare
- 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/reduction/parity.mjs:1-71 · blob 489258b140e1e8a1f12bf67f09975f4e40ad023c · 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 { loadInstruments, screen } from '../cable-screen/route-screen.mjs';
import { screen as conventional } from '../cable-screen/baseline.mjs';
import { project } from './projected.mjs';
export const fixture = JSON.parse(readFileSync(new URL('../cable-screen/fixture.json', import.meta.url)));
export function verify(runtime) {
const reduced = project(runtime);
const compare = input => assert.deepEqual(screen(input, reduced), screen(input, runtime));
compare(fixture);
let generatedVectors = 0;
for (const phases of ['single', 'three']) {
for (const powerFactor of [0.0001, 0.6, 0.8, 0.999, 1]) {
for (const type of Object.keys(runtime.obstacles.OBSTACLES)) {
const input = structuredClone(fixture);
input.electrical.phases = phases;
input.electrical.powerFactor = powerFactor;
input.options[0].crossings = [
{ type, widthM: 31, setbackM: 15.5, depthM: 7.1, count: 3 },
{ type, count: 2 },
];
compare(input);
generatedVectors++;
}
}
}
const extreme = structuredClone(fixture);
extreme.electrical = {
currentA: 1, nominalVolts: 1e308, resistanceOhmPerKm: 1e307,
reactanceOhmPerKm: 0, powerFactor: 1, phases: 'single',
};
compare(extreme);
assert(Math.abs(screen(extreme, reduced).options[0].electrical.dropPct - 20) < 1e-12);
let conventionalBoundary = 'finite percentage on the independent implementation';
let independent;
try {
independent = conventional(extreme);
} catch (error) {
assert.match(error.message, /percentage drop/);
conventionalBoundary = '100 * drop overflows before division whereas pinned drop/nominal*100 remains finite';
}
if (independent) assert(Math.abs(independent.options[0].electrical.dropPct - 20) < 1e-12);
const invalid = [
input => { input.electrical.currentA = Number.MIN_VALUE; },
input => { input.electrical.currentA = Number.MAX_VALUE; },
input => { input.electrical.powerFactor = 80; },
input => { input.electrical.resistanceOhmPerKm = 0; },
input => { input.options[0].installedLengthM = 999; },
input => { input.options[0].crossings[0].type = '__proto__'; },
input => { delete input.options[0].crossings[0].widthM; },
input => { input.options[0].crossings[0].depthM = -1; },
input => { input.options[0].crossings[0].count = Number.MAX_SAFE_INTEGER;
input.options[0].crossings.push({type:'railway'}); },
input => { input.options[0].crossings[0].widthM = Number.MAX_VALUE;
input.options[0].crossings[0].setbackM = Number.MAX_VALUE; },
];
for (const edit of invalid) {
const input = structuredClone(fixture);
edit(input);
assert.throws(() => screen(input, runtime));
assert.throws(() => screen(input, reduced));
}
return { exactKnownAndGenerated: 2 + generatedVectors, alignedRefusals: invalid.length,
conventionalExtremeRefusal: conventionalBoundary };
}
if (process.argv[2]) console.log(JSON.stringify(verify(await loadInstruments(process.argv[2])), null, 2));Projected
A JavaScript module in the reduction folder of Seed Data that works with crossing schedule (`crossingSchedule`) and voltage drop volts (`voltageDropVolts`) and calculates planar distances (units: Ω).
electricalseed-data / experiments/economical-seeds/next-invention/reduction/projected.mjs · lines 1–56 of 56 · pattern crossingSchedule (shared by 2 files)
- What it does
- It calculates its inputs. Defines 6 functions or classes, including project, crossingSchedule, voltageDropVolts, dropPercent, lossesWatts.
- 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.
- Downstream impact
- Used directly by 3 files: Invoke (seed-data); Measure (seed-data); Parity (seed-data). Reached from 1 other entry point, including Seed Regressions Workflow (seed-data).
- What it achieves
- It prepares projected screen (`prepareProjectedScreen`) and is built from the project step (`project`) and the crossing schedule helper (`crossingSchedule`). Its `voltageDropVolts` function gives voltage drop record from current a, length m and resistance ohm per km (VEDIC: drop).
- Why it matters
- Imported by Invoke and Parity. Run by Measure.
- Application
- seed-data · experiments/economical-seeds/next-invention/reduction · JavaScript module
- VEDIC
- DROP (GG2050-VEDIC-000024): Ventus Grid Engine / voltage-drop · Electrical engineering / Applied mathematics. current_a, length_m, resistance_ohm_per_km, reactance_ohm_per_km, power_factor, phases → voltage_drop_record
- VEDIC
- PERCENT (GG2050-VEDIC-000025): Ventus Grid Engine / voltage-drop · Electrical engineering / Applied mathematics. drop_volts, nominal_volts → drop_percent
- VEDIC
- LOSS (GG2050-VEDIC-000026): Ventus Grid Engine / voltage-drop · Electrical engineering / Applied mathematics. current_a, length_m, resistance_ohm_per_km, phases → losses_watts
- Uses
- Route Screen (import)
- Used by
- imported by Invoke (import), run by Measure (script call), imported by Parity (import)
- Produces
- project, prepareProjectedScreen
- Defines here
- project, crossingSchedule, voltageDropVolts, dropPercent, lossesWatts, prepareProjectedScreen
- 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/reduction/projected.mjs:1-56 · blob 2389c63cdbdc302c308011c6515491a2d784849f · GitHub at these lines
- State
- achieves: code · context: readme_derived · stage: transform · effects: none found · domain stage: experimental · users: none · canonical: supporting_data
/** Numeric projection of the pinned component contracts consumed by route-screen. */
import { loadInstruments, screen } from '../cable-screen/route-screen.mjs';
export function project(runtime) {
// The outer screen owns input validation, declared-length gating and ranking.
// These providers only implement fields consumed by that screen.
const classes = runtime.obstacles.OBSTACLES;
function crossingSchedule({ crossings }) {
let crossingCount = 0, trenchlessCount = 0, openCutCount = 0, addedLengthM = 0;
let corridorApplicable = true;
const items = [];
for (const crossing of crossings) {
const type = classes[crossing.type];
const count = crossing.count ?? 1;
const span = crossing.widthM === undefined ? 0 : crossing.widthM + 2 * crossing.setbackM;
const depth = crossing.depthM ?? 0;
const length = (depth > 0 ? Math.hypot(span / 2, depth) * 2 : span) * count;
crossingCount += count;
if (type.trenchless) trenchlessCount += count;
else openCutCount += count;
if (type.blocksCorridor) corridorApplicable = false;
addedLengthM += length;
items.push({ count, lengthDeclared: length > 0 });
}
return { crossingCount, trenchlessCount, openCutCount, addedLengthM, corridorApplicable, items };
}
function voltageDropVolts({ currentA, lengthM, resistanceOhmPerKm, reactanceOhmPerKm,
powerFactor, phases }) {
const effective = resistanceOhmPerKm * powerFactor
+ reactanceOhmPerKm * Math.sqrt(1 - powerFactor * powerFactor);
return { value: runtime.voltage.PHASE_FACTOR[phases] * currentA * (lengthM / 1000) * effective };
}
function dropPercent({ dropVolts, nominalVolts }) {
if (!Number.isFinite(dropVolts) || dropVolts <= 0) throw new RangeError('Drop must be finite and positive');
return { value: (dropVolts / nominalVolts) * 100 };
}
function lossesWatts({ currentA, lengthM, resistanceOhmPerKm, phases }) {
const conductors = phases === 'three' ? 3 : 2;
return { value: conductors * currentA * currentA * resistanceOhmPerKm * (lengthM / 1000) };
}
return {
obstacles: { OBSTACLES: classes, crossingSchedule },
corridor: runtime.corridor,
voltage: { voltageDropVolts, dropPercent, lossesWatts },
};
}
export async function prepareProjectedScreen(checkout) {
const runtime = project(await loadInstruments(checkout));
return request => screen(request, runtime);
}
Identify Missing Evidence
A Python command-line tool in the sufficiency folder of Seed Data that works with valid digest (`valid_digest`) and indexed observations (`indexed_observations`), using SHA-256.
ingestseed-data / experiments/economical-seeds/next-invention/reduction/sufficiency/identify_missing_evidence.py · lines 1–246 of 246 · Entry point · pattern Budget (shared by 2 files)
- What it does
- Defines 16 functions or classes, including sha256, unique_keys, decode, fields, time. Uses libraries argparse, collections, datetime, hashlib, json. 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: command-line arguments.
- Downstream impact
- Used directly by 2 files: Session (seed-data); Test Identify Missing Evidence (seed-data). Reached from 1 other entry point, including Seed Regressions Workflow (seed-data).
- What it achieves
- It is built from the sha256 step (`sha256`), the unique keys helper (`unique_keys`) and the decode step (`decode`). Bounded evidence sufficiency for a fictional engineering bench question. It accepts `--request`, `--manifest` and `--bundle`.
- Why it matters
- Run by Session. Checked by Test Identify Missing Evidence.
- Application
- seed-data · experiments/economical-seeds/next-invention/reduction/sufficiency · Python CLI
- Uses
- argparse, collections, datetime, hashlib, json, pathlib, re, stat
- Used by
- run by Session (script call), imported by Test Identify Missing Evidence (import)
- Produces
- sha256, unique_keys, decode, fields, time, uint, valid_digest, require_text, indexed_observations, Budget, witness, metric_result
- Defines here
- sha256, unique_keys, decode, fields, time, uint, valid_digest, require_text, indexed_observations, Budget, __init__, inspect, witness, metric_result, assess, 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/economical-seeds/next-invention/reduction/sufficiency/identify_missing_evidence.py:1-246 · blob 662e2ed7459a3c9625c841b39464c19b2437dcb2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem · domain stage: experimental · users: none · canonical: supporting_data
"""Bounded evidence sufficiency for a fictional engineering bench question."""
import argparse
from collections import defaultdict
from datetime import datetime
import hashlib
import json
from pathlib import Path
import re
import stat
QUESTION = "synthetic-sealed-bench-v1"
PREDICATES = {
"peak_force": {"unit": "N", "op": ">=", "threshold": 12},
"leak_volume": {"unit": "mL", "op": "<=", "threshold": 3},
}
NONOBSERVATIONS = {"missing", "unsearched", "withheld"}
SHA256 = re.compile(r"[0-9a-f]{64}")
TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z")
def sha256(data):
return hashlib.sha256(data).hexdigest()
def unique_keys(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("Duplicate JSON key")
result[key] = value
return result
def decode(data):
return json.loads(data, object_pairs_hook=unique_keys)
def fields(value, expected):
if not isinstance(value, dict) or set(value) != expected:
raise ValueError("Unexpected input fields")
def time(value):
if not isinstance(value, str) or not TIMESTAMP.fullmatch(value):
raise ValueError("Use a whole-second UTC timestamp")
return datetime.fromisoformat(value)
def uint(value):
return type(value) is int and value >= 0
def valid_digest(value):
return isinstance(value, str) and SHA256.fullmatch(value) is not None
def require_text(*values):
if any(not isinstance(value, str) or not value.strip() for value in values):
raise ValueError("Blank evidence identity or locator")
def indexed_observations(manifest, request, as_of):
fields(manifest, {"schema", "subject", "evidence"})
if manifest["schema"] != "seed.synthetic-bench-evidence.v1" or manifest["subject"] != request["subject"]:
raise ValueError("Index question or subject mismatch")
if not isinstance(manifest["evidence"], list):
raise ValueError("Expected an evidence index")
by_metric, ignored, identities = defaultdict(list), 0, set()
for row in manifest["evidence"]:
if not isinstance(row, dict):
raise ValueError("Expected an evidence index record")
base = {"id", "metric", "source", "state"}
state = row.get("state")
if state == "observed":
fields(row, base | {"observed_at", "path", "sha256", "bytes"})
timestamp = time(row["observed_at"])
require_text(row["path"])
if not valid_digest(row["sha256"]) or not uint(row["bytes"]):
raise ValueError("Invalid observation identity or size")
if timestamp > as_of:
state = "future"
elif (as_of - timestamp).total_seconds() > request["max_age_seconds"]:
state = "stale"
elif isinstance(state, str) and state in NONOBSERVATIONS:
fields(row, base)
else:
raise ValueError("Unknown evidence completeness")
require_text(row["id"], row["metric"], row["source"])
if row["id"] in identities:
raise ValueError("Duplicate evidence identity")
identities.add(row["id"])
if row["metric"] in PREDICATES:
by_metric[row["metric"]].append((state, row))
else:
ignored += 1
return by_metric, ignored
class Budget:
def __init__(self, bundle, maximum):
self.bundle = bundle.resolve()
self.maximum = maximum
self.used = 0
self.opened = 0
def inspect(self, row, request, rule):
size = row["bytes"]
if self.used + size > self.maximum:
return "budget_exhausted", None
name = Path(row["path"])
try:
path = (self.bundle / name).resolve()
if name.anchor or not path.is_relative_to(self.bundle):
return "invalid_locator", None
metadata = path.stat()
if not stat.S_ISREG(metadata.st_mode):
return "invalid_locator", None
if metadata.st_size != size:
return "corrupted", None
with path.open("rb") as stream:
self.opened += 1
raw = stream.read(size)
self.used += len(raw)
if len(raw) != size or sha256(raw) != row["sha256"] or path.stat().st_size != size:
return "corrupted", None
except FileNotFoundError:
return "missing", None
except OSError:
return "unavailable", None
except (ValueError, RuntimeError):
return "invalid_locator", None
try:
claim = decode(raw)
fields(claim, {"subject", "metric", "observed_at", "value", "unit"})
except (ValueError, UnicodeError):
return "invalid_payload", None
if (claim["subject"] != request["subject"] or claim["metric"] != row["metric"]
or claim["observed_at"] != row["observed_at"] or claim["unit"] != rule["unit"]
or not uint(claim["value"])):
return "invalid_payload", None
return "verified", claim["value"]
def witness(row, state, value=None):
result = {"id": row["id"], "source": row["source"], "state": state}
for key in ("observed_at", "sha256"):
if key in row:
result[key] = row[key]
if value is not None:
result["value"] = value
return result
def metric_result(metric, rows, budget, request):
rule = PREDICATES[metric]
result = {"metric": metric, "predicate": rule, "status": "unknown", "witnesses": [],
"unresolved": []}
groups = {}
for state, row in sorted(rows, key=lambda item: item[1]["id"]):
if state == "observed":
key = (row["sha256"], row["bytes"], row["observed_at"])
groups.setdefault(key, []).append(row)
else:
result["witnesses"].append(witness(row, state))
if state in NONOBSERVATIONS:
result["unresolved"].append({"state": state, "ids": [row["id"]]})
if result["unresolved"]:
result["stop"] = "resolve_indexed_omissions_first"
result["deferred_ids"] = [row["id"] for group in groups.values() for row in group]
return result
if not groups:
result["unresolved"] = [{"state": "fresh_observation_required",
"ids": [entry["id"] for entry in result["witnesses"]]}]
result["stop"] = "no_current_payload"
return result
values = {}
group_list = list(groups.values())
for ordinal, group in enumerate(group_list):
tried = []
for position, row in enumerate(group):
state, value = budget.inspect(row, request, rule)
result["witnesses"].append(witness(row, state, value))
if state == "verified":
values[value] = row["id"]
result["witnesses"].extend(witness(item, "duplicate_unread") for item in group[position + 1:])
break
tried.append({"state": state, "ids": [row["id"]]})
else:
result["unresolved"].extend(tried)
result["deferred_ids"] = [row["id"] for rest in group_list[ordinal + 1:] for row in rest]
result["stop"] = "resolve_required_payloads"
return result
if len(values) > 1:
result["unresolved"].append({"state": "conflicting", "ids": sorted(values.values())})
result["deferred_ids"] = [row["id"] for rest in group_list[ordinal + 1:] for row in rest]
result["stop"] = "reconcile_conflicting_values"
return result
value, = values
passes = value >= rule["threshold"] if rule["op"] == ">=" else value <= rule["threshold"]
result.update(status="supported" if passes else "contradicted", measured_value=value,
stop="predicate_answered")
return result
def assess(request, index_raw, bundle):
fields(request, {"question", "subject", "as_of", "max_age_seconds", "max_payload_bytes",
"manifest_sha256"})
require_text(request["subject"])
if request["question"] != QUESTION or not uint(request["max_age_seconds"]) or not uint(request["max_payload_bytes"]):
raise ValueError("Unsupported question or invalid evidence budget")
as_of = time(request["as_of"])
digest = sha256(index_raw)
if not valid_digest(request["manifest_sha256"]) or digest != request["manifest_sha256"]:
raise ValueError("Evidence index SHA-256 differs from the declared pin")
rows, ignored = indexed_observations(decode(index_raw), request, as_of)
budget = Budget(bundle, request["max_payload_bytes"])
results = [metric_result(metric, rows[metric], budget, request) for metric in PREDICATES]
complete = all(row["status"] != "unknown" for row in results)
return {"schema": "seed.synthetic-evidence-sufficiency.v1", "question": QUESTION,
"subject": request["subject"], "as_of": request["as_of"], "manifest_sha256": digest,
"status": "evidence_sufficient" if complete else "additional_evidence_required",
"predicates": results, "resources": {"index_bytes": len(index_raw),
"payload_reads": budget.opened,
"payload_bytes": budget.used,
"ignored_index_rows": ignored}}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--request", required=True, type=Path)
parser.add_argument("--manifest", required=True, type=Path)
parser.add_argument("--bundle", required=True, type=Path)
args = parser.parse_args()
try:
result = assess(decode(args.request.read_bytes()), args.manifest.read_bytes(), args.bundle)
except (ValueError, OSError, OverflowError) as error:
print(json.dumps({"status": "refused", "reason": str(error)}))
return 2
print(json.dumps(result, indent=2))
return 0
if __name__ == "__main__":
raise SystemExit(main())