GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / chatgpt-audits / automation/202608310322-gpt-reasoning-timer

Render Response and 1 more file

A Python command-line tool in the automation folder of ChatGPT Audits that validates claim rows and improvement and renders markdown, covering model review and model metadata, using SHA-256.

633 lines of Python from chatgpt-audits, in 2 files. Topic: AI agents and coordination. Section 1596 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. Render Response storage · chatgpt-audits / automation/202608310322-gpt-reasoning-timer/render_response.py lines 1–383
  2. Run Copilot storage · chatgpt-audits / automation/202608310322-gpt-reasoning-timer/run_copilot.py lines 1–250

Render Response

A Python command-line tool in the automation folder of ChatGPT Audits that validates claim rows and improvement and renders markdown, covering model review and model metadata, using SHA-256.

storagechatgpt-audits / automation/202608310322-gpt-reasoning-timer/render_response.py · lines 1–383 of 383 · version 2026-08-31 03:22 · Entry point · pattern render_markdown (shared by 5 files)

What it does
Defines 11 functions or classes, including sha256_bytes, load_response, require_string, require_string_list, validate_claim_rows. Uses libraries __future__, argparse, hashlib, json, os. Side effects: reads or writes files.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'chatgpt'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: command-line arguments. Out: JSON file MODEL-REVIEW.json; JSON file MODEL-METADATA.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It loads response (`load_response`), validates claim rows (`validate_claim_rows`) and validates improvement (`validate_improvement`). Validate and render a structured GPT architecture review. It accepts `--response`, `--prompt` 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/202608310322-gpt-reasoning-timer · Python CLI
Uses
__future__, argparse, hashlib, json, os, datetime, pathlib, typing
Used by
none found
Produces
sha256_bytes, load_response, require_string, require_string_list, validate_claim_rows, validate_improvement, validate_tests, validate, bullet_claim, render_markdown, main
Defines here
sha256_bytes, load_response, require_string, require_string_list, validate_claim_rows, validate_improvement, validate_tests, validate, bullet_claim, render_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/202608310322-gpt-reasoning-timer/render_response.py:1-383 · blob def8ac3daee110b45e1d064899afe3c8561bfd24 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Validate and render a structured GPT architecture review.

REVIEW STATUS: UNREVIEWED.

