# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-detect-a-manifest-drift-skill-injection-before-the-poisoned-description-reaches-the-planner-context.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-detect-a-manifest-drift-skill-injection-before-the-poisoned-description-reaches-the-planner-context.warrant.json
# Markdown SHA-256:   ec48e93f259ac2dac61232083a5e8edea0f97b5201c56645b96e46e1f57e28d4
# Code AST SHA-256:   2b0aa102265469174ebd8203ccd8eb677b1553eabf9c423a047a12a63eefde68
# Verified Classes:   SkillManifestDriftError, CapabilityEnvelopeViolation, SignedManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import unicodedata
from dataclasses import dataclass
from typing import Optional


class SkillManifestDriftError(RuntimeError):
    """Raised when injected manifest bytes diverge from the signed, pinned manifest."""
    pass


class CapabilityEnvelopeViolation(RuntimeError):
    """Raised when a skill's declared/executed capabilities exceed its granted envelope."""
    pass


@dataclass(frozen=True)
class SignedManifest:
    skill_id: str
    version: str
    description: str          # MUST be inside the signed region
    declared_caps: frozenset  # e.g. {"reads:database"}
    manifest_digest: str      # sha256 over canonical bytes incl. description


def _canonical(description: str) -> bytes:
    # NFC before hashing AND before injection; identical at sign and verify.
    return unicodedata.normalize("NFC", description).encode("utf-8")


def _digest(skill_id: str, version: str, description: str, caps: frozenset) -> str:
    h = hashlib.sha256()
    h.update(skill_id.encode())
    h.update(b"\x00")
    h.update(version.encode())
    h.update(b"\x00")
    h.update(_canonical(description))
    h.update(b"\x00")
    h.update(",".join(sorted(caps)).encode())
    return h.hexdigest()


def verify_and_gate(
    signed: SignedManifest,
    live_description: str,
    pinned_version: str,
    signature_valid: bool,
    granted_envelope: frozenset,
) -> str:
    """Return the description safe to inject, or raise. Runs at injection time."""
    if not signature_valid:
        raise SkillManifestDriftError(
            f"skill={signed.skill_id} signature invalid; quarantine"
        )
    if signed.version != pinned_version:
        raise SkillManifestDriftError(
            f"skill={signed.skill_id} version drift "
            f"pinned={pinned_version} live={signed.version}"
        )
    live_digest = _digest(
        signed.skill_id, signed.version, live_description, signed.declared_caps
    )
    if live_digest != signed.manifest_digest:
        raise SkillManifestDriftError(
            f"skill={signed.skill_id} manifest digest mismatch; "
            f"injected bytes diverge from signed bytes"
        )
    if not signed.declared_caps <= granted_envelope:
        raise CapabilityEnvelopeViolation(
            f"skill={signed.skill_id} declares "
            f"{sorted(signed.declared_caps - granted_envelope)} "
            f"outside granted envelope"
        )
    return _canonical(live_description).decode("utf-8")


def enumerate_for_context(
    manifests: list[tuple[SignedManifest, str, bool]],
    pinned_versions: dict[str, str],
    granted_envelope: frozenset,
) -> list[dict]:
    """Assemble planner context; quarantined skills become structured stubs."""
    context: list[dict] = []
    for signed, live_desc, sig_ok in manifests:
        try:
            safe = verify_and_gate(
                signed,
                live_desc,
                pinned_versions.get(signed.skill_id, ""),
                sig_ok,
                granted_envelope,
            )
            context.append({"id": signed.skill_id, "status": "ok", "description": safe})
        except (SkillManifestDriftError, CapabilityEnvelopeViolation) as exc:
            # Fail closed: no free-text from the manifest reaches the planner.
            context.append(
                {
                    "id": signed.skill_id,
                    "status": "quarantined",
                    "reason_code": type(exc).__name__,
                }
            )
    return context
