# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-attenuation-scope-is-satisfiable-but-whose-warrant-chain-has-been-silently-truncated.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-a-delegated-capability-token-whose-attenuation-scope-is-satisfiable-but-whose-warrant-chain-has-been-silently-truncated.warrant.json
# Markdown SHA-256:   24dcfeee16bea11b1a79292f2bb7101e1a31d7934955b37033a33289d95db5d3
# Code AST SHA-256:   d14ed6c67414057df9f338b73d6c5acef16b0e654d62031a38cda20070dd6bde
# Verified Classes:   TruncatedWarrantChainError
# Defensive Guards:   6 fail-closed invariants (zero external deps)

class TruncatedWarrantChainError(RuntimeError):
    """Raised when a delegated capability token's warrant chain is not provably maximal."""
    pass


def validate_delegated_token(token, ledger):
    """
    token: dict with keys 'token_id', 'scope', 'parent_id', 'chain' (list of token_ids)
    ledger: dict mapping token_id -> {'parent_id': str|None, 'scope': set, 'depth': int}

    Enforces chain-completeness BEFORE scope containment.
    Scope containment alone is insufficient: attenuation is monotone under truncation.
    """
    chain = token["chain"]
    if not chain or chain[-1] != token["token_id"]:
        raise TruncatedWarrantChainError(
            f"terminal token {token['token_id']} not present as chain tail"
        )

    # 1. Chain-completeness: every adjacent pair must be a true parent->child edge.
    for i in range(len(chain) - 1):
        parent_id, child_id = chain[i], chain[i + 1]
        record = ledger.get(child_id)
        if record is None:
            raise TruncatedWarrantChainError(
                f"no ledger record for {child_id}; completeness unprovable"
            )
        if record["parent_id"] != parent_id:
            raise TruncatedWarrantChainError(
                f"parent-pointer mismatch: {child_id} recorded parent "
                f"{record['parent_id']} but chain asserts {parent_id}"
            )

    # 2. Depth check: chain length must equal ledger-recorded depth of terminal token.
    terminal = ledger.get(token["token_id"])
    if terminal is None:
        raise TruncatedWarrantChainError(
            f"no ledger record for terminal {token['token_id']}"
        )
    if len(chain) != terminal["depth"]:
        raise TruncatedWarrantChainError(
            f"depth mismatch: chain length {len(chain)} != recorded depth "
            f"{terminal['depth']} for {token['token_id']}"
        )

    # 3. Only now, with a proven-complete chain, check scope attenuation transitively.
    for i in range(len(chain) - 1):
        parent_scope = ledger[chain[i]]["scope"]
        child_scope = ledger[chain[i + 1]]["scope"]
        if not child_scope.issubset(parent_scope):
            raise TruncatedWarrantChainError(
                f"attenuation violated: {chain[i+1]} scope not subset of {chain[i]}"
            )

    return True
