GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / chatgpt-audits / automation/202608310209-hourly-logic-review/candidates

Review and 4 more files

A Python command-line tool in the automation folder of ChatGPT Audits that uses SHA-256 using data from GitHub API.

700 lines of Python from chatgpt-audits, in 5 files. Topic: AI agents and coordination. Section 1593 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. Identity Conflict Gate transform · chatgpt-audits / automation/202608310209-hourly-logic-review/candidates/identity_conflict_gate.py lines 1–42
  2. Search Query Planner transform · chatgpt-audits / automation/202608310209-hourly-logic-review/candidates/search_query_planner.py lines 1–61
  3. Search Replay Harness transform · chatgpt-audits / automation/202608310209-hourly-logic-review/candidates/search_replay_harness.py lines 1–36
  4. Source Diversity Ranker transform · chatgpt-audits / automation/202608310209-hourly-logic-review/candidates/source_diversity_ranker.py lines 1–44
  5. Review storage · chatgpt-audits / automation/202608310209-hourly-logic-review/review.py lines 1–517

Identity Conflict Gate

A Python module in the candidates folder of ChatGPT Audits. It is built from the binding class (`Binding`).

transformchatgpt-audits / automation/202608310209-hourly-logic-review/candidates/identity_conflict_gate.py · lines 1–42 of 42 · version 2026-08-31 02:09 · Entry point

