GLOBALGRID2050 / EXPLORE CODE

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

Run Study (part 1)

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 1588 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 1–700

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 1–700 of 1652 · version 2026-08-31 00:52 · 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
now_utc, now_london, sha256_file, load_json, write_json, write_text, md_header, run, relative_posix, iter_files, is_text_candidate, read_text, tree_digest, make_read_only, excerpt, source_entry, source_root_for, git_full_tree_paths, snapshot_repository, cmd_snapshot, evidence_rows, workflow_risks, repo_inventory, phase_one, responsibility_categories, analyse_pipeline_file, phase_two
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:1-700 · 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
#!/usr/bin/env python3
"""Deterministic, read-only study controller for Ventusltd/chatgpt-audits.

REVIEW STATUS: UNREVIEWED.

The controller may clone only the repositories explicitly listed in study-plan.json.
It never calls a live data API and never writes inside a product repository snapshot.
"""

from __future__ import annotations

import argparse
import collections
import hashlib
import json
import os
import re
import shutil
import stat
import subprocess
import sys
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterator, Mapping, Sequence
from zoneinfo import ZoneInfo

GENERATION = "202608310052"
REVIEW_STATUS = "UNREVIEWED"
CLASSIFICATIONS = {
    "observed",
    "inferred",
    "contradicted",
    "unknown",
    "not_checked",
    "not_observed_in_snapshot",
}
TEXT_SUFFIXES = {
    "",
    ".cjs",
    ".css",
    ".csv",
    ".graphql",
    ".htm",
    ".html",
    ".ini",
    ".js",
    ".json",
    ".jsonl",
    ".jsx",
    ".md",
    ".mjs",
    ".py",
    ".rst",
    ".sh",
    ".sql",
    ".toml",
    ".ts",
    ".tsx",
    ".txt",
    ".xml",
    ".yaml",
    ".yml",
}
SKIP_DIRS = {
    ".git",
    ".idea",
    ".pytest_cache",
    ".venv",
    "__pycache__",
    "node_modules",
    "vendor",
}
GENERATION_RE = re.compile(r"(?<!\d)20\d{10}(?!\d)")
URL_RE = re.compile(r"https?://[^\s'\"`)<>]+")
BACKTICK_RE = re.compile(r"`([^`\n]{2,260})`")


def now_utc() -> str:
    return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")


def now_london() -> str:
    return datetime.now(ZoneInfo("Europe/London")).isoformat()


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 load_json(path: Path) -> Any:
    return json.loads(path.read_text(encoding="utf-8"))


