# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-reconcile-a-compaction-summary-against-the-raw-transcript-before-resuming-and-what-breaks-when-it-trusts-the-summary-alone.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-reconcile-a-compaction-summary-against-the-raw-transcript-before-resuming-and-what-breaks-when-it-trusts-the-summary-alone.warrant.json
# Markdown SHA-256:   c9b4fa79592561ffd7d5b11b8adf0fd12fea86617c6a2ac9b96b644593501340
# Code AST SHA-256:   3065cece76281e43666a78f78280da5f2c96a5fec9e7488b27e134f9909f70eb
# Verified Classes:   CompactionFidelityError, SummaryClause, CompactionResult
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class CompactionFidelityError(RuntimeError):
    """Raised when a summary cannot be safely treated as authoritative state."""


# Phrases whose presence in a summary means the clause carries a decision,
# a rejection, or an under-specified entity reference. These are exactly the
# compressions that drop operational payload while keeping narrative shape.
TRIPWIRE_PREFIXES = (
    "settled on",
    "decided against",
    "the problematic",
    "the path",
    "chose ",
    "abandoned ",
)


@dataclass
class SummaryClause:
    text: str
    turn_range: tuple[int, int]
    raw_span_available: bool
    resolved_entities: list[str] = field(default_factory=list)


@dataclass
class CompactionResult:
    clauses: list[SummaryClause]
    raw_fetch: Callable[[tuple[int, int]], str] | None


def _is_tripwire(text: str) -> bool:
    low = text.lower()
    return any(low.startswith(p) or f" {p}" in low for p in TRIPWIRE_PREFIXES)


def reconcile(
    result: CompactionResult,
    resolve_entity: Callable[[str], list[str]],
) -> list[SummaryClause]:
    """Confirm or demote every decision-bearing clause before resume.

    Returns the clauses the instance may treat as authoritative. Clauses that
    cannot be confirmed are demoted (marked unverified) so the execute phase
    must re-validate rather than trust them.
    """
    confirmed: list[SummaryClause] = []
    for clause in result.clauses:
        if not _is_tripwire(clause.text):
            confirmed.append(clause)
            continue

        # Condition 1: referential closure. Every entity mention must resolve
        # to exactly one target; ambiguity is a hard stop, not a warning.
        matches = resolve_entity(clause.text)
        if len(matches) > 1:
            raise CompactionFidelityError(
                f"Ambiguous entity in clause {clause.text!r}: "
                f"resolves to {matches}. Summary is under-specified; "
                f"cannot resume without disambiguation."
            )

        # Condition 2 & 3: negative-result retention requires the raw span.
        # If it was discarded at compaction, the clause is a hypothesis.
        if not clause.raw_span_available or result.raw_fetch is None:
            clause.resolved_entities = []
            # Demote: caller must re-validate any re-attempted approach.
            confirmed.append(_demote(clause))
            continue

        raw = result.raw_fetch(clause.turn_range)
        if not _clause_supported_by(clause.text, raw):
            raise CompactionFidelityError(
                f"Clause {clause.text!r} not supported by raw span "
                f"{clause.turn_range}. Summary diverges from transcript; "
                f"refusing to resume from a contradicted summary."
            )
        confirmed.append(clause)
    return confirmed


def _demote(clause: SummaryClause) -> SummaryClause:
    clause.text = f"[UNVERIFIED] {clause.text}"
    return clause


def _clause_supported_by(text: str, raw: str) -> bool:
    # Operational check: the raw span must contain the mechanism named in the
    # clause, not merely the conclusion. A "settled on X" clause is supported
    # only if the raw span shows X being chosen AND the alternative rejected.
    tokens = [t for t in text.lower().split() if len(t) > 4]
    return all(t in raw.lower() for t in tokens[:3])


def resume(
    result: CompactionResult,
    resolve_entity: Callable[[str], list[str]],
    next_action: str,
) -> list[SummaryClause]:
    """Gate resume on reconciliation when the next action commits."""
    commits = any(
        kw in next_action.lower()
        for kw in ("edit", "write", "re-attempt", "retry", "migrate", "apply")
    )
    if not commits:
        return result.clauses
    return reconcile(result, resolve_entity)
