GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / spiders / codex/build-plan

Validate and 9 more files

A Python command-line tool in the plan tracker folder of Spiders that reads plan and validation, using SHA-256.

591 lines of Python and JavaScript from spiders, in 10 files. Topic: AI agents and coordination. Section 1644 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 Audit Test test · spiders / codex/build-plan/estate-audit.test.py lines 1–27
  2. Viewer Browser storage · spiders / codex/build-plan/viewer.browser.mjs lines 1–25
  3. Viewer render · spiders / codex/build-plan/viewer.mjs lines 1–25
  4. Campaign storage · spiders / codex/reload/plan-tracker/campaign.py lines 1–97
  5. Observe CI automation · spiders / codex/reload/plan-tracker/observe_ci.py lines 1–54
  6. Test Campaign test · spiders / codex/reload/plan-tracker/test_campaign.py lines 1–41
  7. Test Roadmap test · spiders / codex/reload/plan-tracker/test_roadmap.py lines 1–31
  8. Test Validate test · spiders / codex/reload/plan-tracker/test_validate.py lines 1–88
  9. Validate storage · spiders / codex/reload/plan-tracker/validate.py lines 1–156
  10. Validate Roadmap other · spiders / codex/reload/plan-tracker/validate_roadmap.py lines 1–47

Estate Audit Test

A test in the build plan folder of Spiders. It audits test (`AuditTest`).

testspiders / codex/build-plan/estate-audit.test.py · lines 1–27 of 27 · Entry point

What it does
It tests its inputs. Defines AuditTest, test_reference_evidence, test_prewrite_budget. Uses libraries importlib.util, pathlib, tempfile, unittest. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file small.json; JSON file large.json.
Downstream impact
Used directly by 1 file: Estate Audit Workflow (spiders).
What it achieves
Defines `AuditTest`, `test_reference_evidence` and `test_prewrite_budget`.
Why it matters
Run by Estate Audit Workflow.
Application
spiders · codex/build-plan · test
Uses
importlib.util, pathlib, tempfile, unittest
Used by
run by Estate Audit Workflow (workflow run)
Produces
AuditTest
Defines here
AuditTest, test_reference_evidence, test_prewrite_budget
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 codex/build-plan/estate-audit.test.py:1-27 · blob 5b94795292bd2f38cbf4c2f03fa1e888cf0b4e1c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import importlib.util
from pathlib import Path
import tempfile
import unittest

spec = importlib.util.spec_from_file_location('audit', Path(__file__).with_name('estate-audit.py'))
audit = importlib.util.module_from_spec(spec)
spec.loader.exec_module(audit)


class AuditTest(unittest.TestCase):
    def test_reference_evidence(self):
        self.assertEqual(audit.references('uses: actions/checkout@abc\nnode scripts/run.mjs\nhttps://github.com/Ventusltd/gridatlas'), [
            ('action-reference', 'actions/checkout@abc'), ('repository-reference', 'Ventusltd/gridatlas'), ('script-reference', 'scripts/run.mjs')])

    def test_prewrite_budget(self):
        with tempfile.TemporaryDirectory() as folder:
            root = Path(folder)
            receipt = audit.save(root, 'small.json', {'key': 'a'})
            self.assertEqual(receipt['bytes'], len((root / 'small.json').read_bytes()))
            with self.assertRaises(ValueError):
                audit.save(root, 'large.json', {'value': 'x' * audit.MAX_PART})
            self.assertFalse((root / 'large.json').exists())


if __name__ == '__main__':
    unittest.main()

Viewer Browser

A JavaScript module in the build plan folder of Spiders.

storagespiders / codex/build-plan/viewer.browser.mjs · lines 1–25 of 25 · Not reached from any entry point (candidate for review)

What it does
It fetches data. Defines arg. Uses libraries node:fs/promises, node:path, node:assert/strict, node:url. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file nodes.json; command-line arguments. Out: JSON file results.json.
What it achieves
Defines `arg`.
Why it matters
No other file in the estate was found to import it.
Application
spiders · codex/build-plan · JavaScript module
Uses
node:fs/promises, node:path, node:assert/strict, node:url
Used by
none found
Produces
arg
Defines here
arg
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 codex/build-plan/viewer.browser.mjs:1-25 · blob 6f26f3c60d2f5eb15e3b435a3da21c9f9e91be9c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import fs from 'node:fs/promises';
import path from 'node:path';
import assert from 'node:assert/strict';
import {pathToFileURL} from 'node:url';
const arg=name=>process.argv.find(a=>a.startsWith(`--${name}=`))?.slice(name.length+3);
const {chromium}=await import(pathToFileURL(arg('playwright')));
const out=path.resolve(arg('out'));await fs.mkdir(out,{recursive:true});
const records=[];
for(const viewport of [{width:1400,height:900},{width:393,height:852}]){
 let browser;const record={viewport,ok:false};
 try{
  browser=await chromium.launch({channel:'chrome',headless:true});const page=await browser.newPage({viewport});
  const errors=[];page.on('pageerror',e=>errors.push(String(e)));
  await page.goto(arg('base'));await page.locator('#status').filter({hasText:'Validated:100'.replace(':',': ')}).waitFor();
  assert.equal(await page.locator('#build option').count(),100);
  await page.locator('#build').selectOption('ATLAS-41');await page.locator('#title').filter({hasText:'Metals source adapter'}).waitFor();
  assert.match(await page.locator('#relations').innerText(),/migration_source/);
  await page.locator('summary').click();assert.match(await page.locator('#detail').innerText(),/blocked_pending_dependency_audit/);
  await page.screenshot({path:path.join(out,`plan-${viewport.width}.png`),fullPage:true});
  assert.deepEqual(errors,[]);record.relations=await page.locator('#relations li').count();
  await page.route('**/data/nodes.json',async route=>{const r=await route.fetch();const d=await r.json();d.features.pop();await route.fulfill({json:d});});
  await page.reload();await page.locator('#status').filter({hasText:'Plan refused:'}).waitFor();record.tamperedGraphRefused=true;record.ok=true;
 }catch(e){record.error=String(e);process.exitCode=1;}finally{await browser?.close();records.push(record);}
}
await fs.writeFile(path.join(out,'results.json'),JSON.stringify({scope:'Real Chrome viewer interaction and tampered graph refusal; viewport emulation, not physical devices',records},null,2)+'\n');console.log(JSON.stringify(records));

