# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-level-policy-violation-telemetry-as-non-authoritative-when-the-emitting-agent-retains-write-access-to-i.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-trace-level-policy-violation-telemetry-as-non-authoritative-when-the-emitting-agent-retains-write-access-to-i.warrant.json
# Markdown SHA-256:   e5ab95bcc6c3012589c1f832b6824dbdf79752cdefda5060d26a786aa6cceca8
# Code AST SHA-256:   68b224b2462bda2f2b868bd025bcb112f2df54c251aa7acb6983e1c5c36bcba4
# Verified Classes:   UntrustedVerdictError, Provenance, Attr, Span
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum
from typing import Iterable


class UntrustedVerdictError(RuntimeError):
    """Raised when a security decision would rely on an agent-writable attribute."""


class Provenance(str, Enum):
    RUNTIME = "runtime"      # sidecar / proxy / kernel: outside agent trust boundary
    AGENT = "agent"          # written by the agent process: untrusted claim


@dataclass(frozen=True)
class Attr:
    key: str
    value: str
    source: Provenance
    sealed: bool = False     # append-only + externally keyed


@dataclass
class Span:
    action_id: str | None    # externally issued; None => self-declared, unusable as join key
    attrs: dict[str, Attr] = field(default_factory=dict)
    phase: str = "outcome"   # "intent" | "outcome"


DENY_SUPPRESSING_KEYS = {"security.verdict", "policy.check.result"}


def _is_trusted_for_decision(attr: Attr) -> bool:
    if attr.source is Provenance.RUNTIME:
        return True
    # agent-written is trusted only if externally sealed AND not deny-suppressing
    return attr.sealed and attr.key not in DENY_SUPPRESSING_KEYS


def evaluate_trace(spans: Iterable[Span]) -> str:
    """
    Return "violation", "clean", or "indeterminate".
    Invariant: no agent-writable, unsealed attribute may suppress a deny.
    """
    saw_external_deny = False
    saw_agent_allow_claim = False
    saw_preemptive_verdict = False
    external_action_ids: set[str] = set()

    for span in spans:
        if span.action_id is None:
            raise UntrustedVerdictError(
                f"span phase={span.phase} has no externally issued action_id; "
                "cannot bind verdict to executed action"
            )
        external_action_ids.add(span.action_id)

        verdict_attr = span.attrs.get("security.verdict")
        if verdict_attr is None:
            continue

        if span.phase == "intent" and verdict_attr.key in DENY_SUPPRESSING_KEYS:
            # pre-emptive verdict: the signature of the pre-population attack
            saw_preemptive_verdict = True

        if not _is_trusted_for_decision(verdict_attr):
            if verdict_attr.value == "allow":
                saw_agent_allow_claim = True
            # untrusted deny is still useful for triage but cannot be sole basis
            continue

        if verdict_attr.value == "deny":
            saw_external_deny = True

    if saw_preemptive_verdict:
        raise UntrustedVerdictError(
            "pre-execution verdict present on deny-suppressing key; "
            "treat trace as indeterminate and escalate to external sensor join"
        )

    if saw_external_deny:
        return "violation"

    if saw_agent_allow_claim:
        # an agent claim of allow cannot clear the trace; require corroboration
        return "indeterminate"

    if not external_action_ids:
        raise UntrustedVerdictError("no externally bound action IDs; trace unusable")

    return "clean"


def decide(spans: Iterable[Span], external_sensor_verdict: str) -> str:
    trace_verdict = evaluate_trace(spans)
    if trace_verdict == "indeterminate":
        # default to the external sensor, never to allow
        if external_sensor_verdict not in {"clean", "violation"}:
            raise UntrustedVerdictError(
                f"external sensor verdict {external_sensor_verdict!r} unusable; "
                "refusing to default to allow"
            )
        return external_sensor_verdict
    return trace_verdict
