# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-hierarchical-transcript-compaction-from-silently-deleting-the-evidence-an-agent-s-own-verifier-needs.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-hierarchical-transcript-compaction-from-silently-deleting-the-evidence-an-agent-s-own-verifier-needs.warrant.json
# Markdown SHA-256:   2736cc7419096108e49323a9aad7b240a88cc0ea72da9ae0e12a3deb4e02fdc0
# Code AST SHA-256:   c4d57d20012f9cb2315db3de2c5fa798f1f85610b5f81eba76f85a671ae675a2
# Verified Classes:   UnwitnessedCompletionError, WitnessRecord, SummaryNode
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from typing import Literal

Outcome = Literal["exit_0", "exit_nonzero", "not_run"]


class UnwitnessedCompletionError(RuntimeError):
    """Raised when a verifier is asked to accept a completion claim whose
    supporting tool outcome was paraphrased away by transcript compaction."""


@dataclass(frozen=True)
class WitnessRecord:
    step_id: int
    tool: str
    args_hash: str
    outcome: Outcome
    stderr_excerpt: str  # byte-truncated, never paraphrased
    touched_paths: tuple[str, ...]


@dataclass
class SummaryNode:
    covers_steps: tuple[int, int]
    prose: str
    witness_ids: frozenset[int] = field(default_factory=frozenset)
    # claims of the form (path, "linter_completed") that the summary asserts
    completion_claims: frozenset[tuple[str, str]] = field(default_factory=frozenset)


def verify_completion(
    summary: SummaryNode,
    witnesses: dict[int, WitnessRecord],
    required_paths: set[str],
) -> None:
    """Verify that every required path has a witnessed, successful linter run
    at or after the summary's coverage window. Refuses to trust prose."""
    witnessed_ok: set[str] = set()
    for wid in summary.witness_ids:
        rec = witnesses.get(wid)
        if rec is None:
            raise UnwitnessedCompletionError(
                f"summary cites witness id {wid} that is absent from the log"
            )
        if rec.tool == "schema_linter" and rec.outcome == "exit_0":
            witnessed_ok.update(rec.touched_paths)

    for path, claim in summary.completion_claims:
        if claim != "linter_completed":
            continue
        if path not in witnessed_ok:
            raise UnwitnessedCompletionError(
                f"summary asserts '{claim}' for {path!r} at steps "
                f"{summary.covers_steps}, but no exit_0 witness record covers it; "
                f"re-execution required before PASS"
            )

    missing = required_paths - witnessed_ok
    if missing:
        raise UnwitnessedCompletionError(
            f"required paths lack witnessed success: {sorted(missing)}"
        )


# Reproduction of the incident, now bounded:
witnesses = {
    91: WitnessRecord(
        step_id=91,
        tool="schema_linter",
        args_hash="sha256:0007",
        outcome="exit_nonzero",
        stderr_excerpt='column "user_email" referenced in index idx_users_email does not exist',
        touched_paths=("migrations/0007_users.sql",),
    ),
}
compacted = SummaryNode(
    covers_steps=(88, 96),
    prose="Applied edits to 0007_users.sql; linter run completed; "
          "noted index reconciliation as a follow-up.",
    witness_ids=frozenset({91}),
    completion_claims=frozenset({("migrations/0007_users.sql", "linter_completed")}),
)

try:
    verify_completion(compacted, witnesses, {"migrations/0007_users.sql"})
except UnwitnessedCompletionError as exc:
    print(f"BLOCKED: {exc}")
    # Agent must re-run the linter and append a fresh witness before retrying.
