GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / chatgpt-audits / automation/202608310122-failure-repair

Watchdog and 2 more files

A Python command-line tool in the automation folder of ChatGPT Audits using data from GitHub API. It classifies logs (`classify_logs`) and writes report (`write_report`).

659 lines of Python from chatgpt-audits, in 3 files. Topic: AI agents and coordination. Section 1592 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. Repair storage · chatgpt-audits / automation/202608310122-failure-repair/repair.py lines 1–261
  2. Watchdog storage · chatgpt-audits / automation/202608310125-actions-watchdog/watchdog.py lines 1–349
  3. Evidence Fingerprint transform · chatgpt-audits / automation/202608310209-hourly-logic-review/candidates/evidence_fingerprint.py lines 1–49

Repair

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

storagechatgpt-audits / automation/202608310122-failure-repair/repair.py · lines 1–261 of 261 · version 2026-08-31 01:22 · Entry point · pattern redact (shared by 6 files)

What it does
It fetches data. Defines 7 functions or classes, including redact, request, failed_logs, classify, rerun. Uses libraries __future__, argparse, json, os, re. Side effects: 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).
Inputs & outputs
In: data source: GitHub API; command-line arguments. Out: JSON file repair.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It writes markdown (`write_markdown`) and is built from the redact step (`redact`) and the request step (`request`). Diagnose and boundedly re-run a failed ChatGPT-audits workflow. It accepts `--run-id` and `--output`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
chatgpt-audits · automation/202608310122-failure-repair · Python CLI
Uses
__future__, argparse, json, os, re, subprocess, sys, time
Used by
none found
Produces
redact, request, failed_logs, classify, rerun, write_markdown, main
Defines here
redact, request, failed_logs, classify, rerun, write_markdown, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
chatgpt-audits@5808fde29b91027ec7a3de40c451a82b6714437c automation/202608310122-failure-repair/repair.py:1-261 · blob 72ab27673bd89ef3281ca34ed4f2b9c6ac27a3bd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, network, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Diagnose and boundedly re-run a failed chatgpt-audits workflow.

REVIEW STATUS: UNREVIEWED.

