GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / chatgpt-audits / automation/202608310052-five-hour-study

Run Study (part 2)

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.

700 lines of Python from chatgpt-audits, in 1 file. Topic: AI agents and coordination. Section 1589 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. Run Study energy-data · chatgpt-audits / automation/202608310052-five-hour-study/run_study.py lines 701–1400

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 701–1400 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_three, find_first_line, claim, phase_four, schema_evidence_event, schema_transition, schema_summary, reference_state_machine, State, Lane, Evidence, usable, observed_lanes, has_dual_register_corroboration, propose_transition, publish, reference_tests, TimingStateMachineTests, test_one_signal_stays_silent, test_dual_register_evidence_can_form_candidate_window, test_retracted_signal_does_not_count, test_contradiction_wins, test_release_requires_human_review, test_audit_scaffold_cannot_publish, phase_five
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:701-1400 · 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
    module_lines = []
    for module, paths in observed_module_names.items():
        if paths:
            module_lines.append(f"- **Observed `{module}` names:** " + ", ".join(f"`{path}`" for path in paths[:10]))
        else:
            module_lines.append(f"- **Not observed in selected snapshot:** dedicated `{module}` filename/interface.")
    content = md_header("02 — PipelineNews intelligence-engine audit") + "\n"
    content += (
        f"Pinned source: `{entry['repository']}@{entry['commit']}`.\n\n"
        "| Candidate file | Bytes | Lines | Responsibilities observed | Monolith candidate |\n"
        "|---|---:|---:|---|---:|\n"
        + "\n".join(top_rows)
        + "\n\n## Module-boundary observations\n\n"
        + "\n".join(module_lines)
        + "\n\n## Current deep-link producer\n\n"
        + (f"- **Observed:** `{base_url_observation['base_url']}` in `{base_url_observation['path']}`.\n" if base_url_observation["base_url"] else "- **Not observed in selected snapshot:** a readable `BASE_URL`.\n")
        + "\n## Architectural conclusion\n\n"
        "- **Observed:** collection, network access, evidence handling, identity terms, validation and release/promotion terms coexist in large runner files.\n"
        "- **Inferred:** adding another runner would increase coupling and make abstention, retraction and source revision harder to prove.\n"
        "- **Inferred:** the vNext boundary should be `collectors → evidence ledger → identity binder → timing state machine → reviewed read model`.\n"
        "- **Not checked:** this automated scan does not execute live feeds or prove current public Pages behaviour.\n"
    )
    write_text(output_root / "02-PIPELINENEWS-ENGINE-AUDIT.md", content)


