# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-capability-tokens-when-an-aaif-attestation-chain-is-re-rooted-mid-execution.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-delegated-capability-tokens-when-an-aaif-attestation-chain-is-re-rooted-mid-execution.warrant.json
# Markdown SHA-256:   bb2cf2555e57f32bb6094b3263b77d524ca1b1487ef63f90e604e4cbc3e97100
# Code AST SHA-256:   dc2a5262e986038a142e7b974bf5e542e2905383c1a2bdd7db429a247dd7fb9b
# Verified Classes:   AttestationReRootingError, CapabilityDenied
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class AttestationReRootingError(RuntimeError):
    """Raised when a delegation chain cannot be reconciled against a rotated root."""
    pass


class CapabilityDenied(RuntimeError):
    """Raised when a DCT is valid but the requested scope is not granted."""
    pass


def reconcile_delegation(dct: dict, trust_store: dict, now: int) -> str:
    """
    Returns one of: 'valid', 'rotation_in_progress', 'dead'.
    Raises AttestationReRootingError if the DCT cannot be classified,
    and CapabilityDenied only for genuine scope violations.
    """
    root_epoch = dct.get("root_epoch")
    if root_epoch is None:
        # Unreconcilable: cannot tell which root this was valid against.
        raise AttestationReRootingError(
            f"DCT {dct.get('id')} carries no root_epoch; "
            "cannot reconcile under re-rooting. Re-mint required."
        )

    record = trust_store.get(root_epoch)
    if record is None:
        raise AttestationReRootingError(
            f"No trust record for root_epoch={root_epoch}; "
            "verifier window too short or DCT forged."
        )

    if record["status"] == "current":
        return "valid"

    if record["status"] == "revoked":
        grace_until = record.get("grace_until", 0)
        if now < grace_until:
            return "rotation_in_progress"
        return "dead"

    raise AttestationReRootingError(
        f"Unknown trust status {record['status']!r} for epoch {root_epoch}."
    )


def execute_tool_call(dct: dict, scope: str, trust_store: dict, now: int) -> None:
    state = reconcile_delegation(dct, trust_store, now)

    if state == "dead":
        raise AttestationReRootingError(
            f"Delegation for scope {scope!r} is dead (root rotated past grace). "
            "Halt dependent sub-task; request fresh delegation."
        )
    if state == "rotation_in_progress":
        # Continue, but flag for re-issue at next checkpoint.
        dct["_needs_reissue"] = True
        return
    if scope not in dct.get("scopes", []):
        raise CapabilityDenied(f"Scope {scope!r} not granted by DCT {dct.get('id')}.")
