GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / spiders / tools

GridAtlas Build Part and 2 more files

A JavaScript module in the drivers folder of Teleprinter that uses SHA-256. It is built from the flatten step (`flatten`) and the normalise step (`normalise`).

466 lines of JavaScript from spiders, teleprinter, in 3 files. Topic: Maps, GIS and field navigation. Section 717 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. Estate Survey storage · spiders / tools/estate-survey.mjs lines 385–503
  2. Test Estate Survey test · spiders / tools/test-estate-survey.mjs lines 1–150
  3. GridAtlas Build Part render · teleprinter / drivers/gridatlas/build-part.mjs lines 1–197

Estate Survey

A JavaScript module in the tools folder of Spiders that uses SHA-256 using data from GitHub API. It parses JSON (`parseJson`), validates registry (`validateRegistry`) and fetches JSON (`fetchJson`).

storagespiders / tools/estate-survey.mjs · lines 385–503 of 503 (continued from section 716) · Entry point · pattern validateRegistry (shared by 2 files)

What it does
It fetches data. Defines 17 functions or classes, including valueAfter, portable, sha256, byteCompare, shardFor. Uses libraries node:crypto, node:fs, node:path. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'spiders'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: data source: GitHub API; command-line arguments.
Downstream impact
Used directly by 1 file: Estate Survey Workflow (spiders).
What it achieves
Defines `valueAfter`, `portable`, `sha256` and 13 more.
Why it matters
Run by Estate Survey Workflow.
Application
spiders · tools · JavaScript module
Uses
node:crypto, node:fs, node:path
Used by
run by Estate Survey Workflow (workflow run)
Produces
valueAfter, portable, sha256, byteCompare, shardFor, stableWrite, parseJson, validateRegistry, localReceipt, fetchJson, fixtureReader, liveReader
Defines here
main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 tools/estate-survey.mjs:385-503 · blob dfc85148e8c313cb2132af4c2580b4df93de59bd · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
    if (seenRepositories.has(observation.name)) errors.push(`duplicate observation ${observation.name}`);
    seenRepositories.add(observation.name);
    const expectation = expectations.get(observation.name);
    if (!expectation) {
      errors.push(`unexpected observation ${observation.name}`);
      continue;
    }
    if (JSON.stringify(observation.expected) !== JSON.stringify({
      default_branch: expectation.default_branch,
      head_sha: expectation.head_sha,
    })) errors.push(`${observation.name} expectation differs from local receipt`);
    if (expectation.shard !== shardFor(local.owner, observation.name, local.shard_count)) {
      errors.push(`${observation.name} has inconsistent deterministic shard`);
    }
    let recomputedFindings = [];
    if (observation.availability === 'not-found') {
      if (observation.observed !== null) errors.push(`${observation.name} not-found observation carries remote state`);
      recomputedFindings = ['repository-not-found'];
    } else if (observation.availability === 'observed') {
      const observed = observation.observed;
      if (!observed
          || typeof observed.default_branch !== 'string'
          || !/^[0-9a-f]{40}$/.test(observed.head_sha || '')
          || typeof observed.private !== 'boolean'
          || typeof observed.archived !== 'boolean'
          || typeof observed.disabled !== 'boolean'
          || typeof observed.fork !== 'boolean'
          || typeof observed.has_pages !== 'boolean'
          || !Number.isInteger(observed.workflow_files_total)
          || !Array.isArray(observed.workflow_files)
          || observed.workflow_files.length !== observed.workflow_files_total
          || observed.workflow_files.some(file => !file || typeof file.name !== 'string'
            || !/^[0-9a-f]{40}$/.test(file.sha || '') || !Number.isInteger(file.size))) {
        errors.push(`${observation.name} carries malformed observed state`);
      } else {
        if (observed.private) recomputedFindings.push('visibility-became-private');
        if (observed.default_branch !== expectation.default_branch) recomputedFindings.push('default-branch-drift');
        if (observed.head_sha !== expectation.head_sha) recomputedFindings.push('head-drift');
        if (observed.archived) recomputedFindings.push('repository-archived');
        if (observed.disabled) recomputedFindings.push('repository-disabled');
      }
    } else {
      errors.push(`${observation.name} has invalid availability ${String(observation.availability)}`);
    }
    if (JSON.stringify(observation.findings) !== JSON.stringify(recomputedFindings)) {
      errors.push(`${observation.name} findings do not match observed state`);
    }
  }
  for (const name of expectations.keys()) {
    if (!seenRepositories.has(name)) errors.push(`missing observation ${name}`);
  }
  const findings = observations.flatMap(findingRows).sort((a, b) =>
    byteCompare(`${a.repository}/${a.kind}`, `${b.repository}/${b.kind}`));
  const uniqueErrors = [...new Set(errors)].sort(byteCompare);
  return {
    schema: AGGREGATE_SCHEMA,
    comparison: 'cloud-observation-vs-committed-local-registry',
    registry_sha256: local.registry_sha256,
    inputs: {
      local_receipt_sha256: sha256(localParsed.bytes),
      shard_receipts: shardInputs.sort((a, b) => a.shard_index - b.shard_index),
    },
    repository_count: local.repository_count,
    observed_count: observations.length,
    findings_count: findings.length,
    findings,
    machinery_errors: uniqueErrors,
    repositories: observations,
    status: uniqueErrors.length ? 'fail' : 'pass',
  };
}