def write_json(path: Path, payload: Mapping[str, Any] | Sequence[Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(payload, indent=2, sort_keys=False) + "\n", encoding="utf-8")


def write_text(path: Path, content: str) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(content.rstrip() + "\n", encoding="utf-8")


def md_header(title: str, classification: str = "observed") -> str:
    if classification not in CLASSIFICATIONS:
        raise ValueError(f"unknown classification: {classification}")
    return (
        f"# {title}\n\n"
        f"> **REVIEW STATUS: {REVIEW_STATUS}**  \n"
        f"> Classification: `{classification}`  \n"
        "> This is quarantined study output. It is not installed, trusted or published.\n"
    )


def run(
    command: Sequence[str],
    *,
    cwd: Path | None = None,
    check: bool = True,
    timeout: int = 600,
) -> subprocess.CompletedProcess[str]:
    completed = subprocess.run(
        list(command),
        cwd=str(cwd) if cwd else None,
        text=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        check=False,
        timeout=timeout,
        env={**os.environ, "GIT_TERMINAL_PROMPT": "0"},
    )
    if check and completed.returncode != 0:
        raise RuntimeError(
            f"command failed ({completed.returncode}): {' '.join(command)}\n"
            f"stdout:\n{completed.stdout[-4000:]}\n"
            f"stderr:\n{completed.stderr[-4000:]}"
        )
    return completed


def relative_posix(path: Path, root: Path) -> str:
    return path.relative_to(root).as_posix()


def iter_files(root: Path, *, limit: int | None = None) -> Iterator[Path]:
    yielded = 0
    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_symlink() or not path.is_file():
                continue
            yield path
            yielded += 1
            if limit is not None and yielded >= limit:
                return


def is_text_candidate(path: Path, max_bytes: int) -> bool:
    try:
        if path.stat().st_size > max_bytes:
            return False
    except OSError:
        return False
    name = path.name.lower()
    if name in {"dockerfile", "makefile", "license", "readme"}:
        return True
    return path.suffix.lower() in TEXT_SUFFIXES


def read_text(path: Path, max_bytes: int) -> str | None:
    if not is_text_candidate(path, max_bytes):
        return None
    try:
        raw = path.read_bytes()
    except OSError:
        return None
    if b"\x00" in raw[:8192]:
        return None
    try:
        return raw.decode("utf-8")
    except UnicodeDecodeError:
        return None


def tree_digest(root: Path) -> tuple[str, int, int]:
    digest = hashlib.sha256()
    files = 0
    total_bytes = 0
    for path in iter_files(root):
        rel = relative_posix(path, root)
        size = path.stat().st_size
        file_hash = sha256_file(path)
        digest.update(rel.encode("utf-8"))
        digest.update(b"\0")
        digest.update(str(size).encode("ascii"))
        digest.update(b"\0")
        digest.update(file_hash.encode("ascii"))
        digest.update(b"\n")
        files += 1
        total_bytes += size
    return digest.hexdigest(), files, total_bytes


def make_read_only(root: Path) -> None:
    for directory, dirnames, filenames in os.walk(root):
        base = Path(directory)
        for name in filenames:
            path = base / name
            if path.is_symlink():
                continue
            mode = stat.S_IMODE(path.stat().st_mode)
            path.chmod(mode & ~0o222)
        for name in dirnames:
            path = base / name
            if path.is_symlink():
                continue
            mode = stat.S_IMODE(path.stat().st_mode)
            path.chmod((mode & ~0o222) | 0o500)
    mode = stat.S_IMODE(root.stat().st_mode)
    root.chmod((mode & ~0o222) | 0o500)


def excerpt(value: str, limit: int) -> str:
    compact = " ".join(value.strip().split())
    if len(compact) <= limit:
        return compact
    return compact[: max(0, limit - 1)] + "…"


def source_entry(manifest: Mapping[str, Any], name: str) -> Mapping[str, Any] | None:
    for entry in manifest.get("repositories", []):
        if entry.get("name") == name:
            return entry
    return None


def source_root_for(source_root: Path, name: str) -> Path:
    return source_root / name


def git_full_tree_paths(repo_dir: Path) -> set[str]:
    completed = run(["git", "ls-tree", "-r", "--name-only", "HEAD"], cwd=repo_dir)
    return {line.strip() for line in completed.stdout.splitlines() if line.strip()}


def snapshot_repository(config: Mapping[str, Any], destination: Path, limits: Mapping[str, Any]) -> dict[str, Any]:
    repo = str(config["repository"])
    name = str(config["name"])
    url = f"https://github.com/{repo}.git"
    if destination.exists():
        shutil.rmtree(destination)
    destination.parent.mkdir(parents=True, exist_ok=True)

    started = now_utc()
    run(
        [
            "git",
            "clone",
            "--depth",
            "1",
            "--filter=blob:none",
            "--sparse",
            "--no-tags",
            url,
            str(destination),
        ],
        timeout=1200,
    )

    sparse_paths = [str(item) for item in config.get("sparse_paths", [])]
    if sparse_paths == ["."]:
        run(["git", "sparse-checkout", "disable"], cwd=destination, timeout=1200)
        selected_paths = ["."]
    else:
        root_dirs_result = run(["git", "ls-tree", "-d", "--name-only", "HEAD"], cwd=destination)
        root_dirs = {line.strip() for line in root_dirs_result.stdout.splitlines() if line.strip()}
        selected_paths = [path for path in sparse_paths if path.split("/", 1)[0] in root_dirs]
        if selected_paths:
            run(
                ["git", "sparse-checkout", "set", "--cone", *selected_paths],
                cwd=destination,
                timeout=1200,
            )

    commit = run(["git", "rev-parse", "HEAD"], cwd=destination).stdout.strip()
    branch = run(["git", "branch", "--show-current"], cwd=destination).stdout.strip() or "detached"
    commit_date = run(["git", "show", "-s", "--format=%cI", "HEAD"], cwd=destination).stdout.strip()
    commit_subject = run(["git", "show", "-s", "--format=%s", "HEAD"], cwd=destination).stdout.strip()
    full_tree_paths = git_full_tree_paths(destination)

    probes: dict[str, bool] = {}
    for probe in config.get("tree_probes", []):
        probes[str(probe)] = str(probe) in full_tree_paths

    run(["git", "remote", "remove", "origin"], cwd=destination)
    shutil.rmtree(destination / ".git", ignore_errors=True)
    digest, files, total_bytes = tree_digest(destination)
    make_read_only(destination)

    return {
        "name": name,
        "repository": repo,
        "required": bool(config.get("required", False)),
        "priority": int(config.get("priority", 0)),
        "status": "SNAPSHOT_READY",
        "classification": "observed",
        "snapshot_started_at": started,
        "snapshot_finished_at": now_utc(),
        "branch": branch,
        "commit": commit,
        "commit_date": commit_date,
        "commit_subject": commit_subject,
        "selected_sparse_paths": selected_paths,
        "full_tree_file_count": len(full_tree_paths),
        "tree_probes": probes,
        "snapshot_tree_sha256": digest,
        "snapshot_files": files,
        "snapshot_bytes": total_bytes,
        "source_remote_removed": True,
        "source_git_metadata_removed": True,
        "source_made_read_only": True,
        "max_repository_files_scanned": int(limits["max_repository_files_scanned"]),
    }


def cmd_snapshot(args: argparse.Namespace) -> int:
    plan_path = Path(args.plan).resolve()
    source_root = Path(args.source_root).resolve()
    manifest_path = Path(args.manifest).resolve()
    plan = load_json(plan_path)
    source_root.mkdir(parents=True, exist_ok=True)

    records: list[dict[str, Any]] = []
    required_failures: list[str] = []
    for config in sorted(plan["repositories"], key=lambda item: (-int(item["priority"]), item["name"])):
        name = str(config["name"])
        print(f"[snapshot] {config['repository']} -> {name}", flush=True)
        try:
            record = snapshot_repository(config, source_root / name, plan["limits"])
        except Exception as exc:
            record = {
                "name": name,
                "repository": str(config["repository"]),
                "required": bool(config.get("required", False)),
                "priority": int(config.get("priority", 0)),
                "status": "SNAPSHOT_FAILED",
                "classification": "not_checked",
                "error": excerpt(str(exc), 1200),
                "snapshot_finished_at": now_utc(),
            }
            if record["required"]:
                required_failures.append(name)
        records.append(record)

    payload = {
        "schema": "chatgpt-audits.source-snapshot.v1",
        "generation": GENERATION,
        "review_status": REVIEW_STATUS,
        "classification": "observed" if not required_failures else "not_checked",
        "created_at": now_utc(),
        "created_at_london": now_london(),
        "plan_path": plan_path.name,
        "plan_sha256": sha256_file(plan_path),
        "source_root": str(source_root),
        "network_boundary": plan["source_policy"],
        "required_failures": required_failures,
        "repositories": records,
    }
    write_json(manifest_path, payload)
    print(f"[snapshot] manifest {manifest_path}", flush=True)
    return 2 if required_failures else 0


def evidence_rows(
    repo_name: str,
    repo_root: Path,
    patterns: Mapping[str, re.Pattern[str]],
    *,
    commit: str,
    max_file_bytes: int,
    max_excerpt_chars: int,
    max_rows: int,
    include_paths: re.Pattern[str] | None = None,
) -> list[dict[str, Any]]:
    rows: list[dict[str, Any]] = []
    for path in iter_files(repo_root):
        rel = relative_posix(path, repo_root)
        if include_paths and not include_paths.search(rel):
            continue
        text = read_text(path, max_file_bytes)
        if text is None:
            continue
        for line_number, line in enumerate(text.splitlines(), 1):
            for category, pattern in patterns.items():
                if pattern.search(line):
                    rows.append(
                        {
                            "classification": "observed",
                            "category": category,
                            "repository": repo_name,
                            "commit": commit,
                            "path": rel,
                            "line": line_number,
                            "excerpt": excerpt(line, max_excerpt_chars),
                        }
                    )
                    if len(rows) >= max_rows:
                        return rows
    return rows


def workflow_risks(repo_name: str, repo_root: Path, commit: str, limits: Mapping[str, Any]) -> list[dict[str, Any]]:
    patterns = {
        "contents_write": re.compile(r"\bcontents\s*:\s*write\b", re.I),
        "pages_write": re.compile(r"\bpages\s*:\s*write\b", re.I),
        "actions_write": re.compile(r"\bactions\s*:\s*write\b", re.I),
        "git_push": re.compile(r"\bgit\s+push\b", re.I),
        "live_network_command": re.compile(r"\b(curl|wget)\b|\bgh\s+api\b", re.I),
        "scheduled": re.compile(r"\bschedule\s*:", re.I),
        "workflow_dispatch": re.compile(r"\bworkflow_dispatch\s*:", re.I),
    }
    return evidence_rows(
        repo_name,
        repo_root,
        patterns,
        commit=commit,
        max_file_bytes=int(limits["max_text_file_bytes"]),
        max_excerpt_chars=int(limits["max_excerpt_chars"]),
        max_rows=min(250, int(limits["max_evidence_rows_per_report"])),
        include_paths=re.compile(r"(^|/)\.github/workflows/.*\.(ya?ml)$", re.I),
    )


def repo_inventory(repo_entry: Mapping[str, Any], root: Path, limits: Mapping[str, Any]) -> dict[str, Any]:
    suffixes: collections.Counter[str] = collections.Counter()
    top_level: collections.Counter[str] = collections.Counter()
    generations: collections.Counter[str] = collections.Counter()
    text_files = 0
    text_bytes = 0
    total_files = 0
    total_bytes = 0
    largest: list[tuple[int, str]] = []
    refs: collections.Counter[str] = collections.Counter()
    max_files = int(limits["max_repository_files_scanned"])

    for path in iter_files(root, limit=max_files):
        rel = relative_posix(path, root)
        size = path.stat().st_size
        total_files += 1
        total_bytes += size
        suffixes[path.suffix.lower() or "[no suffix]"] += 1
        top_level[rel.split("/", 1)[0]] += 1
        largest.append((size, rel))
        text = read_text(path, int(limits["max_text_file_bytes"]))
        if text is None:
            continue
        text_files += 1
        text_bytes += size
        generations.update(GENERATION_RE.findall(text))
        for target in ["pipelinenews", "gridatlas", "companies", "globalgrid2050", "data-gridatlas", "spiders", "cvaa", "data-centres-gb", "data-gb-electricity"]:
            count = text.lower().count(target.lower())
            if count:
                refs[target] += count

    largest.sort(reverse=True)
    return {
        "name": repo_entry["name"],
        "repository": repo_entry["repository"],
        "commit": repo_entry.get("commit"),
        "classification": "observed",
        "files_scanned": total_files,
        "bytes_scanned": total_bytes,
        "text_files": text_files,
        "text_bytes": text_bytes,
        "suffix_counts": dict(suffixes.most_common()),
        "top_level_counts": dict(top_level.most_common()),
        "generation_tokens": [
            {"generation": token, "occurrences": count}
            for token, count in generations.most_common(30)
        ],
        "cross_repository_reference_counts": dict(refs.most_common()),
        "largest_files": [{"path": rel, "bytes": size} for size, rel in largest[:15]],
    }


def phase_one(plan: Mapping[str, Any], manifest: Mapping[str, Any], source_root: Path, output_root: Path) -> None:
    inventories: list[dict[str, Any]] = []
    risks: list[dict[str, Any]] = []
    for entry in manifest["repositories"]:
        if entry.get("status") != "SNAPSHOT_READY":
            continue
        root = source_root_for(source_root, str(entry["name"]))
        inventories.append(repo_inventory(entry, root, plan["limits"]))
        risks.extend(workflow_risks(str(entry["name"]), root, str(entry["commit"]), plan["limits"]))

    payload = {
        "schema": "chatgpt-audits.repository-inventory.v1",
        "generation": GENERATION,
        "review_status": REVIEW_STATUS,
        "classification": "observed",
        "created_at": now_utc(),
        "repositories": inventories,
        "workflow_evidence": risks,
    }
    write_json(output_root / "01-REPOSITORY-INVENTORY.json", payload)

    rows = []
    for item in inventories:
        rows.append(
            f"| {item['name']} | `{str(item['commit'])[:12]}` | {item['files_scanned']:,} | "
            f"{item['text_files']:,} | {item['bytes_scanned'] / 1024 / 1024:.2f} MiB |"
        )
    risk_counts = collections.Counter(row["category"] for row in risks)
    risk_lines = "\n".join(f"- `{key}`: {value} observed line(s)" for key, value in risk_counts.most_common()) or "- None observed in selected workflow snapshots."
    content = md_header("01 — Repository inventory and topology") + "\n"
    content += (
        "This checkpoint records exact commits and scans the selected source-code surface. It does not infer that an unselected path is absent.\n\n"
        "| Repository | Commit | Files scanned | Text files | Selected bytes |\n"
        "|---|---:|---:|---:|---:|\n"
        + "\n".join(rows)
        + "\n\n## Workflow evidence categories\n\n"
        + risk_lines
        + "\n\n## Interpretation\n\n"
        "- **Observed:** the manifest pins each analysed repository commit and content digest.\n"
        "- **Observed:** product repositories contain several workflows with write-capable permissions or push commands; each exact line is in the JSON evidence ledger.\n"
        "- **Inferred:** cross-repository seam verification should be treated as a first-class test surface because the repositories reference each other frequently.\n"
        "- **Not checked:** raw datasets and excluded release/data directories were not downloaded.\n"
    )
    write_text(output_root / "01-REPOSITORY-INVENTORY.md", content)


def responsibility_categories(text: str) -> set[str]:
    lower = text.lower()
    categories: set[str] = set()
    rules = {
        "collection": ("fetch(", "source", "query", "rss", "search", "adapter"),
        "evidence": ("evidence", "provenance", "source_card", "source-card", "ledger"),
        "identity": ("repd_ref", "gg_project_id", "company_number", "binding_status", "identity"),
        "scoring": ("score", "confidence", "rank", "weight"),
        "publication": ("publish", "promotion", "release", "current.json", "pointer"),
        "network": ("https://", "fetch(", "request(", "curl ", "wget "),
        "presentation": ("headline", "render", "html", "table", "card"),
        "validation": ("assert", "invariant", "schema", "validate", "fixture"),
    }
    for category, markers in rules.items():
        if any(marker in lower for marker in markers):
            categories.add(category)
    return categories


def analyse_pipeline_file(path: Path, root: Path, limits: Mapping[str, Any]) -> dict[str, Any] | None:
    text = read_text(path, int(limits["max_text_file_bytes"]))
    if text is None:
        return None
    rel = relative_posix(path, root)
    lower_rel = rel.lower()
    lower_text = text.lower()
    if not any(marker in lower_rel or marker in lower_text for marker in ("discover", "news", "evidence", "headline", "identity", "sector", "pipeline")):
        return None
    categories = responsibility_categories(text)
    urls = URL_RE.findall(text)
    generations = GENERATION_RE.findall(text)
    function_count = len(re.findall(r"\b(?:function\s+|const\s+[A-Za-z_$][\w$]*\s*=\s*(?:async\s*)?\(|def\s+)[A-Za-z_$]?", text))
    hardcoded_dates = sorted(set(re.findall(r"\b20\d{2}-\d{2}-\d{2}\b", text)))
    return {
        "path": rel,
        "bytes": path.stat().st_size,
        "lines": text.count("\n") + 1,
        "function_markers": function_count,
        "responsibilities": sorted(categories),
        "responsibility_count": len(categories),
        "url_count": len(urls),
        "generation_tokens": sorted(set(generations))[:30],
        "hardcoded_dates": hardcoded_dates[:30],
        "monolith_candidate": path.stat().st_size >= 25000 and len(categories) >= 4,
    }


def phase_two(plan: Mapping[str, Any], manifest: Mapping[str, Any], source_root: Path, output_root: Path) -> None:
    entry = source_entry(manifest, "pipelinenews")
    if not entry or entry.get("status") != "SNAPSHOT_READY":
        raise RuntimeError("pipelinenews snapshot is required for phase 2")
    root = source_root_for(source_root, "pipelinenews")
    files: list[dict[str, Any]] = []
    for path in iter_files(root, limit=int(plan["limits"]["max_repository_files_scanned"])):
        analysed = analyse_pipeline_file(path, root, plan["limits"])
        if analysed:
            files.append(analysed)
    files.sort(key=lambda item: (item["monolith_candidate"], item["responsibility_count"], item["bytes"]), reverse=True)

    patterns = {
        "identity_rule": re.compile(r"repd_ref|gg_project_id|binding_status|identity", re.I),
        "evidence_rule": re.compile(r"evidence|provenance|source[_-]?card|ledger", re.I),
        "publication_rule": re.compile(r"publish|promotion|release|pointer", re.I),
        "network_rule": re.compile(r"fetch\s*\(|https?://|request\s*\(", re.I),
        "abstention_rule": re.compile(r"abstain|ambiguous|reject", re.I),
    }
    evidence = evidence_rows(
        "pipelinenews",
        root,
        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=int(plan["limits"]["max_evidence_rows_per_report"]),
        include_paths=re.compile(r"(^|/)(discovery|ui|automation|orchestration|contracts|state)/", re.I),
    )

    observed_module_names = {
        "collector": [],
        "evidence_ledger": [],
        "identity_binder": [],
        "timing_state_machine": [],
        "publisher": [],
    }
    module_patterns = {
        "collector": re.compile(r"collect(or|ion)|adapter", re.I),
        "evidence_ledger": re.compile(r"evidence.*ledger|ledger.*evidence", re.I),
        "identity_binder": re.compile(r"identity.*bind|bind.*identity|entity.*resolution", re.I),
        "timing_state_machine": re.compile(r"timing.*state|state.*machine|window.*state", re.I),
        "publisher": re.compile(r"publish|promotion", re.I),
    }
    for item in files:
        for name, pattern in module_patterns.items():
            if pattern.search(item["path"]):
                observed_module_names[name].append(item["path"])

    base_url_observation: dict[str, Any] = {
        "classification": "not_observed_in_snapshot",
        "path": "ui/atlas-v9-deep-links.js",
        "base_url": None,
    }
    deep_link_path = root / "ui/atlas-v9-deep-links.js"
    deep_link_text = read_text(deep_link_path, int(plan["limits"]["max_text_file_bytes"])) if deep_link_path.exists() else None
    if deep_link_text:
        match = re.search(r"BASE_URL\s*=\s*[\"']([^\"']+)", deep_link_text)
        if match:
            base_url_observation = {
                "classification": "observed",
                "path": "ui/atlas-v9-deep-links.js",
                "base_url": match.group(1),
            }

    findings: list[dict[str, Any]] = []
    monoliths = [item for item in files if item["monolith_candidate"]]
    if monoliths:
        findings.append(
            {
                "classification": "observed",
                "finding": "Large PipelineNews files combine four or more responsibility categories.",
                "evidence_paths": [item["path"] for item in monoliths[:10]],
            }
        )
        findings.append(
            {
                "classification": "inferred",
                "finding": "The next version should extract collectors, evidence ledger, identity binding and timing promotion into separate contracts instead of adding another monolithic runner.",
                "derived_from": [item["path"] for item in monoliths[:5]],
            }
        )
    for module, paths in observed_module_names.items():
        if not paths:
            findings.append(
                {
                    "classification": "not_observed_in_snapshot",
                    "finding": f"No selected PipelineNews path was named as a dedicated {module.replace('_', ' ')} module.",
                }
            )

    payload = {
        "schema": "chatgpt-audits.pipelinenews-engine-audit.v1",
        "generation": GENERATION,
        "review_status": REVIEW_STATUS,
        "classification": "observed",
        "created_at": now_utc(),
        "repository": entry["repository"],
        "commit": entry["commit"],
        "candidate_files": files[:200],
        "monolith_candidates": monoliths,
        "dedicated_module_name_observations": observed_module_names,
        "deep_link_base_url": base_url_observation,
        "evidence": evidence,
        "findings": findings,
    }
    write_json(output_root / "02-PIPELINENEWS-ENGINE-AUDIT.json", payload)

    top_rows = []
    for item in files[:20]:
        top_rows.append(
            f"| `{item['path']}` | {item['bytes']:,} | {item['lines']:,} | "
            f"{', '.join(item['responsibilities']) or 'none'} | {'YES' if item['monolith_candidate'] else 'no'} |"
        )