Viewer

A JavaScript module in the build plan folder of Spiders that draws master plan, using SHA-256. It is built from the SVG step (`svg`) and the draw step (`draw`).

renderspiders / codex/build-plan/viewer.mjs · lines 1–25 of 25 · Not reached from any entry point (candidate for review) · pattern canonical (shared by 28 files)

What it does
It draws master plan. Defines 6 functions or classes, including $, canonical, hash, read, svg. Side effects: changes the web page (DOM); makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: GeoJSON file master-plan.geojson; JSON file nodes.json; JSON file edges.json. Out: SVG drawing.
What it achieves
Defines `canonical`, `hash`, `read` and 2 more. It responds to change events.
Why it matters
No other file in the estate was found to import it.
Application
spiders · codex/build-plan · JavaScript module
Uses
none found
Used by
none found
Produces
$, canonical, hash, read, svg, draw
Defines here
$, canonical, hash, read, svg, draw
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 codex/build-plan/viewer.mjs:1-25 · blob 302136f1c4a819e951036e7b3826aa1d8ea35983 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
const $=id=>document.getElementById(id);
const canonical=x=>Array.isArray(x)?'['+x.map(canonical).join(',')+']':x!==null&&typeof x==='object'?'{'+Object.keys(x).sort().map(k=>JSON.stringify(k)+':'+canonical(x[k])).join(',')+'}':JSON.stringify(x);
const hash=async x=>Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256',new TextEncoder().encode(canonical(x)))),b=>b.toString(16).padStart(2,'0')).join('');
async function read(url){const r=await fetch(url);if(!r.ok)throw Error(`${url} HTTP ${r.status}`);return r.json();}
try{
 const [plan,manifest,nodeDoc,edgeDoc]=await Promise.all(['./master-plan.geojson','./data/manifest.json','./data/nodes.json','./data/edges.json'].map(read));
 const digests=await Promise.all([plan,nodeDoc,edgeDoc].map(hash));
 if(digests.some((d,i)=>d!==manifest.provenance[['planSha256','nodesSha256','edgesSha256'][i]]))throw Error('Plan and graph digests do not match');
 const nodes=nodeDoc.features,edges=edgeDoc.edges;
 if(plan.features.length!==100||nodes.length!==manifest.counts.nodes||edges.length!==manifest.counts.edges||edges.some(e=>!nodes[e[0]]||!nodes[e[1]]))throw Error('Invalid graph counts or endpoints');
 for(const f of plan.features){const o=document.createElement('option');o.value=f.id;o.textContent=`${f.id} — ${f.properties.title}`;$('build').append(o);}
 $('status').textContent=`Validated: ${plan.features.length} builds, ${nodes.length} nodes, ${edges.length} unique relationships. All builds planned. Revision ${plan.metadata.revision}.`;
 const svgNS='http://www.w3.org/2000/svg';
 function svg(name,attrs,text){const e=document.createElementNS(svgNS,name);for(const [k,v]of Object.entries(attrs))e.setAttribute(k,v);if(text)e.textContent=text;$('graph').append(e);return e;}
 function draw(){
  const id=$('build').value,f=plan.features.find(f=>f.id===id),index=nodes.findIndex(n=>n.id==='build:'+id);
  const related=edges.filter(e=>e[0]===index||e[1]===index);$('graph').replaceChildren();$('relations').replaceChildren();
  const neighbors=[...new Set(related.map(e=>e[0]===index?e[1]:e[0]))];
  const positions=new Map([[index,[550,220]]]);neighbors.forEach((n,i)=>{const a=i*2*Math.PI/neighbors.length;positions.set(n,[550+385*Math.cos(a),220+170*Math.sin(a)]);});
  for(const e of related){const [a,b]=[positions.get(e[0]),positions.get(e[1])];svg('line',{x1:a[0],y1:a[1],x2:b[0],y2:b[1]});const li=document.createElement('li');li.textContent=`${nodes[e[0]].properties.label} → ${e[2]} → ${nodes[e[1]].properties.label}`;$('relations').append(li);}
  for(const [n,[x,y]]of positions){svg('rect',{x:x-125,y:y-20,width:250,height:40,rx:8});const label=nodes[n].properties.label;svg('text',{x,y:y+4,'text-anchor':'middle'},label.length>35?label.slice(0,32)+'…':label);}
  $('title').textContent=`${id}: ${f.properties.title}`;$('change').textContent=f.properties.change;$('detail').textContent=JSON.stringify(f.properties,null,2);
 }
 $('build').addEventListener('change',draw);draw();
}catch(error){$('status').textContent='Plan refused: '+error.message;}

Campaign

A Python command-line tool in the plan tracker folder of Spiders that fetches checkpoint, using SHA-256 from GitHub API.

storagespiders / codex/reload/plan-tracker/campaign.py · lines 1–97 of 97 · Entry point