def phase_three(plan: Mapping[str, Any], manifest: Mapping[str, Any], source_root: Path, output_root: Path) -> None:
    patterns = {
        "funding_fact": re.compile(r"\b(charge|charges|allotment|statement of capital|accounts filed|company number|company_number|mortgage|funding|finance|financing)\b", re.I),
        "procurement_fact": re.compile(r"\b(planning|condition discharge|discharge of condition|procurement|tender|contract award|epc|reserved matters|pre-commencement)\b", re.I),
        "identity_key": re.compile(r"\b(repd_ref|gg_project_id|company_number|planning_application|application_ref)\b", re.I),
        "privacy_boundary": re.compile(r"\b(director|psc|date of birth|residential address|privacy|personal data)\b", re.I),
        "inference_term": re.compile(r"\b(score|confidence|window|inferred|candidate|prediction)\b", re.I),
    }
    all_rows: list[dict[str, Any]] = []
    for repo_name in ("companies", "pipelinenews", "spiders", "data-gridatlas"):
        entry = source_entry(manifest, repo_name)
        if not entry or entry.get("status") != "SNAPSHOT_READY":
            continue
        rows = evidence_rows(
            repo_name,
            source_root_for(source_root, repo_name),
            patterns,
            commit=str(entry["commit"]),
            max_file_bytes=int(plan["limits"]["max_text_file_bytes"]),
            max_excerpt_chars=int(plan["limits"]["max_excerpt_chars"]),
            max_rows=140,
        )
        all_rows.extend(rows)
    all_rows = all_rows[: int(plan["limits"]["max_evidence_rows_per_report"])]

    event_contract = {
        "schema": "pipelinenews.event-contract.candidate.v1",
        "generation": GENERATION,
        "review_status": REVIEW_STATUS,
        "classification": "inferred",
        "status": "QUARANTINED_DRAFT",
        "separation_rule": "Observed register events and inferred commercial windows are separate records joined only by evidence IDs.",
        "observed_event": {
            "required": [
                "event_id",
                "source_system",
                "source_record_id",
                "event_type",
                "observed_at",
                "effective_at",
                "evidence_sha256",
                "fact_status"
            ],
            "fact_status_allowed": ["OBSERVED", "REVISED", "RETRACTED", "CONTRADICTED"],
            "event_type_candidates": [
                "COMPANY_CHARGE_CREATED",
                "COMPANY_CHARGE_SATISFIED",
                "COMPANY_ALLOTMENT_FILED",
                "COMPANY_ACCOUNTS_FILED",
                "PLANNING_APPLICATION_STATUS",
                "PLANNING_CONDITION_EVENT",
                "PROCUREMENT_NOTICE_OBSERVED"
            ]
        },
        "inferred_window": {
            "required": [
                "inference_id",
                "project_id",
                "inference_type",
                "classification",
                "rule_version",
                "input_evidence_ids",
                "calculated_at",
                "review_status"
            ],
            "classification_constant": "inferred",
            "inference_type_candidates": ["FUNDING_WINDOW", "PROCUREMENT_WINDOW", "CORROBORATED_SALES_WINDOW"],
            "may_publish_without_human_review": False
        },
        "identity_join": {
            "project_key": "gg_project_id",
            "project_source_key": "repd_ref",
            "company_key": "company_number",
            "planning_key": "planning_application_ref",
            "relationship_required_fields": ["relationship_type", "evidence_ids", "valid_from", "valid_to", "binding_status", "review_status"]
        },
        "privacy": {
            "forbidden_public_fields": ["director_name", "individual_psc", "date_of_birth", "residential_address"],
            "company_number_is_an_organisation_identifier": True
        }
    }
    write_json(output_root / "03-EVENT-CONTRACT-CANDIDATE.json", event_contract)
    write_json(
        output_root / "03-FUNDING-PROCUREMENT-EVIDENCE.json",
        {
            "schema": "chatgpt-audits.funding-procurement-evidence.v1",
            "generation": GENERATION,
            "review_status": REVIEW_STATUS,
            "classification": "observed",
            "created_at": now_utc(),
            "evidence": all_rows,
        },
    )

    counts = collections.Counter(row["category"] for row in all_rows)
    count_lines = "\n".join(f"- `{category}`: {count} selected source-code line(s)" for category, count in counts.most_common())
    content = md_header("03 — Funding and procurement signal separation") + "\n"
    content += (
        "The commercial timing engine needs two independent evidence lanes. The source scan below records only code and contract language; it does not assert that a real project is funded or procuring.\n\n"
        "## Evidence-language inventory\n\n"
        + (count_lines or "- No matching lines observed in the selected snapshots.")
        + "\n\n## Candidate event model\n\n"
        "1. **Observed register event:** a source-stamped filing, charge, planning status, condition or procurement notice.\n"
        "2. **Identity relationship:** a separately evidenced binding between company, planning application and canonical project.\n"
        "3. **Inferred window:** a rule-versioned interpretation that cites observed evidence IDs and is always labelled `inferred`.\n"
        "4. **Corroborated sales window:** permitted only when an observed funding lane and an observed procurement lane both exist for the same reviewed project identity.\n\n"
        "## Hard boundary\n\n"
        "- One lane alone must remain silent.\n"
        "- Absence of a filing or planning event is not negative evidence.\n"
        "- News may corroborate or explain evidence; it must not manufacture the funding or procurement fact.\n"
        "- Company relationship Parquet can stay compact; event history belongs in a separate, append-only contract.\n"
        "- Public outputs must preserve the Companies privacy boundary and exclude individual director/PSC details.\n"
    )
    write_text(output_root / "03-FUNDING-AND-PROCUREMENT-SIGNALS.md", content)


