# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-handle-delegated-credential-scope-collapse-when-a-per-tool-capability-attestation-is-satisfied-by-an-ancestor-warrant-rather-th.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-handle-delegated-credential-scope-collapse-when-a-per-tool-capability-attestation-is-satisfied-by-an-ancestor-warrant-rather-th.warrant.json
# Markdown SHA-256:   e0ca4e3336aad848383f739d70352212909d306a90d7c84ebc7d720d507a280d
# Code AST SHA-256:   934355012d587c1adfd41354461237b89940e9611b4295dd103188361dfdece2
# Verified Classes:   AttestationWitnessMismatch, ScopeMonotonicityViolation, Warrant
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationWitnessMismatch(RuntimeError):
    """Raised when a tool's capability attestation is satisfied by a warrant
    node other than the presented leaf, without an explicit delegation record
    joining that node to the leaf."""
    pass


class ScopeMonotonicityViolation(RuntimeError):
    """Raised when a leaf warrant's scope is not a subset of its parent's,
    i.e. the attenuation chain widened instead of narrowing."""
    pass


@dataclass(frozen=True)
class Warrant:
    node_id: str
    parent_id: str | None
    scope: frozenset[str]
    capabilities: frozenset[str]
    signature: str

    def digest(self) -> str:
        h = hashlib.sha256()
        h.update(self.node_id.encode())
        h.update(b"|")
        h.update(",".join(sorted(self.scope)).encode())
        h.update(b"|")
        h.update(",".join(sorted(self.capabilities)).encode())
        return h.hexdigest()


def _walk_to_root(leaf: Warrant, by_id: dict[str, Warrant]) -> list[Warrant]:
    chain = [leaf]
    cur = leaf
    while cur.parent_id is not None:
        parent = by_id.get(cur.parent_id)
        if parent is None:
            raise AttestationWitnessMismatch(
                f"broken chain: parent {cur.parent_id!r} of {cur.node_id!r} not found"
            )
        chain.append(parent)
        cur = parent
    return chain


def verify_scope_lattice(leaf: Warrant, by_id: dict[str, Warrant]) -> None:
    """Recompute scope(child) subset-of scope(parent) at every edge."""
    chain = _walk_to_root(leaf, by_id)
    for child, parent in zip(chain, chain[1:]):
        if not child.scope.issubset(parent.scope):
            raise ScopeMonotonicityViolation(
                f"edge {child.node_id!r}->{parent.node_id!r}: scope widened "
                f"({sorted(child.scope - parent.scope)} not in parent)"
            )


def attest_capability(
    leaf: Warrant,
    required_cap: str,
    by_id: dict[str, Warrant],
    delegation_edges: set[tuple[str, str, str]],
) -> str:
    """Return the witness node id for `required_cap`, or raise if the only
    witnesses are ancestors not joined to the leaf by a delegation record.

    A delegation edge is (from_node, to_node, capability) and must form a
    contiguous path from witness down to leaf.
    """
    verify_scope_lattice(leaf, by_id)
    chain = _walk_to_root(leaf, by_id)

    for node in chain:
        if required_cap not in node.capabilities:
            continue
        if node.digest() == leaf.digest():
            return node.node_id
        # Ancestor carries the cap; require a delegation path down to leaf.
        path_ok = _has_delegation_path(
            node.node_id, leaf.node_id, required_cap, delegation_edges, by_id
        )
        if path_ok:
            return node.node_id

    raise AttestationWitnessMismatch(
        f"capability {required_cap!r} not attested for leaf {leaf.node_id!r}: "
        f"no witness at leaf and no delegation path from any ancestor"
    )


def _has_delegation_path(
    src: str,
    dst: str,
    cap: str,
    edges: set[tuple[str, str, str]],
    by_id: dict[str, Warrant],
) -> bool:
    # BFS over delegation edges restricted to `cap`, from src toward dst.
    frontier = {src}
    seen = {src}
    while frontier:
        nxt: set[str] = set()
        for u in frontier:
            for (a, b, c) in edges:
                if a == u and c == cap and b not in seen:
                    if b == dst:
                        return True
                    seen.add(b)
                    nxt.add(b)
        frontier = nxt
    return False


def tool_read(
    leaf: Warrant,
    path: str,
    by_id: dict[str, Warrant],
    delegation_edges: set[tuple[str, str, str]],
) -> str:
    attest_capability(leaf, "cap:file_read", by_id, delegation_edges)
    if not any(path.startswith(p.rstrip("*")) for p in leaf.scope if p.startswith("fs:read:")):
        raise AttestationWitnessMismatch(
            f"path {path!r} outside leaf scope {sorted(leaf.scope)}"
        )
    return path


# --- Reproduction of the observed collapse -----------------------------------
#
# W0 (root)  scope {fs:read:/data/**}          caps {cap:file_read}
# W1         scope {fs:read:/data/reports/**}   caps {cap:file_read}   (copied)
# W2         scope {fs:read:/data/reports/q3/**} caps {cap:file_read}  (copied)
# W2'        scope {fs:read:/data/**}           caps {cap:file_read}   (widened leaf)
#
# With the naive upward-search attestation and no lattice check, W2' attests
# against W0 and reads /data/secrets/keys. With the guardrail above, the
# widened edge is rejected before attestation is consulted.

if __name__ == "__main__":
    by_id = {
        "W0": Warrant("W0", None, frozenset({"fs:read:/data/**"}), frozenset({"cap:file_read"}), "sig0"),
        "W1": Warrant("W1", "W0", frozenset({"fs:read:/data/reports/**"}), frozenset({"cap:file_read"}), "sig1"),
        "W2": Warrant("W2", "W1", frozenset({"fs:read:/data/reports/q3/**"}), frozenset({"cap:file_read"}), "sig2"),
        "W2p": Warrant("W2p", "W1", frozenset({"fs:read:/data/**"}), frozenset({"cap:file_read"}), "sig2p"),
    }
    try:
        tool_read(by_id["W2p"], "/data/secrets/keys", by_id, delegation_edges=set())
    except ScopeMonotonicityViolation as e:
        print(f"REJECTED widened leaf: {e}")

    # Even with a monotonic chain, an ancestor-only witness without a
    # delegation record must not satisfy a leaf check.
    by_id["W2n"] = Warrant("W2n", "W1", frozenset({"fs:read:/data/reports/q3/**"}), frozenset(), "sig2n")
    try:
        tool_read(by_id["W2n"], "/data/reports/q3/x", by_id, delegation_edges=set())
    except AttestationWitnessMismatch as e:
        print(f"REJECTED ancestor-only witness: {e}")