async function main() {
  const output = valueAfter('--out');
  if (!output) throw new Error('missing --out receipt path');
  if (mode === 'registry') {
    const registry = valueAfter('--registry');
    if (!registry) throw new Error('missing --registry path');
    const { receipt } = localReceipt(registry);
    stableWrite(output, receipt);
    console.log(JSON.stringify(receipt));
    return receipt.status === 'pass' ? 0 : 1;
  }
  if (mode === 'survey') {
    const registry = valueAfter('--registry');
    const rawShard = valueAfter('--shard');
    if (!registry || rawShard === null) throw new Error('survey requires --registry and --shard');
    const receipt = await surveyShard(registry, Number(rawShard), valueAfter('--fixture'));
    stableWrite(output, receipt);
    console.log(JSON.stringify(receipt));
    return receipt.status === 'pass' ? 0 : 1;
  }
  if (mode === 'aggregate') {
    const registry = valueAfter('--registry');
    const local = valueAfter('--local');
    const shards = (valueAfter('--shards') || '').split(',').filter(Boolean);
    if (!registry || !local || !shards.length) throw new Error('aggregate requires --registry, --local and --shards');
    const receipt = aggregate(registry, local, shards);
    stableWrite(output, receipt);
    console.log(JSON.stringify(receipt));
    return receipt.status === 'pass' ? 0 : 1;
  }
  throw new Error('usage: estate-survey.mjs registry|survey|aggregate ...');
}

try {
  process.exitCode = await main();
} catch (error) {
  const output = valueAfter('--out');
  const receipt = {
    schema: 'spiders.estate-survey-machinery-failure.v1',
    mode: mode || null,
    machinery_errors: [`${error.name}: ${error.message}`],
    status: 'fail',
  };
  if (output) stableWrite(output, receipt);
  console.error(JSON.stringify(receipt));
  process.exitCode = 1;
}

Test Estate Survey

A JavaScript module in the tools folder of Spiders that tests estate survey registry, fixture incomplete, local repeated and aggregate failed.

testspiders / tools/test-estate-survey.mjs · lines 1–150 of 150 · Entry point · pattern assert (shared by 7 files)

What it does
It tests estate survey registry, fixture incomplete, local repeated and aggregate failed. Defines assert, run, read. Uses libraries node:fs, node:os, node:path, node:child_process. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'spiders'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file 20260904-estate-survey-registry.json; JSON file fixture.json; JSON file local.json; JSON file local-repeated.json; JSON file aggregate.json; JSON file shard-0-repeated.json; JSON file fixture-incomplete.json; JSON file shard-failed.json.
Downstream impact
Used directly by 1 file: Estate Survey Workflow (spiders).
What it achieves
Defines `assert`, `run` and `read`.
Why it matters
Run by Estate Survey Workflow.
Application
spiders · tools · JavaScript module
Uses
node:fs, node:os, node:path, node:child_process
Used by
run by Estate Survey Workflow (workflow run)
Produces
assert, run, read
Defines here
assert, run, read
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 tools/test-estate-survey.mjs:1-150 · blob 004bad2fc0c2e5d5c920f124fded33f0e371c7a7 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env node
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join, resolve } from 'node:path';
import { spawnSync } from 'node:child_process';

const root = resolve(import.meta.dirname, '..');
const tool = join(root, 'tools', 'estate-survey.mjs');
const registryPath = join(root, 'control', '20260904-estate-survey-registry.json');
const registry = JSON.parse(readFileSync(registryPath, 'utf8'));
const temporary = mkdtempSync(join(tmpdir(), 'spiders-estate-survey-test-'));
let checks = 0;
const assert = (condition, message) => {
  if (!condition) throw new Error(message);
  checks += 1;
};
const run = arguments_ => spawnSync(process.execPath, [tool, ...arguments_], {
  cwd: root,
  encoding: 'utf8',
});
const read = path => JSON.parse(readFileSync(path, 'utf8'));

