# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-transcript-whose-oldest-segment-is-the-only-surviving-witness-of-a-tool-call-side-effect.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-compacts-a-transcript-whose-oldest-segment-is-the-only-surviving-witness-of-a-tool-call-side-effect.warrant.json
# Markdown SHA-256:   363e6ab3792551c33042885d65f2059316b77af074c68f88aa18eecc12c418ae
# Code AST SHA-256:   8b40bf0097f74c6a3b1bbab42bcba3a7122e55a3106862358dcd58d401b9a18d
# Verified Classes:   WitnessLossError, ToolCallRecord, CompactionPlan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Any


class WitnessLossError(RuntimeError):
    """Raised when compaction drops or paraphrases a non-reconcilable tool-call witness."""


@dataclass(frozen=True)
class ToolCallRecord:
    ordinal: int
    tool: str
    args: dict[str, Any]
    result: dict[str, Any]
    reconcilable_id: str | None  # e.g. dedup_key, resource ID, journal pointer


@dataclass
class CompactionPlan:
    summary_text: str
    preserved_records: list[ToolCallRecord] = field(default_factory=list)


def compact_transcript(
    records: list[ToolCallRecord],
    mutating_tools: set[str],
    journal_available: bool,
) -> CompactionPlan:
    """Compact a transcript, preserving witness records verbatim.

    A record is a witness if its tool is mutating AND it has no reconcilable
    external identifier (or no journal to point at). Witnesses must survive
    verbatim; everything else may be summarized.
    """
    preserved: list[ToolCallRecord] = []
    for rec in records:
        is_witness = rec.tool in mutating_tools and (
            rec.reconcilable_id is None or not journal_available
        )
        if is_witness:
            preserved.append(rec)

    # The summarizer is invoked only on non-witness records; its output is
    # narrative and must never be treated as a witness substitute.
    summary_text = _summarize([r for r in records if r not in preserved])
    return CompactionPlan(summary_text=summary_text, preserved_records=preserved)


def verify_compaction(
    before: list[ToolCallRecord],
    after: CompactionPlan,
    mutating_tools: set[str],
    journal_available: bool,
) -> None:
    """Post-compaction audit: witness set must be identical, byte-for-byte."""
    expected = {
        r.ordinal: r
        for r in before
        if r.tool in mutating_tools and (r.reconcilable_id is None or not journal_available)
    }
    actual = {r.ordinal: r for r in after.preserved_records}

    missing = set(expected) - set(actual)
    if missing:
        raise WitnessLossError(
            f"compaction dropped witnesses at ordinals {sorted(missing)}; "
            f"these tool calls have no reconcilable external ID and no journal "
            f"pointer, so their effects are now unverifiable from transcript. "
            f"Refusing to commit compacted transcript."
        )

    for ordinal, exp in expected.items():
        act = actual[ordinal]
        if act.args != exp.args or act.result != exp.result or act.tool != exp.tool:
            raise WitnessLossError(
                f"witness at ordinal {ordinal} was paraphrased during compaction: "
                f"expected args={exp.args!r} result={exp.result!r}, "
                f"got args={act.args!r} result={act.result!r}. "
                f"A summary is not a witness; retry/dedup/rollback logic will "
                f"fail to match this record."
            )


def _summarize(records: list[ToolCallRecord]) -> str:
    # Placeholder for the model-backed summarizer. Must never be called on
    # witness records; its output is narrative, not identity.
    return f"<summary of {len(records)} reconstructible turns>"