def find_first_line(path: Path, pattern: re.Pattern[str], max_bytes: int) -> tuple[int, str] | None:
    text = read_text(path, max_bytes)
    if text is None:
        return None
    for number, line in enumerate(text.splitlines(), 1):
        if pattern.search(line):
            return number, excerpt(line, 280)
    return None


def claim(
    claim_id: str,
    statement: str,
    classification: str,
    evidence: list[dict[str, Any]],
    note: str,
) -> dict[str, Any]:
    if classification not in CLASSIFICATIONS:
        raise ValueError(classification)
    return {
        "claim_id": claim_id,
        "statement": statement,
        "classification": classification,
        "evidence": evidence,
        "note": note,
    }


def phase_four(
    plan: Mapping[str, Any],
    manifest: Mapping[str, Any],
    source_root: Path,
    audit_root: Path,
    output_root: Path,
) -> None:
    max_bytes = int(plan["limits"]["max_text_file_bytes"])
    claims: list[dict[str, Any]] = []

    pipeline = source_entry(manifest, "pipelinenews")
    grid = source_entry(manifest, "gridatlas")
    companies = source_entry(manifest, "companies")

    pipeline_root = source_root_for(source_root, "pipelinenews")
    grid_root = source_root_for(source_root, "gridatlas")
    companies_root = source_root_for(source_root, "companies")

    deep_path = pipeline_root / "ui/atlas-v9-deep-links.js"
    old_url = re.compile(r"https://ventusltd\.github\.io/gridatlas/202608300453-atlas-v9/")
    hit = find_first_line(deep_path, old_url, max_bytes) if deep_path.exists() else None
    if hit and pipeline:
        claims.append(
            claim(
                "CROSSCHECK-001",
                "PipelineNews still emits the pre-move root GridAtlas release route.",
                "observed",
                [{"repository": "pipelinenews", "commit": pipeline["commit"], "path": "ui/atlas-v9-deep-links.js", "line": hit[0], "excerpt": hit[1]}],
                "The copied study's producer-side string is present at the pinned commit.",
            )
        )
    else:
        claims.append(
            claim(
                "CROSSCHECK-001",
                "PipelineNews still emits the pre-move root GridAtlas release route.",
                "contradicted" if deep_path.exists() else "not_checked",
                [],
                "The expected literal was not found in the selected current file." if deep_path.exists() else "The current file was not available in the selected snapshot.",
            )
        )

    live_route_evidence: list[dict[str, Any]] = []
    for rel in ("state/live-set.json", "atlas/current.json"):
        path = grid_root / rel
        if not path.exists() or not grid:
            continue
        route_hit = find_first_line(path, re.compile(r"/gridatlas/atlas/"), max_bytes)
        if route_hit:
            live_route_evidence.append({"repository": "gridatlas", "commit": grid["commit"], "path": rel, "line": route_hit[0], "excerpt": route_hit[1]})
    if live_route_evidence:
        claims.append(
            claim(
                "CROSSCHECK-002",
                "GridAtlas declares `/gridatlas/atlas/` as its stable live route.",
                "observed",
                live_route_evidence,
                "Current selected pointer/composition files contain the stable route.",
            )
        )
    else:
        claims.append(claim("CROSSCHECK-002", "GridAtlas declares `/gridatlas/atlas/` as its stable live route.", "not_checked", [], "No readable selected pointer file proved the route."))

    if grid:
        probes = grid.get("tree_probes", {})
        old_probe = probes.get("202608300453-atlas-v9/index.html")
        new_probe = probes.get("atlas/releases/202608300453-atlas-v9/index.html")
        if old_probe is False and new_probe is True:
            classification = "observed"
            note = "The full Git tree probe records the old root path absent and the moved release path present."
        elif old_probe is not None or new_probe is not None:
            classification = "contradicted"
            note = f"Tree probes did not match the copied claim: old={old_probe!r}, new={new_probe!r}."
        else:
            classification = "not_checked"
            note = "The source plan did not contain both full-tree probes."
        claims.append(
            claim(
                "CROSSCHECK-003",
                "The `202608300453-atlas-v9` release moved from repository root to `atlas/releases/`.",
                classification,
                [{"repository": "gridatlas", "commit": grid.get("commit"), "tree_probes": {"old": old_probe, "new": new_probe}}],
                note,
            )
        )

    overnight_rel = ".github/workflows/202608310015-gridatlas-overnight-next-versions.yml"
    overnight = grid_root / overnight_rel
    push_hit = find_first_line(overnight, re.compile(r"git\s+push\s+origin\s+HEAD:main", re.I), max_bytes) if overnight.exists() else None
    if push_hit and grid:
        claims.append(
            claim(
                "CROSSCHECK-004",
                "A GridAtlas overnight study workflow can commit study/candidate output directly to product `main`.",
                "observed",
                [{"repository": "gridatlas", "commit": grid["commit"], "path": overnight_rel, "line": push_hit[0], "excerpt": push_hit[1]}],
                "This is an anti-pattern for the audit automation; the new workflow writes only to an audit branch.",
            )
        )
    else:
        claims.append(claim("CROSSCHECK-004", "A GridAtlas overnight study workflow can commit study/candidate output directly to product `main`.", "not_observed_in_snapshot", [], "No exact push line was observed in the selected workflow snapshot."))

    companies_readme = companies_root / "README.md"
    compact_hit = find_first_line(companies_readme, re.compile(r"key-only relationship|compact relationship", re.I), max_bytes) if companies_readme.exists() else None
    if compact_hit and companies:
        claims.append(
            claim(
                "CROSSCHECK-005",
                "Companies preserves a compact relationship-candidate and privacy boundary rather than publishing a company master dataset.",
                "observed",
                [{"repository": "companies", "commit": companies["commit"], "path": "README.md", "line": compact_hit[0], "excerpt": compact_hit[1]}],
                "The boundary should be retained while adding a separate event-history contract.",
            )
        )
    else:
        claims.append(claim("CROSSCHECK-005", "Companies preserves a compact relationship-candidate and privacy boundary rather than publishing a company master dataset.", "not_checked", [], "The selected README did not prove the claim."))

    if grid:
        build_plan_probe = grid.get("tree_probes", {}).get("_build-plan/summary.md")
        claims.append(
            claim(
                "CROSSCHECK-006",
                "Claude's `_build-plan` exists at the current GridAtlas commit.",
                "observed" if build_plan_probe is True else "not_observed_in_snapshot" if build_plan_probe is False else "not_checked",
                [{"repository": "gridatlas", "commit": grid.get("commit"), "tree_probe": build_plan_probe}],
                "A false tree probe means only that the named path was not observed at this commit; copied study material remains in chatgpt-audits.",
            )
        )

    copied_study = audit_root / "202608310033-study"
    tokens: collections.Counter[str] = collections.Counter()
    for path in iter_files(copied_study, limit=5000):
        if "AUTOMATION-RUNS" in path.parts:
            continue
        text = read_text(path, max_bytes)
        if text is None:
            continue
        for token in BACKTICK_RE.findall(text):
            if "/" in token and len(token) <= 220 and not token.startswith(("http://", "https://")):
                tokens[token] += 1
    path_census = [{"token": token, "mentions": count} for token, count in tokens.most_common(250)]

    ledger = {
        "schema": "chatgpt-audits.claude-crosscheck-ledger.v1",
        "generation": GENERATION,
        "review_status": REVIEW_STATUS,
        "classification": "observed",
        "created_at": now_utc(),
        "source_note": "Claims were copied into chatgpt-audits and re-tested against pinned repository snapshots. No live product or external data source was queried.",
        "claims": claims,
        "copied_study_path_token_census": path_census,
    }
    write_json(output_root / "04-CLAUDE-CROSSCHECK-LEDGER.json", ledger)

    claim_rows = []
    for item in claims:
        claim_rows.append(f"| `{item['claim_id']}` | `{item['classification']}` | {item['statement']} | {item['note']} |")
    content = md_header("04 — Seams and copied-Claude-study cross-check") + "\n"
    content += (
        "The copied study is treated as a hypothesis corpus, not as current truth. Every row below was tested against exact commits captured at run start.\n\n"
        "| Claim | Result | Statement | Note |\n"
        "|---|---|---|---|\n"
        + "\n".join(claim_rows)
        + "\n\n## Governing interpretation\n\n"
        "- Agreement between copied study and current source raises confidence but does not constitute human review.\n"
        "- A contradiction is preserved in the ledger; the older text is not silently rewritten.\n"
        "- `not_observed_in_snapshot` is not evidence of non-existence.\n"
        "- The highest-priority seam remains PipelineNews's producer URL versus GridAtlas's current stable route.\n"
        "- No repair is installed here; the output is a quarantined graduation candidate only.\n"
    )
    write_text(output_root / "04-SEAMS-AND-CLAUDE-CROSSCHECK.md", content)