What it does
It fetches checkpoint. Defines sha, validate, check, main. Uses libraries argparse, datetime, hashlib, json, re. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: data source: GitHub API; JSON file -checkpoint.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the sha step (`sha`), the validate step (`validate`) and the check step (`check`). Validate the five-version ledger and observe publication CI without dispatching it. It accepts `--ledger`, `--evidence-root` and `--out`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
spiders · codex/reload/plan-tracker · Python CLI
Uses
argparse, datetime, hashlib, json, re, urllib.request, pathlib
Used by
none found
Produces
sha, validate, main
Defines here
sha, validate, check, 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 codex/reload/plan-tracker/campaign.py:1-97 · blob 20a7d42ea5f3f40da871bbc6570638324f43a854 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Validate the five-version ledger and observe publication CI without dispatching it."""
import argparse
import datetime
import hashlib
import json
import re
import urllib.request
from pathlib import Path


def sha(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def validate(ledger, root):
    errors = []
    seen = set()
    def check(ok, message):
        if not ok:
            errors.append(message)
    for slot in ledger['versions']:
        label = slot['id']
        state = slot['status']
        check(state in {'planned', 'in_progress', 'built', 'deployed', 'tested', 'accepted', 'failed'}, label + ': unknown status')
        generation = slot.get('generation')
        if generation:
            check(bool(re.fullmatch(r'\d{12}', generation)), label + ': malformed generation')
            check(generation not in seen, label + ': duplicate generation')
            seen.add(generation)
        if state in {'built', 'deployed', 'tested', 'accepted'}:
            check(bool(generation), label + ': missing generation')
            for key in ('sourceCommit', 'engineCommit'):
                check(bool(re.fullmatch('[0-9a-f]{40}', slot.get(key) or '')), label + ': missing ' + key)
            check(bool(re.fullmatch('[0-9a-f]{64}', slot.get('buildSha256') or '')), label + ': missing buildSha256')
        if state in {'deployed', 'tested', 'accepted'}:
            check(bool(re.fullmatch('[0-9a-f]{40}', slot.get('publicationCommit') or '')), label + ': missing publicationCommit')
        kinds = set()
        for ref in slot.get('evidence', []):
            try:
                path = (root / ref['path']).resolve()
                check(path.is_relative_to(root.resolve()), label + ': evidence escapes offline root')
                if not path.is_relative_to(root.resolve()):
                    continue
                check(sha(path) == ref['sha256'], label + ': evidence bytes changed')
                # Measured record is still reviewed by the domain owner; no screenshot/string inference.
                if ref.get('result') == 'pass' and ref.get('generation') == generation:
                    expected_identity = {key: slot.get(key) for key in ('generation', 'sourceCommit', 'engineCommit', 'buildSha256')}
                    check(ref.get('release') == expected_identity, label + ': evidence release identity mismatch')
                    kinds.add(ref['kind'])
            except (KeyError, OSError) as error:
                errors.append(label + ': unavailable evidence ' + str(error))
        if state in {'deployed', 'tested', 'accepted'}:
            check('served-bytes' in kinds, label + ': missing exact served-byte receipt')
        if state in {'tested', 'accepted'}:
            check('real-app-browser' in kinds, label + ': missing real app browser receipt')
            check(set(slot['requiredProofs']) <= kinds, label + ': missing substantive change proof')
        if state == 'accepted':
            check(not slot.get('unresolvedBlockers'), label + ': accepted with unresolved blocker')
    check(len(ledger['versions']) >= 5, 'campaign requires at least five version slots')
    return errors


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--ledger', type=Path, required=True)
    parser.add_argument('--evidence-root', type=Path, required=True)
    parser.add_argument('--out', type=Path, required=True)
    parser.add_argument('--observe-ci', action='store_true')
    args = parser.parse_args()
    if not args.out.resolve().is_relative_to(args.evidence_root.resolve()):
        parser.error('write campaign observations only beneath the evidence folder')
    ledger = json.loads(args.ledger.read_text(encoding='utf8'))
    errors = validate(ledger, args.evidence_root)
    result = {'schema': 'spiders.five-version-checkpoint.v1',
              'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(),
              'ledgerSha256': sha(args.ledger), 'errors': errors,
              'scope': 'Receipt references and CI observations; not an independent rerun of product proofs.',
              'versions': [{k: s.get(k) for k in ('id', 'generation', 'status', 'nextAction')} for s in ledger['versions']]}
    if args.observe_ci:
        try:
            url = 'https://api.github.com/repos/Ventusltd/globalgrid2050/actions/runs?per_page=8'
            request = urllib.request.Request(url, headers={'User-Agent': 'spiders-build-context'})
            with urllib.request.urlopen(request, timeout=20) as response:
                runs = json.load(response)['workflow_runs']
            result['publicationCI'] = [{k: r.get(k) for k in ('id', 'name', 'head_sha', 'status', 'conclusion', 'html_url')} for r in runs]
        except Exception as error:
            errors.append('CI observation failed: ' + str(error))
    args.out.mkdir(parents=True, exist_ok=True)
    stamp = datetime.datetime.now(datetime.timezone.utc).strftime('%Y%m%dT%H%M%S%fZ')
    output = args.out / (stamp + '-checkpoint.json')
    output.write_text(json.dumps(result, indent=2) + '\n', encoding='utf8')
    print(json.dumps({'errors': errors, 'versions': result['versions'], 'receipt': str(output)}))
    raise SystemExit(bool(errors))


if __name__ == '__main__':
    main()

Observe CI

A Python command-line tool in the plan tracker folder of Spiders that fetches plan and CI context from GitHub API.

automationspiders / codex/reload/plan-tracker/observe_ci.py · lines 1–54 of 54 · Entry point · pattern inspect (shared by 40 files)

What it does
It fetches plan and CI context. Defines fetch, inspect, main. Uses libraries argparse, concurrent.futures, datetime, json, urllib.request. Side effects: reads or writes files; makes network requests.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "`observe_ci.py` uses public read-only GitHub REST."
Inputs & outputs
In: data source: GitHub API; JSON file plan.json; command-line arguments. Out: JSON file ci-context.json.
Downstream impact
Used directly by 1 file: Build Context Workflow (spiders).
What it achieves
It is built from the fetch step (`fetch`) and the inspect step (`inspect`). Read exact public GitHub Actions runs; never dispatch, rerun or promote a release. It accepts `--plan` and `--out`.
Why it matters
Run by Build Context Workflow.
Application
spiders · codex/reload/plan-tracker · Python CLI
Uses
argparse, concurrent.futures, datetime, json, urllib.request, pathlib
Used by
run by Build Context Workflow (workflow run)
Produces
fetch, inspect, main
Defines here
fetch, inspect, 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 codex/reload/plan-tracker/observe_ci.py:1-54 · blob 5e75e02cf1eb0208e196a94e87b67219a21aeea2 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Read exact public GitHub Actions runs; never dispatch, rerun or promote a release."""
import argparse
import concurrent.futures
import datetime
import json
import urllib.request
from pathlib import Path


