# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-attenuate-the-scope-narrowing-trap-in-delegation-chains.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-attenuate-the-scope-narrowing-trap-in-delegation-chains.warrant.json
# Markdown SHA-256:   987764322f600b2cf7f104134ffc0abda95566a1a8b25ca746d5e8c01de82a22
# Code AST SHA-256:   d343298d219d5f2914cc424115ed22441a459c824fc27dab062012472357f1de
# Verified Classes:   ProvenanceWitnessError, CapabilityToken
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, replace
from typing import FrozenSet, Optional


class ProvenanceWitnessError(RuntimeError):
    """Raised when a delegation step cannot derive a consistent child witness
    from the parent token, meaning the resulting chain would not be
    audit-reconstructable to a single root principal."""


@dataclass(frozen=True)
class CapabilityToken:
    root_id: str
    hop: int
    scope: FrozenSet[str]
    parent_hash: Optional[str]
    issued_at: float

    def digest(self) -> str:
        payload = f"{self.root_id}|{self.hop}|{sorted(self.scope)}|{self.parent_hash}|{self.issued_at}"
        return hashlib.sha256(payload.encode()).hexdigest()


def attenuate(
    parent: CapabilityToken,
    delegator_id: str,
    narrowed_scope: FrozenSet[str],
    issued_at: float,
) -> CapabilityToken:
    # Invariant 1: scope monotonicity (least privilege).
    if not narrowed_scope.issubset(parent.scope):
        raise ProvenanceWitnessError(
            f"scope widening rejected: {narrowed_scope} not subset of {parent.scope}"
        )

    # Invariant 2: witness immutability. The child's witness must be derived
    # from the parent token, never re-authored from the delegator's identity.
    # The delegator may only extend the chain; it may not claim to be the root.

    # Guard: a non-root delegator must have a parent_hash to extend.
    if parent.hop > 0 and parent.parent_hash is None:
        raise ProvenanceWitnessError(
            f"delegator {delegator_id} holds hop-{parent.hop} token with no parent_hash; "
            "chain continuity unprovable, refusing to mint child"
        )

    # Guard: the delegator must not equal the parent's declared root at hop > 0
    # unless it actually is the root (hop 0). Equality at hop > 0 signals a
    # prior hop rewrote root_id, and the chain is already a forest.
    if parent.hop > 0 and delegator_id == parent.root_id:
        raise ProvenanceWitnessError(
            f"delegator {delegator_id} matches parent root_id at hop {parent.hop}; "
            "prior hop corrupted root attribution, refusing to extend"
        )

    # Derive child witness by hashing forward. root_id is inherited, not assigned.
    child = replace(
        parent,
        hop=parent.hop + 1,
        scope=narrowed_scope,
        parent_hash=parent.digest(),
        issued_at=issued_at,
        root_id=parent.root_id,  # inherited, never set to delegator_id
    )

    # Post-condition: the child must be reconstructable to the parent's root.
    if child.root_id != parent.root_id:
        raise ProvenanceWitnessError(
            f"witness derivation produced root {child.root_id} != parent root {parent.root_id}"
        )
    return child


def audit_replay(leaf: CapabilityToken, chain: dict[str, CapabilityToken]) -> str:
    """Walk parent_hash backward and assert a single root principal."""
    node = leaf
    seen_roots = {node.root_id}
    while node.parent_hash is not None:
        parent = chain.get(node.parent_hash)
        if parent is None:
            raise ProvenanceWitnessError(
                f"missing parent token {node.parent_hash} at hop {node.hop}; "
                "provenance chain is broken"
            )
        seen_roots.add(parent.root_id)
        node = parent
    if len(seen_roots) != 1:
        raise ProvenanceWitnessError(
            f"provenance forest detected: roots {sorted(seen_roots)}; "
            "leaf action is not attributable to a single principal"
        )
    return node.root_id