def schema_evidence_event() -> dict[str, Any]:
    return {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "$id": "urn:ventus:pipelinenews:evidence-event:vnext",
        "title": "UNREVIEWED PipelineNews evidence event",
        "review_status": REVIEW_STATUS,
        "classification": "inferred",
        "type": "object",
        "additionalProperties": False,
        "required": [
            "event_id", "source_system", "source_record_id", "event_type", "observed_at",
            "effective_at", "fact_status", "evidence_sha256", "source_card_id"
        ],
        "properties": {
            "event_id": {"type": "string", "minLength": 8, "maxLength": 160},
            "source_system": {"type": "string", "enum": ["COMPANIES_HOUSE", "PLANNING_REGISTER", "PROCUREMENT_REGISTER", "REPD", "NEWS_CORROBORATION"]},
            "source_record_id": {"type": "string", "minLength": 1, "maxLength": 240},
            "event_type": {"type": "string", "minLength": 3, "maxLength": 100},
            "observed_at": {"type": "string", "format": "date-time"},
            "effective_at": {"type": ["string", "null"], "format": "date-time"},
            "fact_status": {"type": "string", "enum": ["OBSERVED", "REVISED", "RETRACTED", "CONTRADICTED"]},
            "evidence_sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
            "source_card_id": {"type": "string", "minLength": 3, "maxLength": 160},
            "project_keys": {
                "type": "object",
                "additionalProperties": False,
                "properties": {
                    "repd_ref": {"type": ["string", "null"], "maxLength": 40},
                    "gg_project_id": {"type": ["string", "null"], "pattern": "^GG2050-REPD-[0-9]+$"},
                    "company_number": {"type": ["string", "null"], "maxLength": 16},
                    "planning_application_ref": {"type": ["string", "null"], "maxLength": 120}
                }
            },
            "supersedes_event_id": {"type": ["string", "null"], "maxLength": 160}
        }
    }


