GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / gpu-drivers-for-global-grid / codex

Codex Overnight and 8 more files

A Python command-line tool in GPU Drivers for Global Grid that reads review owners and queue, using SHA-256. It stops child (`stop_child`) and writes JSON (`write_json`).

682 lines of Python and JavaScript from gpu-drivers-for-global-grid, gridmachine2, linux-for-the-power-grid, in 9 files. Topic: AI agents and coordination. Section 1625 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. Codex Monitor Local storage · gpu-drivers-for-global-grid / codex/monitor-local.py lines 1–52
  2. Codex Overnight storage · gpu-drivers-for-global-grid / codex/overnight.py lines 1–181
  3. Codex Precision Schedule storage · gpu-drivers-for-global-grid / codex/precision-schedule.py lines 1–117
  4. Codex Review Group ingest · gpu-drivers-for-global-grid / codex/review-group.py lines 1–30
  5. Codex Review Repo storage · gpu-drivers-for-global-grid / codex/review-repo.py lines 1–101
  6. Codex Review Repo Test test · gpu-drivers-for-global-grid / codex/review-repo.test.py lines 1–27
  7. Claude Report Probe ingest · gridmachine2 / probes/202609071400-claude-report-probe.mjs lines 1–102
  8. Codex Check Citations storage · linux-for-the-power-grid / codex/check-citations.py lines 1–20
  9. Codex Coverage storage · linux-for-the-power-grid / codex/coverage.py lines 1–52

Codex Monitor Local

A Python module in GPU Drivers for Global Grid that reads progress. It is built from the read step (`read`), the state step (`state`) and the handler class (`Handler`).

storagegpu-drivers-for-global-grid / codex/monitor-local.py · lines 1–52 of 52 · Not reached from any entry point (candidate for review) · pattern do_GET (shared by 7 files)

What it does
It loads progress. Defines 6 functions or classes, including read, state, Handler, do_GET, log_message. Uses libraries argparse, datetime, json, pathlib, threading. 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 RUN.json; JSON file STATUS.json; JSON file PROGRESS.json; JSON file FINAL.json; JSON file status.json; command-line arguments. Out: JSON file latest.json.
What it achieves
Read-only loopback progress display for existing overnight controllers. It reads `RUN.json`. It accepts `--run`, `--schedule` and `--out`.
Why it matters
No other file in the estate was found to import it.
Application
gpu-drivers-for-global-grid · codex · Python module
Uses
argparse, datetime, json, pathlib, threading, time, http.server, psutil
Used by
none found
Produces
read, state, Handler, watch
Defines here
read, state, Handler, do_GET, log_message, watch
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe codex/monitor-local.py:1-52 · blob bf4fa8fbcb8c152560f6bd5fa28d936c6b5e9bcf · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Read-only loopback progress display for existing overnight controllers."""
import argparse
import datetime as dt
import json
from pathlib import Path
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import psutil

parser=argparse.ArgumentParser()
parser.add_argument('--run',type=Path,required=True)
parser.add_argument('--schedule',type=Path,required=True)
parser.add_argument('--out',type=Path,required=True)
parser.add_argument('--learning',type=Path)
parser.add_argument('--port',type=int,default=8978)
args=parser.parse_args()
args.out.mkdir(parents=True,exist_ok=True)
def read(path):
    try: return json.loads(path.read_text(encoding='utf-8'))
    except (OSError,ValueError): return {}
run=read(args.run/'RUN.json')
deadline=dt.datetime.fromisoformat(run['startedAt']).timestamp()+run['hours']*3600
def state():
    s=read(args.run/'STATUS.json'); plan=read(args.schedule/'PROGRESS.json')
    age=time.time()-dt.datetime.fromisoformat(s['at']).timestamp() if s.get('at') else None
    try:
        process=psutil.Process(run['pid'])
        alive=any('overnight.py' in a for a in process.cmdline())
    except psutil.Error: alive=False
    learning=read(args.learning/'STATUS.json') if args.learning else {}
    learningFinal=read(args.learning/'FINAL.json') if args.learning else {}
    return {'checkedAt':dt.datetime.now(dt.timezone.utc).isoformat(),'supervisorAlive':alive,'heartbeatAgeSeconds':round(age,1) if age is not None else None,'alert': 'Supervisor absent or heartbeat stale' if not alive or age is None or age>60 else None,'status':s,'learning':learning,'learningFinal':learningFinal,'verified':sum(v=='verified' for v in plan.get('states',{}).values()),'scopeCount':len  … [line shortened here: 526 characters; full line on GitHub]
class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path=='/status.json': payload=json.dumps(state()).encode();kind='application/json'
        elif self.path=='/': payload=Path(__file__).with_name('monitor-local.html').read_bytes();kind='text/html; charset=utf-8'
        else: self.send_error(404);return
        self.send_response(200);self.send_header('Content-Type',kind);self.send_header('Cache-Control','no-store');self.end_headers();self.wfile.write(payload)
    def log_message(self,*args): pass
server=ThreadingHTTPServer(('127.0.0.1',args.port),Handler)
def watch():
    while time.time()<deadline+60 and not (args.out/'STOP').exists():
        value=state();(args.out/'latest.json').write_text(json.dumps(value,indent=2),encoding='utf-8')
        # Compact summaries only; bounded to approximately 960 records over eight hours.
        with (args.out/'health.jsonl').open('a',encoding='utf-8') as f:
            f.write(json.dumps({k:value[k] for k in ['checkedAt','supervisorAlive','heartbeatAgeSeconds','alert','verified']})+'\n')
        time.sleep(30)
    server.shutdown()
threading.Thread(target=watch,daemon=True).start()
try: server.serve_forever()
finally: server.server_close()

Codex Overnight

A Python command-line tool in GPU Drivers for Global Grid that reads review owners and queue, using SHA-256. It stops child (`stop_child`) and writes JSON (`write_json`).

storagegpu-drivers-for-global-grid / codex/overnight.py · lines 1–181 of 181 · Entry point · pattern guard (shared by 15 files)

What it does
It loads review owners and queue. Defines 6 functions or classes, including now, sample, stop_child, guard, write_json. Uses libraries argparse, ctypes, datetime, hashlib, json. Side effects: reads or writes files; starts processes.
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 RUN.json; JSON file review-owners.json; JSON file QUEUE.json; JSON file REVIEW-INDEX.json; JSON file STATUS.json; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Bounded local CPU/WebGPU soak study; measurements are benchmarks, not source compilation. It writes `RUN.json`. It accepts `--artifact`, `--out` and `--hours`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gpu-drivers-for-global-grid · codex · Python CLI
Uses
Codex Review Group (script call), Codex Corpus Review (script call), argparse, ctypes, datetime, hashlib, json, os, pathlib, shutil
Used by
none found
Produces
now, sample, stop_child, guard, write_json, main
Defines here
now, sample, stop_child, guard, write_json, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe codex/overnight.py:1-181 · blob f9de277e09a6443f85a3f80b44d3d6c54f6cd489 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Bounded local CPU/WebGPU soak study; measurements are benchmarks, not source compilation."""
import argparse
import ctypes
import datetime as dt
import hashlib
import json
import os
from pathlib import Path
import shutil
import subprocess
import time
import psutil

GIB = 1024 ** 3
HERE = Path(__file__).resolve().parents[1]


def now():
    return dt.datetime.now(dt.timezone.utc).isoformat()