This controller never touches product repositories and never patches source from
logs. It preserves the failed evidence, classifies likely failure modes, and may
request one GitHub-native re-run while the source run is below attempt 3.
"""

from __future__ import annotations

import argparse
import json
import os
import re
import subprocess
import sys
import time
import urllib.error
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from zoneinfo import ZoneInfo

REPOSITORY = "Ventusltd/chatgpt-audits"
LONDON = ZoneInfo("Europe/London")
REVIEW_STATUS = "UNREVIEWED"
PATTERNS = [
    ("bytecode_boundary", re.compile(r"__pycache__|\.pyc|immutable output-only boundary", re.I)),
    ("snapshot_integrity", re.compile(r"source snapshot changed|file count changed|byte count changed", re.I)),
    ("git_race", re.compile(r"non-fast-forward|failed to push|rebase|reference update failed", re.I)),
    ("runner_capacity", re.compile(r"runner.*(lost|stopped|capacity)|hosted agent|startup_failure", re.I)),
    ("network_transient", re.compile(r"timed out|timeout|429|502|503|504|connection reset|temporary failure", re.I)),
    ("artifact_failure", re.compile(r"artifact.*(not found|upload|download)|BlobNotFound", re.I)),
    ("quarantine_boundary", re.compile(r"escaped quarantine|forbidden output|secret-like|symlink", re.I)),
    ("contract_assertion", re.compile(r"AssertionError|assertion failed|contract.*(invalid|mismatch)|schema", re.I)),
]
SECRET_SHAPES = [
    re.compile(r"gh[pousr]_[A-Za-z0-9_]{20,}"),
    re.compile(r"github_pat_[A-Za-z0-9_]{20,}"),
    re.compile(r"AKIA[0-9A-Z]{16}"),
]


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


def request(method: str, endpoint: str, token: str) -> tuple[bool, int, Any, str | None]:
    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-failure-repair/202608310122",
        "X-GitHub-Api-Version": "2022-11-28",
    }
    for attempt in range(1, 4):
        req = urllib.request.Request(url, method=method, headers=headers)
        try:
            with urllib.request.urlopen(req, timeout=30) as response:
                raw = response.read()
                return True, response.status, json.loads(raw.decode("utf-8")) if raw else None, None
        except urllib.error.HTTPError as exc:
            message = exc.read().decode("utf-8", "replace")
            if exc.code not in {429, 500, 502, 503, 504} or attempt == 3:
                return False, exc.code, None, f"HTTP {exc.code}: {message[:700]}"
        except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
            if attempt == 3:
                return False, 0, None, f"{type(exc).__name__}: {exc}"
        time.sleep(attempt * 2)
    return False, 0, None, "unknown request failure"


def failed_logs(run_id: int) -> str:
    command = ["gh", "run", "view", str(run_id), "--repo", REPOSITORY, "--log-failed"]
    for attempt in range(1, 4):
        completed = subprocess.run(command, text=True, capture_output=True, check=False)
        combined = "\n".join(part for part in [completed.stdout, completed.stderr] if part)
        if combined.strip() or completed.returncode == 0:
            return redact(combined[-120_000:])
        time.sleep(attempt * 3)
    return "Failed logs were not available when the repair controller inspected the completed run."


def classify(logs: str) -> list[dict[str, Any]]:
    matches = []
    for disease, pattern in PATTERNS:
        found = pattern.search(logs)
        if found:
            start = max(0, found.start() - 180)
            end = min(len(logs), found.end() + 320)
            excerpt = " ".join(logs[start:end].split())
            matches.append(
                {
                    "disease": disease,
                    "classification": "inferred",
                    "evidence_excerpt": excerpt[:600],
                }
            )
    if not matches:
        matches.append(
            {
                "disease": "unclassified",
                "classification": "unknown",
                "evidence_excerpt": "No bounded classifier matched the retained failed-job log.",
            }
        )
    return matches


def rerun(run: dict[str, Any], token: str) -> dict[str, Any]:
    conclusion = str(run.get("conclusion") or "")
    endpoint = (
        f"/repos/{REPOSITORY}/actions/runs/{run['id']}/rerun-failed-jobs"
        if conclusion == "failure"
        else f"/repos/{REPOSITORY}/actions/runs/{run['id']}/rerun"
    )
    ok, status, _, error = request("POST", endpoint, token)
    return {
        "requested": ok,
        "endpoint": endpoint,
        "http_status": status,
        "error": error,
        "classification": "observed",
    }


def write_markdown(report: dict[str, Any]) -> str:
    lines = [
        "# Audit workflow failure diagnosis",
        "",
        "> **REVIEW STATUS: UNREVIEWED**  ",
        "> Classification: mixed `observed` / `inferred`  ",
        "> This diagnosis belongs only to `Ventusltd/chatgpt-audits`.",
        "",
        f"Source workflow: **{report['workflow']['name']}**  ",
        f"Run: `{report['workflow']['id']}` attempt `{report['workflow']['run_attempt']}`  ",
        f"Conclusion: **{report['workflow']['conclusion']}**  ",
        f"Head SHA: `{report['workflow']['head_sha']}`  ",
        f"Inspected: `{report['inspected_at_london']}` Europe/London",
        "",
        "## Classified failure modes",
        "",
    ]
    for item in report["diagnosis"]:
        lines.extend(
            [
                f"### {item['disease']}",
                "",
                f"Classification: `{item['classification']}`",
                "",
                f"> {item['evidence_excerpt']}",
                "",
            ]
        )
    lines.extend(
        [
            "## Bounded action",
            "",
            f"- Re-run requested: **{report['repair_action']['requested']}**",
            f"- Endpoint class: `{report['repair_action']['endpoint'] or 'none'}`",
            f"- Reason: {report['repair_action']['reason']}",
            "",
            "## Hard boundary",
            "",
            "- Maximum source-run attempt: 3.",
            "- No product workflow is dispatched or re-run.",
            "- No source file is automatically rewritten from a log inference.",
            "- The failed log is retained in redacted form for human review.",
            "",
        ]
    )
    return "\n".join(lines)


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--run-id", required=True, type=int)
    parser.add_argument("--output", required=True)
    args = parser.parse_args(argv)

    token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") or ""
    if not token:
        print("GH_TOKEN or GITHUB_TOKEN is required", file=sys.stderr)
        return 2
    if os.environ.get("GITHUB_REPOSITORY") not in {None, "", REPOSITORY}:
        print("repair controller may run only in Ventusltd/chatgpt-audits", file=sys.stderr)
        return 2

    ok, status, run, error = request(
        "GET", f"/repos/{REPOSITORY}/actions/runs/{args.run_id}", token
    )
    if not ok or not isinstance(run, dict):
        print(f"could not fetch source run ({status}): {error}", file=sys.stderr)
        return 2

    logs = failed_logs(args.run_id)
    diagnosis = classify(logs)
    attempt = int(run.get("run_attempt") or 1)
    conclusion = str(run.get("conclusion") or "")
    eligible = conclusion in {"failure", "cancelled", "timed_out", "startup_failure"} and attempt < 3
    if eligible:
        action = rerun(run, token)
        action["reason"] = "GitHub-native bounded retry requested because the completed audit run is below attempt 3."
    else:
        action = {
            "requested": False,
            "endpoint": None,
            "http_status": None,
            "error": None,
            "classification": "observed",
            "reason": "No automatic retry: the run is not retry-eligible or has reached attempt 3.",
        }

    now = datetime.now(timezone.utc)
    report = {
        "schema": "chatgpt-audits.failure-repair.v1",
        "generation": "202608310122",
        "review_status": REVIEW_STATUS,
        "classification": "observed",
        "inspected_at": now.isoformat().replace("+00:00", "Z"),
        "inspected_at_london": now.astimezone(LONDON).isoformat(),
        "workflow": {
            "id": run.get("id"),
            "name": run.get("name"),
            "path": run.get("path"),
            "event": run.get("event"),
            "status": run.get("status"),
            "conclusion": run.get("conclusion"),
            "run_attempt": run.get("run_attempt"),
            "head_sha": run.get("head_sha"),
            "html_url": run.get("html_url"),
        },
        "diagnosis": diagnosis,
        "repair_action": action,
        "source_policy": {
            "write_boundary": REPOSITORY,
            "product_repo_writes": "FORBIDDEN",
            "product_workflow_dispatches": "FORBIDDEN",
            "automatic_source_patch": "FORBIDDEN",
        },
    }

    output = Path(args.output)
    output.mkdir(parents=True, exist_ok=True)
    (output / "repair.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
    (output / "REPAIR.md").write_text(write_markdown(report), encoding="utf-8")
    (output / "failed-job.log.txt").write_text(
        "REVIEW STATUS: UNREVIEWED\n\n" + logs, encoding="utf-8"
    )
    print(json.dumps({"rerun_requested": action["requested"], "diagnoses": len(diagnosis)}))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

Watchdog

A Python command-line tool in the automation folder of ChatGPT Audits using data from GitHub API. It classifies logs (`classify_logs`) and writes report (`write_report`).

storagechatgpt-audits / automation/202608310125-actions-watchdog/watchdog.py · lines 1–349 of 349 · version 2026-08-31 01:25 · Entry point · pattern now_london (shared by 2 files)

What it does
It fetches data. Defines 18 functions or classes, including now_utc, now_london, GitHubAPI, __init__, request. Uses libraries __future__, argparse, json, os, re. 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; command-line arguments. Out: JSON file WATCHDOG.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
Bounded same-repository GitHub Actions watchdog for the overnight audit. It accepts `--output`, `--event-path` and `--dry-run`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
chatgpt-audits · automation/202608310125-actions-watchdog · Python CLI
Uses
__future__, argparse, json, os, re, urllib.error, urllib.parse, urllib.request
Used by
none found
Produces
now_utc, now_london, GitHubAPI, classify_logs, newest_completed, active_newer_than, inspect_run, write_report, event_run, main
Defines here
now_utc, now_london, GitHubAPI, __init__, request, main_sha, workflow_runs, jobs, job_log, rerun_failed, dispatch, classify_logs, newest_completed, active_newer_than, inspect_run, write_report, event_run, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
chatgpt-audits@5808fde29b91027ec7a3de40c451a82b6714437c automation/202608310125-actions-watchdog/watchdog.py:1-349 · blob 8202b4e47d3081969f9a4474fe006993b857a721 · 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
"""Bounded same-repository GitHub Actions watchdog for the overnight audit.