def fetch(url):
    request = urllib.request.Request(url, headers={'User-Agent': 'spiders-build-context', 'Accept': 'application/vnd.github+json'})
    with urllib.request.urlopen(request, timeout=20) as response:
        return json.load(response)


def inspect(target):
    repo, run_id = target['repository'], target['runId']
    base = f'https://api.github.com/repos/{repo}/actions/runs/{run_id}'
    record = {'repository': repo, 'runId': run_id, 'taskId': target['taskId'], 'scope': target['scope']}
    try:
        run = fetch(base)
        record.update({key: run.get(key) for key in ('head_sha', 'status', 'conclusion', 'html_url', 'updated_at')})
        record['expectedCommit'] = target['commit']
        record['identityMatches'] = run['head_sha'] == target['commit']
        jobs = fetch(base + '/jobs?per_page=100')
        record['jobsComplete'] = jobs['total_count'] <= 100
        record['jobs'] = [{'name': job['name'], 'conclusion': job['conclusion'], 'steps': [
            {'name': step['name'], 'status': step['status'], 'conclusion': step['conclusion']}
            for step in job.get('steps', [])]} for job in jobs['jobs']]
    except Exception as error:
        record['error'] = type(error).__name__ + ': ' + str(error)
    return record


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--plan', type=Path, default=Path(__file__).with_name('plan.json'))
    parser.add_argument('--out', type=Path, required=True)
    args = parser.parse_args()
    targets = json.loads(args.plan.read_text(encoding='utf8'))['ciWatch']
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as pool:
        records = list(pool.map(inspect, targets))
    result = {'schema': 'spiders.ci-context.v1', 'observedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(),
              'scope': 'Read-only historical exact-run observations, not latest-head or product certification.', 'runs': records}
    args.out.mkdir(parents=True, exist_ok=True)
    (args.out / 'ci-context.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf8')
    errors = sum(bool(r.get('error')) or not r.get('identityMatches', False) or not r.get('jobsComplete', False) for r in records)
    print(json.dumps({'observed': len(records), 'observationErrors': errors, 'productFailures': sum(r.get('conclusion') == 'failure' for r in records)}))
    # Product failures stay visible in the receipt; this exit reports observer health.
    raise SystemExit(1 if errors else 0)


if __name__ == '__main__':
    main()

Test Campaign

A test in the plan tracker folder of Spiders that uses SHA-256. It sets up (`setUp`) and is built from the campaign receipts class (`CampaignReceipts`).

testspiders / codex/reload/plan-tracker/test_campaign.py · lines 1–41 of 41 · Entry point

What it does
It tests its inputs. Defines CampaignReceipts, setUp, test_empty_slots_are_pending_not_accepted, test_same_generation_wrong_engine_proof_rejected. Uses libraries copy, importlib.util, tempfile, unittest, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file proof.json.
Downstream impact
Used directly by 1 file: Build Context Workflow (spiders).
What it achieves
Defines `CampaignReceipts`, `setUp`, `test_empty_slots_are_pending_not_accepted` and 1 more.
Why it matters
Run by Build Context Workflow.
Application
spiders · codex/reload/plan-tracker · test
Uses
copy, importlib.util, tempfile, unittest, pathlib
Used by
run by Build Context Workflow (workflow run)
Produces
CampaignReceipts
Defines here
CampaignReceipts, setUp, test_empty_slots_are_pending_not_accepted, test_same_generation_wrong_engine_proof_rejected
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 codex/reload/plan-tracker/test_campaign.py:1-41 · blob 79f1dd66fc20d77c1712c380fe8df534e0840ac5 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import copy
import importlib.util
import tempfile
import unittest
from pathlib import Path

spec = importlib.util.spec_from_file_location('campaign', Path(__file__).with_name('campaign.py'))
campaign = importlib.util.module_from_spec(spec)
spec.loader.exec_module(campaign)


