# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-when-a-unified-agent-run-ledger-silently-splits-one-logical-run-into-two-traces.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-when-a-unified-agent-run-ledger-silently-splits-one-logical-run-into-two-traces.warrant.json
# Markdown SHA-256:   5c225b52f9b33243f2581c7f290a89de2023a29b453b4145481ab05dc47c1e76
# Code AST SHA-256:   212b13831e8fa8aa20da3f58f4b778c8b22706d8a123fd90d41f805f653b4873
# Verified Classes:   LedgerBifurcation, TraceTree
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Optional


class LedgerBifurcation(RuntimeError):
    """Raised when one logical run is split across two ledger keys."""


@dataclass
class TraceTree:
    run_id: str
    session_id: str
    first_span_ts: float
    last_span_ts: float
    step_count: int
    safety_events: list = field(default_factory=list)
    eval_verdict: Optional[str] = None


def derive_key(session_id: str, first_user_turn: str) -> str:
    # Content-derived key: subject to truncation/normalization drift.
    return hashlib.sha256(f"{session_id}|{first_user_turn}".encode()).hexdigest()[:16]


def detect_bifurcation(
    closed: list[TraceTree],
    incoming: TraceTree,
    adjacency_window_s: float = 30.0,
) -> None:
    """Structural detector: contiguous-but-disjoint trace trees under
    different run_ids in the same session constitute a bifurcation."""
    for prior in closed:
        if prior.run_id == incoming.run_id:
            continue
        if prior.session_id != incoming.session_id:
            continue
        gap = incoming.first_span_ts - prior.last_span_ts
        if 0.0 <= gap <= adjacency_window_s:
            raise LedgerBifurcation(
                f"run split across keys {prior.run_id!r} -> {incoming.run_id!r} "
                f"in session {incoming.session_id!r}; gap={gap:.3f}s, "
                f"steps {prior.step_count}+{incoming.step_count}; "
                f"prior safety={prior.safety_events}, "
                f"prior eval={prior.eval_verdict!r}"
            )


def ingest(closed: list[TraceTree], incoming: TraceTree) -> None:
    detect_bifurcation(closed, incoming)
    closed.append(incoming)


# Reproduction: truncation at handoff changes the re-derived key.
session = "S-42"
full_turn = "Summarize the diff between v1 and v2 of the contract, then flag PII."
truncated = full_turn[:40]  # context-budget truncation at sub-agent handoff

orchestrator = TraceTree(
    run_id=derive_key(session, full_turn),
    session_id=session,
    first_span_ts=1000.0,
    last_span_ts=1042.0,
    step_count=9,
    safety_events=["pii_redaction@step6"],
    eval_verdict=None,
)
sub_agent = TraceTree(
    run_id=derive_key(session, truncated),  # re-derived: digest differs
    session_id=session,
    first_span_ts=1043.0,
    last_span_ts=1101.0,
    step_count=5,
    safety_events=["policy_refusal@step12"],
    eval_verdict="pass",
)

ingest([orchestrator], sub_agent)  # raises LedgerBifurcation