REVIEW STATUS: UNREVIEWED.

The watchdog may only re-run failed jobs or dispatch the current default-branch
version of explicitly allowlisted workflows in Ventusltd/chatgpt-audits.
It never modifies or dispatches a product repository.
"""
from __future__ import annotations

import argparse
import json
import os
import re
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Iterable
from zoneinfo import ZoneInfo

REVIEW_STATUS = "UNREVIEWED"
REPOSITORY = "Ventusltd/chatgpt-audits"
WATCHED = {
    "202608310052 five-hour quarantined cross-repo study": "202608310052-five-hour-quarantined-study.yml",
    "202608310116 overnight audit swarm": "202608310116-overnight-audit-swarm.yml",
}
FAILURES = {"failure", "cancelled", "timed_out", "action_required", "stale"}
ACTIVE = {"queued", "in_progress", "waiting", "requested", "pending"}
TRANSIENT_PATTERNS = {
    "github-5xx": re.compile(r"\b(?:500|502|503|504)\b|bad gateway|service unavailable|gateway timeout", re.I),
    "rate-limit": re.compile(r"rate limit|secondary rate|abuse detection", re.I),
    "network": re.compile(
        r"connection (?:reset|refused|timed out)|temporary failure|could not resolve host|network is unreachable|"
        r"remote end hung up|tls handshake timeout|unexpected eof|failed to connect|connection closed",
        re.I,
    ),
    "runner": re.compile(r"runner.*lost communication|runner.*disconnected|hosted runner.*error|machine.*unavailable", re.I),
    "action-download": re.compile(r"failed to download action|unable to download|download.*failed|blobnotfound", re.I),
    "artifact-service": re.compile(r"artifact.*(?:failed|timeout|conflict)|failed to upload artifact|failed to finalize artifact", re.I),
    "git-race": re.compile(r"non-fast-forward|failed to push some refs|reference already exists|cannot lock ref|another git process", re.I),
    "cancelled-operation": re.compile(r"the operation was canceled|the operation was cancelled|job was cancelled", re.I),
}
DETERMINISTIC_PATTERNS = {
    "assertion": re.compile(r"assertionerror|assert\.ok|assertion failed|contract.*mismatch", re.I),
    "syntax": re.compile(r"syntaxerror|yaml.*(?:error|invalid)|unexpected token|indentationerror", re.I),
    "test-failure": re.compile(r"tests? failed|failures?=|quarantine verification failed|process completed with exit code [1-9]", re.I),
    "integrity": re.compile(r"sha(?:256)? .*mismatch|digest mismatch|file closure mismatch|escaped quarantine", re.I),
    "traceback": re.compile(r"traceback \(most recent call last\)", re.I),
}


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()


class GitHubAPI:
    def __init__(self, repository: str, token: str) -> None:
        self.repository = repository
        self.base = f"https://api.github.com/repos/{repository}"
        self.token = token

    def request(self, method: str, path: str, payload: Any | None = None, *, raw: bool = False) -> Any:
        url = path if path.startswith("https://") else f"{self.base}{path}"
        data = None
        headers = {
            "Accept": "application/vnd.github+json",
            "Authorization": f"Bearer {self.token}",
            "X-GitHub-Api-Version": "2022-11-28",
            "User-Agent": "chatgpt-audits-actions-watchdog",
        }
        if payload is not None:
            data = json.dumps(payload).encode("utf-8")
            headers["Content-Type"] = "application/json"
        request = urllib.request.Request(url, data=data, headers=headers, method=method)
        try:
            with urllib.request.urlopen(request, timeout=60) as response:
                body = response.read()
                if raw:
                    return body
                if not body:
                    return None
                return json.loads(body.decode("utf-8"))
        except urllib.error.HTTPError as exc:
            body = exc.read().decode("utf-8", "replace")
            raise RuntimeError(f"GitHub API {method} {url} -> {exc.code}: {body[:2000]}") from exc

    def main_sha(self) -> str:
        payload = self.request("GET", "/branches/main")
        return str(payload["commit"]["sha"])

    def workflow_runs(self, filename: str, *, per_page: int = 20) -> list[dict[str, Any]]:
        workflow = urllib.parse.quote(filename, safe="")
        payload = self.request("GET", f"/actions/workflows/{workflow}/runs?branch=main&per_page={per_page}")
        return list(payload.get("workflow_runs", []))

    def jobs(self, run_id: int) -> list[dict[str, Any]]:
        payload = self.request("GET", f"/actions/runs/{run_id}/jobs?filter=latest&per_page=100")
        return list(payload.get("jobs", []))

    def job_log(self, job_id: int) -> str:
        try:
            body = self.request("GET", f"/actions/jobs/{job_id}/logs", raw=True)
        except Exception as exc:
            return f"WATCHDOG_LOG_FETCH_ERROR: {exc}"
        return body.decode("utf-8", "replace")[-500_000:]

    def rerun_failed(self, run_id: int) -> None:
        self.request("POST", f"/actions/runs/{run_id}/rerun-failed-jobs", {})

    def dispatch(self, filename: str) -> None:
        workflow = urllib.parse.quote(filename, safe="")
        self.request("POST", f"/actions/workflows/{workflow}/dispatches", {"ref": "main"})


def classify_logs(logs: str) -> dict[str, Any]:
    transient = [name for name, pattern in TRANSIENT_PATTERNS.items() if pattern.search(logs)]
    deterministic = [name for name, pattern in DETERMINISTIC_PATTERNS.items() if pattern.search(logs)]
    if transient and not deterministic:
        classification = "TRANSIENT"
    elif deterministic:
        classification = "DETERMINISTIC_OR_CODE"
    elif logs.strip():
        classification = "UNKNOWN"
    else:
        classification = "NO_LOGS"
    excerpts: list[str] = []
    for line in logs.splitlines():
        if any(pattern.search(line) for pattern in [*TRANSIENT_PATTERNS.values(), *DETERMINISTIC_PATTERNS.values()]):
            compact = " ".join(line.split())
            if compact and compact not in excerpts:
                excerpts.append(compact[:500])
            if len(excerpts) >= 20:
                break
    return {
        "classification": classification,
        "transient_matches": transient,
        "deterministic_matches": deterministic,
        "excerpts": excerpts,
    }


def newest_completed(runs: Iterable[dict[str, Any]]) -> dict[str, Any] | None:
    for run in runs:
        if run.get("status") == "completed":
            return run
    return None


def active_newer_than(runs: Iterable[dict[str, Any]], run: dict[str, Any]) -> list[dict[str, Any]]:
    created = str(run.get("created_at", ""))
    return [
        candidate
        for candidate in runs
        if candidate.get("status") in ACTIVE and str(candidate.get("created_at", "")) >= created
    ]


def inspect_run(api: GitHubAPI, workflow_name: str, filename: str, run: dict[str, Any], main_sha: str) -> dict[str, Any]:
    run_id = int(run["id"])
    result: dict[str, Any] = {
        "workflow": workflow_name,
        "workflow_file": filename,
        "run_id": run_id,
        "run_attempt": int(run.get("run_attempt", 1)),
        "head_sha": run.get("head_sha"),
        "main_sha_at_check": main_sha,
        "status": run.get("status"),
        "conclusion": run.get("conclusion"),
        "created_at": run.get("created_at"),
        "updated_at": run.get("updated_at"),
        "classification": "NOT_FAILED",
        "decision": "NONE",
        "action_taken": False,
        "failed_jobs": [],
    }
    if run.get("conclusion") not in FAILURES:
        return result

    job_logs: list[str] = []
    for job in api.jobs(run_id):
        if job.get("conclusion") not in FAILURES:
            continue
        text = api.job_log(int(job["id"]))
        analysis = classify_logs(text)
        result["failed_jobs"].append(
            {
                "job_id": int(job["id"]),
                "name": job.get("name"),
                "status": job.get("status"),
                "conclusion": job.get("conclusion"),
                **analysis,
            }
        )
        job_logs.append(text)

    combined = classify_logs("\n".join(job_logs))
    result["classification"] = combined["classification"]
    result["transient_matches"] = combined["transient_matches"]
    result["deterministic_matches"] = combined["deterministic_matches"]
    result["excerpts"] = combined["excerpts"]
    return result


def write_report(output: Path, payload: dict[str, Any]) -> None:
    output.mkdir(parents=True, exist_ok=True)
    (output / "WATCHDOG.json").write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
    lines = [
        "# Overnight GitHub Actions watchdog",
        "",
        f"> **REVIEW STATUS: {REVIEW_STATUS}**  ",
        "> Classification: `observed` for API state; failure causes remain classified below.  ",
        "> This watchdog can act only inside `Ventusltd/chatgpt-audits`.",
        "",
        f"Checked: `{payload['checked_at_london']}`  ",
        f"Main SHA: `{payload['main_sha']}`  ",
        f"Actions taken: **{payload['actions_taken']}**  ",
        f"Unresolved failures: **{payload['unresolved_failures']}**",
        "",
        "| Workflow | Run | Attempt | Conclusion | Classification | Decision |",
        "|---|---:|---:|---|---|---|",
    ]
    for row in payload["checks"]:
        lines.append(
            f"| {row['workflow']} | {row.get('run_id', '—')} | {row.get('run_attempt', '—')} | "
            f"{row.get('conclusion') or row.get('status')} | {row.get('classification')} | {row.get('decision')} |"
        )
    lines.extend(
        [
            "",
            "## Governing boundary",
            "",
            "- No product repository is read with write credentials.",
            "- No product workflow can be dispatched.",
            "- A stale failed audit run is replaced by the current `main` workflow.",
            "- A same-SHA transient failure receives at most one failed-job rerun.",
            "- Deterministic or repeated failures are retained for human/code repair; they are not disguised as green.",
        ]
    )
    (output / "WATCHDOG.md").write_text("\n".join(lines) + "\n", encoding="utf-8")


def event_run(event_path: str | None) -> dict[str, Any] | None:
    if not event_path:
        return None
    path = Path(event_path)
    if not path.exists():
        return None
    payload = json.loads(path.read_text(encoding="utf-8"))
    run = payload.get("workflow_run")
    return run if isinstance(run, dict) else None


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--output", required=True)
    parser.add_argument("--event-path")
    parser.add_argument("--dry-run", action="store_true")
    args = parser.parse_args()

    repository = os.environ.get("GITHUB_REPOSITORY", REPOSITORY)
    if repository != REPOSITORY:
        raise SystemExit(f"watchdog repository boundary violated: {repository}")
    token = os.environ.get("GITHUB_TOKEN", "")
    if not token:
        raise SystemExit("GITHUB_TOKEN is required")
    api = GitHubAPI(repository, token)
    main_sha = api.main_sha()
    supplied = event_run(args.event_path or os.environ.get("GITHUB_EVENT_PATH"))

    checks: list[dict[str, Any]] = []
    actions_taken = 0
    unresolved = 0
    for workflow_name, filename in WATCHED.items():
        runs = api.workflow_runs(filename)
        if supplied and supplied.get("name") == workflow_name:
            target = next((row for row in runs if int(row["id"]) == int(supplied["id"])), supplied)
        else:
            target = newest_completed(runs)

        if not target:
            checks.append(
                {
                    "workflow": workflow_name,
                    "workflow_file": filename,
                    "classification": "NO_COMPLETED_RUN",
                    "decision": "NONE",
                    "action_taken": False,
                    "status": "not_observed",
                    "conclusion": None,
                }
            )
            continue

        row = inspect_run(api, workflow_name, filename, target, main_sha)
        if row["conclusion"] in FAILURES:
            newer_active = active_newer_than(runs, target)
            if newer_active:
                row["decision"] = "WAIT_NEWER_ACTIVE_RUN"
                row["newer_active_run_ids"] = [int(item["id"]) for item in newer_active]
            elif row["head_sha"] != main_sha:
                row["decision"] = "DISPATCH_CURRENT_MAIN"
                if not args.dry_run:
                    api.dispatch(filename)
                row["action_taken"] = True
                actions_taken += 1
            elif row["classification"] == "TRANSIENT" and row["run_attempt"] < 2:
                row["decision"] = "RERUN_FAILED_JOBS_ONCE"
                if not args.dry_run:
                    api.rerun_failed(int(row["run_id"]))
                row["action_taken"] = True
                actions_taken += 1
            else:
                row["decision"] = "UNRESOLVED_REPAIR_REQUIRED"
                unresolved += 1
        checks.append(row)

    payload = {
        "schema": "chatgpt-audits.actions-watchdog-report.v1",
        "generation": "202608310125",
        "review_status": REVIEW_STATUS,
        "classification": "observed",
        "checked_at": now_utc(),
        "checked_at_london": now_london(),
        "repository": repository,
        "main_sha": main_sha,
        "dry_run": bool(args.dry_run),
        "actions_taken": actions_taken,
        "unresolved_failures": unresolved,
        "mutation_or_incident": bool(actions_taken or unresolved),
        "checks": checks,
    }
    write_report(Path(args.output), payload)
    print(json.dumps({
        "actions_taken": actions_taken,
        "unresolved_failures": unresolved,
        "mutation_or_incident": payload["mutation_or_incident"],
    }))
    return 2 if unresolved else 0


if __name__ == "__main__":
    raise SystemExit(main())

Evidence Fingerprint

A Python module in the candidates folder of ChatGPT Audits that works with canonical URL (`canonical_url`), using SHA-256.

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

What it does
It calculates its inputs. Defines Fingerprint, canonical_url, normalise_text, fingerprint. Uses libraries __future__, hashlib, re, urllib.parse, dataclasses.
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
It normalises text (`normalise_text`) and is built from the fingerprint class (`Fingerprint`) and the fingerprint step (`fingerprint`). Evidence canonicalisation and hashing.
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__, hashlib, re, urllib.parse, dataclasses
Used by
none found
Produces
Fingerprint, canonical_url, normalise_text, fingerprint
Defines here
Fingerprint, canonical_url, normalise_text, fingerprint
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/evidence_fingerprint.py:1-49 · blob b042d01c10d159db7f419521338ebec0331b10c4 · 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: evidence canonicalisation and hashing."""

