# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-distinguish-a-retried-tool-call-from-a-causally-independent-duplicate-in-a-reasoning-trace.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-distinguish-a-retried-tool-call-from-a-causally-independent-duplicate-in-a-reasoning-trace.warrant.json
# Markdown SHA-256:   52e8a9ef802f03e5edf9aaaca2d9e9b117f74480ef686954413ce93877f0dcb1
# Code AST SHA-256:   3b17971798396c62c4446946edee769f4b984930a54664636709f3195fee53ce
# Verified Classes:   TraceAttributionError, ToolCallSpan
# Defensive Guards:   2 fail-closed invariants (zero external deps)

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


class TraceAttributionError(RuntimeError):
    """Raised when a tool-call span cannot be soundly attributed to a causal parent."""


@dataclass
class ToolCallSpan:
    agent_id: str
    tool_name: str
    arguments: dict
    intent_id: Optional[str]          # minted by the agent loop BEFORE the call
    context_digest: Optional[str]     # hash of the context snapshot at emission
    parent_intent_id: Optional[str] = None

    def args_hash(self) -> str:
        payload = repr(sorted(self.arguments.items())).encode()
        return hashlib.sha256(payload).hexdigest()[:16]


def attribute_causal_parent(
    span: ToolCallSpan,
    prior_spans: list[ToolCallSpan],
) -> Optional[ToolCallSpan]:
    """
    Return the causal parent of `span`, or None if it is an independent root.

    Sound attribution requires intent_id AND context_digest. Falling back to
    argument-hash identity is forbidden: it conflates retries across a context
    compaction with coincidentally identical independent calls.
    """
    if span.intent_id is None or span.context_digest is None:
        raise TraceAttributionError(
            f"span for {span.tool_name!r} lacks intent_id/context_digest; "
            "cannot attribute causally. Emit 'unattributed' instead of "
            "guessing from argument hash."
        )

    # Explicit retry edge from the loop is authoritative.
    if span.parent_intent_id is not None:
        for prior in prior_spans:
            if prior.intent_id == span.parent_intent_id:
                if prior.context_digest != span.context_digest:
                    # Retry issued after context changed (compaction/retrieval).
                    # Still a causal child, but flagged: the retry is NOT a
                    # clean continuation of the prior decision state.
                    span.parent_intent_id = prior.intent_id
                return prior
        raise TraceAttributionError(
            f"parent_intent_id {span.parent_intent_id!r} not found in trace; "
            "state transfer or span loss suspected."
        )

    # No explicit edge: only link if the loop reused an intent_id (same call,
    # same context). Argument-hash matches are NOT sufficient.
    for prior in prior_spans:
        if (
            prior.intent_id == span.intent_id
            and prior.context_digest == span.context_digest
        ):
            return prior

    # Independent root. A same-args prior with a different context_digest is
    # deliberately NOT linked — this is the boundary case.
    for prior in prior_spans:
        if (
            prior.tool_name == span.tool_name
            and prior.args_hash() == span.args_hash()
            and prior.context_digest != span.context_digest
        ):
            # Do not raise here; record as independent but surface the signal.
            span.parent_intent_id = None
            break

    return None
