# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-attenuates-its-own-authority-mid-delegation-and-the-audit-trail-forks.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-attenuates-its-own-authority-mid-delegation-and-the-audit-trail-forks.warrant.json
# Markdown SHA-256:   4cbe7b274475627455bb78ab0ff3507c01facbadd9384b291b1276b7ded34c52
# Code AST SHA-256:   efc97014b53b6fe04100d69d9afaa39e8fb1e2961f61d7aa1475c80449bf21fe
# Verified Classes:   WarrantForkError, Warrant, DelegationLedger
# Defensive Guards:   8 fail-closed invariants (zero external deps)

import hashlib
import time
from dataclasses import dataclass, field


class WarrantForkError(RuntimeError):
    """Raised when a warrant is mutated after it has living descendants,
    forking the non-repudiable audit trail."""


@dataclass(frozen=True)
class Warrant:
    warrant_id: str          # content hash of signed bytes
    scope: frozenset[str]
    issued_at: float
    parent_id: str | None
    _descendants: tuple[str, ...] = field(default=(), compare=False)


class DelegationLedger:
    def __init__(self) -> None:
        self._warrants: dict[str, Warrant] = {}
        self._children: dict[str, set[str]] = {}
        self._revoked: set[str] = set()

    def _hash(self, scope: frozenset[str], parent_id: str | None) -> str:
        payload = f"{sorted(scope)}|{parent_id}|{time.time_ns()}"
        return hashlib.sha256(payload.encode()).hexdigest()

    def issue(self, scope: frozenset[str], parent_id: str | None) -> Warrant:
        if parent_id is not None:
            parent = self._warrants.get(parent_id)
            if parent is None:
                raise WarrantForkError(f"parent {parent_id} unknown")
            if parent_id in self._revoked:
                raise WarrantForkError(f"parent {parent_id} revoked; no descent")
            if not scope.issubset(parent.scope):
                raise WarrantForkError("scope escalation: child exceeds parent")
        wid = self._hash(scope, parent_id)
        w = Warrant(wid, scope, time.time(), parent_id)
        self._warrants[wid] = w
        if parent_id is not None:
            self._children.setdefault(parent_id, set()).add(wid)
        return w

    def narrow_in_place(self, warrant_id: str, new_scope: frozenset[str]) -> Warrant:
        """Attempt to re-sign an existing warrant with a reduced scope.

        Legal ONLY if the warrant has no living descendants. Otherwise the
        parent's identity changes while children still commit to the old
        hash -> audit trail forks -> non-repudiation collapses.
        """
        original = self._warrants.get(warrant_id)
        if original is None:
            raise WarrantForkError(f"unknown warrant {warrant_id}")
        living = self._children.get(warrant_id, set()) - self._revoked
        if living:
            raise WarrantForkError(
                f"refusing to mutate warrant {warrant_id}: "
                f"{len(living)} living descendant(s) commit to its current hash; "
                f"issue a sibling warrant and re-delegate instead"
            )
        if not new_scope.issubset(original.scope):
            raise WarrantForkError("narrowing may not expand scope")
        new_id = self._hash(new_scope, original.parent_id)
        replacement = Warrant(new_id, new_scope, time.time(), original.parent_id)
        self._warrants[new_id] = replacement
        return replacement

    def verify_chain(self, leaf_id: str) -> list[str]:
        """Walk leaf -> root; reject any fork where a parent's audit record
        was superseded before its child was issued."""
        chain: list[str] = []
        current = leaf_id
        while current is not None:
            w = self._warrants.get(current)
            if w is None:
                raise WarrantForkError(f"dangling warrant {current} in chain")
            if current in self._revoked:
                raise WarrantForkError(f"warrant {current} revoked")
            chain.append(current)
            current = w.parent_id
        return chain


# Demonstration of the trigger condition.
ledger = DelegationLedger()
w1 = ledger.issue(frozenset({"files:read", "files:write", "net:post"}), None)
w2 = ledger.issue(frozenset({"files:read", "net:post"}), w1.warrant_id)   # descent begins
w3 = ledger.issue(frozenset({"net:post"}), w2.warrant_id)

try:
    # P tries to narrow its own authority after W2/W3 already exist.
    ledger.narrow_in_place(w1.warrant_id, frozenset({"files:read", "net:post"}))
except WarrantForkError as e:
    print(f"blocked fork: {e}")

# Correct path: freeze W1, issue a sibling, re-delegate.
w1_new = ledger.issue(frozenset({"files:read", "net:post"}), None)
print("verified leaf chain:", ledger.verify_chain(w3.warrant_id))
