# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegated-aaif-capability-chain-as-structurally-broken-rather-than-merely-expired.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-delegated-aaif-capability-chain-as-structurally-broken-rather-than-merely-expired.warrant.json
# Markdown SHA-256:   20783ff05a37e8e7e8eb2b8b3d0f029abaf6ff4ee8c4e45b138058776bd33514
# Code AST SHA-256:   c57eb3eab59fbbc7ad8753db73a806756242166908cdb42a3e06ec3d2b859fb7
# Verified Classes:   StructuralChainBreak
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class StructuralChainBreak(RuntimeError):
    """Raised when an AAIF delegated chain violates the scope-narrowing invariant
    across a re-issuance boundary, independent of temporal validity."""
    pass


def verify_delegated_capability(
    terminal_token: dict,
    reconstructed_chain: list[dict],
    last_observed_scope: dict,  # keyed by (parent_id, subject) -> frozenset of scope atoms
) -> frozenset:
    """
    Verify a terminal AAIF capability token against its reconstructed chain.
    Returns the composed scope if structurally valid; raises otherwise.
    Temporal checks (exp/not_after) are assumed already passed by the caller.
    """
    if not reconstructed_chain:
        raise StructuralChainBreak("empty chain: no lineage to compose against")

    composed = frozenset(reconstructed_chain[0]["scope"])
    for i, hop in enumerate(reconstructed_chain[1:], start=1):
        parent = reconstructed_chain[i - 1]
        if hop["parent_id"] != parent["delegation_id"]:
            raise StructuralChainBreak(
                f"lineage break at hop {i}: parent_id {hop['parent_id']!r} "
                f"does not match parent delegation_id {parent['delegation_id']!r}"
            )
        if not frozenset(hop["scope"]).issubset(frozenset(parent["scope"])):
            raise StructuralChainBreak(
                f"scope widening at hop {i}: {hop['scope']} not subset of {parent['scope']}"
            )
        if "attenuation" not in hop:
            raise StructuralChainBreak(
                f"provenance gap at hop {i}: no signed attenuation record"
            )
        composed &= frozenset(hop["scope"])

    # The non-obvious gate: re-issuance must be monotone against last-observed scope,
    # not merely a subset of the parent. This catches re-derivation from a stale baseline.
    for hop in reconstructed_chain:
        key = (hop["parent_id"], hop["subject"])
        prior = last_observed_scope.get(key)
        if prior is not None and not frozenset(hop["scope"]).issubset(prior):
            raise StructuralChainBreak(
                f"re-issuance widened scope for lineage {key}: "
                f"{hop['scope']} not subset of last-observed {sorted(prior)}"
            )

    if not frozenset(terminal_token["scope"]).issubset(composed):
        raise StructuralChainBreak(
            f"terminal token scope {terminal_token['scope']} exceeds composed grant {sorted(composed)}"
        )
    return composed
