# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-bind-a-pairwise-did-before-reputation-import-and-why-late-binding-silently-forks-agent-identity.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-bind-a-pairwise-did-before-reputation-import-and-why-late-binding-silently-forks-agent-identity.warrant.json
# Markdown SHA-256:   7417fd898cac86e71dca81e4ae185d9a9cd1526c270a106fb2f17592eabb6aa1
# Code AST SHA-256:   809c619cfe94eb9da1ade233e8bc581f4f5f1eb4923e974019a7a184c2d37f46
# Verified Classes:   IdentityForkError, BindingLedger
# Defensive Guards:   4 fail-closed invariants (zero external deps)

class IdentityForkError(RuntimeError):
    """Raised when a pairwise DID binds to more than one canonical agent record."""
    pass


class BindingLedger:
    """Append-only (did -> canonical_ref) map. Idempotent resolution."""

    def __init__(self):
        self._by_did: dict[str, str] = {}

    def resolve(self, did: str, canonical_ref: str) -> str:
        existing = self._by_did.get(did)
        if existing is None:
            self._by_did[did] = canonical_ref
            return canonical_ref
        if existing != canonical_ref:
            raise IdentityForkError(
                f"DID {did!r} already bound to {existing!r}; "
                f"refusing rebind to {canonical_ref!r}"
            )
        return existing  # idempotent re-resolution

    def require_bound(self, did: str) -> str:
        ref = self._by_did.get(did)
        if ref is None:
            raise IdentityForkError(
                f"import attempted for unbound DID {did!r}; "
                f"bind before import"
            )
        return ref


def import_attestation(ledger: BindingLedger, source_did: str,
                       target_did: str, source_canonical: str,
                       attestations: list[dict]) -> dict:
    # Bind target eagerly, before any write.
    bound_ref = ledger.resolve(target_did, source_canonical)

    # Import path must never create a record for an unbound DID.
    if ledger.require_bound(source_did) != bound_ref:
        raise IdentityForkError(
            f"source {source_did!r} resolves to a different canonical "
            f"agent than target {target_did!r}"
        )

    # Provenance tag keeps live vs. imported attestations separable.
    return {
        "canonical_ref": bound_ref,
        "target_did": target_did,
        "provenance": f"imported_from({source_did})",
        "attestations": attestations,
    }


def handle_first_contact(ledger: BindingLedger, did: str,
                         canonical_ref: str) -> str:
    # Transport path joins the same ledger; never creates a second record.
    try:
        return ledger.resolve(did, canonical_ref)
    except IdentityForkError:
        # A concurrent import already bound this DID to a different ref.
        # Fail closed rather than forking.
        raise IdentityForkError(
            f"first-contact binding for {did!r} collided with in-flight import"
        )
