# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-preserve-tool-call-causal-lineage-across-automatic-context-compaction.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-preserve-tool-call-causal-lineage-across-automatic-context-compaction.warrant.json
# Markdown SHA-256:   0f5b25aeefc8c712e8d1def099dd7f95e39fcfbcb577be73fea042e7a04199f8
# Code AST SHA-256:   48320bfa3deddb1fb03dc653c96ad30cc27bd2d9e86e5c453f500aaa6bee6c90
# Verified Classes:   LineageCompactionError, ToolCall, LineageIndex
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class LineageCompactionError(RuntimeError):
    """Raised when compaction would sever a load-bearing tool-call edge."""
    pass


@dataclass
class ToolCall:
    call_id: str
    tool: str
    arg_hash: str
    result_digest: str
    summarized_into: str | None = None  # tombstone -> summary span id


@dataclass
class LineageIndex:
    calls: dict[str, ToolCall] = field(default_factory=dict)
    open_dependencies: set[str] = field(default_factory=set)

    def register(self, call: ToolCall) -> None:
        if call.call_id in self.calls:
            raise LineageCompactionError(
                f"call_id {call.call_id!r} already registered; ids must be append-only"
            )
        self.calls[call.call_id] = call

    def compact_region(self, call_ids: list[str], summary_span: str) -> None:
        for cid in call_ids:
            call = self.calls.get(cid)
            if call is None:
                raise LineageCompactionError(
                    f"cannot compact unknown call {cid!r}"
                )
            if cid in self.open_dependencies:
                # Load-bearing edge: a surviving step still needs this call.
                # Refuse semantic collapse; require lineage-preserving tombstone.
                raise LineageCompactionError(
                    f"call {cid!r} is load-bearing for an unresolved step; "
                    f"lineage-preserving compaction required, not semantic collapse"
                )
            call.summarized_into = summary_span  # tombstone, id stays resolvable

    def resolve(self, call_id: str) -> ToolCall:
        call = self.calls.get(call_id)
        if call is None:
            raise LineageCompactionError(
                f"dangling lineage reference to {call_id!r}: "
                f"conclusion cannot be grounded"
            )
        return call

    def assert_grounded(self, conclusion_span: str, cited_call_id: str) -> None:
        call = self.resolve(cited_call_id)
        if call.summarized_into is None and call.result_digest is None:
            raise LineageCompactionError(
                f"conclusion {conclusion_span!r} cites {cited_call_id!r} "
                f"but that call has no surviving result digest; "
                f"treat conclusion as ungrounded"
            )


def reconcile_after_compaction(
    index: LineageIndex,
    summarized_claim_span: str,
    fresh_call: ToolCall,
) -> str:
    """Resolve conflict between an unaddressable summary claim and a fresh probe.

    Returns the winning source. Raises if the summary claim cannot be grounded.
    """
    index.register(fresh_call)
    # A fresh observation is always addressable. A summarized claim is only
    # trustworthy if its cited call_id still resolves to a live digest.
    try:
        index.assert_grounded(summarized_claim_span, fresh_call.call_id)
    except LineageCompactionError:
        return "fresh"  # summary is ungrounded -> defer to addressable observation
    return "summary"
