# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-lossy-transcript-compaction-from-severing-tool-call-causality-across-checkpoint-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-lossy-transcript-compaction-from-severing-tool-call-causality-across-checkpoint-boundaries.warrant.json
# Markdown SHA-256:   a93ac696f3d4b60fa9da18210039eceb22c5e73458f8fda32d087c4f77ae5609
# Code AST SHA-256:   6fef469545cf0028e3042057f39b79d1815515f9b5a66733ee922311cd409798
# Verified Classes:   CompactionCausalityError
# Defensive Guards:   2 fail-closed invariants (zero external deps)

class CompactionCausalityError(RuntimeError):
    """Raised when a compaction pass would sever tool-call causality or
    launder an ungrounded premise into a resumable checkpoint."""
    pass


def compact_transcript(turns, summarizer, consumer_index):
    """
    turns: list of dicts with keys: kind ('call'|'result'|'reason'|'decision'),
           id, ref (for results: originating call id), payload.
    consumer_index: dict mapping tool_result id -> set of downstream turn ids
                    that reference its ID or output fields.
    Enforces I1 (pair closure), I2 (provenance anchoring), I3 (re-derivability).
    """
    compacted = []
    dropped = set()

    for turn in turns:
        if turn["kind"] == "reason":
            # Reasoning traces may be lossily summarized freely.
            compacted.append(summarizer(turn))
            continue

        if turn["kind"] == "result":
            consumers = consumer_index.get(turn["id"], set())
            if consumers:
                # Load-bearing evidence: retain pair under I1, anchor under I2.
                compacted.append({
                    "kind": "result",
                    "id": turn["id"],
                    "ref": turn["ref"],
                    "payload": turn["payload"],
                    "anchor": turn["id"],
                    "consumers": sorted(consumers),
                })
            else:
                # Safe to summarize, but keep the call id for re-derivability (I3).
                compacted.append({
                    "kind": "result_summary",
                    "ref": turn["ref"],
                    "summary": summarizer(turn),
                    "anchor": turn["id"],
                })
                dropped.add(turn["id"])
            continue

        if turn["kind"] == "decision":
            # Any premise consumed by a decision must be grounded or tagged.
            for premise_id in turn.get("premises", []):
                if premise_id in dropped:
                    raise CompactionCausalityError(
                        f"decision {turn['id']} consumes premise {premise_id} "
                        f"whose evidence was compacted away; premise would be "
                        f"laundered as ungrounded fact on resume"
                    )
            compacted.append(turn)

    # I1: verify no orphaned half-pairs survived.
    call_ids = {t["id"] for t in compacted if t["kind"] == "call"}
    for t in compacted:
        if t["kind"] == "result" and t["ref"] not in call_ids:
            raise CompactionCausalityError(
                f"result {t['id']} references call {t['ref']} absent from "
                f"compacted context; pair closure violated"
            )

    return compacted
