# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-manifest-signature-replay-window-collapse-in-agent-to-agent-capability-discovery.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-manifest-signature-replay-window-collapse-in-agent-to-agent-capability-discovery.warrant.json
# Markdown SHA-256:   6c41693286801b35b923aa177eb93e536b58bf351e98f51c7cd461e391aa242c
# Code AST SHA-256:   25c2595df27261c660c34215c1220dbd5bc08aff7ddad443251bd928f99f7a43
# Verified Classes:   ManifestRotationAnomaly, Manifest, CapabilityCache
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass, field


class ManifestRotationAnomaly(RuntimeError):
    """Raised when a validly signed manifest reuses a seq with different content."""


@dataclass
class Manifest:
    issuer: str
    capability: str
    seq: int
    key_id: str
    valid_until: float
    schema: dict
    status: str = "active"

    def manifest_hash(self) -> str:
        body = json.dumps(
            {"capability": self.capability, "seq": self.seq,
             "key_id": self.key_id, "schema": self.schema, "status": self.status},
            sort_keys=True,
        )
        return hashlib.sha256(body.encode()).hexdigest()


@dataclass
class CapabilityCache:
    # keyed on (issuer, capability) -> (seq, manifest_hash, manifest)
    entries: dict = field(default_factory=dict)
    last_seen_seq: dict = field(default_factory=dict)

    def admit(self, m: Manifest, now: float) -> Manifest:
        if m.valid_until <= now:
            raise ManifestRotationAnomaly(
                f"manifest {m.capability} from {m.issuer} expired at {m.valid_until}"
            )
        key = (m.issuer, m.capability)
        prev_seq = self.last_seen_seq.get(key)
        incoming_hash = m.manifest_hash()

        if prev_seq is None or m.seq > prev_seq:
            # Strictly newer: invalidate any cached entry regardless of hash.
            self.entries[key] = (m.seq, incoming_hash, m)
            self.last_seen_seq[key] = m.seq
            return m

        if m.seq == prev_seq:
            cached_seq, cached_hash, cached = self.entries.get(key, (None, None, None))
            if cached_hash == incoming_hash:
                return cached  # idempotent re-delivery, no cache write
            # Same seq, different content, possibly rotated key: quarantine.
            raise ManifestRotationAnomaly(
                f"rotation anomaly for {key}: seq={m.seq} "
                f"cached_hash={cached_hash} incoming_hash={incoming_hash} "
                f"key_id={m.key_id}; issuer must re-issue at seq={m.seq + 1}"
            )

        # m.seq < prev_seq: replay, reject without serving cached entry.
        raise ManifestRotationAnomaly(
            f"replay rejected for {key}: seq={m.seq} < last_seen={prev_seq}"
        )

    def admissible(self, issuer: str, capability: str) -> Manifest:
        entry = self.entries.get((issuer, capability))
        if entry is None:
            raise ManifestRotationAnomaly(f"no admitted manifest for {(issuer, capability)}")
        _, _, m = entry
        if m.status != "active":
            # Deprecated capabilities must be absent, not low-ranked.
            raise ManifestRotationAnomaly(
                f"capability {capability} from {issuer} is {m.status}; exclude from composition"
            )
        return m