The renderer is provider-neutral. It accepts only the bounded JSON contract and
records the exact provider/runtime supplied by the workflow. A model response
that is prose, incomplete or schema-incompatible is rejected rather than being
silently repaired.
"""

from __future__ import annotations

import argparse
import hashlib
import json
import os
from datetime import datetime, timezone
from pathlib import Path
from typing import Any
from zoneinfo import ZoneInfo

REVIEW_STATUS = "UNREVIEWED"
LONDON = ZoneInfo("Europe/London")
CLASSIFICATIONS = {
    "observed",
    "inferred",
    "contradicted",
    "unknown",
    "not_checked",
    "not_observed_in_snapshot",
}
REQUIRED_KEYS = {
    "overall_assessment",
    "what_happened",
    "good",
    "bad",
    "recommended_improvement",
    "deterministic_tests",
    "do_not_change",
    "uncertainties",
}


def sha256_bytes(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def load_response(path: Path) -> tuple[dict[str, Any], bytes]:
    raw = path.read_bytes()
    text = raw.decode("utf-8", "replace").strip()
    if text.startswith("```"):
        lines = text.splitlines()
        if lines and lines[0].startswith("```"):
            lines = lines[1:]
        if lines and lines[-1].strip() == "```":
            lines = lines[:-1]
        text = "\n".join(lines).strip()
    payload = json.loads(text)
    if not isinstance(payload, dict):
        raise ValueError("model response must be a JSON object")
    return payload, raw


def require_string(value: Any, field: str) -> str:
    if not isinstance(value, str) or not value.strip():
        raise ValueError(f"{field} must be a non-empty string")
    return value.strip()


def require_string_list(value: Any, field: str) -> list[str]:
    if not isinstance(value, list):
        raise ValueError(f"{field} must be an array")
    result = [require_string(item, f"{field}[]") for item in value]
    if not result:
        raise ValueError(f"{field} must not be empty")
    return result


def validate_claim_rows(
    value: Any,
    field: str,
    *,
    issue_mode: bool = False,
) -> list[dict[str, str]]:
    if not isinstance(value, list) or not value:
        raise ValueError(f"{field} must be a non-empty array")
    rows: list[dict[str, str]] = []
    for index, row in enumerate(value):
        if not isinstance(row, dict):
            raise ValueError(f"{field}[{index}] must be an object")
        statement_key = "issue" if issue_mode else "claim"
        expected = {statement_key, "evidence", "classification"}
        if issue_mode:
            expected.add("impact")
        if set(row) != expected:
            raise ValueError(
                f"{field}[{index}] keys must be exactly {sorted(expected)}; "
                f"received {sorted(row)}"
            )
        classification = require_string(
            row.get("classification"), f"{field}[{index}].classification"
        )
        if classification not in CLASSIFICATIONS:
            raise ValueError(f"unsupported classification {classification!r}")
        item = {
            statement_key: require_string(
                row.get(statement_key), f"{field}[{index}].{statement_key}"
            ),
            "evidence": require_string(
                row.get("evidence"), f"{field}[{index}].evidence"
            ),
            "classification": classification,
        }
        if issue_mode:
            item["impact"] = require_string(
                row.get("impact"), f"{field}[{index}].impact"
            )
        rows.append(item)
    return rows


def validate_improvement(value: Any) -> dict[str, Any]:
    if not isinstance(value, dict):
        raise ValueError("recommended_improvement must be an object")
    expected = {
        "kind",
        "name",
        "purpose",
        "evidence_basis",
        "algorithm",
        "inputs",
        "outputs",
        "rejection_conditions",
    }
    if set(value) != expected:
        raise ValueError(
            "recommended_improvement keys must be exactly "
            f"{sorted(expected)}; received {sorted(value)}"
        )
    kind = require_string(value.get("kind"), "recommended_improvement.kind")
    if kind not in {"workflow", "python"}:
        raise ValueError("recommended_improvement.kind must be workflow or python")
    return {
        "kind": kind,
        "name": require_string(value.get("name"), "recommended_improvement.name"),
        "purpose": require_string(
            value.get("purpose"), "recommended_improvement.purpose"
        ),
        "evidence_basis": require_string(
            value.get("evidence_basis"), "recommended_improvement.evidence_basis"
        ),
        "algorithm": require_string(
            value.get("algorithm"), "recommended_improvement.algorithm"
        ),
        "inputs": require_string_list(
            value.get("inputs"), "recommended_improvement.inputs"
        ),
        "outputs": require_string_list(
            value.get("outputs"), "recommended_improvement.outputs"
        ),
        "rejection_conditions": require_string_list(
            value.get("rejection_conditions"),
            "recommended_improvement.rejection_conditions",
        ),
    }


def validate_tests(value: Any) -> list[dict[str, str]]:
    if not isinstance(value, list) or len(value) < 3:
        raise ValueError("deterministic_tests must contain at least three tests")
    result = []
    expected = {"name", "fixture", "assertion"}
    for index, row in enumerate(value):
        if not isinstance(row, dict):
            raise ValueError(f"deterministic_tests[{index}] must be an object")
        if set(row) != expected:
            raise ValueError(
                f"deterministic_tests[{index}] keys must be exactly "
                f"{sorted(expected)}; received {sorted(row)}"
            )
        result.append(
            {
                "name": require_string(
                    row.get("name"), f"deterministic_tests[{index}].name"
                ),
                "fixture": require_string(
                    row.get("fixture"), f"deterministic_tests[{index}].fixture"
                ),
                "assertion": require_string(
                    row.get("assertion"), f"deterministic_tests[{index}].assertion"
                ),
            }
        )
    return result


def validate(payload: dict[str, Any]) -> dict[str, Any]:
    missing = REQUIRED_KEYS - payload.keys()
    extra = payload.keys() - REQUIRED_KEYS
    if missing:
        raise ValueError(f"missing required response keys: {sorted(missing)}")
    if extra:
        raise ValueError(f"unexpected response keys: {sorted(extra)}")
    return {
        "overall_assessment": require_string(
            payload["overall_assessment"], "overall_assessment"
        ),
        "what_happened": validate_claim_rows(
            payload["what_happened"], "what_happened"
        ),
        "good": validate_claim_rows(payload["good"], "good"),
        "bad": validate_claim_rows(payload["bad"], "bad", issue_mode=True),
        "recommended_improvement": validate_improvement(
            payload["recommended_improvement"]
        ),
        "deterministic_tests": validate_tests(payload["deterministic_tests"]),
        "do_not_change": require_string_list(
            payload["do_not_change"], "do_not_change"
        ),
        "uncertainties": require_string_list(
            payload["uncertainties"], "uncertainties"
        ),
    }


def bullet_claim(row: dict[str, str], issue_mode: bool = False) -> str:
    key = "issue" if issue_mode else "claim"
    suffix = f" Impact: {row['impact']}" if issue_mode else ""
    return (
        f"- **{row[key]}** — `{row['classification']}`. "
        f"Evidence: {row['evidence']}.{suffix}"
    )


def render_markdown(
    payload: dict[str, Any],
    sequence: int,
    model: str,
    provider: str,
    runtime: str,
) -> str:
    improvement = payload["recommended_improvement"]
    lines = [
        "# GPT hourly architecture review",
        "",
        f"> **REVIEW STATUS: {REVIEW_STATUS}**  ",
        "> Model reasoning is advisory and quarantined. Source excerpts were supplied as untrusted evidence.  ",
        "> Nothing in this review is installed, promoted or published to a product repository.",
        "",
        f"Sequence: **{sequence}/5**  ",
        f"Provider: `{provider}`  ",
        f"Model: `{model}`  ",
        f"Runtime: `{runtime}`",
        "",
        "## Overall assessment",
        "",
        payload["overall_assessment"],
        "",
        "## What happened",
        "",
    ]
    lines.extend(bullet_claim(row) for row in payload["what_happened"])
    lines.extend(["", "## What is good", ""])
    lines.extend(bullet_claim(row) for row in payload["good"])
    lines.extend(["", "## What is bad, contradictory or unknown", ""])
    lines.extend(bullet_claim(row, issue_mode=True) for row in payload["bad"])
    lines.extend(
        [
            "",
            "## Highest-leverage quarantined improvement",
            "",
            f"- Type: `{improvement['kind']}`",
            f"- Name: `{improvement['name']}`",
            f"- Purpose: {improvement['purpose']}",
            f"- Evidence basis: {improvement['evidence_basis']}",
            "",
            "### Algorithm",
            "",
            improvement["algorithm"],
            "",
            "### Inputs",
            "",
        ]
    )
    lines.extend(f"- {item}" for item in improvement["inputs"])
    lines.extend(["", "### Outputs", ""])
    lines.extend(f"- {item}" for item in improvement["outputs"])
    lines.extend(["", "### Rejection conditions", ""])
    lines.extend(f"- {item}" for item in improvement["rejection_conditions"])
    lines.extend(["", "## Deterministic acceptance tests", ""])
    for test in payload["deterministic_tests"]:
        lines.extend(
            [
                f"### {test['name']}",
                "",
                f"- Fixture: {test['fixture']}",
                f"- Assertion: {test['assertion']}",
                "",
            ]
        )
    lines.extend(["## Do not change or promote", ""])
    lines.extend(f"- {item}" for item in payload["do_not_change"])
    lines.extend(["", "## Remaining uncertainties", ""])
    lines.extend(f"- {item}" for item in payload["uncertainties"])
    lines.append("")
    return "\n".join(lines)


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--response", required=True)
    parser.add_argument("--prompt", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--sequence", required=True, type=int)
    parser.add_argument("--model", required=True)
    parser.add_argument("--provider", required=True)
    parser.add_argument("--runtime", required=True)
    args = parser.parse_args()
    if not 1 <= args.sequence <= 5:
        raise SystemExit("sequence must be between 1 and 5")

    response_path = Path(args.response)
    prompt_path = Path(args.prompt)
    output = Path(args.output)
    output.mkdir(parents=True, exist_ok=True)

    parsed, raw = load_response(response_path)
    validated = validate(parsed)
    prompt_raw = prompt_path.read_bytes()
    now = datetime.now(timezone.utc)

    (output / "MODEL-RAW.txt").write_bytes(raw)
    (output / "MODEL-REVIEW.json").write_text(
        json.dumps(validated, indent=2) + "\n", encoding="utf-8"
    )
    (output / "MODEL-REVIEW.md").write_text(
        render_markdown(
            validated,
            args.sequence,
            args.model,
            args.provider,
            args.runtime,
        ),
        encoding="utf-8",
    )
    metadata = {
        "schema": "chatgpt-audits.real-gpt-review-metadata.v2",
        "generation": "202608310322",
        "review_status": REVIEW_STATUS,
        "classification": "inferred",
        "sequence": args.sequence,
        "provider": args.provider,
        "model": args.model,
        "runtime": args.runtime,
        "github_ai_inference_action_sha": "2c43c91ae16266ca159d311430343c67a5ffa222",
        "created_at": now.isoformat().replace("+00:00", "Z"),
        "created_at_london": now.astimezone(LONDON).isoformat(),
        "workflow_run_id": os.environ.get("GITHUB_RUN_ID"),
        "workflow_run_attempt": os.environ.get("GITHUB_RUN_ATTEMPT"),
        "prompt_sha256": sha256_bytes(prompt_raw),
        "raw_response_sha256": sha256_bytes(raw),
        "product_repository_writes": "FORBIDDEN",
        "product_workflow_dispatches": "FORBIDDEN",
    }
    (output / "MODEL-METADATA.json").write_text(
        json.dumps(metadata, indent=2) + "\n", encoding="utf-8"
    )
    print(
        json.dumps(
            {
                "sequence": args.sequence,
                "provider": args.provider,
                "model": args.model,
                "validated": True,
            }
        )
    )
    return 0


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

Run Copilot

A Python command-line tool in the automation folder of ChatGPT Audits that reads copilot run.

storagechatgpt-audits / automation/202608310322-gpt-reasoning-timer/run_copilot.py · lines 1–250 of 250 · version 2026-08-31 03:22 · Entry point · pattern redact (shared by 6 files)

What it does
It loads copilot run. Defines redact, classify, minimal_environment, main. Uses libraries __future__, argparse, json, os, re. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'chatgpt'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief).
Inputs & outputs
In: command-line arguments. Out: JSON file COPILOT-RUN.json.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It is built from the redact step (`redact`), the classify step (`classify`) and the minimal environment helper (`minimal_environment`). Run one bounded GitHub Copilot GPT judgement and retain exact diagnostics. It accepts `--cli`, `--prompt` and `--system`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
chatgpt-audits · automation/202608310322-gpt-reasoning-timer · Python CLI
Uses
__future__, argparse, json, os, re, subprocess, datetime, pathlib
Used by
none found
Produces
redact, classify, minimal_environment, main
Defines here
redact, classify, minimal_environment, 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/202608310322-gpt-reasoning-timer/run_copilot.py:1-250 · blob c9409f916ae1f14daa92dea08f50b866f701ea0c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
#!/usr/bin/env python3
"""Run one bounded GitHub Copilot GPT judgement and retain exact diagnostics.