try {
  const fixture = {
    schema: 'spiders.estate-survey-fixture.v1',
    repositories: {},
  };
  for (const repository of registry.repositories) {
    fixture.repositories[repository.name] = {
      metadata: {
        default_branch: repository.default_branch,
        private: false,
        archived: false,
        disabled: false,
        fork: repository.name === 'pandapower',
        has_pages: false,
      },
      commit: { sha: repository.head_sha },
      workflow_files: [],
    };
  }
  fixture.repositories.architecture.commit.sha = 'f'.repeat(40);
  fixture.repositories.architecture.metadata.archived = true;
  fixture.repositories.Mahabharata = { not_found: true };
  const fixturePath = join(temporary, 'fixture.json');
  writeFileSync(fixturePath, `${JSON.stringify(fixture, null, 2)}\n`);

  const localPath = join(temporary, 'local.json');
  let result = run(['registry', '--registry', registryPath, '--out', localPath]);
  assert(result.status === 0, `registry command failed: ${result.stderr}`);
  const local = read(localPath);
  assert(local.status === 'pass' && local.repository_count === 33, 'registry receipt is not a 33-repository pass');
  assert(local.shard_repository_counts.join(',') === '9,11,6,7', 'unexpected deterministic shard distribution');
  const repeatedLocalPath = join(temporary, 'local-repeated.json');
  result = run(['registry', '--registry', registryPath, '--out', repeatedLocalPath]);
  assert(result.status === 0, 'repeated registry command failed');
  assert(readFileSync(localPath).equals(readFileSync(repeatedLocalPath)), 'local registry receipt is not deterministic');

  const shards = [];
  for (let shard = 0; shard < 4; shard += 1) {
    const path = join(temporary, `shard-${shard}.json`);
    result = run([
      'survey', '--registry', registryPath, '--shard', String(shard),
      '--fixture', fixturePath, '--out', path,
    ]);
    assert(result.status === 0, `fixture shard ${shard} failed: ${result.stderr}`);
    assert(read(path).status === 'pass', `fixture shard ${shard} did not pass`);
    shards.push(path);
  }

  const aggregatePath = join(temporary, 'aggregate.json');
  result = run([
    'aggregate', '--registry', registryPath, '--local', localPath,
    '--shards', shards.join(','), '--out', aggregatePath,
  ]);
  assert(result.status === 0, `informational aggregation failed: ${result.stderr}`);
  const aggregate = read(aggregatePath);
  assert(aggregate.status === 'pass', 'informational findings made aggregate fail');
  assert(aggregate.observed_count === 33, 'aggregate did not observe every registry entry');
  assert(aggregate.findings.some(finding => finding.repository === 'architecture' && finding.kind === 'head-drift'), 'head drift was not reported');
  assert(aggregate.findings.some(finding => finding.repository === 'architecture' && finding.kind === 'repository-archived'), 'archival was not reported');
  assert(aggregate.findings.some(finding => finding.repository === 'Mahabharata' && finding.kind === 'repository-not-found'), 'missing repository was not informational');

  const repeatedShardPath = join(temporary, 'shard-0-repeated.json');
  result = run([
    'survey', '--registry', registryPath, '--shard', '0',
    '--fixture', fixturePath, '--out', repeatedShardPath,
  ]);
  assert(result.status === 0, 'repeated shard command failed');
  assert(readFileSync(shards[0]).equals(readFileSync(repeatedShardPath)), 'shard receipt is not deterministic');

  const incompleteFixture = structuredClone(fixture);
  delete incompleteFixture.repositories.architecture;
  const incompleteFixturePath = join(temporary, 'fixture-incomplete.json');
  const failedShardPath = join(temporary, 'shard-failed.json');
  writeFileSync(incompleteFixturePath, `${JSON.stringify(incompleteFixture, null, 2)}\n`);
  result = run([
    'survey', '--registry', registryPath, '--shard', '0',
    '--fixture', incompleteFixturePath, '--out', failedShardPath,
  ]);
  assert(result.status !== 0, 'missing fixture response passed the shard');
  assert(read(failedShardPath).status === 'fail', 'missing response did not emit a failed shard receipt');

  const corrupted = read(shards[0]);
  corrupted.registry_sha256 = '0'.repeat(64);
  const corruptedPath = join(temporary, 'shard-corrupt.json');
  writeFileSync(corruptedPath, `${JSON.stringify(corrupted, null, 2)}\n`);
  const brokenShards = [corruptedPath, ...shards.slice(1)];
  const failedAggregatePath = join(temporary, 'aggregate-failed.json');
  result = run([
    'aggregate', '--registry', registryPath, '--local', localPath,
    '--shards', brokenShards.join(','), '--out', failedAggregatePath,
  ]);
  assert(result.status !== 0, 'altered shard receipt passed aggregation');
  assert(read(failedAggregatePath).status === 'fail', 'altered shard did not produce a failed machinery receipt');

  const alteredLocal = read(localPath);
  alteredLocal.owner = 'OtherOwner';
  const alteredLocalPath = join(temporary, 'local-altered.json');
  const alteredLocalAggregatePath = join(temporary, 'aggregate-local-altered.json');
  writeFileSync(alteredLocalPath, `${JSON.stringify(alteredLocal, null, 2)}\n`);
  result = run([
    'aggregate', '--registry', registryPath, '--local', alteredLocalPath,
    '--shards', shards.join(','), '--out', alteredLocalAggregatePath,
  ]);
  assert(result.status !== 0, 'altered local receipt passed aggregation');
  const alteredLocalAggregate = read(alteredLocalAggregatePath);
  assert(alteredLocalAggregate.status === 'fail', 'altered local receipt did not fail the aggregate');
  assert(alteredLocalAggregate.machinery_errors.includes('local receipt differs from the checked-in registry receipt'),
    'altered local receipt was not reconciled against the checked-in registry');

  const invalidRegistry = structuredClone(registry);
  invalidRegistry.repositories[1] = structuredClone(invalidRegistry.repositories[0]);
  const invalidRegistryPath = join(temporary, 'registry-invalid.json');
  const invalidReceiptPath = join(temporary, 'registry-invalid-receipt.json');
  writeFileSync(invalidRegistryPath, `${JSON.stringify(invalidRegistry, null, 2)}\n`);
  result = run(['registry', '--registry', invalidRegistryPath, '--out', invalidReceiptPath]);
  assert(result.status !== 0, 'duplicated registry entry passed validation');
  assert(read(invalidReceiptPath).status === 'fail', 'invalid registry did not emit a failed receipt');

  console.log(JSON.stringify({
    schema: 'spiders.estate-survey-test.v1',
    status: 'pass',
    checks,
    repositories: 33,
    shards: 4,
  }));
} finally {
  rmSync(temporary, { recursive: true, force: true });
}