def sample():
    battery = psutil.sensors_battery()
    record = {'at': now(), 'availableGiB': psutil.virtual_memory().available / GIB,
              'cpuPercent': psutil.cpu_percent(), 'plugged': battery.power_plugged if battery else None,
              'cpuTemperature': None, 'cpuTemperatureNote': 'No validated CPU temperature sensor configured; CPU affinity and memory controls are enforced.'}
    try:
        r = subprocess.run(['nvidia-smi', '--query-gpu=temperature.gpu,utilization.gpu,memory.used,memory.total', '--format=csv,noheader,nounits'], capture_output=True, text=True, timeout=5)
        temp, use, used, total = map(float, r.stdout.splitlines()[0].split(','))
        record.update(gpuTemperature=temp, gpuPercent=use, gpuMemoryUsedMiB=used, gpuMemoryTotalMiB=total)
    except Exception as error:
        record['gpuError'] = type(error).__name__
    return record


def stop_child(child):
    try:
        process = psutil.Process(child.pid)
        descendants = process.children(recursive=True)
        for p in descendants:
            try: p.terminate()
            except psutil.Error: pass
        process.terminate()
        _, alive = psutil.wait_procs(descendants + [process], timeout=3)
        for p in alive:
            try: p.kill()
            except psutil.Error: pass
    except psutil.NoSuchProcess:
        pass


def guard(s):
    if s['plugged'] is False: return 'AC power disconnected'
    if s['availableGiB'] < 2: return 'Less than 2 GiB available RAM'
    if s.get('gpuTemperature', 100) >= 78: return 'GPU temperature high or sensor unavailable'
    if s.get('gpuMemoryTotalMiB', 0) - s.get('gpuMemoryUsedMiB', 0) < 1024: return 'Less than 1 GiB GPU memory available'
    return None