def schema_transition() -> dict[str, Any]:
    return {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "$id": "urn:ventus:pipelinenews:timing-transition:vnext",
        "title": "UNREVIEWED PipelineNews timing transition",
        "review_status": REVIEW_STATUS,
        "classification": "inferred",
        "type": "object",
        "additionalProperties": False,
        "required": ["transition_id", "project_id", "from_state", "to_state", "input_evidence_ids", "classification", "rule_version", "calculated_at", "review_status"],
        "properties": {
            "transition_id": {"type": "string"},
            "project_id": {"type": "string", "pattern": "^GG2050-REPD-[0-9]+$"},
            "from_state": {"$ref": "#/$defs/state"},
            "to_state": {"$ref": "#/$defs/state"},
            "input_evidence_ids": {"type": "array", "items": {"type": "string"}, "uniqueItems": True},
            "classification": {"const": "inferred"},
            "rule_version": {"type": "string"},
            "calculated_at": {"type": "string", "format": "date-time"},
            "review_status": {"type": "string", "enum": ["UNREVIEWED", "HUMAN_REVIEWED", "REJECTED"]},
            "reason": {"type": "string", "maxLength": 1000}
        },
        "$defs": {
            "state": {
                "type": "string",
                "enum": [
                    "DISCOVERED", "IDENTITY_CANDIDATE", "FUNDING_OBSERVED", "PROCUREMENT_OBSERVED",
                    "CORROBORATED_WINDOW", "HUMAN_REVIEWED", "RELEASE_CANDIDATE", "WITHHELD", "CONFLICTED", "STALE"
                ]
            }
        }
    }


