# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-prompt-mid-flight-and-silently-drop-the-tool-call-that-authorized-the-rewrite.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-rewrite-its-own-prompt-mid-flight-and-silently-drop-the-tool-call-that-authorized-the-rewrite.warrant.json
# Markdown SHA-256:   c66eaf9e11aa027b9e1a3f702673497493443c1698e2388a40614c3095498191
# Code AST SHA-256:   bfc6af5b51f6a3bae9eab2e6028230e4d51ec7237686176b30f2ffd571c185f2
# Verified Classes:   OrphanedToolResultError, Turn, Context
# Defensive Guards:   2 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Optional


class OrphanedToolResultError(RuntimeError):
    """Raised when a tool_result arrives with no live tool_call in context."""
    pass


@dataclass
class Turn:
    kind: str  # "call" | "result" | "text" | "summary"
    call_id: Optional[str] = None
    body: str = ""


@dataclass
class Context:
    turns: list[Turn] = field(default_factory=list)

    def live_call_ids(self) -> set[str]:
        return {t.call_id for t in self.turns if t.kind == "call" and t.call_id}

    def result_call_ids(self) -> set[str]:
        return {t.call_id for t in self.turns if t.kind == "result" and t.call_id}


def apply_pruning_policy(ctx: Context, similarity_scores: dict[int, float],
                         threshold: float = 0.92) -> Context:
    """Prune turns whose similarity to a retained summary exceeds threshold.

    Guardrail: never prune a 'call' turn that has no matching 'result' yet.
    """
    open_calls = ctx.live_call_ids() - ctx.result_call_ids()
    kept: list[Turn] = []
    for i, turn in enumerate(ctx.turns):
        redundant = similarity_scores.get(i, 0.0) >= threshold
        if redundant and turn.kind == "call" and turn.call_id in open_calls:
            # In-flight commitment: must preserve identity, defer pruning.
            kept.append(turn)
            continue
        if redundant and turn.kind == "call":
            # Safe to absorb only if we emit a tombstone; here we keep it
            # verbatim to preserve call_id for result resolution.
            kept.append(turn)
            continue
        if redundant:
            continue
        kept.append(turn)
    return Context(turns=kept)


def integrate_result(ctx: Context, result: Turn) -> Context:
    if result.kind != "result" or not result.call_id:
        raise OrphanedToolResultError(
            f"malformed result turn: {result!r}"
        )
    live = ctx.live_call_ids()
    if result.call_id not in live:
        raise OrphanedToolResultError(
            f"tool_result call_id={result.call_id!r} has no live tool_call "
            f"in context; live calls={sorted(live)}. "
            "Context policy pruned the authorizing call mid-flight."
        )
    return Context(turns=ctx.turns + [result])


# --- reproduction of the observed failure ---
ctx = Context(turns=[
    Turn("text", body="plan step 3"),
    Turn("call", call_id="c7", body="fetch(url=...)"),
])
# Policy fires mid-flight; turn 1 (the call) scores 0.94 against summary.
pruned = apply_pruning_policy(ctx, similarity_scores={1: 0.94})
# Guardrail keeps the call because c7 is open -> no orphan.
integrate_result(pruned, Turn("result", call_id="c7", body="doc body"))
