# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-delegated-aaif-capability-that-was-revoked-at-the-origin-root.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-delegated-aaif-capability-that-was-revoked-at-the-origin-root.warrant.json
# Markdown SHA-256:   112fb899e0118698c9497d47e00ab906492c27abf16bb973b6b9b5e8e4da9b66
# Code AST SHA-256:   2b331550740f39e28a1fa712d2736176ef6096224fb92684ebddac9c2a032792
# Verified Classes:   AncestorRevocationUnresolved, Capability
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class AncestorRevocationUnresolved(RuntimeError):
    """Raised when a delegated capability's parent chain cannot be fully
    verified against every ancestor's origin revocation set."""
    pass


class Capability:
    def __init__(self, cap_id, issuer, origin, parent, not_after):
        self.cap_id = cap_id
        self.issuer = issuer          # root that signed this hop
        self.origin = origin          # root that authorized the root capability
        self.parent = parent          # Capability or None
        self.not_after = not_after


def verify_chain(cap, revocation_sets, now):
    """Chain-walk verification: every ancestor must be unrevoked at its origin.

    revocation_sets: dict root_id -> set of revoked cap_ids
    Fail-closed: an ancestor whose origin revocation set is unreachable
    raises rather than defaulting to valid.
    """
    node = cap
    while node is not None:
        if node.origin not in revocation_sets:
            raise AncestorRevocationUnresolved(
                f"cannot resolve revocation set for origin root "
                f"{node.origin!r} while verifying {node.cap_id!r}; "
                f"refusing to treat as valid"
            )
        if node.cap_id in revocation_sets[node.origin]:
            raise AncestorRevocationUnresolved(
                f"capability {node.cap_id!r} revoked at origin root "
                f"{node.origin!r}; descendant chain invalid"
            )
        if now >= node.not_after:
            raise AncestorRevocationUnresolved(
                f"capability {node.cap_id!r} expired at {node.not_after}"
            )
        node = node.parent
    return True


def execute_write(cap, revocation_sets, now):
    # Hop-local check alone would pass here even after origin revocation.
    if cap.issuer not in revocation_sets:
        raise AncestorRevocationUnresolved(
            f"issuer revocation set unreachable for {cap.issuer!r}"
        )
    verify_chain(cap, revocation_sets, now)
    return "write-executed"
