# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-peer-s-policy-bundle-before-its-own-trust-root-has-been-anchored-policy-precedence-inversion-at-the.md
# Remnant Warrant:    https://corpusfetch.com/c/what-happens-when-an-instance-accepts-a-federated-peer-s-policy-bundle-before-its-own-trust-root-has-been-anchored-policy-precedence-inversion-at-the.warrant.json
# Markdown SHA-256:   52c5571444c1e1fccf515e9a130bfbc5a8aa40173c44bb6276c3f4de149c865b
# Code AST SHA-256:   64bb912f48a9e89b17fefa9fc9c608a48a94e06b7306fb3bc29533ccf5e89cfd
# Verified Classes:   TrustBoundaryError, ArtifactState, TrustRoot, PeerBundle
# Defensive Guards:   2 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class TrustBoundaryError(RuntimeError):
    """Raised when a federated policy artifact crosses the trust boundary
    without satisfying the anchoring-before-materialization invariant, or
    when a cross-root merge is attempted with a non-intersecting operator."""


class ArtifactState(Enum):
    SPOOLED = "spooled"          # written by transport, NOT evaluator-visible
    ANCHORED = "anchored"        # peer chain verified to local root
    MATERIALIZED = "materialized"  # committed to policy store, evaluator-visible


@dataclass
class TrustRoot:
    root_id: str
    pinned_intermediates: frozenset[str] = frozenset()


@dataclass
class PeerBundle:
    peer_id: str
    cert_chain: list[str]
    grants: dict[str, set[str]]  # principal -> capabilities
    bundle_sig: str
    state: ArtifactState = ArtifactState.SPOOLED
    local_root: Optional[TrustRoot] = None


def anchor_and_materialize(
    bundle: PeerBundle,
    local_root: TrustRoot,
    spool_dir: str,
    policy_store_dir: str,
) -> PeerBundle:
    """The only function permitted to move an artifact from SPOOLED to
    MATERIALIZED. Enforces: (1) chain anchored before materialization,
    (2) merge operator selected by root comparison, (3) abort is total.
    """
    # Invariant 1: identity gate precedes materialization.
    if not _chain_anchors_to(bundle.cert_chain, local_root):
        # Total abort: delete the spooled artifact so no globbing evaluator
        # can observe it. This is the step the incident's abort path skipped.
        _delete_spooled(spool_dir, bundle.peer_id)
        raise TrustBoundaryError(
            f"peer {bundle.peer_id!r} chain does not anchor to "
            f"local root {local_root.root_id!r}; spooled artifact purged, "
            f"no grants materialized"
        )

    if not _verify_bundle_sig(bundle):
        _delete_spooled(spool_dir, bundle.peer_id)
        raise TrustBoundaryError(
            f"peer {bundle.peer_id!r} bundle signature invalid; purged"
        )

    bundle.state = ArtifactState.ANCHORED
    bundle.local_root = local_root

    # Invariant 2: merge operator is selected by trust-boundary crossing.
    # peer_root is carried in the bundle; if it differs from local_root,
    # the only sound operator is intersection (both orgs' policies apply).
    peer_root_id = _peer_root_of(bundle.cert_chain)
    if peer_root_id != local_root.root_id:
        effective = _intersect_grants(bundle.grants, _local_grants())
    else:
        effective = _union_grants(bundle.grants, _local_grants())

    # Invariant 3: materialization is the atomic commit that makes the
    # artifact visible to the evaluator. Rename is atomic within a store.
    _atomic_commit(policy_store_dir, bundle.peer_id, effective)
    bundle.state = ArtifactState.MATERIALIZED
    return bundle


def evaluate_policy(policy_store_dir: str, principal: str) -> set[str]:
    """Evaluator read path. By construction it can only name the policy
    store, never the spool. A globbing evaluator that reaches the spool
    is the defect this function's signature is meant to make impossible."""
    return _read_store(policy_store_dir, principal)


# --- stubs for the surrounding system (elided in the record) ---
def _chain_anchors_to(chain: list[str], root: TrustRoot) -> bool:
    return any(link in root.pinned_intermediates for link in chain)

def _verify_bundle_sig(b: PeerBundle) -> bool:
    return hashlib.sha256(repr(sorted(b.grants.items())).encode()).hexdigest() == b.bundle_sig

def _peer_root_of(chain: list[str]) -> str:
    return chain[-1] if chain else ""

def _local_grants() -> dict[str, set[str]]:
    return {}

def _intersect_grants(a: dict[str, set[str]], b: dict[str, set[str]]) -> dict[str, set[str]]:
    return {k: a[k] & b.get(k, set()) for k in a}

def _union_grants(a: dict[str, set[str]], b: dict[str, set[str]]) -> dict[str, set[str]]:
    return {k: a.get(k, set()) | b.get(k, set()) for k in set(a) | set(b)}

def _delete_spooled(spool_dir: str, peer_id: str) -> None:
    pass

def _atomic_commit(store_dir: str, peer_id: str, effective: dict[str, set[str]]) -> None:
    pass

def _read_store(store_dir: str, principal: str) -> set[str]:
    return set()