def schema_summary() -> dict[str, Any]:
    return {
        "$schema": "https://json-schema.org/draft/2020-12/schema",
        "$id": "urn:ventus:pipelinenews:project-intelligence-summary:vnext",
        "title": "UNREVIEWED publishable project intelligence read model",
        "review_status": REVIEW_STATUS,
        "classification": "inferred",
        "type": "object",
        "additionalProperties": False,
        "required": ["gg_project_id", "repd_ref", "state", "as_of", "review_status", "observed_facts", "inferred_windows", "source_refs", "staleness"],
        "properties": {
            "gg_project_id": {"type": "string", "pattern": "^GG2050-REPD-[0-9]+$"},
            "repd_ref": {"type": "string", "pattern": "^[A-Za-z0-9-]{1,40}$"},
            "state": {"type": "string"},
            "as_of": {"type": "string", "format": "date-time"},
            "review_status": {"const": "HUMAN_REVIEWED"},
            "observed_facts": {"type": "array", "items": {"type": "object"}},
            "inferred_windows": {
                "type": "array",
                "items": {
                    "type": "object",
                    "required": ["classification", "inference_type", "input_evidence_ids", "rule_version"],
                    "properties": {
                        "classification": {"const": "inferred"},
                        "inference_type": {"type": "string"},
                        "input_evidence_ids": {"type": "array", "items": {"type": "string"}},
                        "rule_version": {"type": "string"}
                    }
                }
            },
            "source_refs": {"type": "array", "items": {"type": "string"}},
            "staleness": {"type": "object"},
            "gridatlas_deep_link": {"type": ["string", "null"], "format": "uri"}
        }
    }


def reference_state_machine() -> str:
    return '''# REVIEW STATUS: UNREVIEWED
"""Quarantined reference state machine for PipelineNews vNext.

This module is a design artefact only. It deliberately cannot publish.
"""
from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import Iterable


class State(str, Enum):
    DISCOVERED = "DISCOVERED"
    IDENTITY_CANDIDATE = "IDENTITY_CANDIDATE"
    FUNDING_OBSERVED = "FUNDING_OBSERVED"
    PROCUREMENT_OBSERVED = "PROCUREMENT_OBSERVED"
    CORROBORATED_WINDOW = "CORROBORATED_WINDOW"
    HUMAN_REVIEWED = "HUMAN_REVIEWED"
    RELEASE_CANDIDATE = "RELEASE_CANDIDATE"
    WITHHELD = "WITHHELD"
    CONFLICTED = "CONFLICTED"
    STALE = "STALE"


class Lane(str, Enum):
    FUNDING = "FUNDING"
    PROCUREMENT = "PROCUREMENT"
    CORROBORATION = "CORROBORATION"


@dataclass(frozen=True)
class Evidence:
    evidence_id: str
    lane: Lane
    fact_status: str = "OBSERVED"
    retracted: bool = False

    @property
    def usable(self) -> bool:
        return self.fact_status == "OBSERVED" and not self.retracted


def observed_lanes(evidence: Iterable[Evidence]) -> set[Lane]:
    return {item.lane for item in evidence if item.usable}


def has_dual_register_corroboration(evidence: Iterable[Evidence]) -> bool:
    lanes = observed_lanes(evidence)
    return Lane.FUNDING in lanes and Lane.PROCUREMENT in lanes


def propose_transition(
    current: State,
    requested: State,
    evidence: Iterable[Evidence],
    *,
    identity_reviewed: bool = False,
    human_reviewed: bool = False,
    contradiction: bool = False,
) -> State:
    evidence = tuple(evidence)
    lanes = observed_lanes(evidence)

    if contradiction:
        return State.CONFLICTED

    if requested == State.IDENTITY_CANDIDATE:
        return State.IDENTITY_CANDIDATE

    if requested == State.FUNDING_OBSERVED:
        if Lane.FUNDING not in lanes:
            raise ValueError("observed funding evidence is required")
        return State.FUNDING_OBSERVED

    if requested == State.PROCUREMENT_OBSERVED:
        if Lane.PROCUREMENT not in lanes:
            raise ValueError("observed procurement evidence is required")
        return State.PROCUREMENT_OBSERVED

    if requested == State.CORROBORATED_WINDOW:
        if not identity_reviewed:
            raise ValueError("reviewed project identity is required")
        if not has_dual_register_corroboration(evidence):
            raise ValueError("both funding and procurement evidence are required")
        return State.CORROBORATED_WINDOW

    if requested == State.HUMAN_REVIEWED:
        if current != State.CORROBORATED_WINDOW or not human_reviewed:
            raise ValueError("human review follows a corroborated window")
        return State.HUMAN_REVIEWED

    if requested == State.RELEASE_CANDIDATE:
        if current != State.HUMAN_REVIEWED or not human_reviewed:
            raise ValueError("release candidate requires recorded human review")
        return State.RELEASE_CANDIDATE

    raise ValueError(f"unsupported or forbidden transition: {requested.value}")


def publish(*_args: object, **_kwargs: object) -> None:
    raise RuntimeError("PUBLISHED transitions are forbidden in chatgpt-audits")
'''


