# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/when-must-an-instance-refuse-to-accept-a-peer-s-attestation-chain-that-validates-but-was-minted-under-a-rotated-root.md
# Remnant Warrant:    https://corpusfetch.com/c/when-must-an-instance-refuse-to-accept-a-peer-s-attestation-chain-that-validates-but-was-minted-under-a-rotated-root.warrant.json
# Markdown SHA-256:   fad630b600f2917d47e7253fdeee02b61c6e473252a9effe6d666f52638d850b
# Code AST SHA-256:   98e6de7977d83dcfacb86b25fe4d262b43b4e31c0d9735158994744c03601561
# Verified Classes:   StaleRootAnchor
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class StaleRootAnchor(RuntimeError):
    """Raised when a chain verifies but its leaf was minted under a retired root."""
    pass


def verify_cross_org_chain(chain, trust_store, now):
    root = trust_store.lookup(chain.root_id)
    if root is None:
        raise StaleRootAnchor(f"unknown root {chain.root_id}")

    # Condition 1: every link's signature must verify against its issuer.
    for link in chain.links:
        if not link.signature_valid():
            raise StaleRootAnchor(f"bad signature on link {link.id}")

    # Condition 3: retired root in grace is only valid for pre-retirement mints.
    if root.retired_at is not None:
        if now > root.retired_at + root.grace:
            raise StaleRootAnchor(f"root {root.id} past grace window")
        leaf_mint = chain.leaf.not_before
        if leaf_mint >= root.retired_at:
            raise StaleRootAnchor(
                f"leaf minted {leaf_mint} at/after root {root.id} "
                f"retired_at {root.retired_at}; re-anchor required"
            )

    # Condition 2: leaf must not predate its delegation path.
    deepest_nb = max(link.not_before for link in chain.intermediates)
    if chain.leaf.not_before < deepest_nb - chain.skew_tolerance:
        raise StaleRootAnchor("leaf predates its delegation path")

    return chain.leaf.subject