GridAtlas Build Part

A JavaScript module in the drivers folder of Teleprinter that uses SHA-256. It is built from the flatten step (`flatten`) and the normalise step (`normalise`).

renderteleprinter / drivers/gridatlas/build-part.mjs · lines 1–197 of 197 · Not reached from any entry point (candidate for review) · pattern flatten (shared by 8 files)

What it does
It loads data. Defines flatten, normalise. Uses libraries node:fs/promises, node:crypto, node:path, node:child_process, node:url. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage upstream_foresight (path word 'gridatlas'): upstream engineering foresight over GB transmission and distribution topology (TSO/DNO, 132kV and above, the REPD pipeline, data centres), which Ventus Ltd states it models for foresight.
Inputs & outputs
In: JSON file current.json; command-line arguments.
What it achieves
Vendor the GridAtlas Teleprinter drivers into one GridAtlas cartridge part. --------------------------------------------------------------------------- GridAtlas ships an immutable shell plus hashed cartridges, and a cartridge is ONE classic script assembled from a list of parts.
Why it matters
No other file in the estate was found to import it.
Application
teleprinter · drivers/gridatlas · JavaScript module
Uses
node:fs/promises, node:crypto, node:path, node:child_process, node:url, node:fs, node:os
Used by
none found
Produces
flatten, normalise
Defines here
flatten, normalise
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
teleprinter@e45bfe38c3040b0f36f7df94ce262b63db8d0b60 drivers/gridatlas/build-part.mjs:1-197 · blob 01193e6274116d3eb0fc3f84c4f7f000ff6a895c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: upstream_foresight · users: IPP_developer, ICP_grid_engineer · canonical: unreached_review
/**
 * Vendor the GridAtlas Teleprinter drivers into one GridAtlas cartridge part.
 * ---------------------------------------------------------------------------
 * GridAtlas ships an immutable shell plus hashed cartridges, and a cartridge is
 * ONE classic script assembled from a list of parts. That is not a limitation
 * to be worked around; it is the thing that makes a served generation
 * reproducible. So the drivers, which are authored as ES modules here, are
 * mechanically transformed into one part rather than imported at runtime.
 *
 * WHY NOT A RUNTIME import(). The atlas is served at /gridatlas/atlas/ AND at
 * /gridatlas/atlas/v/<generation>/, and a pinned generation is byte-identical
 * to the live one. A relative specifier therefore resolves to a different place
 * depending on which URL the reader opened, and an absolute one pins a pinned
 * build to whatever the live engine happens to be tomorrow -- which is exactly
 * the "improvements went backwards into a published version" failure this
 * estate has already had once. Concatenation has neither problem.
 *
 * WHY A SCRIPT AND NOT A COPY-PASTE. A hand-copied part drifts from its source
 * silently. This records the SHA-256 of every source file in the generated
 * header, so `verify` can prove the part still matches the drivers it claims to
 * be built from, and a drifted part is a failed check rather than a surprise.
 *
 *   node drivers/gridatlas/build-part.mjs <gridatlas-repo> [--verify]
 */