REVIEW STATUS: UNREVIEWED.

The CLI runs in an empty temporary directory with a fresh configuration home.
All model tools except `ask_user` are unavailable, `--no-ask-user` is enabled,
and explicit deny rules cover reads, writes, shell commands, URLs and memory.
The model therefore receives only the assembled prompt and cannot inspect or
mutate a product repository.
"""

from __future__ import annotations

import argparse
import json
import os
import re
import subprocess
from datetime import datetime, timezone
from pathlib import Path
from typing import Mapping
from zoneinfo import ZoneInfo

LONDON = ZoneInfo("Europe/London")
REVIEW_STATUS = "UNREVIEWED"
MINIMUM_AI_CREDITS = 30
TOKEN_PATTERNS = [
    re.compile(r"github_pat_[A-Za-z0-9_]{20,}"),
    re.compile(r"gh[pousr]_[A-Za-z0-9_]{20,}"),
    re.compile(r"Bearer\s+[A-Za-z0-9._~-]{20,}", re.I),
]


def redact(text: str, secrets: list[str]) -> str:
    result = text
    for secret in sorted((item for item in secrets if item), key=len, reverse=True):
        result = result.replace(secret, "[REDACTED]")
    for pattern in TOKEN_PATTERNS:
        result = pattern.sub("[REDACTED]", result)
    return result


def classify(exit_code: int, stderr: str, stdout: str) -> str:
    if exit_code == 0 and stdout.strip():
        return "SUCCESS"
    text = f"{stderr}\n{stdout}".lower()
    if "allow use of copilot cli billed to the organization" in text:
        return "ORG_COPILOT_BILLING_POLICY_DISABLED"
    if "copilot cli" in text and "policy" in text and any(
        marker in text for marker in ("disabled", "not enabled", "blocked", "denied")
    ):
        return "ORG_COPILOT_POLICY_BLOCKED"
    if any(marker in text for marker in ("401", "403", "unauthorized", "forbidden")):
        return "COPILOT_AUTH_OR_ENTITLEMENT_REJECTED"
    if "model" in text and any(
        marker in text
        for marker in ("not found", "not available", "unsupported", "invalid model", "unknown model")
    ):
        return "REQUESTED_GPT_MODEL_UNAVAILABLE"
    if any(marker in text for marker in ("trust this", "permission prompt", "requires approval")):
        return "NONINTERACTIVE_PERMISSION_REJECTED"
    if "rate limit" in text or "quota" in text or "budget" in text:
        return "COPILOT_QUOTA_OR_BUDGET_REJECTED"
    if exit_code == 124:
        return "COPILOT_TIMEOUT"
    if exit_code == 0:
        return "EMPTY_MODEL_RESPONSE"
    return f"COPILOT_CLI_EXIT_{exit_code}"


def minimal_environment(token: str, home: Path) -> dict[str, str]:
    env = {
        "PATH": os.environ.get("PATH", "/usr/local/bin:/usr/bin:/bin"),
        "HOME": str(home),
        "COPILOT_HOME": str(home / ".copilot"),
        "GITHUB_TOKEN": token,
        "CI": "true",
        "TERM": "dumb",
        "NO_COLOR": "1",
        "COPILOT_AUTO_UPDATE": "false",
        "COPILOT_ENABLE_HTTP2": "false",
    }
    for key in (
        "SSL_CERT_FILE",
        "SSL_CERT_DIR",
        "HTTPS_PROXY",
        "HTTP_PROXY",
        "ALL_PROXY",
        "NO_PROXY",
        "https_proxy",
        "http_proxy",
        "all_proxy",
        "no_proxy",
    ):
        value = os.environ.get(key)
        if value:
            env[key] = value
    return env


def main() -> int:
    parser = argparse.ArgumentParser()
    parser.add_argument("--cli", required=True)
    parser.add_argument("--prompt", required=True)
    parser.add_argument("--system", required=True)
    parser.add_argument("--output", required=True)
    parser.add_argument("--model", required=True)
    parser.add_argument("--timeout-seconds", type=int, default=240)
    args = parser.parse_args()

    cli = Path(args.cli).resolve()
    prompt_path = Path(args.prompt).resolve()
    system_path = Path(args.system).resolve()
    output = Path(args.output).resolve()
    output.mkdir(parents=True, exist_ok=True)

    if not cli.is_file() or not os.access(cli, os.X_OK):
        raise SystemExit(f"Copilot CLI is not executable: {cli}")
    if not prompt_path.is_file() or not system_path.is_file():
        raise SystemExit("prompt and system instruction files are required")

    token = os.environ.get("GITHUB_TOKEN", "")
    if not token:
        raise SystemExit("GITHUB_TOKEN is required")

    system = system_path.read_text(encoding="utf-8", errors="strict").strip()
    prompt = prompt_path.read_text(encoding="utf-8", errors="replace").strip()
    combined = (
        f"<SYSTEM_BOUNDARY>\n{system}\n</SYSTEM_BOUNDARY>\n\n"
        f"<USER_EVIDENCE_REQUEST>\n{prompt}\n</USER_EVIDENCE_REQUEST>"
    )
    if len(combined.encode("utf-8")) >= 100_000:
        raise SystemExit("combined Copilot prompt exceeded 100000 bytes")

    runtime = output / "copilot-isolated-runtime"
    work = runtime / "empty-workspace"
    home = runtime / "home"
    logs = runtime / "logs"
    for path in (work, home, logs):
        path.mkdir(parents=True, exist_ok=True)

    command = [
        str(cli),
        "-C",
        str(work),
        "-p",
        combined,
        "-s",
        "--no-ask-user",
        "--model",
        args.model,
        "--max-ai-credits",
        str(MINIMUM_AI_CREDITS),
        "--yolo",
        "--available-tools=ask_user",
        "--deny-tool=read",
        "--deny-tool=write",
        "--deny-tool=shell",
        "--deny-tool=url",
        "--deny-tool=memory",
        "--log-level=debug",
        "--log-dir",
        str(logs),
    ]
    env = minimal_environment(token, home)
    started = datetime.now(timezone.utc)
    try:
        completed = subprocess.run(
            command,
            cwd=work,
            env=env,
            text=True,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            timeout=max(30, args.timeout_seconds),
            check=False,
        )
        exit_code = completed.returncode
        stdout = completed.stdout
        stderr = completed.stderr
    except subprocess.TimeoutExpired as exc:
        exit_code = 124
        stdout = exc.stdout if isinstance(exc.stdout, str) else ""
        stderr = exc.stderr if isinstance(exc.stderr, str) else ""
        stderr += f"\nTimed out after {args.timeout_seconds} seconds."

    finished = datetime.now(timezone.utc)
    secrets = [token, os.environ.get("COPILOT_GITHUB_TOKEN", ""), os.environ.get("GH_TOKEN", "")]
    clean_stdout = redact(stdout, secrets)
    clean_stderr = redact(stderr, secrets)
    classification = classify(exit_code, clean_stderr, clean_stdout)

    (output / "COPILOT-STDOUT.txt").write_text(clean_stdout, encoding="utf-8")
    (output / "COPILOT-STDERR.txt").write_text(clean_stderr, encoding="utf-8")
    (output / "COPILOT-RESPONSE.txt").write_text(clean_stdout, encoding="utf-8")
    command_record = [
        "copilot",
        "-C",
        "<EMPTY_WORKSPACE>",
        "-p",
        "<ASSEMBLED_PROMPT>",
        "-s",
        "--no-ask-user",
        "--model",
        args.model,
        "--max-ai-credits",
        str(MINIMUM_AI_CREDITS),
        "--yolo",
        "--available-tools=ask_user",
        "--deny-tool=read",
        "--deny-tool=write",
        "--deny-tool=shell",
        "--deny-tool=url",
        "--deny-tool=memory",
    ]
    report: Mapping[str, object] = {
        "schema": "chatgpt-audits.direct-copilot-run.v3",
        "generation": "202608310417",
        "review_status": REVIEW_STATUS,
        "classification": "observed",
        "provider": "github-copilot-cli",
        "model": args.model,
        "exit_code": exit_code,
        "outcome": "success" if classification == "SUCCESS" else "failure",
        "reason": classification,
        "stdout_bytes": len(clean_stdout.encode("utf-8")),
        "stderr_bytes": len(clean_stderr.encode("utf-8")),
        "started_at": started.isoformat().replace("+00:00", "Z"),
        "finished_at": finished.isoformat().replace("+00:00", "Z"),
        "finished_at_london": finished.astimezone(LONDON).isoformat(),
        "isolated_empty_workspace": True,
        "fresh_copilot_home": True,
        "model_tools_available": ["ask_user"],
        "ask_user_disabled": True,
        "explicit_denials": ["read", "write", "shell", "url", "memory"],
        "max_ai_credits": MINIMUM_AI_CREDITS,
        "command": command_record,
        "product_repository_writes": "FORBIDDEN",
        "product_workflow_dispatches": "FORBIDDEN",
    }
    (output / "COPILOT-RUN.json").write_text(
        json.dumps(report, indent=2) + "\n", encoding="utf-8"
    )
    print(json.dumps({"outcome": report["outcome"], "reason": classification, "exit_code": exit_code}))
    return 0


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