What it does
It calculates its inputs. Defines Binding, conflicts. Uses libraries __future__, collections, dataclasses, typing.
Why it exists in the grid workflow
Domain stage field_execution (path word 'gate'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
Defines `Binding` and `conflicts`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
chatgpt-audits · automation/202608310209-hourly-logic-review/candidates · Python module
Uses
__future__, collections, dataclasses, typing
Used by
none found
Produces
Binding, conflicts
Defines here
Binding, conflicts
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/202608310209-hourly-logic-review/candidates/identity_conflict_gate.py:1-42 · blob c8d6a013d098f8ca99fec7147818abb872a820c1 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
#!/usr/bin/env python3
"""UNREVIEWED quarantined candidate: identity collision gate."""

from __future__ import annotations

from collections import defaultdict
from dataclasses import dataclass
from typing import Iterable


@dataclass(frozen=True)
class Binding:
    evidence_id: str
    subject_key: str
    candidate_key: str
    confidence: float


def conflicts(
    rows: Iterable[Binding],
    *,
    minimum_confidence: float = 0.70,
) -> list[dict[str, object]]:
    grouped: dict[str, list[Binding]] = defaultdict(list)
    for row in rows:
        if row.confidence >= minimum_confidence:
            grouped[row.subject_key].append(row)

    findings: list[dict[str, object]] = []
    for subject, candidates in sorted(grouped.items()):
        keys = sorted({row.candidate_key for row in candidates})
        if len(keys) <= 1:
            continue
        findings.append(
            {
                "subject_key": subject,
                "candidate_keys": keys,
                "evidence_ids": sorted({row.evidence_id for row in candidates}),
                "decision": "ABSTAIN_IDENTITY_COLLISION",
            }
        )
    return findings

Search Query Planner

A Python module in the candidates folder of ChatGPT Audits that normalises terms (`normalise_terms`). It is built from the query class (`Query`) and the plan queries helper (`plan_queries`).

transformchatgpt-audits / automation/202608310209-hourly-logic-review/candidates/search_query_planner.py · lines 1–61 of 61 · version 2026-08-31 02:09 · Entry point

What it does
It calculates its inputs. Defines Query, normalise_terms, plan_queries. Uses libraries __future__, dataclasses, typing.
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).
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
Entity-aware search query planner.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
chatgpt-audits · automation/202608310209-hourly-logic-review/candidates · Python module
Uses
__future__, dataclasses, typing
Used by
none found
Produces
Query, normalise_terms, plan_queries
Defines here
Query, normalise_terms, plan_queries
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/202608310209-hourly-logic-review/candidates/search_query_planner.py:1-61 · blob bd501090c038aed9d0ac031adc6c975fdd45af90 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: landowner_planner, ai_agent · canonical: unknown
#!/usr/bin/env python3
"""UNREVIEWED quarantined candidate: entity-aware search query planner.

No network I/O. Consumer code supplies aliases, exclusions and source lanes.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable, Mapping, Sequence


@dataclass(frozen=True)
class Query:
    text: str
    lane: str
    reason: str


def normalise_terms(values: Iterable[str]) -> tuple[str, ...]:
    cleaned = {" ".join(value.split()).strip() for value in values if value.strip()}
    return tuple(sorted(cleaned, key=lambda value: (value.casefold(), value)))


def plan_queries(
    canonical_name: str,
    *,
    aliases: Sequence[str] = (),
    identifiers: Sequence[str] = (),
    event_terms: Sequence[str] = (),
    excluded_terms: Sequence[str] = (),
    source_lanes: Mapping[str, Sequence[str]] | None = None,
) -> list[Query]:
    names = normalise_terms([canonical_name, *aliases, *identifiers])
    events = normalise_terms(event_terms)
    exclusions = normalise_terms(excluded_terms)
    lanes = source_lanes or {"open_web": ()}
    output: list[Query] = []
    seen: set[tuple[str, str]] = set()

    for lane, lane_terms in sorted(lanes.items()):
        lane_suffix = " ".join(normalise_terms(lane_terms))
        for name in names:
            for event in events or ("",):
                positive = " ".join(
                    part for part in [f'"{name}"', event, lane_suffix] if part
                )
                negative = " ".join(f'-"{term}"' for term in exclusions)
                text = " ".join(part for part in [positive, negative] if part)
                key = (lane, text.casefold())
                if key in seen:
                    continue
                seen.add(key)
                output.append(
                    Query(
                        text=text,
                        lane=lane,
                        reason="canonical/alias x event x source-lane expansion",
                    )
                )
    return output

Search Replay Harness

A Python module in the candidates folder of ChatGPT Audits. It is built from the fixture class (`Fixture`).

transformchatgpt-audits / automation/202608310209-hourly-logic-review/candidates/search_replay_harness.py · lines 1–36 of 36 · version 2026-08-31 02:09 · Entry point · pattern Fixture (shared by 3 files)

What it does
It calculates its inputs. Defines Fixture, replay. Uses libraries __future__, dataclasses, typing.
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).
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
Defines `Fixture` and `replay`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
chatgpt-audits · automation/202608310209-hourly-logic-review/candidates · Python module
Uses
__future__, dataclasses, typing
Used by
none found
Produces
Fixture, replay
Defines here
Fixture, replay
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/202608310209-hourly-logic-review/candidates/search_replay_harness.py:1-36 · blob aef1125c992f8b24db3cbb9553a28a31565cf236 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""UNREVIEWED quarantined candidate: deterministic search replay harness."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Callable, Iterable, Sequence


@dataclass(frozen=True)
class Fixture:
    query: str
    required_ids: tuple[str, ...]
    forbidden_ids: tuple[str, ...] = ()


def replay(
    fixtures: Iterable[Fixture],
    search: Callable[[str], Sequence[str]],
) -> list[dict[str, object]]:
    findings: list[dict[str, object]] = []
    for fixture in fixtures:
        returned = tuple(search(fixture.query))
        returned_set = set(returned)
        missing = sorted(set(fixture.required_ids) - returned_set)
        forbidden = sorted(set(fixture.forbidden_ids) & returned_set)
        findings.append(
            {
                "query": fixture.query,
                "returned": list(returned),
                "missing_required": missing,
                "returned_forbidden": forbidden,
                "pass": not missing and not forbidden,
            }
        )
    return findings

Source Diversity Ranker

A Python module in the candidates folder of ChatGPT Audits. It is built from the evidence class (`Evidence`), the rank step (`rank`) and the score step (`score`).

transformchatgpt-audits / automation/202608310209-hourly-logic-review/candidates/source_diversity_ranker.py · lines 1–44 of 44 · version 2026-08-31 02:09 · Entry point · pattern Evidence (shared by 2 files)

What it does
It calculates its inputs. Defines Evidence, rank, score. Uses libraries __future__, dataclasses, typing.
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).
Downstream impact
It is itself an entry point (Python module); no other file was found loading it.
What it achieves
Relevance/diversity evidence reranker.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
chatgpt-audits · automation/202608310209-hourly-logic-review/candidates · Python module
Uses
__future__, dataclasses, typing
Used by
none found
Produces
Evidence, rank
Defines here
Evidence, rank, score
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/202608310209-hourly-logic-review/candidates/source_diversity_ranker.py:1-44 · blob 8f6323b724b90c0ff4bd655b26df69deff788199 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: agent_infra · users: ai_agent · canonical: unknown
#!/usr/bin/env python3
"""UNREVIEWED quarantined candidate: relevance/diversity evidence reranker."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Iterable