import { readFile, writeFile, readdir } from 'node:fs/promises';
import { createHash } from 'node:crypto';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';

const HERE = path.dirname(fileURLToPath(import.meta.url));
const SOURCES = ['screen-frame.js', 'print-pdf.js', 'print-source-code.js'];

const target = process.argv[2];
const verifyOnly = process.argv.includes('--verify');
if (!target) {
  console.error('usage: node build-part.mjs <gridatlas-repo> [--verify]');
  process.exit(2);
}

/* The transform is deliberately dumb and total: every `export ` prefix is
   dropped and every intra-driver import line is removed, because the three
   files become one scope. Anything cleverer -- a real module graph, a bundler
   -- would be a second thing to trust. If a driver ever imports something that
   is NOT one of its siblings, this refuses rather than emitting a part with a
   dangling reference. */
function flatten(name, text) {
  const lines = text.split(/\r?\n/);
  const out = [];
  for (const line of lines) {
    const importMatch = line.match(/^\s*import\s+.*from\s+'\.\/([^']+)';?\s*$/);
    if (importMatch) {
      if (!SOURCES.includes(importMatch[1])) {
        throw new Error(`${name} imports ${importMatch[1]}, which is not vendored`);
      }
      continue;
    }
    if (/^\s*import\s/.test(line)) {
      throw new Error(`${name} has an import this build cannot flatten: ${line.trim()}`);
    }
    out.push(line.replace(/^(\s*)export\s+(async\s+function|function|const|let|class)\s/, '$1$2 '));
  }
  return out.join('\n');
}

/* HASH THE SOURCE, NOT THE CHECKOUT.
   ---------------------------------------------------------------------------
   These hashes were taken over the bytes as they sat on the building machine,
   and that made the part UNVERIFIABLE ANYWHERE ELSE. Git stores these files
   with LF and hands them to a Windows working tree as CRLF, so the same commit
   produces two different SHA-256 values depending on who checked it out. A part
   built here recorded the CRLF hashes; the parse gate on ubuntu-24.04 rebuilt
   from the LF checkout, got different hashes in the header, and reported DRIFT
   on a part that was byte-for-byte correct. Measured: the first CI run of
   teleprint-parse-gate.yml failed in 40 seconds for exactly this and nothing
   else.

   Normalising to LF before hashing makes the identity a property of the SOURCE
   rather than of the machine that happened to build it, which is the only
   version of this check worth having -- a hash that means something different
   on each platform is not an integrity check, it is a coin toss with extra
   steps. */
const normalise = (text) => text.replace(/\r\n/g, '\n');

const hashes = {};
const bodies = [];
for (const name of SOURCES) {
  const text = normalise(await readFile(path.join(HERE, name), 'utf8'));
  hashes[name] = createHash('sha256').update(text).digest('hex');
  bodies.push(`  /* ---- ${name} (sha256 ${hashes[name].slice(0, 16)}) ---- */\n`
    + flatten(name, text).split('\n').map(l => (l ? '  ' + l : l)).join('\n'));
}

const wiring = normalise(await readFile(path.join(HERE, 'gridatlas-wiring.js'), 'utf8'));
hashes['gridatlas-wiring.js'] = createHash('sha256')
  .update(wiring).digest('hex');