class CampaignReceipts(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.root = Path(self.temp.name)
        self.ledger = {'versions': [{'id': 'V' + str(i), 'status': 'planned', 'generation': None,
                                   'requiredProofs': ['geometry'], 'evidence': []} for i in range(1, 6)]}

    def test_empty_slots_are_pending_not_accepted(self):
        self.assertEqual([], campaign.validate(self.ledger, self.root))
        self.ledger['versions'][0]['status'] = 'accepted'
        errors = campaign.validate(self.ledger, self.root)
        self.assertTrue(any('missing exact served-byte' in e for e in errors))
        self.assertTrue(any('missing real app' in e for e in errors))

    def test_same_generation_wrong_engine_proof_rejected(self):
        slot = self.ledger['versions'][0]
        slot.update(status='built', generation='202609051844', sourceCommit='a' * 40,
                    engineCommit='b' * 40, buildSha256='c' * 64)
        artifact = self.root / 'proof.json'
        artifact.write_text('{"ok":true}')
        identity = {key: slot[key] for key in ('generation', 'sourceCommit', 'engineCommit', 'buildSha256')}
        identity['engineCommit'] = 'd' * 40
        slot['evidence'] = [{'path': artifact.name, 'sha256': campaign.sha(artifact),
                            'kind': 'geometry', 'result': 'pass', 'generation': slot['generation'], 'release': identity}]
        self.assertTrue(any('identity mismatch' in e for e in campaign.validate(self.ledger, self.root)))


if __name__ == '__main__':
    unittest.main()

Test Roadmap

A test in the plan tracker folder of Spiders that checks Validate Roadmap. It sets up (`setUp`) and is built from the roadmap proof class (`RoadmapProof`).

testspiders / codex/reload/plan-tracker/test_roadmap.py · lines 1–31 of 31 · Entry point

What it does
It tests its inputs. Defines RoadmapProof, setUp, test_real_queue_and_duplicate, test_cycle_cannot_be_scheduled, test_roadmap_cannot_invent_completion_or_receipts. Uses libraries copy, json, pathlib, unittest. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file NEXT-50.json.
Downstream impact
Used directly by 1 file: Build Context Workflow (spiders).
What it achieves
Defines `RoadmapProof`, `setUp`, `test_real_queue_and_duplicate` and 2 more.
Why it matters
Run by Build Context Workflow.
Application
spiders · codex/reload/plan-tracker · test
Uses
Validate Roadmap (import), copy, json, pathlib, unittest
Used by
run by Build Context Workflow (workflow run)
Produces
RoadmapProof
Defines here
RoadmapProof, setUp, test_real_queue_and_duplicate, test_cycle_cannot_be_scheduled, test_roadmap_cannot_invent_completion_or_receipts
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 codex/reload/plan-tracker/test_roadmap.py:1-31 · blob cf222333043ba2f6f4aca2e3363b498d384c7e90 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import copy
import json
from pathlib import Path
import unittest
from validate_roadmap import validate


class RoadmapProof(unittest.TestCase):
    def setUp(self):
        self.plan = json.loads(Path(__file__).with_name('NEXT-50.json').read_bytes())

    def test_real_queue_and_duplicate(self):
        self.assertEqual(validate(self.plan), [])
        self.plan['items'][1]['id'] = 'N01'
        self.assertTrue(validate(self.plan))

    def test_cycle_cannot_be_scheduled(self):
        self.plan['items'][0]['dependsOn'] = ['N02']
        self.assertIn('dependency cycle', validate(self.plan))

    def test_roadmap_cannot_invent_completion_or_receipts(self):
        row = self.plan['items'][0]
        row['status'] = 'accepted'
        self.assertTrue(validate(self.plan))
        row['status'] = 'linked'
        row.pop('checkpoint', None)
        self.assertTrue(validate(self.plan))


if __name__ == '__main__':
    unittest.main()

Test Validate

A test in the plan tracker folder of Spiders that uses SHA-256. It sets up (`setUp`) and is built from the checkpoint proofs class (`CheckpointProofs`).

testspiders / codex/reload/plan-tracker/test_validate.py · lines 1–88 of 88 · Entry point

What it does
It tests its inputs. Defines 11 functions or classes, including CheckpointProofs, setUp, save_proof, test_completed_without_proof_fails, test_wrong_release_fails_even_with_correct_hash. Uses libraries copy, hashlib, importlib.util, json, tempfile. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file actual-test.json; JSON file proof.json; JSON file outside.json. Out: JSON file actual-test.json.
Downstream impact
Used directly by 1 file: Build Context Workflow (spiders).
What it achieves
Defines `CheckpointProofs`, `setUp`, `save_proof` and 8 more.
Why it matters
Run by Build Context Workflow.
Application
spiders · codex/reload/plan-tracker · test
Uses
copy, hashlib, importlib.util, json, tempfile, unittest, pathlib
Used by
run by Build Context Workflow (workflow run)
Produces
CheckpointProofs
Defines here
CheckpointProofs, setUp, save_proof, test_completed_without_proof_fails, test_wrong_release_fails_even_with_correct_hash, test_valid_receipt_then_underlying_tamper, test_claim_and_incomplete_dependency_cannot_complete, test_cycle_and_escaping_path_fail, test_completion_not_validated_without_offline_evidence, test_wrong_owning_commit_rejected, test_wrong_environment_rejected
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 codex/reload/plan-tracker/test_validate.py:1-88 · blob caf6f2194ad22f8b176d18725e7ebb3f2c6048b5 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
import copy
import hashlib
import importlib.util
import json
import tempfile
import unittest
from pathlib import Path

spec = importlib.util.spec_from_file_location('plan_validator', Path(__file__).with_name('validate.py'))
validator = importlib.util.module_from_spec(spec)
spec.loader.exec_module(validator)


class CheckpointProofs(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.addCleanup(self.temp.cleanup)
        self.root = Path(self.temp.name)
        self.release = {'generation': '202609051820', 'sourceCommit': 'a' * 40,
                        'engineCommit': 'b' * 40, 'buildSha256': 'c' * 64}
        self.plan = {'schema': 'spiders.build-plan.v1', 'baselineRelease': self.release,
                     'tasks': [{'id': 'P2', 'status': 'completed', 'owner': 'teleprinter',
                                'nextAction': 'retained acceptance', 'acceptance': 'actual app path',
                                'dependsOn': [], 'requiredProofs': ['app-pdf'],
                                'targetRelease': self.release, 'targetCommits': {'teleprinter': 'b' * 40},
                                'targetEnvironments': {'app-pdf': 'Chrome desktop'}, 'proofs': []}]}
        artifact = self.root / 'actual-test.json'
        artifact.write_text('{"ok":true,"forbiddenCalls":0}')
        self.proof = {'schema': 'spiders.build-proof.v1', 'taskId': 'P2', 'kind': 'app-pdf',
                      'result': 'pass', 'verification': 'measured', 'checkedAt': '2026-09-05T18:00:00Z',
                      'environment': 'Chrome desktop', 'release': copy.deepcopy(self.release),
                      'commits': {'teleprinter': 'b' * 40},
                      'artifacts': [{'path': artifact.name, 'sha256': validator.digest(artifact)}]}

    def save_proof(self):
        path = self.root / 'proof.json'
        path.write_text(json.dumps(self.proof))
        self.plan['tasks'][0]['proofs'] = [{'path': path.name, 'sha256': validator.digest(path)}]

    def test_completed_without_proof_fails(self):
        self.assertTrue(any('missing proof categories' in e for e in validator.validate(self.plan, self.root)))

    def test_wrong_release_fails_even_with_correct_hash(self):
        self.proof['release']['generation'] = '202609051623'
        self.save_proof()
        self.assertTrue(any('wrong release identity' in e for e in validator.validate(self.plan, self.root)))

    def test_valid_receipt_then_underlying_tamper(self):
        self.save_proof()
        self.assertEqual([], validator.validate(self.plan, self.root))
        (self.root / 'actual-test.json').write_text('{"ok":false}')
        self.assertTrue(any('underlying artifact changed' in e for e in validator.validate(self.plan, self.root)))

    def test_claim_and_incomplete_dependency_cannot_complete(self):
        self.proof['verification'] = 'recorded-claim'
        self.save_proof()
        self.plan['tasks'].append({'id': 'P1', 'status': 'in_progress', 'owner': 'testcode',
                                   'nextAction': 'inspect', 'acceptance': 'pass', 'dependsOn': []})
        self.plan['tasks'][0]['dependsOn'] = ['P1']
        errors = validator.validate(self.plan, self.root)
        self.assertTrue(any('incomplete prerequisite' in e for e in errors))
        self.assertTrue(any('recorded claim' in e for e in errors))

    def test_cycle_and_escaping_path_fail(self):
        self.save_proof()
        self.plan['tasks'][0]['dependsOn'] = ['P2']
        self.plan['tasks'][0]['proofs'][0]['path'] = '../outside.json'
        errors = validator.validate(self.plan, self.root)
        self.assertTrue(any('dependency cycle' in e for e in errors))
        self.assertTrue(any('beneath' in e for e in errors))

    def test_completion_not_validated_without_offline_evidence(self):
        self.save_proof()
        self.assertTrue(any('local evidence' in e for e in validator.validate(self.plan)))

    def test_wrong_owning_commit_rejected(self):
        self.proof['commits']['teleprinter'] = 'd' * 40
        self.save_proof()
        self.assertTrue(any('wrong owning commit' in e for e in validator.validate(self.plan, self.root)))

    def test_wrong_environment_rejected(self):
        self.proof['environment'] = 'Plain static localhost server'
        self.save_proof()
        self.assertTrue(any('wrong environment identity' in e for e in validator.validate(self.plan, self.root)))


if __name__ == '__main__':
    unittest.main()

Validate

A Python command-line tool in the plan tracker folder of Spiders that reads plan and validation, using SHA-256.

storagespiders / codex/reload/plan-tracker/validate.py · lines 1–156 of 156 · Entry point · pattern visit (shared by 13 files)

What it does
It loads plan and validation. Defines 6 functions or classes, including digest, beneath, validate, require, visit. Uses libraries argparse, hashlib, json, re, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file plan.json; JSON file NEXT-50.json; command-line arguments. Out: JSON file validation.json.
Downstream impact
Used directly by 1 file: Build Context Workflow (spiders).
What it achieves
It is built from the digest step (`digest`), the beneath step (`beneath`) and the validate step (`validate`). Validate resumable build checkpoints. Receipt integrity is not product certification. It accepts `--plan`, `--evidence-root` and `--out`.
Why it matters
Run by Build Context Workflow.
Application
spiders · codex/reload/plan-tracker · Python CLI
Uses
Validate Roadmap (import), argparse, hashlib, json, re, pathlib
Used by
run by Build Context Workflow (workflow run)
Produces
digest, beneath, validate, main
Defines here
digest, beneath, validate, require, visit, 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 codex/reload/plan-tracker/validate.py:1-156 · blob a6a85ac6753e2fca07088744684467571b4565bc · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Validate resumable build checkpoints. Receipt integrity is not product certification."""
import argparse
import hashlib
import json
import re
from pathlib import Path

STATES = {'planned', 'in_progress', 'blocked', 'completed'}
SHA = re.compile(r'^[0-9a-f]{40}$')
HASH = re.compile(r'^[0-9a-f]{64}$')
RELEASE_KEYS = ('generation', 'sourceCommit', 'engineCommit', 'buildSha256')


def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()


def beneath(root, relative):
    path = (root / relative).resolve()
    if not path.is_relative_to(root.resolve()) or Path(relative).is_absolute():
        raise ValueError('receipt path must stay beneath its supplied evidence root')
    return path


def validate(plan, root=None):
    errors = []
    def require(condition, message):
        if not condition:
            errors.append(message)
    require(plan.get('schema') == 'spiders.build-plan.v1', 'unsupported schema')
    tasks = plan.get('tasks', [])
    by_id = {t.get('id'): t for t in tasks}
    require(len(by_id) == len(tasks), 'duplicate task ID')
    release = plan.get('baselineRelease', {})
    require(bool(re.fullmatch(r'\d{12}', release.get('generation', ''))), 'invalid baseline generation')
    for key in ('sourceCommit', 'engineCommit'):
        require(bool(SHA.fullmatch(release.get(key, ''))), 'invalid baseline ' + key)
    require(bool(HASH.fullmatch(release.get('buildSha256', ''))), 'invalid baseline build hash')
    if root is not None:
        for ref in plan.get('handoverEvidence', []):
            try:
                require(digest(beneath(root, ref['path'])) == ref['sha256'], 'handover evidence changed: ' + ref['path'])
            except (OSError, ValueError, KeyError) as error:
                errors.append('handover evidence unavailable: ' + str(error))
    # Dependency cycles prevent any trustworthy resume order.
    def visit(task_id, stack):
        if task_id in stack:
            require(False, 'dependency cycle: ' + ' -> '.join(stack + [task_id]))
            return
        for dep in by_id[task_id].get('dependsOn', []):
            if dep in by_id:
                visit(dep, stack + [task_id])
    for task_id in by_id:
        visit(task_id, [])
    for task in tasks:
        tid = task.get('id', '<missing>')
        require(task.get('status') in STATES, tid + ': invalid status')
        for key in ('owner', 'nextAction', 'acceptance'):
            require(bool(task.get(key)), tid + ': missing ' + key)
        for dep in task.get('dependsOn', []):
            require(dep in by_id, tid + ': unknown dependency ' + dep)
            if task.get('status') == 'completed':
                require(by_id.get(dep, {}).get('status') == 'completed', tid + ': incomplete prerequisite ' + dep)
        if task.get('status') == 'blocked':
            require(bool(task.get('blockers')), tid + ': blocked without blocker')
        if task.get('status') != 'completed':
            continue
        require(root is not None, tid + ': completion requires local evidence validation')
        required = set(task.get('requiredProofs', []))
        require(bool(required), tid + ': completion has no required proof categories')
        proved = set()
        for ref in task.get('proofs', []):
            try:
                require(bool(HASH.fullmatch(ref.get('sha256', ''))), tid + ': invalid receipt digest')
                if root is None:
                    continue
                path = beneath(root, ref['path'])
                require(digest(path) == ref['sha256'], tid + ': receipt bytes changed')
                receipt = json.loads(path.read_text(encoding='utf8'))
                require(receipt.get('schema') == 'spiders.build-proof.v1', tid + ': unsupported proof schema')
                require(receipt.get('taskId') == tid, tid + ': proof belongs to another task')
                require(receipt.get('result') == 'pass', tid + ': non-passing proof')
                require(receipt.get('verification') == 'measured', tid + ': recorded claim cannot complete task')
                require(bool(receipt.get('checkedAt')), tid + ': missing proof time')
                require(bool(receipt.get('environment')), tid + ': missing environment')
                expected_environment = task.get('targetEnvironments', {}).get(receipt.get('kind'))
                require(bool(expected_environment) and receipt.get('environment') == expected_environment, tid + ': wrong environment identity')
                expected = task.get('targetRelease')
                require(bool(expected), tid + ': completed task lacks explicit target release')
                require(receipt.get('release') == expected, tid + ': wrong release identity')
                require(set((expected or {}).keys()) == set(RELEASE_KEYS), tid + ': incomplete target release tuple')
                if expected:
                    require(bool(re.fullmatch(r'\d{12}', expected.get('generation', ''))), tid + ': invalid target generation')
                    require(all(SHA.fullmatch(expected.get(k, '')) for k in ('sourceCommit', 'engineCommit')), tid + ': invalid target commits')
                    require(bool(HASH.fullmatch(expected.get('buildSha256', ''))), tid + ': invalid target build hash')
                commits = receipt.get('commits', {})
                require(bool(commits) and all(SHA.fullmatch(v) for v in commits.values()), tid + ': missing exact owning commits')
                require(bool(task.get('targetCommits')) and commits == task.get('targetCommits'), tid + ': wrong owning commit identity')
                artifacts = receipt.get('artifacts', [])
                require(bool(artifacts), tid + ': no underlying artifacts')
                for artifact in artifacts:
                    artifact_path = beneath(root, artifact['path'])
                    require(digest(artifact_path) == artifact.get('sha256'), tid + ': underlying artifact changed')
                proved.add(receipt.get('kind'))
            except (OSError, ValueError, KeyError, TypeError) as error:
                errors.append(tid + ': unreadable proof: ' + str(error))
        require(required <= proved, tid + ': missing proof categories ' + ', '.join(sorted(required - proved)))
    return errors


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--plan', type=Path, default=Path(__file__).with_name('plan.json'))
    parser.add_argument('--evidence-root', type=Path)
    parser.add_argument('--out', type=Path, required=True)
    args = parser.parse_args()
    plan = json.loads(args.plan.read_text(encoding='utf8'))
    errors = validate(plan, args.evidence_root)
    roadmap = None
    if plan.get('nextFiftyRoadmap'):
        if plan['nextFiftyRoadmap'] != 'NEXT-50.json':
            errors.append('unsupported roadmap filename')
        else:
            from validate_roadmap import validate as validate_queue
            roadmap_path = args.plan.with_name('NEXT-50.json')
            roadmap = json.loads(roadmap_path.read_bytes())
            errors.extend(validate_queue(roadmap))
    # Deliberately excludes artifact paths, machine paths and arbitrary evidence content.
    result = {'schema': 'spiders.plan-validation.v1', 'planSha256': digest(args.plan),
              'ok': not errors, 'errors': errors,
              'scope': 'Checkpoint structure and supplied receipt integrity; not a product pass.',
              'tasks': [{k: t[k] for k in ('id', 'status', 'owner', 'dependsOn', 'nextAction')} for t in plan['tasks']]}
    result['campaign'] = plan.get('campaign', [])
    if roadmap:
        result['roadmapSha256'] = digest(roadmap_path)
        result['nextFifty'] = [{k: item[k] for k in ('id', 'title', 'owner', 'status', 'dependsOn', 'nextAction', 'generation')} for item in roadmap['items']]
    args.out.mkdir(parents=True, exist_ok=True)
    (args.out / 'validation.json').write_text(json.dumps(result, indent=2) + '\n', encoding='utf8')
    lines = ['# Build plan resume', '', 'Plan SHA-256: ' + result['planSha256'], '', result['scope'], '']
    for task in result['tasks']:
        lines.extend([f"- {task['id']} | {task['status']} | {task['owner']}: {task['nextAction']}"])
    if result['campaign']:
        lines.extend(['', '## Five-version campaign', '', 'Statuses are declared checkpoints; consult exact receipts before advancing.', ''])
        for version in result['campaign']:
            lines.append(f"- {version['id']} | {version.get('generation') or 'not allocated'} | {version['status']}: {version['change']}")
    if roadmap:
        lines.extend(['', '## Next fifty substantive increments', '', 'Roadmap SHA-256: ' + result['roadmapSha256'], 'Planned and in-progress entries are not accepted builds.', ''])
        for item in result['nextFifty']:
            lines.append(f"- {item['id']} | {item['status']} | {item['title']} | dependencies: {', '.join(item['dependsOn']) or 'baseline'}: {item['nextAction']}")
    (args.out / 'RESUME.md').write_text('\n'.join(lines) + '\n', encoding='utf8')
    print(json.dumps({'ok': result['ok'], 'tasks': len(plan['tasks']), 'errors': errors}))
    raise SystemExit(0 if not errors else 1)


if __name__ == '__main__':
    main()

Validate Roadmap

A Python command-line tool in the plan tracker folder of Spiders that checks the next fifty work items; linked receipts are pointers, not acceptance, using SHA-256.

otherspiders / codex/reload/plan-tracker/validate_roadmap.py · lines 1–47 of 47 · Entry point · pattern visit (shared by 13 files)

What it does
Defines validate, visit. Uses libraries json, re, pathlib. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'codex'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: JSON file NEXT-50.json.
Downstream impact
Used directly by 3 files: Test Roadmap (spiders); Validate (spiders); Build Context Workflow (spiders).
What it achieves
Its name says it validates roadmap. Defines `validate` and `visit`.
Why it matters
Imported by Validate. Run by Build Context Workflow. Checked by Test Roadmap.
Application
spiders · codex/reload/plan-tracker · Python CLI
Uses
json, re, pathlib
Used by
imported by Test Roadmap (import), imported by Validate (import), run by Build Context Workflow (workflow run)
Produces
validate
Defines here
validate, visit
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
spiders@78fc0f90bd5ca73f3d5d7c0e0b7b5712cfe781e5 codex/reload/plan-tracker/validate_roadmap.py:1-47 · blob 3f259757c9209f58d5e8e0266e889ef447d5891d · GitHub at these lines
State
achieves: name · context: readme_derived · stage: ingest · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Check the next fifty work items; linked receipts are pointers, not acceptance."""
import json
import re
from pathlib import Path


def validate(data):
    errors = []
    rows = data.get('items', [])
    expected = {f'N{i:02}' for i in range(1, 51)}
    ids = [row.get('id') for row in rows]
    if len(ids) != 50 or set(ids) != expected:
        errors.append('exactly fifty unique N01..N50 items required')
    by_id = {row.get('id'): row for row in rows}
    for row in rows:
        for key in ['title', 'owner', 'module', 'feature', 'requiredProof', 'nextAction']:
            if not isinstance(row.get(key), str) or not row[key].strip():
                errors.append(f'{row.get("id")}: missing {key}')
        if row.get('status') not in ['planned', 'in_progress', 'blocked', 'linked']:
            errors.append(f'{row.get("id")}: roadmap cannot declare acceptance')
        if row.get('generation') and not re.fullmatch(r'\d{12}', row['generation']):
            errors.append(f'{row.get("id")}: invalid generation')
        if row.get('status') == 'linked':
            receipt = row.get('checkpoint', {})
            if not row.get('generation') or not receipt.get('path') or not re.fullmatch('[0-9a-f]{64}', receipt.get('sha256', '')):
                errors.append(f'{row.get("id")}: linked work requires generation and hashed checkpoint')
        if any(dep not in expected for dep in row.get('dependsOn', [])):
            errors.append(f'{row.get("id")}: unknown dependency')
    visiting, visited = set(), set()
    def visit(key):
        if key in visiting:
            errors.append('dependency cycle'); return
        if key in visited or key not in by_id:
            return
        visiting.add(key)
        for dep in by_id[key].get('dependsOn', []):
            visit(dep)
        visiting.remove(key); visited.add(key)
    for key in by_id:
        visit(key)
    return errors


if __name__ == '__main__':
    errors = validate(json.loads(Path(__file__).with_name('NEXT-50.json').read_bytes()))
    print(json.dumps({'ok': not errors, 'errors': errors, 'scope': 'Roadmap structure; no product acceptance claim.'}))
    raise SystemExit(bool(errors))