In this section
- Run Study energy-data · chatgpt-audits / automation/202608310052-five-hour-study/run_study.py lines 1401–1652
- Verify Quarantine ingest · chatgpt-audits / automation/202608310052-five-hour-study/verify_quarantine.py lines 1–288
- Assemble Controller storage · chatgpt-audits / automation/202608310116-overnight-swarm/assemble_controller.py lines 1–75
Run Study
A Python command-line tool in the automation folder of ChatGPT Audits that fetches repository inventory, PipelineNews engine audit, event contract candidate and funding procurement evidence, using SHA-256.
energy-datachatgpt-audits / automation/202608310052-five-hour-study/run_study.py · lines 1401–1652 of 1652 · version 2026-08-31 00:52 (continued from section 1588) · Entry point · pattern source_entry (shared by 2 files)
- What it does
- It fetches repository inventory, PipelineNews engine audit, event contract candidate and funding procurement evidence. Defines 58 functions or classes, including now_utc, now_london, sha256_file, load_json, write_json. Uses libraries __future__, argparse, collections, hashlib, json. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'chatgpt'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "`run_study.py` — source snapshotter, deterministic scanners, cross-checker and vNext generator."
- Inputs & outputs
- In: JSON file 01-REPOSITORY-INVENTORY.json; JSON file current.json; JSON file 02-PIPELINENEWS-ENGINE-AUDIT.json; JSON file 03-EVENT-CONTRACT-CANDIDATE.json; JSON file 03-FUNDING-PROCUREMENT-EVIDENCE.json; JSON file live-set.json; JSON file 04-CLAUDE-CROSSCHECK-LEDGER.json; JSON file architecture.vnext.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It loads JSON (`load_json`), writes JSON (`write_json`) and writes text (`write_text`). Deterministic, read-only study controller for Ventusltd/ChatGPT-audits. It writes `01-REPOSITORY-INVENTORY.json`. It accepts `--plan`, `--source-root` and `--manifest`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- chatgpt-audits · automation/202608310052-five-hour-study · Python CLI
- Uses
- __future__, argparse, collections, hashlib, json, os, re, shutil
- Used by
- none found
- Produces
- now_utc, now_london, sha256_file, load_json, write_json, write_text, md_header, run, relative_posix, iter_files, is_text_candidate, read_text
- Defines here
- phase_status, cmd_phase, cmd_initialise, cmd_finalise, build_parser, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- chatgpt-audits@5808fde29b91027ec7a3de40c451a82b6714437c automation/202608310052-five-hour-study/run_study.py:1401-1652 · blob cbed31a2d3be0788ab9b160acbb502d9144f5afb · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
2. Extract the current discovery runner into source-specific collectors with source cards and deterministic request receipts.
3. Add an append-only evidence ledger with idempotency keys, source revisions, retractions and contradictions.
4. Build a company/project/planning identity binder that defaults to `ABSTAIN` and records validity intervals.
5. Add a Companies funding-event adapter that consumes only a reviewed compact export; no raw company master is retained.
6. Add a planning/procurement event adapter with authority, application reference, status/effective date and source digest.
7. Enforce the dual-register gate: funding + procurement + reviewed identity, otherwise remain withheld.
8. Produce a reviewed project-intelligence summary for PipelineNews and GridAtlas; keep observed facts and inferred windows visually separate.
9. Replace the hard-coded GridAtlas release URL with a verified current pointer contract and two golden deep-link sentinels.
10. Add regression fixtures for one-signal silence, ambiguous identity, revised filing, retracted event, stale window and conflicting evidence.
## P1 — after P0 is proven
1. Add data-centre demand-side events using the same evidence and identity contracts.
2. Add source-card health, freshness and revision dashboards.
3. Add a human review queue for conflicts, stale windows and candidate relationships.
4. Add an operational scorecard measuring lead-time versus trade-press publication without treating later news as ground truth.
5. Add CVAA vaccines for consumer pointer drift, inference-as-fact, one-signal promotion and missing source revisions.
## Explicitly excluded
- Product-repository mutations from this audit branch.
- Live Companies House, planning, news or scraper network calls.
- Public credit/bankability scores or individual director/PSC output.
- Automatic publication from an inferred score.
"""
write_text(candidate_root / "IMPLEMENTATION-BACKLOG.md", backlog)
migration = md_header("PipelineNews current-to-vNext migration map", "inferred") + "\n"
migration += """| Current responsibility | Candidate destination | Graduation proof |
|---|---|---|
| Source queries and bounded fetch logic | `collectors/<source>` | deterministic fixture + source-card receipt |
| Evidence/provenance arrays inside runners | append-only evidence ledger | idempotent replay; revision and retraction tests |
| Project matching in runner flow | identity binder | exact keys, abstention, validity interval, contradiction evidence |
| Scores/window labels | timing state machine | dual-register gate and rule-versioned transitions |
| Headlines and project rows | reviewed read model | observed/inferred separation and human review receipt |
| Hard-coded GridAtlas release URL | verified pointer consumer | Beacon Fen and East Pye public sentinel proof |
| Release/promotion commands | existing reviewed product workflows | no new publisher in audit code |
"""
write_text(candidate_root / "MIGRATION-MAP.md", migration)
summary = md_header("05 — PipelineNews vNext quarantined candidate", "inferred") + "\n"
summary += (
"The candidate is under `next-versions/202608310052-pipelinenews-intelligence-vnext/`. It contains schemas, module ownership, a non-publishing reference state machine and tests.\n\n"
"## Candidate gates encoded\n\n"
"- Funding and procurement are independent observed lanes.\n"
"- A commercial window is always an inference with evidence IDs and a rule version.\n"
"- One signal remains silent.\n"
"- Retraction removes an event from the usable evidence set.\n"
"- Contradiction wins over promotion.\n"
"- Human review is required before `RELEASE_CANDIDATE`.\n"
"- `PUBLISHED` is deliberately unavailable in the audit reference implementation.\n"
)
write_text(output_root / "05-PIPELINENEWS-VNEXT.md", summary)
def phase_status(output_root: Path, phase: int, plan: Mapping[str, Any]) -> None:
phase_config = next(item for item in plan["phases"] if int(item["number"]) == phase)
write_json(
output_root / f"checkpoint-{phase:02d}.json",
{
"schema": "chatgpt-audits.study-checkpoint.v1",
"generation": GENERATION,
"review_status": REVIEW_STATUS,
"classification": "observed",
"phase": phase,
"slug": phase_config["slug"],
"goal": phase_config["goal"],
"completed_at": now_utc(),
"completed_at_london": now_london(),
},
)
def cmd_phase(args: argparse.Namespace) -> int:
phase = int(args.phase)
if phase not in range(1, 6):
raise ValueError("phase must be 1..5")
plan = load_json(Path(args.plan).resolve())
manifest = load_json(Path(args.manifest).resolve())
source_root = Path(args.source_root).resolve()
audit_root = Path(args.audit_root).resolve()
output_root = Path(args.output_root).resolve()
output_root.mkdir(parents=True, exist_ok=True)
print(f"[phase {phase}] start", flush=True)
if phase == 1:
phase_one(plan, manifest, source_root, output_root)
elif phase == 2:
phase_two(plan, manifest, source_root, output_root)
elif phase == 3:
phase_three(plan, manifest, source_root, output_root)
elif phase == 4:
phase_four(plan, manifest, source_root, audit_root, output_root)
else:
phase_five(plan, manifest, output_root)
phase_status(output_root, phase, plan)
print(f"[phase {phase}] complete", flush=True)
return 0
def cmd_initialise(args: argparse.Namespace) -> int:
plan = load_json(Path(args.plan).resolve())
output_root = Path(args.output_root).resolve()
output_root.mkdir(parents=True, exist_ok=False)
content = md_header("Five-hour quarantined cross-repository study") + "\n"
content += (
f"Generation: `{GENERATION}` \n"
f"Run ID: `{args.run_id}` \n"
f"Quarantine branch: `{args.branch}` \n"
f"Started: `{now_london()}` \n\n"
"## Boundary\n\n"
"- Product repositories are read-only source snapshots.\n"
"- The only Git write target is this timestamped output root on a `chatgpt-audits` quarantine branch.\n"
"- No live data API, planning portal, Companies House download, scraper or news feed is called.\n"
"- Every output remains `UNREVIEWED` until a human graduates it.\n\n"
"## Checkpoints\n\n"
+ "\n".join(f"{item['number']}. **{item['slug']}** — {item['goal']}" for item in plan["phases"])
+ "\n"
)
write_text(output_root / "README.md", content)
write_json(
output_root / "RUN-CONTEXT.json",
{
"schema": "chatgpt-audits.run-context.v1",
"generation": GENERATION,
"review_status": REVIEW_STATUS,
"classification": "observed",
"run_id": str(args.run_id),
"run_attempt": str(args.run_attempt),
"event_name": str(args.event_name),
"quarantine_branch": str(args.branch),
"output_root": str(args.output_root),
"started_at": now_utc(),
"started_at_london": now_london(),
"plan_sha256": sha256_file(Path(args.plan).resolve()),
},
)
return 0
def cmd_finalise(args: argparse.Namespace) -> int:
output_root = Path(args.output_root).resolve()
manifest = load_json(Path(args.manifest).resolve())
source_failures = [entry for entry in manifest["repositories"] if entry.get("status") != "SNAPSHOT_READY"]
synthesis = md_header("00 — Executive synthesis", "inferred") + "\n"
synthesis += (
"## Result\n\n"
"A five-checkpoint, source-pinned audit candidate has been produced without modifying any product repository. The highest-priority next version is a modular PipelineNews timing engine, not another combined news runner.\n\n"
"## Load-bearing findings\n\n"
"1. **Observed:** PipelineNews's selected source contains large files combining collection, network, evidence, identity, validation, presentation and release concerns.\n"
"2. **Observed where cross-check ledger says so:** the current producer deep-link string and GridAtlas route contract disagree at the pinned commits.\n"
"3. **Observed:** Companies already protects a compact relationship/privacy boundary; that boundary can remain while a separate append-only organisation-event contract is added.\n"
"4. **Inferred:** commercial timing needs two independent register lanes — funding and procurement — joined only after reviewed identity binding.\n"
"5. **Inferred:** news is best treated as corroborating evidence and explanation, not as the authority that creates the funding/procurement fact.\n"
"6. **Inferred:** the first graduation should freeze contracts and state-machine tests before touching live products.\n\n"
"## Quarantined vNext package\n\n"
"See `next-versions/202608310052-pipelinenews-intelligence-vnext/` for schemas, module ownership, migration map, backlog, reference state machine and tests.\n\n"
"## Human decisions required\n\n"
"- Accept or reject the dual-register state model.\n"
"- Choose the reviewed source contract for Companies funding events.\n"
"- Choose the planning/procurement source-card and revision policy.\n"
"- Approve the GridAtlas pointer repair contract before any product change.\n"
"- Decide which P0 artefact graduates first and into which product repository.\n"
)
write_text(output_root / "00-EXECUTIVE-SYNTHESIS.md", synthesis)
queue = md_header("Human review queue", "inferred") + "\n"
queue += """| Priority | Review item | Decision |
|---:|---|---|
| 1 | `04-CLAUDE-CROSSCHECK-LEDGER.json` | Confirm the PipelineNews→GridAtlas route finding against a browser proof. |
| 2 | vNext evidence and transition schemas | Approve fields, source revision semantics and observed/inferred separation. |
| 3 | reference state-machine tests | Confirm one-signal silence and human-review gate reflect the commercial doctrine. |
| 4 | Companies event boundary | Confirm which organisation-level events may leave Companies and that PII stays excluded. |
| 5 | planning/procurement source contract | Select supervised sources and source-card requirements. |
| 6 | migration backlog | Select one bounded product-repo graduation; do not bulk-copy the audit candidate. |
"""
write_text(output_root / "REVIEW-QUEUE.md", queue)
files: list[dict[str, Any]] = []
for path in iter_files(output_root):
if path.name == "RUN-MANIFEST.json":
continue
files.append({"path": relative_posix(path, output_root), "bytes": path.stat().st_size, "sha256": sha256_file(path)})
files.sort(key=lambda item: item["path"])
write_json(
output_root / "RUN-MANIFEST.json",
{
"schema": "chatgpt-audits.five-hour-run-manifest.v1",
"generation": GENERATION,
"review_status": REVIEW_STATUS,
"classification": "observed",
"completed_at": now_utc(),
"completed_at_london": now_london(),
"source_snapshot_sha256": sha256_file(Path(args.manifest).resolve()),
"source_failures": source_failures,
"files": files,
"total_files": len(files),
"total_bytes": sum(item["bytes"] for item in files),
"graduation_status": "HUMAN_REVIEW_REQUIRED",
},
)
return 0
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest="command", required=True)
snapshot = sub.add_parser("snapshot")
snapshot.add_argument("--plan", required=True)
snapshot.add_argument("--source-root", required=True)
snapshot.add_argument("--manifest", required=True)
snapshot.set_defaults(func=cmd_snapshot)
initialise = sub.add_parser("initialise")
initialise.add_argument("--plan", required=True)
initialise.add_argument("--output-root", required=True)
initialise.add_argument("--run-id", required=True)
initialise.add_argument("--run-attempt", required=True)
initialise.add_argument("--event-name", required=True)
initialise.add_argument("--branch", required=True)
initialise.set_defaults(func=cmd_initialise)
phase = sub.add_parser("phase")
phase.add_argument("--phase", required=True, type=int)
phase.add_argument("--plan", required=True)
phase.add_argument("--source-root", required=True)
phase.add_argument("--manifest", required=True)
phase.add_argument("--audit-root", required=True)
phase.add_argument("--output-root", required=True)
phase.set_defaults(func=cmd_phase)
finalise = sub.add_parser("finalise")
finalise.add_argument("--output-root", required=True)
finalise.add_argument("--manifest", required=True)
finalise.set_defaults(func=cmd_finalise)
return parser
def main(argv: Sequence[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
try:
return int(args.func(args))
except Exception as exc:
print(f"ERROR: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())Verify Quarantine
A Python command-line tool in the automation folder of ChatGPT Audits that reads run context, repository inventory, checkpoint and PipelineNews engine audit, using SHA-256.
ingestchatgpt-audits / automation/202608310052-five-hour-study/verify_quarantine.py · lines 1–288 of 288 · version 2026-08-31 00:52 · Entry point · pattern tree_digest (shared by 2 files)
- What it does
- It loads run context, repository inventory, checkpoint and PipelineNews engine audit. Defines 8 functions or classes, including sha256_file, iter_files, tree_digest, parse_status_paths, git_changed_paths. Uses libraries __future__, argparse, hashlib, json, os. Side effects: reads or writes files; starts processes.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'chatgpt'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "`verify_quarantine.py` fails the run when:"
- Inputs & outputs
- In: JSON file RUN-CONTEXT.json; JSON file SOURCE-SNAPSHOT.json; JSON file 01-REPOSITORY-INVENTORY.json; JSON file checkpoint-01.json; JSON file 02-PIPELINENEWS-ENGINE-AUDIT.json; JSON file checkpoint-02.json; JSON file 03-EVENT-CONTRACT-CANDIDATE.json; JSON file checkpoint-03.json.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- It parses status paths (`parse_status_paths`) and is built from the sha256 file helper (`sha256_file`) and the iter files helper (`iter_files`). Verify the five-hour study remained inside its quarantine boundary. It accepts `--audit-root`, `--output-root` and `--source-root`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- chatgpt-audits · automation/202608310052-five-hour-study · Python CLI
- Uses
- __future__, argparse, hashlib, json, os, re, sys, pathlib
- Used by
- none found
- Produces
- sha256_file, iter_files, tree_digest, parse_status_paths, git_changed_paths, ensure_unreviewed_label, verify, main
- Defines here
- sha256_file, iter_files, tree_digest, parse_status_paths, git_changed_paths, ensure_unreviewed_label, verify, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- chatgpt-audits@5808fde29b91027ec7a3de40c451a82b6714437c automation/202608310052-five-hour-study/verify_quarantine.py:1-288 · blob 90d9e50d7d5747fb3b695912c93e216567d1f230 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""Verify the five-hour study remained inside its quarantine boundary.
REVIEW STATUS: UNREVIEWED.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import os
import re
import sys
from pathlib import Path
from typing import Any, Iterator, Sequence
REVIEW_STATUS = "UNREVIEWED"
SKIP_DIRS = {
".git",
".idea",
".pytest_cache",
".venv",
"__pycache__",
"node_modules",
"vendor",
}
FORBIDDEN_OUTPUT_DIRS = {
".git",
".idea",
".pytest_cache",
".venv",
"__pycache__",
"node_modules",
"vendor",
}
SECRET_PATTERNS = {
"github_token": re.compile(r"\bgh[pousr]_[A-Za-z0-9_]{20,}\b"),
"github_pat": re.compile(r"\bgithub_pat_[A-Za-z0-9_]{20,}\b"),
"aws_access_key": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
"private_key": re.compile(r"-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----"),
}
ALLOWED_JSON_CLASSIFICATIONS = {
"observed",
"inferred",
"contradicted",
"unknown",
"not_checked",
"not_observed_in_snapshot",
}
def sha256_file(path: Path) -> str:
h = hashlib.sha256()
with path.open("rb") as handle:
for chunk in iter(lambda: handle.read(1024 * 1024), b""):
h.update(chunk)
return h.hexdigest()
def iter_files(root: Path) -> Iterator[Path]:
if not root.exists():
return
for directory, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(name for name in dirnames if name not in SKIP_DIRS)
base = Path(directory)
for name in sorted(filenames):
path = base / name
if path.is_file() and not path.is_symlink():
yield path
def tree_digest(root: Path) -> tuple[str, int, int]:
digest = hashlib.sha256()
count = 0
total = 0
for path in iter_files(root):
rel = path.relative_to(root).as_posix()
size = path.stat().st_size
digest.update(rel.encode())
digest.update(b"\0")
digest.update(str(size).encode())
digest.update(b"\0")
digest.update(sha256_file(path).encode())
digest.update(b"\n")
count += 1
total += size
return digest.hexdigest(), count, total
def parse_status_paths(raw: bytes) -> list[str]:
paths: list[str] = []
for item in raw.split(b"\0"):
if not item:
continue
text = item.decode("utf-8", errors="replace")
paths.append(text[3:] if len(text) >= 4 else text)
return paths
def git_changed_paths(audit_root: Path) -> list[str]:
import subprocess
completed = subprocess.run(
["git", "status", "--porcelain=v1", "-z", "--untracked-files=all"],
cwd=audit_root,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
check=False,
)
if completed.returncode != 0:
raise RuntimeError(completed.stderr.decode("utf-8", errors="replace"))
return parse_status_paths(completed.stdout)
def ensure_unreviewed_label(path: Path) -> list[str]:
failures: list[str] = []
suffix = path.suffix.lower()
try:
text = path.read_text(encoding="utf-8")
except UnicodeDecodeError:
return failures
if suffix in {".md", ".txt"}:
if REVIEW_STATUS not in "\n".join(text.splitlines()[:12]):
failures.append(f"missing UNREVIEWED label near top: {path}")
elif suffix == ".json":
try:
payload: Any = json.loads(text)
except json.JSONDecodeError as exc:
failures.append(f"invalid JSON {path}: {exc}")
return failures
if not isinstance(payload, dict) or payload.get("review_status") != REVIEW_STATUS:
failures.append(f"JSON missing review_status=UNREVIEWED: {path}")
classification = payload.get("classification") if isinstance(payload, dict) else None
if classification is not None and classification not in ALLOWED_JSON_CLASSIFICATIONS:
failures.append(f"invalid top-level classification {classification!r}: {path}")
elif suffix in {".py", ".js", ".mjs", ".cjs", ".ts"}:
if REVIEW_STATUS not in "\n".join(text.splitlines()[:8]):
failures.append(f"reference code missing UNREVIEWED label: {path}")
return failures
def verify(args: argparse.Namespace) -> int:
audit_root = Path(args.audit_root).resolve()
output_root = Path(args.output_root).resolve()
source_root = Path(args.source_root).resolve()
manifest_path = Path(args.manifest).resolve()
plan = json.loads(Path(args.plan).read_text(encoding="utf-8"))
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
failures: list[str] = []
try:
output_rel = output_root.relative_to(audit_root).as_posix()
except ValueError:
failures.append("output root is outside audit checkout")
output_rel = ""
expected_prefix = "202608310033-study/AUTOMATION-RUNS/"
if not output_rel.startswith(expected_prefix):
failures.append(f"output root must start with {expected_prefix}: {output_rel}")
if output_root.is_symlink() or not output_root.is_dir():
failures.append("output root is missing, not a directory or is a symlink")
changed = git_changed_paths(audit_root)
for path in changed:
normalised = path.replace("\\", "/")
if not (normalised == output_rel or normalised.startswith(output_rel + "/")):
failures.append(f"changed path escaped quarantine: {normalised}")
max_file = int(plan["limits"]["max_output_file_bytes"])
max_total = int(plan["limits"]["max_total_output_bytes"])
total_bytes = 0
for directory, dirnames, filenames in os.walk(output_root):
for dirname in dirnames:
if dirname in FORBIDDEN_OUTPUT_DIRS:
failures.append(f"forbidden generated directory in output: {Path(directory) / dirname}")
for filename in filenames:
if filename.endswith((".pyc", ".pyo")):
failures.append(f"compiled bytecode forbidden in output: {Path(directory) / filename}")
for path in iter_files(output_root):
if path.is_symlink():
failures.append(f"symlink forbidden in output: {path}")
continue
size = path.stat().st_size
total_bytes += size
if size > max_file:
failures.append(f"output file exceeds {max_file} bytes: {path} ({size})")
failures.extend(ensure_unreviewed_label(path))
if size <= max_file:
try:
text = path.read_text(encoding="utf-8")
except UnicodeDecodeError:
failures.append(f"binary output forbidden: {path}")
continue
for name, pattern in SECRET_PATTERNS.items():
if pattern.search(text):
failures.append(f"possible {name} in output: {path}")
if total_bytes > max_total:
failures.append(f"total output exceeds {max_total} bytes: {total_bytes}")
for entry in manifest.get("repositories", []):
if entry.get("status") != "SNAPSHOT_READY":
continue
name = str(entry["name"])
repo_root = source_root / name
if not repo_root.exists():
failures.append(f"source snapshot disappeared: {name}")
continue
if (repo_root / ".git").exists():
failures.append(f"source git metadata was not removed: {name}")
digest, files, total = tree_digest(repo_root)
if digest != entry.get("snapshot_tree_sha256"):
failures.append(
f"source snapshot changed: {name} expected={entry.get('snapshot_tree_sha256')} actual={digest}"
)
if files != int(entry.get("snapshot_files", -1)):
failures.append(f"source file count changed: {name} expected={entry.get('snapshot_files')} actual={files}")
if total != int(entry.get("snapshot_bytes", -1)):
failures.append(f"source byte count changed: {name} expected={entry.get('snapshot_bytes')} actual={total}")
required_files = ["README.md", "RUN-CONTEXT.json", "SOURCE-SNAPSHOT.json"]
phase = int(args.phase)
phase_requirements = {
1: ["01-REPOSITORY-INVENTORY.md", "01-REPOSITORY-INVENTORY.json", "checkpoint-01.json"],
2: ["02-PIPELINENEWS-ENGINE-AUDIT.md", "02-PIPELINENEWS-ENGINE-AUDIT.json", "checkpoint-02.json"],
3: ["03-FUNDING-AND-PROCUREMENT-SIGNALS.md", "03-EVENT-CONTRACT-CANDIDATE.json", "checkpoint-03.json"],
4: ["04-SEAMS-AND-CLAUDE-CROSSCHECK.md", "04-CLAUDE-CROSSCHECK-LEDGER.json", "checkpoint-04.json"],
5: [
"05-PIPELINENEWS-VNEXT.md",
"checkpoint-05.json",
"next-versions/202608310052-pipelinenews-intelligence-vnext/README.md",
"next-versions/202608310052-pipelinenews-intelligence-vnext/reference/state_machine.py",
"next-versions/202608310052-pipelinenews-intelligence-vnext/reference/test_state_machine.py"
],
6: ["00-EXECUTIVE-SYNTHESIS.md", "REVIEW-QUEUE.md", "RUN-MANIFEST.json"]
}
for current in range(1, min(phase, 5) + 1):
required_files.extend(phase_requirements[current])
if phase == 6:
for current in range(1, 6):
required_files.extend(phase_requirements[current])
required_files.extend(phase_requirements[6])
for rel in required_files:
if not (output_root / rel).is_file():
failures.append(f"required output missing for phase {phase}: {rel}")
if failures:
print("QUARANTINE VERIFICATION FAILED", file=sys.stderr)
for failure in failures:
print(f"- {failure}", file=sys.stderr)
return 1
print(
json.dumps(
{
"status": "PASS",
"phase": phase,
"output_root": output_rel,
"changed_paths": changed,
"total_output_bytes": total_bytes,
"source_snapshots_verified": sum(1 for item in manifest.get("repositories", []) if item.get("status") == "SNAPSHOT_READY")
},
indent=2
)
)
return 0
def main(argv: Sequence[str] | None = None) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--audit-root", required=True)
parser.add_argument("--output-root", required=True)
parser.add_argument("--source-root", required=True)
parser.add_argument("--manifest", required=True)
parser.add_argument("--plan", required=True)
parser.add_argument("--phase", required=True, type=int, choices=range(1, 7))
args = parser.parse_args(argv)
try:
return verify(args)
except Exception as exc:
print(f"QUARANTINE VERIFICATION ERROR: {exc}", file=sys.stderr)
return 1
if __name__ == "__main__":
raise SystemExit(main())Assemble Controller
A Python command-line tool in the automation folder of ChatGPT Audits that uses SHA-256. It is built from the sha256 step (`sha256`).
storagechatgpt-audits / automation/202608310116-overnight-swarm/assemble_controller.py · lines 1–75 of 75 · version 2026-08-31 01:16 · Entry point
- What it does
- It loads data. Defines sha256, main. Uses libraries __future__, argparse, base64, hashlib, json. Side effects: reads or writes files.
- Why it exists in the grid workflow
- Domain stage agent_infra (repository name word 'chatgpt'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
- Inputs & outputs
- In: command-line arguments.
- Downstream impact
- It is itself an entry point (Python CLI); no other file was found loading it.
- What it achieves
- Assemble and verify the compressed overnight swarm controller. It accepts `--payload-dir`, `--manifest` and `--output`.
- Why it matters
- No other file in the estate was found to import it; it is an entry point.
- Application
- chatgpt-audits · automation/202608310116-overnight-swarm · Python CLI
- Uses
- __future__, argparse, base64, hashlib, json, shutil, tarfile, tempfile
- Used by
- none found
- Produces
- sha256, main
- Defines here
- sha256, main
- Cannot conclude
- Whether this code runs, is used by a live app today, or is correct. This is a static reading.
- Evidence
- chatgpt-audits@5808fde29b91027ec7a3de40c451a82b6714437c automation/202608310116-overnight-swarm/assemble_controller.py:1-75 · blob bbd9b4d61bd1a96f103ca40139c8bbe1a1157ae0 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Assemble and verify the compressed overnight swarm controller.
REVIEW STATUS: UNREVIEWED.
"""
from __future__ import annotations
import argparse
import base64
import hashlib
import json
import shutil
import tarfile
import tempfile
from pathlib import Path
def sha256(data: bytes) -> str:
return hashlib.sha256(data).hexdigest()
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--payload-dir", required=True)
parser.add_argument("--manifest", required=True)
parser.add_argument("--output", required=True)
args = parser.parse_args()
payload_dir = Path(args.payload_dir).resolve()
manifest_path = Path(args.manifest).resolve()
output = Path(args.output).resolve()
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
parts = sorted(payload_dir.glob("controller.part-*"))
expected_parts = manifest["payload"]["parts"]
if [path.name for path in parts] != expected_parts:
raise SystemExit(f"payload part closure mismatch: {[path.name for path in parts]}")
encoded = b"".join(path.read_bytes() for path in parts)
if sha256(encoded) != manifest["payload"]["base64_sha256"]:
raise SystemExit("base64 payload digest mismatch")
archive = base64.b64decode(encoded, validate=True)
if sha256(archive) != manifest["payload"]["archive_sha256"]:
raise SystemExit("controller archive digest mismatch")
if output.exists():
shutil.rmtree(output)
output.mkdir(parents=True)
with tempfile.TemporaryDirectory() as temp:
archive_path = Path(temp) / "controller.tar.gz"
archive_path.write_bytes(archive)
with tarfile.open(archive_path, "r:gz") as handle:
members = handle.getmembers()
expected_files = set(manifest["files"])
actual_files = {member.name for member in members if member.isfile()}
if actual_files != expected_files:
raise SystemExit(f"archive file closure mismatch: {sorted(actual_files)}")
for member in members:
target = (output / member.name).resolve()
if output not in target.parents:
raise SystemExit(f"unsafe archive member: {member.name}")
if member.issym() or member.islnk():
raise SystemExit(f"links forbidden in controller archive: {member.name}")
handle.extractall(output, filter="data")
for name, expected in manifest["file_sha256"].items():
data = (output / name).read_bytes()
actual = sha256(data)
if actual != expected:
raise SystemExit(f"source digest mismatch for {name}: {actual}")
print(json.dumps({"review_status": "UNREVIEWED", "assembled": sorted(manifest["files"]), "archive_sha256": sha256(archive)}))
return 0
if __name__ == "__main__":
raise SystemExit(main())