# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-was-narrowed-mid-chain-but-whose-attenuation-proof-still-verifies.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-reject-a-delegated-aaif-credential-whose-scope-was-narrowed-mid-chain-but-whose-attenuation-proof-still-verifies.warrant.json
# Markdown SHA-256:   d3bde97964e4129c63e1f83a57c9bf2232a58fd5bdda0f0a5e3bd57124266ca5
# Code AST SHA-256:   e765cc6776b1497c103c07d6b114fce1d4154d1a014bd06b37c7f1851177c5f2
# Verified Classes:   ScopeSatisfiabilityError, ChainSoundnessError, Capability, Credential
# Defensive Guards:   4 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field
from typing import FrozenSet


class ScopeSatisfiabilityError(RuntimeError):
    """Raised when an AAIF proof verifies but the effective scope does not cover the action."""


class ChainSoundnessError(RuntimeError):
    """Raised when the attenuation proof itself fails to verify."""


@dataclass(frozen=True)
class Capability:
    kind: str          # e.g. "fs.read", "fs.write", "net.http"
    resource: str      # e.g. "/data/inputs/2024/**"

    def covers(self, other: "Capability") -> bool:
        # Same kind required; resource must be a prefix-narrowing of self.
        if self.kind != other.kind:
            return False
        return other.resource.startswith(self.resource.rstrip("*"))


@dataclass(frozen=True)
class Credential:
    scope: FrozenSet[Capability]
    proof_digest: str
    parent_digest: str | None


def verify_attenuation_proof(cred: Credential, parent_scope: FrozenSet[Capability] | None) -> bool:
    # Soundness only: every capability in cred.scope must be covered by parent_scope.
    if parent_scope is None:
        return True  # root
    return all(any(p.covers(c) for p in parent_scope) for c in cred.scope)


def effective_scope(received: FrozenSet[Capability], host_profile: FrozenSet[Capability]) -> FrozenSet[Capability]:
    # Intersection: a capability survives only if some host-profile cap covers it.
    return frozenset(
        c for c in received
        if any(h.covers(c) for h in host_profile)
    )


def authorize(
    cred: Credential,
    parent_scope: FrozenSet[Capability] | None,
    host_profile: FrozenSet[Capability],
    required: FrozenSet[Capability],
) -> FrozenSet[Capability]:
    # Gate 1: chain soundness (what AAIF verifies).
    if not verify_attenuation_proof(cred, parent_scope):
        raise ChainSoundnessError(
            f"attenuation proof failed for credential {cred.proof_digest}"
        )

    # Gate 2: satisfiability (what AAIF does NOT verify).
    eff = effective_scope(cred.scope, host_profile)
    if not eff:
        raise ScopeSatisfiabilityError(
            f"effective scope empty after host intersection; "
            f"credential {cred.proof_digest} is sound but unusable"
        )

    missing = [r for r in required if not any(e.covers(r) for e in eff)]
    if missing:
        raise ScopeSatisfiabilityError(
            f"proof {cred.proof_digest} verifies but effective scope does not cover "
            f"required capabilities {sorted((m.kind, m.resource) for m in missing)}; "
            f"effective={sorted((e.kind, e.resource) for e in eff)}"
        )

    return eff


# --- Reproduction of the observed trace ---

root = frozenset({
    Capability("fs.read", "/data/**"),
    Capability("fs.write", "/data/out/**"),
    Capability("net.http", "api.internal"),
})
planner_scope = frozenset({
    Capability("fs.read", "/data/inputs/**"),
    Capability("fs.write", "/data/out/**"),
})
planner_cred = Credential(planner_scope, "d1", "d0")

executor_host_profile = frozenset({
    Capability("fs.read", "/data/inputs/2024/**"),
    Capability("net.http", "api.internal"),
})
executor_cred = Credential(planner_scope, "d2", "d1")

required = frozenset({Capability("fs.write", "/data/out/**")})

# Proof verifies (both hops are subsets) — this is the trap.
assert verify_attenuation_proof(executor_cred, planner_scope) is True

# But satisfiability fails; the guardrail must fire.
try:
    authorize(executor_cred, planner_scope, executor_host_profile, required)
except ScopeSatisfiabilityError as e:
    print(f"DENY: {e}")
    # Record the triple for audit replay, not just the proof digest.
