# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/which-invariants-prevent-capability-shadowing-during-federated-agent-registry-anti-entropy-merges.md
# Remnant Warrant:    https://corpusfetch.com/c/which-invariants-prevent-capability-shadowing-during-federated-agent-registry-anti-entropy-merges.warrant.json
# Markdown SHA-256:   33dbaacc152791c8a1ec2d5876c77097b67dde07d67a6f6f72317908682cc5f2
# Code AST SHA-256:   b1137239547ce7c38d9053e54391344f976b1f4b048be9baf553d7e0a9ba617a
# Verified Classes:   CapabilityShadowingError, CapabilityRecord
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import FrozenSet, Optional


class CapabilityShadowingError(RuntimeError):
    """Raised when a merged registry record is not traceable to a single
    atomic emission from the owning agent (violates invariants I1-I3)."""


@dataclass(frozen=True)
class CapabilityRecord:
    agent_id: str
    epoch: int
    schema_version: str
    capability_set: FrozenSet[str]
    signature: str  # over (agent_id, epoch, schema_version, capability_set)

    def canonical(self) -> bytes:
        caps = ",".join(sorted(self.capability_set))
        return f"{self.agent_id}|{self.epoch}|{self.schema_version}|{caps}".encode()


def _sign(record: CapabilityRecord, key: bytes) -> str:
    return hashlib.sha256(key + record.canonical()).hexdigest()


def verify_emission(record: CapabilityRecord, key: bytes) -> None:
    """I1: the record must be a single signed emission as a unit."""
    if _sign(record, key) != record.signature:
        raise CapabilityShadowingError(
            f"record for {record.agent_id}@epoch={record.epoch} is not a "
            f"single atomic emission: signature mismatch"
        )


def merge_records(
    local: CapabilityRecord,
    remote: CapabilityRecord,
    key: bytes,
) -> CapabilityRecord:
    """I2: epoch dominance, whole-record. I3: retraction closure by epoch."""
    if local.agent_id != remote.agent_id:
        raise CapabilityShadowingError(
            f"cannot merge records for distinct agents: "
            f"{local.agent_id} vs {remote.agent_id}"
        )
    verify_emission(local, key)
    verify_emission(remote, key)

    if local.epoch == remote.epoch:
        if local.canonical() != remote.canonical():
            # Same epoch, different content: a fork at the emitter. Do not pick.
            raise CapabilityShadowingError(
                f"forked emission for {local.agent_id} at epoch={local.epoch}: "
                f"{local.capability_set} vs {remote.capability_set}"
            )
        return local

    winner = local if local.epoch > remote.epoch else remote
    # I3: the winner's capability_set is authoritative; the loser's additions
    # are NOT carried forward. This is the line whose absence caused shadowing.
    return winner


def serve_capability(
    record: CapabilityRecord,
    requested_version: str,
    key: bytes,
) -> FrozenSet[str]:
    verify_emission(record, key)
    if requested_version != record.schema_version:
        raise CapabilityShadowingError(
            f"caller expects schema {requested_version} but {record.agent_id} "
            f"advertises {record.schema_version} at epoch={record.epoch}; "
            f"refusing to serve a shadowed capability set"
        )
    return record.capability_set
