# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-latent-intent-scores-as-non-composable-across-tool-call-boundaries.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-litmus-latent-intent-scores-as-non-composable-across-tool-call-boundaries.warrant.json
# Markdown SHA-256:   ab2552a95af210f3e175f01ef02efd29e02239966a22e0a2fca567fab312510c
# Code AST SHA-256:   3585eda628b77ad3c9956212d985bdd992cca31c4c0a9e9893427bcec440a305
# Verified Classes:   LatentIntentCompositionError, ScoredTurn, PendingCall
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import Literal

ADVISORY_THRESHOLD = 0.20
BLOCK_THRESHOLD = 0.35


class LatentIntentCompositionError(RuntimeError):
    """Raised when a per-turn LITMUS score is used to authorize a call
    whose referent closure was never jointly scored."""


@dataclass
class ScoredTurn:
    turn_id: int
    channel: Literal["user", "tool", "system"]
    text: str
    intent_drift: float
    tool_misuse: float

    @property
    def advisory_flagged(self) -> bool:
        return max(self.intent_drift, self.tool_misuse) >= ADVISORY_THRESHOLD


@dataclass
class PendingCall:
    tool: str
    arguments: dict[str, str]
    referent_turn_ids: set[int] = field(default_factory=set)


def resolve_referent_closure(
    call: PendingCall, history: list[ScoredTurn]
) -> set[int]:
    """Resolve argument provenance: verbatim substrings and explicit
    index references to prior turns. Returns the transitive closure."""
    by_id = {t.turn_id: t for t in history}
    closure: set[int] = set(call.referent_turn_ids)
    frontier = list(closure)
    while frontier:
        tid = frontier.pop()
        turn = by_id.get(tid)
        if turn is None:
            continue
        for arg in call.arguments.values():
            if turn.text and turn.text in arg:
                for prior in history:
                    if prior.turn_id < tid and prior.text and prior.text in turn.text:
                        if prior.turn_id not in closure:
                            closure.add(prior.turn_id)
                            frontier.append(prior.turn_id)
    return closure


def authorize_call(
    call: PendingCall,
    history: list[ScoredTurn],
    per_turn_score: float,
    joint_scorer,
) -> bool:
    closure = resolve_referent_closure(call, history)
    flagged = [tid for tid in closure if history_by_id(history, tid).advisory_flagged]

    if flagged:
        # Per-turn score is inadmissible: referent closure was advisory-flagged.
        joint = joint_scorer(closure_turns(history, closure), call)
        if joint >= BLOCK_THRESHOLD:
            raise LatentIntentCompositionError(
                f"call {call.tool!r} blocked: joint score {joint:.2f} over "
                f"referent closure {sorted(closure)} exceeds {BLOCK_THRESHOLD}; "
                f"per-turn score {per_turn_score:.2f} was non-composable"
            )
        return True

    if per_turn_score >= BLOCK_THRESHOLD:
        raise LatentIntentCompositionError(
            f"call {call.tool!r} blocked on per-turn score {per_turn_score:.2f}"
        )
    return True


def history_by_id(history: list[ScoredTurn], tid: int) -> ScoredTurn:
    for t in history:
        if t.turn_id == tid:
            return t
    raise LatentIntentCompositionError(f"unresolved referent turn_id {tid}")


def closure_turns(history: list[ScoredTurn], closure: set[int]) -> list[ScoredTurn]:
    return [t for t in history if t.turn_id in closure]
