# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-trace-id-as-non-transferable-across-an-a2a-handoff-rather-than-a-globally-correlatable-span-key.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-trace-id-as-non-transferable-across-an-a2a-handoff-rather-than-a-globally-correlatable-span-key.warrant.json
# Markdown SHA-256:   9ae77bd1e047abb5ac05dd3eb521bdac625e373a9e97081265e475e71c61677e
# Code AST SHA-256:   c0e5b90f1812c7490a1110b5fe05c0444bfdf0654c401c4f097c2389efae2cfd
# Verified Classes:   TraceCorrelationViolation, BoundaryClass
# Defensive Guards:   1 fail-closed invariants (zero external deps)

class TraceCorrelationViolation(RuntimeError):
    """Raised when a trace_id is propagated across a boundary whose
    clock/trust/ID-allocation invariants are not satisfied."""
    pass


class BoundaryClass:
    SAME_DOMAIN = "same_domain"      # intra-process / same collector / same tenant
    CROSS_DOMAIN = "cross_domain"    # A2A peer, external MCP, sandboxed runner


def build_outbound_context(
    inbound_trace_id: str,
    inbound_span_id: str,
    boundary: str,
    clocks_synced: bool,
    span_id_namespace_disjoint: bool,
    same_tenant_partition: bool,
) -> dict:
    if boundary == BoundaryClass.SAME_DOMAIN:
        # W3C propagation is valid: one causal tree, one clock, one tenant.
        return {"traceparent": f"00-{inbound_trace_id}-{inbound_span_id}-01"}

    # Cross-domain: the inbound trace_id is a correlation token, never a span key.
    conditions_met = (
        clocks_synced
        and span_id_namespace_disjoint
        and same_tenant_partition
    )
    if conditions_met:
        # Caller has explicitly opted into single-trace semantics by
        # enforcing all four validity conditions. Propagate, but flag it.
        return {
            "traceparent": f"00-{inbound_trace_id}-{inbound_span_id}-01",
            "x-trace-mode": "forced-single-trace",
        }

    # Default and safe path: new trace, inbound recorded as a link.
    new_trace_id = _generate_trace_id()
    if new_trace_id == inbound_trace_id:
        raise TraceCorrelationViolation(
            f"trace_id generator produced collision with foreign trace "
            f"{inbound_trace_id}; span-ID namespace is not disjoint"
        )
    return {
        "traceparent": f"00-{new_trace_id}-{_generate_span_id()}-01",
        "links": [{"trace_id": inbound_trace_id, "span_id": inbound_span_id}],
        "correlation_id": inbound_trace_id,
        "x-trace-mode": "linked",
    }


def _generate_trace_id() -> str:
    import secrets
    return secrets.token_hex(16)


def _generate_span_id() -> str:
    import secrets
    return secrets.token_hex(8)