@dataclass(frozen=True)
class Evidence:
    evidence_id: str
    domain: str
    relevance: float
    authority: float
    recency: float


def rank(
    rows: Iterable[Evidence],
    *,
    diversity_penalty: float = 0.18,
    limit: int = 20,
) -> list[Evidence]:
    remaining = list(rows)
    selected: list[Evidence] = []
    domain_counts: dict[str, int] = {}

    while remaining and len(selected) < limit:
        def score(item: Evidence) -> tuple[float, str]:
            base = (
                0.55 * item.relevance
                + 0.30 * item.authority
                + 0.15 * item.recency
            )
            penalty = diversity_penalty * domain_counts.get(item.domain.casefold(), 0)
            return (base - penalty, item.evidence_id)

        best = max(remaining, key=score)
        remaining.remove(best)
        selected.append(best)
        key = best.domain.casefold()
        domain_counts[key] = domain_counts.get(key, 0) + 1
    return selected

Review

A Python command-line tool in the automation folder of ChatGPT Audits that uses SHA-256 using data from GitHub API.

storagechatgpt-audits / automation/202608310209-hourly-logic-review/review.py · lines 1–517 of 774 · version 2026-08-31 02:09 · Entry point · pattern classify_status (shared by 2 files)

What it does
It fetches data. Defines 23 functions or classes, including ApiResult, now_utc, iso, parse_time, redact. Uses libraries __future__, argparse, base64, hashlib, json. Side effects: reads or writes files; makes network requests.
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: data source: GitHub API; JSON file review.json; JSON file REVIEW.json; command-line arguments.
Downstream impact
Used directly by 1 file: Code Generator — Substation Finder Page (code-generator, https://ventusltd.github.io/code-generator/apps/substation-finder/).
What it achieves
It parses time (`parse_time`), collects runs (`collect_runs`) and lists audit branches (`list_audit_branches`). Five-run hourly logic review for Ventusltd/ChatGPT-audits. It writes `MANIFEST.json`. It accepts `--output`, `--candidate-root` and `--lookback-minutes`.
Why it matters
Loaded by the Substation Finder page in Code Generator at https://ventusltd.github.io/code-generator/apps/substation-finder/.
Application
chatgpt-audits · automation/202608310209-hourly-logic-review · Python CLI
Uses
__future__, argparse, base64, hashlib, json, os, re, shutil
Used by
linked from Code Generator — Substation Finder Page (link)
Produces
ApiResult, now_utc, iso, parse_time, redact, api_request, compact_run, collect_runs, branch_score, list_audit_branches, document_score, read_content_file
Defines here
ApiResult, now_utc, iso, parse_time, redact, api_request, compact_run, collect_runs, branch_score, list_audit_branches, document_score, read_content_file, collect_branch_documents, count_signals, classify_status, candidate_catalogue, choose_candidate
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/202608310209-hourly-logic-review/review.py:1-517 · blob b091219cff3f622c73a04ef7128ebef2461c08f7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Five-run hourly logic review for Ventusltd/chatgpt-audits.

REVIEW STATUS: UNREVIEWED.

This controller is deterministic. It does not claim to be ChatGPT and does not
invoke a model. It prepares a bounded evidence packet and an exact prompt for a
ChatGPT Scheduled Task. Product repositories are observed through GitHub
metadata only and are never mutated or dispatched.
"""

from __future__ import annotations

import argparse
import base64
import hashlib
import json
import os
import re
import shutil
import time
import urllib.error
import urllib.parse
import urllib.request
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Mapping, Sequence
from zoneinfo import ZoneInfo

GENERATION = "202608310209"
REVIEW_STATUS = "UNREVIEWED"
AUDIT_REPOSITORY = "Ventusltd/chatgpt-audits"
LOGIC_BRANCH = "audit/202608310209-hourly-logic-review"
LONDON = ZoneInfo("Europe/London")
ACTIVE_STATUSES = {"queued", "in_progress", "waiting", "requested", "pending"}
FAILED_CONCLUSIONS = {
    "failure",
    "cancelled",
    "timed_out",
    "action_required",
    "startup_failure",
}
TARGET_WORKFLOWS = {
    "202608310052 five-hour quarantined cross-repo study",
    "202608310116 overnight audit swarm",
    "202608310121 hourly audit watchdog",
    "202608310122 audit failure auto-repair",
    "202608310125 overnight Actions watchdog",
    "202608310209 hourly intelligence reasoning checkpoint",
}
REPOSITORIES = [
    AUDIT_REPOSITORY,
    "Ventusltd/pipelinenews",
    "Ventusltd/companies",
    "Ventusltd/gridatlas",
    "Ventusltd/data-gridatlas",
    "Ventusltd/globalgrid2050",
    "Ventusltd/spiders",
    "Ventusltd/cvaa",
    "Ventusltd/data-centres-gb",
    "Ventusltd/data-gb-electricity",
]
REDACTIONS = [
    re.compile(r"gh[pousr]_[A-Za-z0-9_]{20,}"),
    re.compile(r"github_pat_[A-Za-z0-9_]{20,}"),
    re.compile(r"sk-[A-Za-z0-9_-]{20,}"),
    re.compile(r"AKIA[0-9A-Z]{16}"),
]
DOC_KEYWORDS = (
    "EXECUTIVE",
    "SYNTHESIS",
    "WATCHDOG",
    "SUMMARY",
    "CHECKPOINT",
    "REVIEW",
    "MANIFEST",
    "FINDING",
    "HANDOFF",
)
PAGES_NAMES = {"pages build and deployment"}


@dataclass(frozen=True)
class ApiResult:
    ok: bool
    status: int
    payload: Any
    error: str | None = None


def now_utc() -> datetime:
    return datetime.now(timezone.utc)


def iso(value: datetime) -> str:
    return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z")


def parse_time(value: str | None) -> datetime | None:
    if not value:
        return None
    try:
        return datetime.fromisoformat(value.replace("Z", "+00:00")).astimezone(timezone.utc)
    except ValueError:
        return None


def redact(text: str) -> str:
    result = text
    for pattern in REDACTIONS:
        result = pattern.sub("[REDACTED]", result)
    return result


def api_request(method: str, endpoint: str, token: str, *, attempts: int = 3) -> ApiResult:
    url = endpoint if endpoint.startswith("https://") else f"https://api.github.com{endpoint}"
    headers = {
        "Accept": "application/vnd.github+json",
        "Authorization": f"Bearer {token}",
        "User-Agent": "chatgpt-audits-hourly-logic-review/202608310209",
        "X-GitHub-Api-Version": "2022-11-28",
    }
    last_error = None
    for attempt in range(1, attempts + 1):
        request = urllib.request.Request(url, method=method, headers=headers)
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                raw = response.read()
                payload = json.loads(raw.decode("utf-8")) if raw else None
                return ApiResult(True, response.status, payload)
        except urllib.error.HTTPError as exc:
            body = exc.read().decode("utf-8", "replace")
            last_error = f"HTTP {exc.code}: {body[:800]}"
            if exc.code not in {429, 500, 502, 503, 504} or attempt == attempts:
                return ApiResult(False, exc.code, None, last_error)
        except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
            last_error = f"{type(exc).__name__}: {exc}"
            if attempt == attempts:
                return ApiResult(False, 0, None, last_error)
        time.sleep(attempt * 2)
    return ApiResult(False, 0, None, last_error or "unknown API error")


def compact_run(run: Mapping[str, Any], current: datetime) -> dict[str, Any]:
    created = parse_time(str(run.get("created_at") or "")) or current
    updated = parse_time(str(run.get("updated_at") or "")) or created
    name = str(run.get("name") or run.get("path") or "unknown")
    return {
        "run_id": run.get("id"),
        "name": name,
        "path": run.get("path"),
        "event": run.get("event"),
        "head_branch": run.get("head_branch"),
        "head_sha": run.get("head_sha"),
        "status": run.get("status"),
        "conclusion": run.get("conclusion"),
        "run_attempt": run.get("run_attempt"),
        "created_at": run.get("created_at"),
        "updated_at": run.get("updated_at"),
        "age_minutes": round((current - created).total_seconds() / 60, 1),
        "quiet_minutes": round((current - updated).total_seconds() / 60, 1),
        "html_url": run.get("html_url"),
        "is_pages": (
            name.lower() in PAGES_NAMES
            or str(run.get("path") or "").lower().startswith("dynamic/pages/")
        ),
    }


def collect_runs(repository: str, token: str, current: datetime, since: datetime) -> dict[str, Any]:
    result = api_request(
        "GET",
        f"/repos/{repository}/actions/runs?per_page=100&exclude_pull_requests=true",
        token,
    )
    record: dict[str, Any] = {
        "repository": repository,
        "classification": "observed",
        "api_error": None,
        "runs": [],
    }
    if not result.ok:
        record["api_error"] = result.error
        return record
    rows: list[dict[str, Any]] = []
    for raw in (result.payload or {}).get("workflow_runs", []):
        run = compact_run(raw, current)
        created = parse_time(str(run.get("created_at") or ""))
        if created and (created >= since or run["status"] in ACTIVE_STATUSES):
            rows.append(run)
    rows.sort(
        key=lambda row: parse_time(str(row.get("created_at") or ""))
        or datetime.min.replace(tzinfo=timezone.utc),
        reverse=True,
    )
    record["runs"] = rows
    return record


def branch_score(name: str) -> tuple[int, str]:
    upper = name.upper()
    score = 0
    if name == LOGIC_BRANCH:
        score += 1000
    if "FIVE-HOUR" in upper:
        score += 500
    if "SWARM" in upper:
        score += 450
    if "WATCHDOG" in upper:
        score += 400
    match = re.search(r"20\d{10}", name)
    return (score + (int(match.group(0)[-6:]) if match else 0), name)


def list_audit_branches(token: str) -> tuple[list[dict[str, Any]], list[str]]:
    result = api_request("GET", f"/repos/{AUDIT_REPOSITORY}/branches?per_page=100", token)
    if not result.ok:
        return [], [result.error or "branch API error"]
    branches = [
        {
            "name": str(item.get("name") or ""),
            "sha": str((item.get("commit") or {}).get("sha") or ""),
        }
        for item in (result.payload or [])
        if str(item.get("name") or "").startswith("audit/")
    ]
    branches.sort(key=lambda item: branch_score(item["name"]), reverse=True)
    selected: list[dict[str, Any]] = []
    seen_classes: set[str] = set()
    for item in branches:
        name = item["name"].lower()
        if item["name"] == LOGIC_BRANCH:
            category = "logic"
        elif "five-hour" in name:
            category = "five-hour"
        elif "swarm" in name:
            category = "swarm"
        elif "watchdog" in name:
            category = "watchdog"
        else:
            category = "other"
        if category != "other" and category in seen_classes:
            continue
        selected.append(item)
        seen_classes.add(category)
        if len(selected) >= 6:
            break
    return selected, []


def document_score(path: str) -> tuple[int, int, str]:
    upper = path.upper()
    score = 0
    for index, word in enumerate(DOC_KEYWORDS):
        if word in upper:
            score += (len(DOC_KEYWORDS) - index) * 20
    if path.lower().endswith(".md"):
        score += 10
    if "/logic-timer/" in path.lower():
        score += 80
    return (score, -len(path), path)


def read_content_file(path: str, ref: str, token: str, *, max_chars: int = 6000) -> str | None:
    encoded_path = urllib.parse.quote(path, safe="/")
    encoded_ref = urllib.parse.quote(ref, safe="")
    result = api_request(
        "GET",
        f"/repos/{AUDIT_REPOSITORY}/contents/{encoded_path}?ref={encoded_ref}",
        token,
    )
    if not result.ok or not isinstance(result.payload, Mapping):
        return None
    payload = result.payload
    if payload.get("encoding") != "base64" or not payload.get("content"):
        return None
    try:
        raw = base64.b64decode(str(payload["content"]).encode("ascii"))
        text = raw.decode("utf-8", "replace")
    except (ValueError, UnicodeError):
        return None
    return redact(text[:max_chars])


def collect_branch_documents(
    branches: Sequence[Mapping[str, Any]],
    token: str,
) -> tuple[list[dict[str, Any]], list[str], int, set[str]]:
    documents: list[dict[str, Any]] = []
    errors: list[str] = []
    previous_candidates: set[str] = set()
    previous_logic_runs = 0

    for branch in branches:
        name = str(branch["name"])
        sha = str(branch["sha"])
        if not sha:
            continue
        tree = api_request(
            "GET",
            f"/repos/{AUDIT_REPOSITORY}/git/trees/{sha}?recursive=1",
            token,
        )
        if not tree.ok:
            errors.append(f"{name}: {tree.error}")
            continue
        paths = [
            str(item.get("path") or "")
            for item in (tree.payload or {}).get("tree", [])
            if item.get("type") == "blob"
            and str(item.get("path") or "").startswith("202608310033-study/")
            and str(item.get("path") or "").lower().endswith((".md", ".json", ".txt"))
            and any(word in str(item.get("path") or "").upper() for word in DOC_KEYWORDS)
        ]

        if name == LOGIC_BRANCH:
            review_paths = [path for path in paths if path.lower().endswith("/review.json")]
            previous_logic_runs = len(review_paths)
            for path in sorted(review_paths)[-8:]:
                text = read_content_file(path, name, token, max_chars=12000)
                if not text:
                    continue
                try:
                    payload = json.loads(text)
                except json.JSONDecodeError:
                    continue
                candidate = str(((payload.get("new_candidate") or {}).get("filename")) or "")
                if candidate:
                    previous_candidates.add(candidate)

        for path in sorted(paths, key=document_score, reverse=True)[:3]:
            text = read_content_file(path, name, token)
            if text is None:
                continue
            documents.append(
                {
                    "branch": name,
                    "sha": sha,
                    "path": path,
                    "classification": "observed",
                    "excerpt": text,
                }
            )

    return documents, errors, previous_logic_runs, previous_candidates


def count_signals(documents: Sequence[Mapping[str, Any]]) -> dict[str, int]:
    corpus = "\n".join(str(item.get("excerpt") or "") for item in documents).lower()
    patterns = {
        "search_or_query": r"\b(search|query|collector|discovery)\b",
        "static_or_hardcoded": r"\b(static|hardcoded|pinned|stale)\b",
        "identity_or_collision": r"\b(identity|collision|binding|repd_ref|company_number)\b",
        "duplicate_or_dedup": r"\b(duplicate|dedup|fingerprint|canonical)\b",
        "source_diversity": r"\b(source diversity|independent source|corroborat)\w*",
        "abstention_or_unknown": r"\b(abstain|unknown|not_observed|not checked|unresolved)\b",
        "schema_or_contract": r"\b(schema|contract|invariant|validator)\b",
        "recency_or_freshness": r"\b(recency|freshness|last seen|newer|stale)\b",
    }
    return {name: len(re.findall(pattern, corpus)) for name, pattern in patterns.items()}


def classify_status(
    run_records: Sequence[Mapping[str, Any]],
) -> tuple[list[str], list[str], list[str], list[dict[str, Any]]]:
    happened: list[str] = []
    good: list[str] = []
    bad: list[str] = []
    evidence: list[dict[str, Any]] = []

    audit = next(
        (item for item in run_records if item["repository"] == AUDIT_REPOSITORY),
        {"runs": [], "api_error": "audit repository absent"},
    )
    latest_by_name: dict[str, Mapping[str, Any]] = {}
    for run in audit.get("runs", []):
        latest_by_name.setdefault(str(run["name"]), run)

    for name in sorted(TARGET_WORKFLOWS):
        run = latest_by_name.get(name)
        if not run:
            bad.append(f"No recent run was observed for `{name}` in the bounded lookback.")
            continue
        happened.append(
            f"`{name}` is `{run['status']}` / `{run['conclusion']}` "
            f"(run `{run['run_id']}`, attempt `{run['run_attempt']}`)."
        )
        evidence.append(
            {
                "repository": AUDIT_REPOSITORY,
                "run_id": run["run_id"],
                "name": name,
                "status": run["status"],
                "conclusion": run["conclusion"],
                "html_url": run["html_url"],
            }
        )
        if run["conclusion"] == "success":
            good.append(f"`{name}` most recently completed successfully.")
        elif (
            name == "202608310122 audit failure auto-repair"
            and run["conclusion"] == "skipped"
        ):
            good.append(
                "`202608310122 audit failure auto-repair` correctly skipped because "
                "its triggering workflow did not require repair."
            )
        elif run["status"] in ACTIVE_STATUSES:
            threshold = 390 if "five-hour" in name else 120
            if float(run["age_minutes"]) <= threshold:
                good.append(
                    f"`{name}` is active within its expected time boundary "
                    f"({run['age_minutes']} minutes old)."
                )
            else:
                bad.append(
                    f"`{name}` appears long-running at {run['age_minutes']} minutes; "
                    "treat this as inferred until the job step is inspected."
                )
        elif run["conclusion"] in FAILED_CONCLUSIONS:
            bad.append(
                f"`{name}` most recently ended `{run['conclusion']}` on run `{run['run_id']}`."
            )
        else:
            bad.append(
                f"`{name}` has an unclassified latest state: "
                f"`{run['status']}` / `{run['conclusion']}`."
            )

    for repository in run_records:
        if repository.get("api_error"):
            bad.append(
                f"GitHub Actions metadata could not be read for `{repository['repository']}`: "
                f"{repository['api_error']}"
            )
        non_pages_failures = [
            run
            for run in repository.get("runs", [])
            if run["conclusion"] in FAILED_CONCLUSIONS and not run["is_pages"]
        ]
        if repository["repository"] != AUDIT_REPOSITORY and non_pages_failures:
            happened.append(
                f"`{repository['repository']}` has {len(non_pages_failures)} "
                "recent non-Pages failed/cancelled run(s), observed read-only."
            )

    if not bad:
        bad.append(
            "No immediate red condition was observed. This is not proof that all "
            "product behaviour or search quality is correct."
        )
    return happened, good, bad, evidence


def candidate_catalogue() -> list[dict[str, Any]]:
    return [
        {
            "filename": "search_query_planner.py",
            "purpose": (
                "Generate entity-aware query bundles with aliases, exclusions, "
                "source lanes and deterministic provenance."
            ),
            "signal": "static_or_hardcoded",
        },
        {
            "filename": "evidence_fingerprint.py",
            "purpose": (
                "Canonicalise URLs and content before hashing so repeated headlines "
                "do not masquerade as independent evidence."
            ),
            "signal": "duplicate_or_dedup",
        },
        {
            "filename": "source_diversity_ranker.py",
            "purpose": (
                "Re-rank evidence for independent-source diversity while retaining "
                "relevance, recency and authoritative-source weight."
            ),
            "signal": "source_diversity",
        },
        {
            "filename": "identity_conflict_gate.py",
            "purpose": (
                "Quarantine ambiguous Company-to-REPD or headline-to-project bindings "
                "before they enter scoring or publication."
            ),
            "signal": "identity_or_collision",
        },
        {
            "filename": "search_replay_harness.py",
            "purpose": (
                "Replay pinned queries and sentinels against each search revision "
                "to measure regressions, abstention and evidence diversity."
            ),
            "signal": "schema_or_contract",
        },
    ]


def choose_candidate(
    sequence: int,
    signals: Mapping[str, int],
    previous: set[str],
) -> dict[str, Any]:
    catalogue = candidate_catalogue()
    available = [item for item in catalogue if item["filename"] not in previous] or catalogue
    preferred = sorted(
        available,
        key=lambda item: (
            int(signals.get(str(item["signal"]), 0)),
            -catalogue.index(item),
        ),
        reverse=True,
    )
    chosen = preferred[0] if preferred else catalogue[(sequence - 1) % len(catalogue)]
    return {