# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-bound-semantic-dedup-collapse-when-auto-compaction-merges-distinct-decision-traces-that-share-surface-tokens.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-bound-semantic-dedup-collapse-when-auto-compaction-merges-distinct-decision-traces-that-share-surface-tokens.warrant.json
# Markdown SHA-256:   f6415b53acaa08eaad02da7a025595f8ee59010ea2303fce6b9c4938200b3dfa
# Code AST SHA-256:   cc8890291bb80d62879158cb0e11c4e5956a588996505ee23fbf7f5ec0675f1e
# Verified Classes:   CompactionInflationError, DecisionSignatureMismatch, Segment
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Sequence

class CompactionInflationError(RuntimeError):
    """Raised when a merge inflates retention rank beyond pre-merge maximum."""
    pass

class DecisionSignatureMismatch(RuntimeError):
    """Raised when a dedup candidate pair has divergent decision signatures."""
    pass

@dataclass(frozen=True)
class Segment:
    id: int
    precondition: str
    action_verb: str
    terminal_outcome: str
    retention_score: float
    token_count: int

def merge_candidates(a: Segment, b: Segment, cosine: float, threshold: float = 0.94) -> bool:
    if cosine < threshold:
        return False
    sig_a = (a.precondition, a.action_verb, a.terminal_outcome)
    sig_b = (b.precondition, b.action_verb, b.terminal_outcome)
    if sig_a != sig_b:
        raise DecisionSignatureMismatch(
            f"segments {a.id} and {b.id} share surface tokens (cos={cosine:.3f}) "
            f"but diverge on decision signature: {sig_a} vs {sig_b}"
        )
    return True

def compact(segments: Sequence[Segment], pairs: Sequence[tuple[int, int, float]]) -> list[Segment]:
    by_id = {s.id: s for s in segments}
    survivors = {s.id: s for s in segments}
    for a_id, b_id, cosine in pairs:
        a, b = by_id[a_id], by_id[b_id]
        if not merge_candidates(a, b, cosine):
            continue
        merged = Segment(
            id=min(a.id, b.id),
            precondition=a.precondition,
            action_verb=a.action_verb,
            terminal_outcome=a.terminal_outcome,
            retention_score=max(a.retention_score, b.retention_score),
            token_count=a.token_count + b.token_count,
        )
        pre_merge_max = max(a.retention_score, b.retention_score)
        if merged.retention_score > pre_merge_max:
            raise CompactionInflationError(
                f"merge of {a.id}+{b.id} inflated score to {merged.retention_score} "
                f"above pre-merge max {pre_merge_max}; halt compaction"
            )
        survivors.pop(a.id, None)
        survivors.pop(b.id, None)
        survivors[merged.id] = merged
    return list(survivors.values())

def resume_plan(compacted: Sequence[Segment], required_edge: tuple[str, str, str]) -> str:
    for s in compacted:
        if (s.precondition, s.action_verb, s.terminal_outcome) == required_edge:
            return s.terminal_outcome
    raise CompactionInflationError(
        f"required decision edge {required_edge} absent from compacted trace; "
        f"resume would reconstruct wrong branch"
    )