def write_json(path, value):
    raw = (json.dumps(value, indent=2) + '\n').encode()
    if len(raw) > 8_000_000: raise ValueError('Output partition cap reached')
    temp = path.with_suffix('.tmp')
    temp.write_bytes(raw)
    temp.replace(path)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--artifact', type=Path, required=True)
    parser.add_argument('--out', type=Path, required=True)
    parser.add_argument('--hours', type=float, default=8)
    args = parser.parse_args()
    if not 0 < args.hours <= 8: parser.error('Duration must be 0 < hours <= 8')
    if not 0 < args.artifact.stat().st_size <= 40_000_000: parser.error('Input must be 1..40 MB')
    out = args.out.resolve(); out.mkdir(parents=True, exist_ok=True)
    if (out / 'RUN.json').exists(): parser.error('Use a new evidence directory per run')
    started = time.monotonic(); deadline = started + args.hours * 3600
    env = dict(os.environ, BENCH_CHANNEL='chrome', NODE_OPTIONS='--max-old-space-size=512')
    affinity = psutil.Process().cpu_affinity()[:max(1, min(16, (psutil.cpu_count() or 2) - 4))]
    record = {'schema': 'ventus.local-soak.v1', 'startedAt': now(), 'pid': os.getpid(), 'hours': args.hours,
              'artifact': str(args.artifact), 'inputBytes': args.artifact.stat().st_size,
              'sha256': hashlib.sha256(args.artifact.read_bytes()).hexdigest(),
              'runnerCommit': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=HERE, text=True).strip(),
              'scope': 'Repeated CPU hash/decode/marker scans and WebGPU byte-count variants checked against CPU. Not full code compilation or application correctness.',
              'limits': {'cpuAffinity': affinity, 'maxWorkers': len(affinity), 'minFreeRamGiB': 2, 'gpuStopC': 78,
                         'gpuResumeC': 70, 'minFreeVramMiB': 1024, 'maxTaskSeconds': 180, 'maxEvidenceBytes': 500_000_000},
              'stop': 'Create a file named STOP in this evidence directory; supervisor checks every 5 seconds.',
              'completed': 0, 'failed': 0, 'interrupted': 0, 'interruptedJobs': []}
    write_json(out / 'RUN.json', record)
    owners = json.loads((HERE / 'codex/review-owners.json').read_text(encoding='utf8'))
    queue = [HERE.parent / name for name in owners if (HERE.parent / name / '.git').exists()]
    write_json(out / 'QUEUE.json', {'repositories': list(map(str, queue)), 'scope': 'Review committed local heads; remote survey runs separately in Actions.'})
    active = None; log = None; batch = 0; last_hour = -1; hourly = []; evidence_bytes = 0; paused_hot = False; bench_pending = []; reviews = []; corpus_pending = True; group = []
    ctypes.windll.kernel32.SetThreadExecutionState(0x80000001)
    try:
        while time.monotonic() < deadline and not (out / 'STOP').exists():
            s = sample(); elapsed = time.monotonic() - started; hour = int(elapsed // 3600)
            if hour != last_hour:
                if hourly: write_json(out / f'hour-{last_hour:02d}.json', {'samples': hourly, 'completed': record['completed'], 'failed': record['failed']})
                hourly = []; last_hour = hour
                bench_pending = ['gpu', 'cpu']
            hourly.append(s)
            if len(hourly) > 900: hourly = hourly[-900:]
            reason = guard(s)
            if s.get('gpuTemperature', 100) >= 78: paused_hot = True
            if paused_hot and s.get('gpuTemperature', 100) <= 70: paused_hot = False
            if paused_hot: reason = 'Cooling to 70 C'
            if shutil.disk_usage(out).free < 5 * GIB: reason = 'Less than 5 GiB disk space'
            if active and (reason or time.monotonic() - task_started > 180):
                stop_child(active); active.wait(timeout=10); log.close()
                record['interruptedJobs'].append({'mode': mode, 'repositories': [p.name for p in group] if mode == 'review' else [], 'reason': reason or '180 second timeout', 'log': str(log_path)})
                record['interrupted'] += 1; active = None
            if active and active.poll() is not None:
                code = active.returncode; log.close()
                evidence_bytes += log_path.stat().st_size
                text = log_path.read_text(encoding='utf8', errors='replace')
                result = None
                try:
                    result = json.loads(next(line[5:] for line in reversed(text.splitlines()) if line.startswith('JSON ')))
                    if mode == 'review':
                        correct = {r['repository'] for r in result['reviews']} == {p.name for p in group}
                        reviews.extend(result['reviews'])
                        write_json(out / 'REVIEW-INDEX.json', reviews)
                        (out / 'REVIEW-INDEX.md').write_text('# Overnight source review cards\n\n' + '\n'.join(f'- [{r["repository"]}](reviews/{r["repository"]}/REVIEW.md): {r["parseFailures"]} parse failures; {r["inspected"]} unique blobs checked; truncated={r["truncated"]}' for r in reviews) + '\n', encoding='utf8')
                    elif mode == 'corpus': correct = result['gpuCorpusVerified'] is True
                    else:
                        correct = all(r['correct'] for r in result['rows']) if mode == 'gpu' else all(r['sectionsAgree'] and r['digestsAgree'] for r in result['ladder'])
                except Exception: correct = False
                success = code == 0 and correct
                record['completed' if success else 'failed'] += 1
                write_json(out / f'batch-{batch:05d}.json', {'mode': mode, 'exitCode': code, 'receiptValidated' if mode == 'review' else 'correct': correct, 'result': result, 'finishedAt': now()})
                active = None
                if not success:
                    record['stopReason'] = 'Benchmark failure; stopped for review'; break
            evidence_bytes = sum(p.stat().st_size for p in out.rglob('*') if p.is_file())
            if evidence_bytes > 450_000_000:
                record['stopReason'] = 'Evidence storage budget reached'; break
            if not active and not reason and s['availableGiB'] >= 2.6 and (bench_pending or queue or corpus_pending):
                batch += 1; mode = bench_pending.pop(0) if bench_pending else ('review' if queue else 'corpus')
                workers = max(1, min(len(affinity), int((s['availableGiB'] - 2.3) / .2)))
                if mode == 'review':
                    group = [queue.pop(0) for _ in range(min(3, len(queue), workers))]
                    command = [os.sys.executable, str(HERE / 'codex/review-group.py'), '--out', str(out / 'reviews'), '--workers', str(workers)]
                    for owner in group: command += ['--root', str(owner)]
                elif mode == 'corpus':
                    corpus_pending = False
                    command = [os.sys.executable, str(HERE / 'codex/corpus-review.py'), '--reviews', str(out / 'reviews'), '--out', str(out / 'gpu-corpus')]
                else:
                    command = ['node', str(HERE / 'claude' / ('bench-gpu.mjs' if mode == 'gpu' else 'bench-cpu-ram.mjs')), str(args.artifact)]
                    command += ['--iters', '100', '--headed=0'] if mode == 'gpu' else ['--threads', ','.join(map(str, sorted({1, max(1, workers // 2), workers})))]
                log_path = out / f'batch-{batch:05d}-{mode}.log'; log = log_path.open('w', encoding='utf8')
                active = subprocess.Popen(command, cwd=HERE, env=env, stdout=log, stderr=subprocess.STDOUT, creationflags=subprocess.CREATE_NO_WINDOW)
                try:
                    process = psutil.Process(active.pid); process.cpu_affinity(affinity); process.nice(psutil.BELOW_NORMAL_PRIORITY_CLASS)
                except psutil.Error: pass
                task_started = time.monotonic()
            write_json(out / 'STATUS.json', {'at': now(), 'elapsedSeconds': round(elapsed), 'active': mode if active else None,
                                            'pauseReason': reason or (('Queue complete; waiting for hourly measurement' if not queue and not bench_pending else 'Waiting for 2.6 GiB available RAM') if not active else None),
                                            'remainingReviewJobs': len(queue),
                                            'completed': record['completed'], 'failed': record['failed'], 'sample': s})
            # Check output growth during the task, not only after it exits.
            if active and log_path.stat().st_size > 8_000_000:
                record['stopReason'] = 'Task log budget reached'; break
            time.sleep(1 if active or queue or bench_pending or corpus_pending else 5)
    finally:
        ctypes.windll.kernel32.SetThreadExecutionState(0x80000000)
        if active:
            stop_child(active)
            record['interruptedJobs'].append({'mode': mode, 'repositories': [p.name for p in group] if mode == 'review' else [], 'reason': 'Controller stopped', 'log': str(log_path)})
        if log and not log.closed: log.close()
        if hourly: write_json(out / f'hour-{last_hour:02d}.json', {'samples': hourly, 'completed': record['completed'], 'failed': record['failed']})
        record['finishedAt'] = now(); record.setdefault('stopReason', 'STOP requested' if (out / 'STOP').exists() else 'Duration complete')
        record['remainingReviews'] = list(map(str, queue))
        record['reviewCoverageComplete'] = not queue and not any(j['mode'] == 'review' for j in record['interruptedJobs']) and record['failed'] == 0
        record['gpuCorpusPending'] = corpus_pending
        write_json(out / 'RUN.json', record)


if __name__ == '__main__':
    main()

Codex Precision Schedule

A Python command-line tool in GPU Drivers for Global Grid that reads progress, plan and pin errors, using SHA-256.

storagegpu-drivers-for-global-grid / codex/precision-schedule.py · lines 1–117 of 117 · Entry point

What it does
It loads progress, plan and pin errors. Defines 6 functions or classes, including write, create_plan, pin, git, refresh. Uses libraries argparse, datetime, hashlib, json, pathlib. Side effects: reads or writes files; starts processes.
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 PROGRESS.json; JSON file PLAN.json; JSON file PIN-ERRORS.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 creates plan (`create_plan`) and is built from the write step (`write`) and the pin step (`pin`). 96 precision-review timeboxes. Hourly queue refresh; never substitutes time for evidence. It writes `PROGRESS.json`. It accepts `--out`, `--watch` and `--pin`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gpu-drivers-for-global-grid · codex · Python CLI
Uses
argparse, datetime, hashlib, json, pathlib, subprocess, time
Used by
none found
Produces
write, create_plan, pin, refresh, main
Defines here
write, create_plan, pin, git, refresh, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe codex/precision-schedule.py:1-117 · blob 46fc867426df7b95a899be33a42c1d1f0381df31 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""96 precision-review timeboxes. Hourly queue refresh; never substitutes time for evidence."""
import argparse
import datetime as dt
import hashlib
import json
from pathlib import Path
import subprocess
import time

GROUPS = [
 ('Release composition', 'gridatlas', 'Does the current release gate reject removal of every required cartridge?'),
 ('Cable geometry', 'globalgrid2050', 'What is the exact loading and behavior impact of the confirmed app.js syntax defect?'),
 ('GRID / SUBS controls', 'gridatlas', 'Do controls and minimised layers behave correctly across desktop and mobile?'),
 ('Project deep links', 'ventus-grid-engine', 'Does Pipeline News select the intended Atlas project and produce a visible outcome?'),
 ('App-only PDF', 'teleprinter', 'Does the real print action preserve visible app content without screen sharing?'),
 ('GIS SLD isolation', 'unnamed-01', 'Does the original sandbox retain its behavior as an independently failing Atlas layer?'),
 ('Source print integrity', 'testcode', 'Does a source download contain the complete pinned dependency closure in the tested environment?'),
 ('GPU evidence', 'gpu-drivers-for-global-grid', 'Are useful GPU results correct end-to-end and attributable to the actual adapter and input?'),
]
PHASES = [
 ('Pin identities', 'Record local HEAD, remote main, working-tree state and origin; do not silently equate local and shipped code.'),
 ('Resolve entrypoints', 'Identify and read the complete actual entrypoint and manifest at the selected commit.'),
 ('Resolve dependencies', 'Account for the complete relevant import/workflow-script closure; unresolved dependencies block completion.'),
 ('Read contracts', 'Record intended inputs, outputs, invariants and applicable owner instructions.'),
 ('Trace implementation', 'Read complete relevant functions and document the behavior path with exact source locations.'),
 ('Establish baseline', 'Reproduce the behavior on the pinned unmodified implementation and retain actual evidence.'),
 ('Challenge hypothesis', 'Test the strongest alternative explanation, including environment and reviewer errors.'),
 ('Negative fixture', 'Construct a targeted failing input or missing-module case and show the check detects it.'),
 ('Boundary cases', 'Test scope-specific edge cases and independent plugin failure behavior.'),
 ('Cross-check evidence', 'Independently verify source identity, outputs and any measured numerical claims.'),
 ('Propose minimal change', 'Describe the smallest justified owner change, dependency effects and rollback; no untested deployment.'),
 ('Issue decision card', 'Provide a short evidence-backed conclusion with unresolved limits and links to the complete review packet.'),
]


def write(path, value):
    raw = (json.dumps(value, indent=2) + '\n').encode()
    if len(raw) > 8_000_000: raise ValueError('Partition budget exceeded')
    tmp = path.with_suffix('.tmp'); tmp.write_bytes(raw); tmp.replace(path)


def create_plan():
    tasks = []
    for group, (title, repo, question) in enumerate(GROUPS):
        for phase, (name, criterion) in enumerate(PHASES):
            number = group * 12 + phase + 1
            tasks.append({'id': f'R{number:02d}', 'group': title, 'owner': repo, 'question': question,
                          'phase': name, 'acceptance': criterion, 'timeboxMinutes': 5,
                          'dependsOn': [f'R{number-1:02d}'] if phase else [], 'priority': group + 1})
    return {'schema': 'ventus.precision-plan.v1', 'tasks': tasks, 'hours': 8,
            'scope': '96 five-minute planning units, not a promise of 96 completed engineering reviews. Carry unresolved work forward.'}


def pin(task, estate, out):
    root = estate / task['owner']
    def git(*args):
        return subprocess.check_output(['git', '-C', str(root), *args], timeout=45).decode('utf8', errors='replace').strip()
    proof = {'repository': task['owner'], 'localCommit': git('rev-parse', 'HEAD'), 'remote': git('remote', 'get-url', 'origin'),
             'remoteMain': git('ls-remote', 'origin', 'refs/heads/main'), 'workingTree': git('status', '--short'),
             'at': dt.datetime.now(dt.timezone.utc).isoformat(), 'scope': 'Identity checkpoint only; no application verification.'}
    if len(proof['localCommit']) != 40 or len(proof['remoteMain'].split()[0]) != 40: raise ValueError('Unresolved commit identity')
    proof_path = out / 'evidence' / (task['id'] + '.json'); write(proof_path, proof)
    write(out / 'receipts' / (task['id'] + '.json'), {'task': task['id'], 'status': 'verified', 'reviewer': 'identity runner',
          'acceptance': task['acceptance'], 'evidence': [{'path': str(proof_path), 'sha256': hashlib.sha256(proof_path.read_bytes()).hexdigest()}]})


def refresh(plan, out, hour):
    states = {}; errors = []
    for task in plan['tasks']:
        states[task['id']] = 'pending'
        receipt = out / 'receipts' / (task['id'] + '.json')
        if not receipt.exists(): continue
        try:
            r = json.loads(receipt.read_text(encoding='utf8'))
            assert r['task'] == task['id'] and r['acceptance'] == task['acceptance'] and r['reviewer']
            assert r['status'] == 'verified' and r['evidence']
            for e in r['evidence']:
                assert hashlib.sha256(Path(e['path']).read_bytes()).hexdigest() == e['sha256']
            assert all(states[d] == 'verified' for d in task['dependsOn'])
            states[task['id']] = 'verified'
        except Exception as error: errors.append({'task': task['id'], 'error': type(error).__name__})
    ready = [t for t in plan['tasks'] if states[t['id']] != 'verified' and all(states[d] == 'verified' for d in t['dependsOn'])]
    ready.sort(key=lambda t: (t['priority'], t['id']))
    record = {'at': dt.datetime.now(dt.timezone.utc).isoformat(), 'hour': hour, 'states': states,
              'nextReady': [t['id'] for t in ready[:12]], 'receiptErrors': errors,
              'schedulerScope': 'Local dependency/evidence checks and prioritisation only. It does not perform unimplemented engineering review or invoke an AI.'}
    write(out / 'PROGRESS.json', record); write(out / f'hour-{hour:02d}-queue.json', record)
    lines = ['# Precision review progress', '', 'Five minutes is a timebox, not proof of completion. These groups are review domains, not simultaneous full-load jobs.', '']
    for title, _, question in GROUPS:
        ts = [t for t in plan['tasks'] if t['group'] == title]; done = sum(states[t['id']] == 'verified' for t in ts)
        lines.append(f'- {title}: ' + '█' * done + '░' * (12 - done) + f' {done}/12 — {question}')
    lines += ['', '## Ready next', ''] + [f'- {t["id"]}: {t["group"]} / {t["phase"]}. {t["acceptance"]}' for t in ready[:12]]
    (out / 'PROGRESS.md').write_text('\n'.join(lines) + '\n', encoding='utf8')


def main():
    p = argparse.ArgumentParser(); p.add_argument('--out', type=Path, required=True); p.add_argument('--watch', action='store_true'); p.add_argument('--pin', action='store_true')
    args = p.parse_args(); out = args.out.resolve(); out.mkdir(parents=True, exist_ok=True)
    for name in ('evidence', 'receipts'): (out / name).mkdir(exist_ok=True)
    plan = create_plan(); write(out / 'PLAN.json', plan)
    (out / 'SCOPES.md').write_text('# 96 precision scopes\n\n' + '\n\n'.join(f'## {t["id"]} — {t["group"]}: {t["phase"]}\n\nQuestion: {t["question"]}\n\nCompletion: {t["acceptance"]}\n\nDependency: {", ".join(t["dependsOn"]) or "none"}. Timebox: 5 minutes; carry forward if unresolved.' for t in plan['tasks']), encoding='utf8')
    if args.pin:
        errors = []
        for task in plan['tasks']:
            if task['phase'] == 'Pin identities':
                try: pin(task, Path(__file__).resolve().parents[2], out)
                except Exception as error: errors.append({'task': task['id'], 'error': str(error)})
        write(out / 'PIN-ERRORS.json', errors)
    start = time.monotonic(); last_hour = -1
    while True:
        hour = int((time.monotonic() - start) // 3600)
        if hour != last_hour: refresh(plan, out, hour); last_hour = hour
        if not args.watch or hour >= 8 or (out / 'STOP').exists(): break
        time.sleep(30)


if __name__ == '__main__': main()

Codex Review Group

A Python module in GPU Drivers for Global Grid that reads cartridge. It is built from the run step (`run`).

ingestgpu-drivers-for-global-grid / codex/review-group.py · lines 1–30 of 30

What it does
It loads cartridge. Defines run. Uses libraries argparse, concurrent.futures, json, pathlib, subprocess. Side effects: reads or writes files; starts processes.
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 cartridge.json; command-line arguments.
Downstream impact
Used directly by 1 file: Codex Overnight (gpu-drivers-for-global-grid).
What it achieves
Parallel owner reviews, with one shared CPU worker budget. It accepts `--root`, `--out` and `--workers`.
Why it matters
Run by Codex Overnight.
Application
gpu-drivers-for-global-grid · codex · Python module
Uses
Codex Review Repo (script call), argparse, concurrent.futures, json, pathlib, subprocess, sys
Used by
run by Codex Overnight (script call)
Produces
run
Defines here
run
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe codex/review-group.py:1-30 · blob 7dbb5ce8c0ed805de4c6350c11a1c7b219a56c66 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Parallel owner reviews, with one shared CPU worker budget."""
import argparse
import concurrent.futures
import json
from pathlib import Path
import subprocess
import sys

p = argparse.ArgumentParser()
p.add_argument('--root', action='append', type=Path, required=True)
p.add_argument('--out', type=Path, required=True)
p.add_argument('--workers', type=int, default=4)
p.add_argument('--offset', type=int, default=0)
p.add_argument('--limit', type=int, default=240)
a = p.parse_args()
parallel = min(3, len(a.root), max(1, a.workers))
per_repo = max(1, a.workers // parallel)


def run(root):
    out = a.out / root.name
    subprocess.run([sys.executable, str(Path(__file__).with_name('review-repo.py')), '--root', str(root), '--out', str(out), '--workers', str(per_repo),'--offset',str(a.offset),'--limit',str(a.limit)], check=True)
    report = json.loads((out / 'cartridge.json').read_text(encoding='utf8'))
    assert report['repository'] == root.name and len(report['commit']) == 40
    return {'repository': report['repository'], 'commit': report['commit'], 'parseFailures': len(report['parseFailures']), 'inspected': report['inspected'], 'truncated': report['truncated']}


with concurrent.futures.ThreadPoolExecutor(max_workers=parallel) as pool:
    reports = list(pool.map(run, a.root))
print('JSON ' + json.dumps({'reviews': reports}))

Codex Review Repo

A Python command-line tool in GPU Drivers for Global Grid covering cartridge, using SHA-256. It is built from the git step (`git`) and the inspect step (`inspect`).

storagegpu-drivers-for-global-grid / codex/review-repo.py · lines 1–101 of 101 · Entry point · pattern inspect (shared by 40 files)

What it does
It lists and searches cartridge. Defines git, inspect, main. Uses libraries argparse, ast, concurrent.futures, hashlib, json. Side effects: reads or writes files; starts processes.
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: command-line arguments. Out: JSON file cartridge.json.
Downstream impact
Used directly by 1 file: Codex Review Group (gpu-drivers-for-global-grid). Reached from 1 other entry point, including Codex Overnight (gpu-drivers-for-global-grid).
What it achieves
Produce a bounded, commit-pinned source review cartridge without executing source. It accepts `--root`, `--out` and `--workers`.
Why it matters
Run by Codex Review Group.
Application
gpu-drivers-for-global-grid · codex · Python CLI
Uses
argparse, ast, concurrent.futures, hashlib, json, pathlib, re, subprocess
Used by
run by Codex Review Group (script call)
Produces
git, inspect, main
Defines here
git, inspect, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe codex/review-repo.py:1-101 · blob bd767ee6d9b4644a10a69d995624c714d292e122 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Produce a bounded, commit-pinned source review cartridge without executing source."""
import argparse
import ast
import concurrent.futures
import hashlib
import json
from pathlib import Path
import re
import subprocess
import time


def git(root, *args):
    return subprocess.check_output(['git', '-C', str(root), *args], timeout=60)


def inspect(root, entry):
    mode, kind, sha, size, name = entry
    raw = git(root, 'cat-file', 'blob', sha)
    text = raw.decode('utf8', errors='replace')
    result = {'path': name, 'blob': sha, 'bytes': len(raw), 'lines': len(text.splitlines()), 'sha256': hashlib.sha256(raw).hexdigest()}
    suffix = Path(name).suffix.lower()
    try:
        if '.excerpt.' in name:
            result['parse'] = 'not-standalone-excerpt'
            result['reviewRequired'] = 'Resolve provenance to the complete enclosing source before syntax or behavioral conclusions'
        elif suffix == '.py': ast.parse(raw, filename=name); result['parse'] = 'pass'
        elif suffix == '.json': json.loads(text); result['parse'] = 'pass'
        elif suffix in ('.js', '.mjs', '.cjs'):
            # Parse stdin only; never import/run target-owned code.
            command = ['node', '--check']
            if suffix == '.mjs' or re.search(r'(?m)^\s*(?:import |export )', text): command += ['--input-type=module']
            checked = subprocess.run(command, input=raw, capture_output=True, timeout=15)
            result['parse'] = 'pass' if checked.returncode == 0 else 'failed'
            if checked.returncode: result['error'] = checked.stderr.decode('utf8', errors='replace')[:1200]
        else: result['parse'] = 'not-applicable'
    except Exception as error:
        result.update(parse='failed', error=str(error)[:1200])
    result['imports'] = sorted(set(re.findall(r'''(?:from\s*|require\(\s*|import\(\s*)['"]([^'"]+)''', text)))[:40]
    result['symbols'] = re.findall(r'(?m)^\s*(?:export\s+)?(?:async\s+)?(?:function|class|def)\s+(\w+)', text)[:40]
    return result


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--root', type=Path, required=True); p.add_argument('--out', type=Path, required=True)
    p.add_argument('--workers', type=int, default=2)
    p.add_argument('--offset', type=int, default=0)
    p.add_argument('--limit', type=int, default=240)
    args = p.parse_args(); args.root = args.root.resolve(); args.out.mkdir(parents=True, exist_ok=True)
    if args.offset < 0 or not 1 <= args.limit <= 2000: p.error('offset must be nonnegative and limit must be 1..2000')
    started = time.monotonic(); head = git(args.root, 'rev-parse', 'HEAD').decode().strip()
    entries = []
    for row in git(args.root, 'ls-tree', '-rlz', head).split(b'\0'):
        if not row: continue
        meta, name = row.split(b'\t', 1); fields = meta.decode().split(); name = name.decode('utf8', errors='replace')
        if len(fields) == 4 and fields[1] == 'blob': entries.append((*fields, name))
    eligible = [e for e in entries if Path(e[4]).suffix.lower() in ('.js', '.mjs', '.cjs', '.py', '.json')
                and int(e[3]) <= 1_000_000 and not any(x in e[4].lower().split('/') for x in ('node_modules', 'vendor', 'data', 'results', 'versions', 'receipts'))
                and not re.search(r'(?:^|/)\d{12}(?:/|$)', e[4])]
    # Largest first exposes monolith boundaries; each blob parsed once per repository.
    eligible.sort(key=lambda e: (-int(e[3]), e[4])); unique = {}; duplicate = {}
    for e in eligible:
        unique.setdefault(e[2], e); duplicate.setdefault(e[2], []).append(e[4])
    selected = list(unique.values())[args.offset:args.offset+args.limit]
    with concurrent.futures.ThreadPoolExecutor(max_workers=max(1, min(12, args.workers))) as pool:
        results = list(pool.map(lambda e: inspect(args.root, e), selected))
    failures = [r for r in results if r['parse'] == 'failed']
    history = git(args.root, 'log', head, '--since=153 days ago', '-500', '--format=COMMIT:%H', '--numstat').decode('utf8', errors='replace')
    churn = {}; history_commits = []
    for line in history.splitlines():
        if line.startswith('COMMIT:'): history_commits.append(line[7:])
        else:
            parts = line.split('\t', 2)
            if len(parts) == 3 and parts[0].isdigit() and parts[1].isdigit():
                item = churn.setdefault(parts[2], {'path': parts[2], 'touches': 0, 'added': 0, 'deleted': 0})
                item['touches'] += 1; item['added'] += int(parts[0]); item['deleted'] += int(parts[1])
    hotspots = sorted(churn.values(), key=lambda x: (-x['touches'], -x['added'] - x['deleted']))[:20]
    candidates = [dict(path=r['path'], bytes=r['bytes'], lines=r['lines'], symbols=r['symbols'], imports=r['imports'],
                       decision='Review extraction boundaries; size alone does not prove separability') for r in results if r['lines'] > 800][:12]
    report = {'schema': 'ventus.source-review-cartridge.v1', 'repository': args.root.name, 'commit': head,
              'scope': 'Committed HEAD only, not dirty work. Bounded source parse and lexical references; no runtime or application correctness claim.',
              'trackedFiles': len(entries), 'eligibleFiles': len(eligible), 'uniqueEligibleBlobs': len(unique), 'inspected': len(results),
              'truncated': len(selected) < len(unique), 'selection': {'offset': args.offset, 'limit': args.limit, 'remainingAfter': max(0,len(unique)-args.offset-len(selected))}, 'seconds': round(time.monotonic() - started, 2),
              'parseFailures': failures, 'extractionCandidates': candidates,
              'changeHotspots': hotspots, 'history': {'windowDays': 153, 'commitsObserved': len(history_commits), 'capMayTruncate': len(history_commits) == 500, 'head': head, 'oldestObservedCommit': history_commits[-1] if history_commits else None},
              'exactBlobDuplicates': [dict(blob=k, paths=v[:30], copies=len(v)) for k, v in duplicate.items() if len(v) > 1][:100],
              'files': results}
    raw = (json.dumps(report, indent=2) + '\n').encode()
    if len(raw) > 8_000_000: raise ValueError('Review partition over 8 MB')
    (args.out / 'cartridge.json').write_bytes(raw)
    brief = f'# {args.root.name}: review cartridge\n\nCommit `{head}`. Inspected {len(results)}/{len(unique)} eligible unique blobs; {len(failures)} parse failures.\n\n'
    brief += '## Inspect first\n\n' + '\n'.join('- `' + r['path'] + '`: ' + r.get('error', '')[:180].replace('\n', ' ') for r in failures[:8])
    brief += '\n\n## Candidate extraction boundaries\n\n' + '\n'.join(f'- `{r["path"]}`: {r["lines"]} lines; symbols: ' + ', '.join(r['symbols'][:8]) for r in candidates[:6])
    brief += '\n\n## Recent change hotspots\n\n' + '\n'.join(f'- `{r["path"]}`: {r["touches"]} touched commits in bounded five-month history.' for r in hotspots[:5])
    brief += '\n\nThese are review proposals, not generated or accepted application cartridges. Read cartridge.json for hashes, exclusions and coverage.\n'
    (args.out / 'REVIEW.md').write_text(brief, encoding='utf8')
    print(json.dumps({'repository': args.root.name, 'inspected': len(results), 'parseFailures': len(failures)}))


if __name__ == '__main__': main()

Codex Review Repo Test

A test in GPU Drivers for Global Grid. It is built from the precision tests class (`PrecisionTests`).

testgpu-drivers-for-global-grid / codex/review-repo.test.py · lines 1–27 of 27 · Entry point

What it does
It tests its inputs. Defines PrecisionTests, check_source, test_python_bom_is_valid, test_excerpt_is_not_a_standalone_program, test_invalid_javascript_is_still_reported. Uses libraries importlib.util, 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).
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Defines `PrecisionTests`, `check_source`, `test_python_bom_is_valid` and 2 more.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
gpu-drivers-for-global-grid · codex · test
Uses
importlib.util, pathlib, unittest
Used by
none found
Produces
PrecisionTests
Defines here
PrecisionTests, check_source, test_python_bom_is_valid, test_excerpt_is_not_a_standalone_program, test_invalid_javascript_is_still_reported
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gpu-drivers-for-global-grid@6c47912a8dde251ffebd92ff129e6a0c11c4ebfe codex/review-repo.test.py:1-27 · blob 3a640a998ceda2d2ca71910fb81ffcfd4cb96df5 · 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 unittest

spec = importlib.util.spec_from_file_location('review', Path(__file__).with_name('review-repo.py'))
review = importlib.util.module_from_spec(spec); spec.loader.exec_module(review)


class PrecisionTests(unittest.TestCase):
    def check_source(self, name, raw):
        original = review.git
        try:
            review.git = lambda *args: raw
            return review.inspect(Path('.'), ('100644', 'blob', 'fixture', str(len(raw)), name))
        finally: review.git = original

    def test_python_bom_is_valid(self):
        self.assertEqual(self.check_source('app.py', b'\xef\xbb\xbfimport json\n')['parse'], 'pass')

    def test_excerpt_is_not_a_standalone_program(self):
        self.assertEqual(self.check_source('function.excerpt.py', b'    return 1\n')['parse'], 'not-standalone-excerpt')

    def test_invalid_javascript_is_still_reported(self):
        self.assertEqual(self.check_source('app.js', 'const x = { …y };'.encode())['parse'], 'failed')


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

Claude Report Probe

A JavaScript module in the probes folder of Gridmachine2 that fetches scan summary, browser maps summary, browser maps receipt and browser layers summary, using SHA-256 from the GridAtlas repository.

ingestgridmachine2 / probes/202609071400-claude-report-probe.mjs · lines 1–102 of 102 · version 2026-09-07 14:00 · Not reached from any entry point (candidate for review) · pattern gitBlob (shared by 17 files)

What it does
It fetches scan summary, browser maps summary, browser maps receipt and browser layers summary. Defines gitBlob, sha, say, live. Uses libraries node:fs, node:crypto, node:path, node:child_process. Side effects: reads or writes files; makes network requests; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (path word 'claude'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: data source: gridatlas data; JSON file scan-summary.json; JSON file export-manifest.json; JSON file browser-maps-summary.json; JSON file current.json; JSON file browser-maps-receipt.json; JSON file browser-layers-summary.json; GeoJSON file interconnectors.geojson.
What it achieves
It is built from the git blob helper (`gitBlob`), the sha step (`sha`) and the say step (`say`). A CI probe over a gridmachine2 report directory.
Why it matters
No other file in the estate was found to import it.
Application
gridmachine2 · probes · JavaScript module
Uses
node:fs, node:crypto, node:path, node:child_process
Used by
none found
Produces
gitBlob, sha, say, live
Defines here
gitBlob, sha, say, live
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
gridmachine2@b15c3d233c406f64168a356989300c8e81f50af8 probes/202609071400-claude-report-probe.mjs:1-102 · blob 08b237a6d03dc9036ba84dc71abf7ba360154de0 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
// A CI probe over a gridmachine2 report directory.
//
// It does not trust the report's own summaries. It re-derives what it can:
// every JSON parses; the inventory row count equals what the README claims;
// every file the export manifest lists exists and hashes to what the manifest
// says; the browser campaigns' inputs are named by hash and those hashes are
// checked against the live origins; the pinned commit vector from the Windows
// handover is looked for in the inventory; and the interconnector footprint is
// counted. Anything it cannot verify is printed as UNVERIFIED, not omitted.
//
// Run: node probes/202609071400-claude-report-probe.mjs reports/20260907T132651Z
import { readFileSync, readdirSync, existsSync, statSync } from "node:fs";
import { createHash } from "node:crypto";
import { join, resolve } from "node:path";
import { execFileSync } from "node:child_process";
// Hash the git blob, not the working copy: a Windows checkout converts LF to
// CRLF and every text file would report drift that does not exist upstream.
const gitBlob = (p) => { try { return execFileSync("git", ["-C", repoRoot, "show", "HEAD:" + p], { maxBuffer: 64 << 20 }); } catch { return null; } };

const dir = resolve(process.argv[2] || "reports/20260907T132651Z");
const repoRoot = resolve(dir, "..", "..");
const sha = (b) => createHash("sha256").update(b).digest("hex");
const out = [];
const say = (k, v) => out.push(`${k.padEnd(34)} ${v}`);

// 1. every JSON parses
let jsonOk = 0, jsonBad = [];
for (const f of readdirSync(dir).filter((f) => f.endsWith(".json"))) {
  try { JSON.parse(readFileSync(join(dir, f), "utf8")); jsonOk += 1; } catch (e) { jsonBad.push(`${f}: ${e.message.slice(0, 60)}`); }
}
say("json files parse", `${jsonOk} ok${jsonBad.length ? ", BAD: " + jsonBad.join("; ") : ""}`);

// 2. inventory rows vs README claim
const parts = readdirSync(join(dir, "inventory")).filter((f) => f.endsWith(".tsv")).sort();
let rows = 0, headerBad = 0, interconnectorRows = [];
const HEADER = "path_json\ttype\tlogical_bytes\tallocated_bytes\tmodified_utc";
for (const p of parts) {
  const lines = readFileSync(join(dir, "inventory", p), "utf8").split("\n").filter(Boolean);
  if (lines[0].replace(/\r$/, "") !== HEADER) headerBad += 1;
  rows += lines.length - 1;
  for (const l of lines.slice(1)) if (/interconnector/i.test(l)) interconnectorRows.push(l.split("\t")[0]);
}
const readme = readFileSync(join(dir, "README.md"), "utf8");
const claimed = Number((readme.match(/every observed entry: ([\d,]+) rows/) || [])[1]?.replace(/,/g, ""));
say("inventory rows", `${rows} in ${parts.length} parts; README claims ${claimed} -> ${rows === claimed ? "MATCH" : "MISMATCH"}${headerBad ? `; ${headerBad} bad headers` : ""}`);
const scan = JSON.parse(readFileSync(join(dir, "scan-summary.json"), "utf8"));
const scanTotal = scan.counts.directory + scan.counts.file + scan.counts.symlink;
say("scan-summary entries", `${scanTotal} (dirs ${scan.counts.directory}, files ${scan.counts.file}, symlinks ${scan.counts.symlink}) -> ${scanTotal === rows ? "MATCH inventory" : "differs from inventory by " + (rows - scanTotal)}`);

// 3. export manifest integrity: each listed file exists and hashes as stated
const manifest = JSON.parse(readFileSync(join(dir, "export-manifest.json"), "utf8"));
let mOk = 0, mMissing = [], mDrift = [];
for (const e of manifest) {
  const p = join(repoRoot, e.path);
  const b = gitBlob(e.path);
  if (!b) { mMissing.push(e.path); continue; }
  const h = sha(b);
  if (h === e.sha256) mOk += 1; else mDrift.push(`${e.path} (manifest ${e.sha256.slice(0, 10)} vs file ${h.slice(0, 10)})`);
}
say("export manifest", `${manifest.length} listed; ${mOk} hash MATCH; ${mMissing.length} missing; ${mDrift.length} drift${mDrift.length ? ": " + mDrift.slice(0, 4).join(", ") : ""}`);

// 4. browser campaign inputs, checked against the live origins
const maps = JSON.parse(readFileSync(join(dir, "browser-maps-summary.json"), "utf8"));
const live = async (url) => { try { const r = await fetch(url, { cache: "no-store", signal: AbortSignal.timeout(20000) }); return r.ok ? sha(Buffer.from(await r.arrayBuffer())) : `HTTP ${r.status}`; } catch (e) { return "ERR"; } };
const pipelineLive = await live(maps.inputs.pipelineURL);
const pointerLive = await live("https://ventusltd.github.io/gridatlas/atlas/current.json");
let pointerGen = "?";
try { pointerGen = JSON.parse(await (await fetch("https://ventusltd.github.io/gridatlas/atlas/current.json", { cache: "no-store" })).text()).generation; } catch {}
say("maps campaign pipeline input", `${maps.inputs.pipeline_sha256.slice(0, 12)} vs live ${String(pipelineLive).slice(0, 12)} -> ${pipelineLive === maps.inputs.pipeline_sha256 ? "SAME BYTES" : "DIFFERENT"}  (${maps.inputs.pipelineURL})`);
say("maps campaign atlas pointer", `${maps.inputs.atlas_pointer_sha256.slice(0, 12)} vs live root ${String(pointerLive).slice(0, 12)} -> ${pointerLive === maps.inputs.atlas_pointer_sha256 ? "SAME BYTES" : "DIFFERENT"}; live root generation ${pointerGen}`);
say("maps campaign progress", `${maps.tested} of ${maps.inventory} tested, complete=${maps.complete}, counts ${JSON.stringify(maps.counts)}`);
const receipt = JSON.parse(readFileSync(join(dir, "browser-maps-receipt.json"), "utf8"));
for (const c of receipt.cases || []) {
  const s = c.snapshot || {}; const e = s.engine || {}; const id = s.identity || {};
  say(`  case ${c.item?.ref}`, `${c.outcome} | gen ${s.generation} | identity ${id.status}/${id.mapped} | links ${e.links_drawn} nearest_km ${e.nearest_km} | rendered answer ${s.rendered_answer ? "yes" : "no"}`);
}
const layers = JSON.parse(readFileSync(join(dir, "browser-layers-summary.json"), "utf8"));
say("layers campaign progress", `${layers.tested} of ${layers.inventory} tested, counts ${JSON.stringify(layers.counts)}`);

// 5. the pinned vector from the Windows handover, looked for in the inventory paths and manifests
const VECTOR = {
  "v9.146 sld-sandbox cartridge": "8916fa66f2ca",
  "v9.145 place-global-search": "15f324e5c279",
  "PN v9.8 interconnector partition": "d13d6c24754a",
  "register parquet": "174040c37f3d",
  "data-interconnectors csv": "0ea612d86962",
  "interconnectors.geojson": "50fb06803d45",
};
const inventoryText = parts.map((p) => readFileSync(join(dir, "inventory", p), "utf8")).join("\n") + readFileSync(join(dir, "DATA-TREE.json"), "utf8");
for (const [k, h] of Object.entries(VECTOR)) say(`  vector ${k}`, inventoryText.includes(h) ? `present (${h})` : `NOT FOUND by hash (${h}) - may be held under a path, not a content hash`);

// 6. interconnector footprint
say("interconnector rows in inventory", `${interconnectorRows.length}`);
for (const p of [...new Set(interconnectorRows)].slice(0, 12)) say("  ", p.replace(/^"|"$/g, "").slice(0, 110));

// 7. attention
const att = JSON.parse(readFileSync(join(dir, "attention.json"), "utf8"));
say("attention", `${att.CODEX_ATTENTION_REQUIRED} - ${att.reasons.length} reasons`);
for (const r of att.reasons) say("  ", r.slice(0, 120));

console.log(`CLAUDE REPORT PROBE  ${new Date().toISOString()}  over ${dir}`);
console.log(out.join("\n"));

Codex Check Citations

A Python module in Linux for the Power Grid that fetches repository coverage and citation check, using SHA-256. It is built from the check step (`check`).

storagelinux-for-the-power-grid / codex/check-citations.py · lines 1–20 of 20 · Not reached from any entry point (candidate for review)

What it does
It fetches repository coverage and citation check. Defines check. Uses libraries concurrent.futures, datetime, hashlib, json, pathlib. 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 EVIDENCE-INDEX.json; JSON file REPOSITORY-COVERAGE.json. Out: JSON file CITATION-CHECK.json.
Downstream impact
Used directly by 1 file: Codex Finalize Paper (linux-for-the-power-grid).
What it achieves
Check public commit/path access and exact blob hashes without publishing anything.
Why it matters
Run by Codex Finalize Paper.
Application
linux-for-the-power-grid · codex · Python module
Uses
concurrent.futures, datetime, hashlib, json, pathlib, urllib.request, urllib.error
Used by
run by Codex Finalize Paper (script call)
Produces
check
Defines here
check
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
linux-for-the-power-grid@b984303b3d9ec104c92d754b8fd6207af021fef8 codex/check-citations.py:1-20 · blob b9bd3fed261cc4a0b5c83e8cb7c26d94c09c390d · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Check public commit/path access and exact blob hashes without publishing anything."""
import concurrent.futures,datetime,hashlib,json,pathlib,urllib.request,urllib.error
P=pathlib.Path(__file__).parent
e=json.loads((P/'EVIDENCE-INDEX.json').read_text());c=json.loads((P/'REPOSITORY-COVERAGE.json').read_text())
files={x['url']:x for x in e}
files.update({f['url']:f for r in c for f in r['files']})
def check(pair):
 url,item=pair;raw=url.replace('https://github.com/','https://raw.githubusercontent.com/').replace('/blob/','/')
 result={'url':url,'rawUrl':raw,'expectedSha256':item['sha256'],'checkedUtc':datetime.datetime.now(datetime.timezone.utc).isoformat()}
 try:
  req=urllib.request.Request(raw,headers={'User-Agent':'Ventus-Codex-paper-citation-check'})
  with urllib.request.urlopen(req,timeout=30) as response:
   data=response.read(1000001);result.update(httpStatus=response.status,bytes=len(data),sha256=hashlib.sha256(data).hexdigest())
  result['verified']=result['sha256']==item['sha256']
 except urllib.error.HTTPError as err:result.update(httpStatus=err.code,verified=False,error=str(err))
 except Exception as err:result.update(verified=False,error=str(err))
 return result
with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool:results=list(pool.map(check,files.items()))
(P/'CITATION-CHECK.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
print(json.dumps({'checked':len(results),'verified':sum(r['verified'] for r in results),'failures':[r for r in results if not r['verified']]},indent=2))

Codex Coverage

A Python module in Linux for the Power Grid that fetches inventory and repository coverage, using SHA-256 from GitHub API.

storagelinux-for-the-power-grid / codex/coverage.py · lines 1–52 of 52 · Not reached from any entry point (candidate for review)

What it does
It fetches inventory and repository coverage. Defines name, get, review. Uses libraries concurrent.futures, hashlib, json, pathlib, subprocess. Side effects: reads or writes files; makes network requests; starts processes.
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 SOURCE-INVENTORY.json. Out: JSON file REPOSITORY-COVERAGE.json; JSON file SOURCE-INVENTORY.json.
Downstream impact
Used directly by 1 file: Codex Finalize Paper (linux-for-the-power-grid).
What it achieves
It is built from the name step (`name`), the get step (`get`) and the review step (`review`). Read repository entry points without cloning remote data or binary payloads.
Why it matters
Run by Codex Finalize Paper.
Application
linux-for-the-power-grid · codex · Python module
Uses
concurrent.futures, hashlib, json, pathlib, subprocess, urllib.request, sys
Used by
run by Codex Finalize Paper (script call)
Produces
name, get, review
Defines here
name, get, review
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
linux-for-the-power-grid@b984303b3d9ec104c92d754b8fd6207af021fef8 codex/coverage.py:1-52 · blob db8eefbe32e9b581e5e482b4fd3cee82f05d6e97 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
"""Read repository entry points without cloning remote data or binary payloads."""
import concurrent.futures, hashlib, json, pathlib, subprocess, urllib.request, sys
sys.stdout.reconfigure(encoding='utf-8')
P=pathlib.Path(__file__).parent
inv=json.loads((P/'SOURCE-INVENTORY.json').read_text())
public=json.loads(pathlib.Path(r'C:\Users\vikra\OneDrive\Desktop\offline-screenshots\ventus-github-repository-index.json').read_text(encoding='utf-8-sig'))
def name(remote): return remote.rstrip('/').removesuffix('.git').rsplit('/',1)[-1]
byname={}
for r in inv['repositories']:
 n=name(r['remote']) if r['remote'] else ''
 if n not in byname or pathlib.Path(r['checkout']).name==n: byname[n]=r
def get(url):
 req=urllib.request.Request(url,headers={'User-Agent':'Ventus-Codex-source-review','Accept':'application/vnd.github+json'})
 with urllib.request.urlopen(req,timeout=30) as r:
  b=r.read(200001)
  if len(b)>200000: raise ValueError('Response exceeds bounded source review size')
  return b
def review(repo):
 n=repo['name']; result=dict(name=n,url=repo['html_url'],coverage='Entry-point source review; not all files',files=[],errors=[])
 try:
  if n in byname:
   r=byname[n]; result.update(local=True,commit=r['head'],checkout=r['checkout'])
   names=subprocess.check_output(['git','-C',r['checkout'],'ls-tree','--name-only',r['head']],text=True).splitlines()
   reader=lambda f:subprocess.check_output(['git','-C',r['checkout'],'show',r['head']+':'+f],stderr=subprocess.DEVNULL)
  else:
   meta=json.loads(get('https://api.github.com/repos/Ventusltd/'+n+'/commits/'+repo['default_branch']))
   result.update(local=False,commit=meta['sha'])
   tree=json.loads(get('https://api.github.com/repos/Ventusltd/'+n+'/git/trees/'+meta['commit']['tree']['sha']))['tree']
   names=[x['path'] for x in tree]
   reader=lambda f:get('https://raw.githubusercontent.com/Ventusltd/'+n+'/'+result['commit']+'/'+urllib.parse.quote(f))
  result['rootEntries']=names
  candidates=[f for f in names if f.lower() in ('readme.md','readme','package.json','pyproject.toml','cargo.toml','index.js','source.js','main.py','app.py','index.html','build.py','makefile')]
  # README and one implementation/config are enough to determine the next review scope.
  selected=sorted(candidates,key=lambda f:(not f.lower().startswith('readme'),f))[:2]
  for f in selected:
   try:
    b=reader(f)
    if len(b)>200000: raise ValueError('File exceeds bounded review size')
    t=b.decode('utf-8-sig'); result['files'].append(dict(path=f,bytes=len(b),sha256=hashlib.sha256(b).hexdigest(),lines=len(t.splitlines()),url=repo['html_url']+'/blob/'+result['commit']+'/'+f))
    result.setdefault('_read',[]).append((f,t[:3500]))
   except Exception as e:result['errors'].append(f+': '+str(e))
  if not selected:result['coverage']='Root tree inspected; no selected textual entry point at root'
 except Exception as e:result['errors'].append(str(e));result['coverage']='Access failed; no source conclusion'
 return result
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as pool: results=list(pool.map(review,public))
for r in results:
 print('\nREPO '+r['name']+' '+r.get('commit','')+' '+str(r['errors']))
 for f,t in r.pop('_read',[]):print('FILE '+f+'\n'+t)
(P/'REPOSITORY-COVERAGE.json').write_text(json.dumps(results,indent=2)+'\n',encoding='utf-8')
inv['publicRepositoryIndex']=public
inv['scopeSummary']={'localCheckouts':len(inv['repositories']),'distinctLocalRemotes':len(byname),'publicRepositories':len(public),'remoteOnlyRepositories':[r['name'] for r in public if r['name'] not in byname]}
(P/'SOURCE-INVENTORY.json').write_text(json.dumps(inv,indent=2)+'\n',encoding='utf-8')