# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-w3c-traceparent-as-a-non-transferable-capability-rather-than-a-correlation-token-across-federated-agent-hops.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-w3c-traceparent-as-a-non-transferable-capability-rather-than-a-correlation-token-across-federated-agent-hops.warrant.json
# Markdown SHA-256:   21929833dad482dd5d226d6a22cebed948ef92c7a776e256e696c6778f311199
# Code AST SHA-256:   2de67c946d11581c036dcc4564678df603c4e15bb52b7047ddfc4c94305b7738
# Verified Classes:   TraceCapabilityConfusion, InboundHop
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hmac
import hashlib
from dataclasses import dataclass
from typing import Optional


class TraceCapabilityConfusion(RuntimeError):
    """Raised when a trace-derived value is used to gate a side effect
    without an independently verifiable signed envelope."""
    pass


@dataclass(frozen=True)
class InboundHop:
    traceparent: str          # "00-<traceid>-<parentid>-<flags>"
    tracestate: str           # caller-controlled, UNTRUSTED
    signed_envelope: Optional[bytes] = None
    envelope_sig: Optional[bytes] = None


def _parse(traceparent: str) -> tuple[str, str]:
    parts = traceparent.split("-")
    if len(parts) != 4 or parts[0] != "00":
        raise TraceCapabilityConfusion(f"malformed traceparent: {traceparent!r}")
    return parts[1], parts[2]


def resolve_hop(hop: InboundHop, signing_key: bytes) -> dict:
    traceid, parentid = _parse(hop.traceparent)

    # Correlation fields: safe to use for span linkage only.
    span_ctx = {"traceid": traceid, "parentid": parentid}

    # Any behavior-gating value MUST come from the signed envelope.
    if hop.signed_envelope is None:
        # Correlation mode: no dedup, no budget, no loop-break from trace.
        return {**span_ctx, "mode": "correlation", "idempotency_key": None,
                "depth": None, "budget": None}

    expected = hmac.new(signing_key, hop.signed_envelope, hashlib.sha256).digest()
    if not hmac.compare_digest(expected, hop.envelope_sig or b""):
        raise TraceCapabilityConfusion(
            "envelope signature invalid; refusing to derive capability from trace"
        )

    import json
    env = json.loads(hop.signed_envelope)
    # Invariant: depth and budget are authoritative only here, never from tracestate.
    if "acme" in hop.tracestate and "budget" in hop.tracestate:
        # Detect the forgery pattern: caller tries to smuggle budget via tracestate.
        if f"budget:{env['budget']}" not in hop.tracestate:
            raise TraceCapabilityConfusion(
                "tracestate budget disagrees with signed envelope; possible forgery"
            )

    return {**span_ctx, "mode": "capability",
            "idempotency_key": env["idem"], "depth": env["depth"],
            "budget": env["budget"]}


def guard_reentry(hop: InboundHop, signing_key: bytes, seen_idem: set[str]) -> str:
    ctx = resolve_hop(hop, signing_key)
    if ctx["mode"] != "capability":
        # Correlation-only hop cannot justify a loop-break or dedup decision.
        raise TraceCapabilityConfusion(
            "cannot deduplicate or break loop on correlation-only trace"
        )
    if ctx["idempotency_key"] in seen_idem:
        return "deduped"          # true retry, keyed on signed idem, not traceid
    seen_idem.add(ctx["idempotency_key"])
    if ctx["depth"] > 8:
        return "loop-abort"       # depth from envelope, not tracestate count
    return "proceed"