from __future__ import annotations

import hashlib
import re
import urllib.parse
from dataclasses import dataclass


TRACKING_KEYS = {"fbclid", "gclid", "mc_cid", "mc_eid"}
SPACE_RE = re.compile(r"\s+")


@dataclass(frozen=True)
class Fingerprint:
    canonical_url: str
    content_sha256: str


def canonical_url(value: str) -> str:
    parsed = urllib.parse.urlsplit(value.strip())
    host = parsed.netloc.casefold().removeprefix("www.")
    pairs = urllib.parse.parse_qsl(parsed.query, keep_blank_values=True)
    pairs = [
        (key, item)
        for key, item in pairs
        if not key.casefold().startswith("utm_")
        and key.casefold() not in TRACKING_KEYS
    ]
    query = urllib.parse.urlencode(sorted(pairs))
    path = re.sub(r"/+", "/", parsed.path or "/")
    return urllib.parse.urlunsplit(
        (parsed.scheme.casefold() or "https", host, path.rstrip("/") or "/", query, "")
    )


def normalise_text(value: str) -> str:
    return SPACE_RE.sub(" ", value.casefold()).strip()


def fingerprint(url: str, title: str, body: str = "") -> Fingerprint:
    canonical = canonical_url(url)
    payload = "\n".join([canonical, normalise_text(title), normalise_text(body)])
    return Fingerprint(
        canonical_url=canonical,
        content_sha256=hashlib.sha256(payload.encode("utf-8")).hexdigest(),
    )