const header = `/**
 * TELEPRINT CONTROLS -- GENERATED. DO NOT EDIT THIS FILE.
 *
 * Built by teleprinter/drivers/gridatlas/build-part.mjs from the drivers in
 * that directory, which are where any change belongs. Editing this copy makes
 * the served bytes disagree with the source they claim to come from, and
 * --verify will say so.
 *
 * Two SEPARATE functions, on the architect's instruction:
 *   Print PDF          a picture of the reader's screen, for a person
 *   Print source code  the entire source and its dependencies, for a machine
 *
 * Sources:
${Object.entries(hashes).map(([k, v]) => ` *   ${k}  sha256 ${v}`).join('\n')}
 */
`;

const part = header + '(function () {\n  \'use strict\';\n\n'
  + bodies.join('\n\n') + '\n\n'
  + wiring.split('\n').map(l => (l ? '  ' + l : l)).join('\n')
  + '\n}());\n';

const partPath = path.join(target, 'atlas', 'modules', 'teleprint-controls.js');
const existingDir = await readdir(path.join(target, 'atlas', 'modules'));
const existing = existingDir.filter(name => /teleprint-controls\.js$/.test(name));

if (verifyOnly) {
  if (!existing.length) {
    console.error('no vendored teleprint-controls part found');
    process.exit(1);
  }
  /* ONLY THE PART THAT IS SERVED.
     ------------------------------------------------------------------------
     The first version of this compared EVERY vendored part against a fresh
     build and reported DRIFT on the older ones. That is backwards: a
     generation is immutable, so a part from an earlier composition is SUPPOSED
     to differ from today's drivers, and flagging it red trains the reader to
     ignore the check. The question worth asking is narrower — does the part
     the CURRENT composition actually serves match the drivers it claims in its
     own header to be built from?

     Older parts are still listed, as history, without a verdict. */
  const current = JSON.parse(
    await readFile(path.join(target, 'atlas', 'current.json'), 'utf8'));
  const holder = current.cartridges
    .map(cartridge => cartridge.assembled_from)
    .filter(Boolean);
  let servedPart = null;
  for (const manifest of holder) {
    const text = await readFile(
      path.join(target, 'atlas', String(manifest).replace(/^\.\//, '')), 'utf8');
    const hit = text.match(/(\d{12}-teleprint-controls\.js)/);
    if (hit) { servedPart = hit[1]; break; }
  }
  if (!servedPart) {
    /* Fall back to the newest, and SAY that is what happened rather than
       silently verifying something the composition may not use. */
    servedPart = existing.sort().reverse()[0];
    console.log(`note   current.json names no parts manifest; verifying newest part ${servedPart}`);
  }
  const served = await readFile(path.join(target, 'atlas', 'modules', servedPart), 'utf8');
  const matches = served.replace(/\r\n/g, '\n') === part.replace(/\r\n/g, '\n');
  console.log(`${matches ? 'OK    ' : 'DRIFT '} ${servedPart} (served by generation ${current.generation})`);
  const history = existing.filter(name => name !== servedPart);
  if (history.length) console.log(`history ${history.length} superseded part(s), not verified: ${history.join(', ')}`);
  process.exit(matches ? 0 : 1);
}

/* PARSE THE THING THAT SHIPS, NOT THE THING IT CAME FROM.
   ------------------------------------------------------------------------
   On 2026-09-05 this build emitted a part containing a single-quoted string
   with a raw line break. `node --check` passed on the ES module it was
   flattened from -- a different file -- so nothing caught it, the part went
   into a cartridge, the cartridge went live, and window.initVentusMap never
   ran: no map, no menu bar, no layer controls, in every browser. The architect
   found it on the live site.

   A generated file that is never parsed is a generated file that is not
   checked. This refuses to write one that does not parse. */
const { writeFileSync, unlinkSync } = await import('node:fs');
const os = await import('node:os');
const probe = path.join(os.tmpdir(), `teleprint-part-${Date.now()}.js`);
writeFileSync(probe, part, 'utf8');
try {
  const checked = spawnSync(process.execPath, ['--check', probe], { encoding: 'utf8' });
  if (checked.status !== 0) {
    console.error('the generated part does not parse; refusing to write it');
    console.error(checked.stderr);
    process.exit(1);
  }
} finally {
  try { unlinkSync(probe); } catch (_) { /* nothing to clean */ }
}

await writeFile(partPath, part, 'utf8');
console.log(JSON.stringify({
  wrote: partPath,
  bytes: part.length,
  sources: hashes
}, null, 2));