def reference_tests() -> str:
    return '''# REVIEW STATUS: UNREVIEWED
import unittest

from state_machine import Evidence, Lane, State, propose_transition, publish


class TimingStateMachineTests(unittest.TestCase):
    def test_one_signal_stays_silent(self):
        evidence = [Evidence("funding-1", Lane.FUNDING)]
        with self.assertRaisesRegex(ValueError, "both funding and procurement"):
            propose_transition(
                State.FUNDING_OBSERVED,
                State.CORROBORATED_WINDOW,
                evidence,
                identity_reviewed=True,
            )

    def test_dual_register_evidence_can_form_candidate_window(self):
        evidence = [
            Evidence("funding-1", Lane.FUNDING),
            Evidence("planning-1", Lane.PROCUREMENT),
        ]
        result = propose_transition(
            State.PROCUREMENT_OBSERVED,
            State.CORROBORATED_WINDOW,
            evidence,
            identity_reviewed=True,
        )
        self.assertEqual(result, State.CORROBORATED_WINDOW)

    def test_retracted_signal_does_not_count(self):
        evidence = [
            Evidence("funding-1", Lane.FUNDING, retracted=True),
            Evidence("planning-1", Lane.PROCUREMENT),
        ]
        with self.assertRaises(ValueError):
            propose_transition(
                State.PROCUREMENT_OBSERVED,
                State.CORROBORATED_WINDOW,
                evidence,
                identity_reviewed=True,
            )

    def test_contradiction_wins(self):
        result = propose_transition(
            State.DISCOVERED,
            State.IDENTITY_CANDIDATE,
            [],
            contradiction=True,
        )
        self.assertEqual(result, State.CONFLICTED)

    def test_release_requires_human_review(self):
        with self.assertRaises(ValueError):
            propose_transition(
                State.CORROBORATED_WINDOW,
                State.RELEASE_CANDIDATE,
                [],
                human_reviewed=False,
            )

    def test_audit_scaffold_cannot_publish(self):
        with self.assertRaisesRegex(RuntimeError, "forbidden"):
            publish()


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


def phase_five(plan: Mapping[str, Any], manifest: Mapping[str, Any], output_root: Path) -> None:
    candidate_root = output_root / "next-versions/202608310052-pipelinenews-intelligence-vnext"
    schemas = candidate_root / "schemas"
    reference = candidate_root / "reference"

    source_commits = {
        entry["name"]: entry.get("commit")
        for entry in manifest["repositories"]
        if entry.get("status") == "SNAPSHOT_READY"
    }
    architecture = {
        "schema": "pipelinenews.intelligence-architecture.candidate.vnext",
        "generation": GENERATION,
        "review_status": REVIEW_STATUS,
        "classification": "inferred",
        "status": "QUARANTINED_DRAFT",
        "source_commits": source_commits,
        "modules": [
            {"name": "collectors", "owns": ["source-specific retrieval adapter", "source card", "raw response receipt"], "must_not_own": ["project identity conclusion", "commercial timing conclusion", "publication"]},
            {"name": "evidence-ledger", "owns": ["append-only observed events", "revision", "retraction", "contradiction", "content digest"], "must_not_own": ["UI", "ranking", "project publication"]},
            {"name": "identity-binder", "owns": ["company-project-planning relationships", "binding status", "validity interval", "abstention"], "must_not_own": ["source collection", "timing promotion"]},
            {"name": "timing-state-machine", "owns": ["funding lane", "procurement lane", "dual-register gate", "staleness", "withheld/conflicted state"], "must_not_own": ["evidence mutation", "public deployment"]},
            {"name": "reviewed-read-model", "owns": ["human-reviewed summary", "GridAtlas deep-link contract", "PipelineNews presentation payload"], "must_not_own": ["raw Companies data", "individual PII", "unreviewed inference"]}
        ],
        "repository_ownership": {
            "companies": "compact factual company/project relationships and organisation-level register events",
            "pipelinenews": "evidence ledger, identity bindings, timing state and reviewed read model",
            "gridatlas": "consumer visualisation and exact project deep-link receiver",
            "globalgrid2050": "catalogue/origin hub and domain topology",
            "data-centres-gb": "demand-side site evidence and relationships",
            "chatgpt-audits": "unreviewed design and test artefacts only"
        },
        "non_negotiable_rules": [
            "News is evidence/corroboration, not the funding or procurement fact.",
            "One register lane alone does not create a sales window.",
            "Every inference cites immutable evidence IDs and a rule version.",
            "Event time, observed time and calculated time are distinct.",
            "Retractions and contradictions are first-class events.",
            "Absence is not evidence.",
            "Human review is required before a release candidate.",
            "This audit candidate cannot publish."
        ]
    }
    write_json(candidate_root / "architecture.vnext.json", architecture)
    write_json(schemas / "evidence-event.schema.json", schema_evidence_event())
    write_json(schemas / "timing-transition.schema.json", schema_transition())
    write_json(schemas / "project-intelligence-summary.schema.json", schema_summary())
    write_text(reference / "state_machine.py", reference_state_machine())
    write_text(reference / "test_state_machine.py", reference_tests())

    candidate_readme = md_header("PipelineNews intelligence engine vNext — quarantined candidate", "inferred") + "\n"
    candidate_readme += (
        "This is a modular design candidate generated after four evidence checkpoints. It is not a product release and cannot write to PipelineNews, GridAtlas, Companies or GlobalGrid2050.\n\n"
        "## Intended chain\n\n"
        "```text\nsource-specific collectors\n  -> append-only evidence ledger\n    -> reviewed identity bindings\n      -> dual-register timing state machine\n        -> human-reviewed read model\n          -> PipelineNews and GridAtlas consumers\n```\n\n"
        "## Why this is the next version\n\n"
        "The present source surface contains large runners with collection, networking, evidence, identity, validation and publication concerns together. The candidate therefore extracts contracts first and leaves product implementation to a separate reviewed graduation.\n\n"
        "## Files\n\n"
        "- `architecture.vnext.json` — module and repository ownership.\n"
        "- `schemas/evidence-event.schema.json` — observed, revised, retracted and contradicted evidence.\n"
        "- `schemas/timing-transition.schema.json` — inferred state transitions with human-review status.\n"
        "- `schemas/project-intelligence-summary.schema.json` — minimal reviewed consumer payload.\n"
        "- `reference/state_machine.py` — non-publishing reference logic.\n"
        "- `reference/test_state_machine.py` — one-signal silence, dual-register gate, retraction and review tests.\n"
    )
    write_text(candidate_root / "README.md", candidate_readme)

    backlog = md_header("PipelineNews intelligence vNext — implementation backlog", "inferred") + "\n"
    backlog += """## P0 — graduate only after human review

1. Freeze the evidence-event, identity-relationship and timing-transition schemas.