# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-skill-manifest-poisoning-when-a-late-registered-tool-shadows-an-already-attested-capability.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-skill-manifest-poisoning-when-a-late-registered-tool-shadows-an-already-attested-capability.warrant.json
# Markdown SHA-256:   064ebefa9bf6dc582d21323b0f399fdc1a27acedaad1f7c48d542bbcc6565d8b
# Code AST SHA-256:   1b34730692e26dcb227d623a4adef6665026ce25b69b597db15a513fb67dd519
# Verified Classes:   ManifestPoisoningError, Attestation, CapabilityManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

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

class ManifestPoisoningError(RuntimeError):
    """Raised when a skill registration attempts to rebind or shadow an attested capability."""
    pass

@dataclass(frozen=True)
class Attestation:
    name: str
    schema_hash: str
    impl_hash: str

    def key(self) -> str:
        return f"{self.name}:{self.schema_hash}:{self.impl_hash}"

def _hash(obj: str) -> str:
    return hashlib.sha256(obj.encode()).hexdigest()[:16]

@dataclass
class CapabilityManifest:
    attested: Dict[str, Attestation] = field(default_factory=dict)
    frozen_names: set = field(default_factory=set)

    def attest(self, name: str, schema: str, impl: str) -> Attestation:
        att = Attestation(name, _hash(schema), _hash(impl))
        self.attested[name] = att
        return att

    def register_runtime_skill(self, name: str, schema: str, impl: str,
                               similarity_to_attested: float = 0.0) -> Attestation:
        new = Attestation(name, _hash(schema), _hash(impl))

        if name in self.frozen_names:
            raise ManifestPoisoningError(
                f"name '{name}' is frozen after prior poisoning attempt; registration refused"
            )

        existing = self.attested.get(name)
        if existing is not None:
            if existing.key() != new.key():
                self.frozen_names.add(name)
                raise ManifestPoisoningError(
                    f"rebind of attested capability '{name}': "
                    f"{existing.key()} -> {new.key()} without unregister/grant"
                )
            return existing

        if similarity_to_attested >= 0.90:
            self.frozen_names.add(name)
            raise ManifestPoisoningError(
                f"near-duplicate skill '{name}' (sim={similarity_to_attested:.2f}) "
                f"shadows an attested capability; quarantined for operator review"
            )

        self.attested[name] = new
        return new

    def resolve(self, name: str, expected: Attestation) -> Attestation:
        current = self.attested.get(name)
        if current is None or current.key() != expected.key():
            raise ManifestPoisoningError(
                f"resolution divergence for '{name}': planner pinned {expected.key()}, "
                f"registry now holds {current.key() if current else 'NONE'}"
            )
        return current
