# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-skill-manifest-before-registry-admission-and-why-signature-valid-manifests-still-poison-the-runtim.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-quarantine-a-skill-manifest-before-registry-admission-and-why-signature-valid-manifests-still-poison-the-runtim.warrant.json
# Markdown SHA-256:   b58f48a618d6d934a5d5e1f99fe916e1c6b2642237a64cbc8975e0584ad5e208
# Code AST SHA-256:   2b1ed6bd65feb487d156b7e8bcad04197b4b4de80bbb663c36258d8c0f4fe006
# Verified Classes:   SkillManifestQuarantineError, SkillManifest
# Defensive Guards:   4 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass, field
from typing import Iterable


class SkillManifestQuarantineError(RuntimeError):
    """Raised when a manifest is rejected at registry admission.

    Distinct from a code-safety rejection: the referenced code may be
    perfectly safe. This fires because the manifest's prose is
    instruction-bearing and reaches outside its own namespace.
    """


# Fields that are rendered into the model's tool preamble.
INSTRUCTION_BEARING_FIELDS = (
    "description",
    "when_to_use",
    "examples",
    "deprecation_notice",
    "changelog",
)

# Second-person / sequencing directives that have no place in a
# self-description.
IMPERATIVE_PATTERN = re.compile(
    r"\b(first|before|then|you must|you should|always|never|call|invoke|"
    r"resolve|fetch|load|include)\b",
    re.IGNORECASE,
)

# A manifest may name only its own tool and its own parameters.
# Any reference to a sibling tool or a parameter it does not declare
# is a cross-namespace instruction.
TOOL_REFERENCE_PATTERN = re.compile(r"\b([a-z_]+\.[a-z_]+)\b")


@dataclass
class SkillManifest:
    name: str
    publisher_id: str
    signature: str
    declared_params: Iterable[str] = field(default_factory=tuple)
    fields: dict = field(default_factory=dict)

    def own_namespace(self) -> set:
        ns = {self.name}
        ns.update(f"{self.name}.{p}" for p in self.declared_params)
        return ns


def verify_signature(manifest: SkillManifest, trusted_keys: dict) -> bool:
    # Real implementation verifies Ed25519 over canonical manifest bytes.
    # Placeholder: presence of a trusted publisher key.
    return manifest.publisher_id in trusted_keys


def admit_manifest(manifest: SkillManifest, trusted_keys: dict) -> None:
    """Admission gate. Raises SkillManifestQuarantineError on rejection.

    Signature validity is necessary but NOT sufficient. Instruction-
    bearing prose must additionally pass the self-only reference check.
    """
    if not verify_signature(manifest, trusted_keys):
        raise SkillManifestQuarantineError(
            f"manifest {manifest.name!r}: signature not anchored to a trusted key"
        )

    own_ns = manifest.own_namespace()

    for fname in INSTRUCTION_BEARING_FIELDS:
        prose = manifest.fields.get(fname)
        if not prose:
            continue

        # 1. Cross-namespace reference: decisive reject.
        for ref in TOOL_REFERENCE_PATTERN.findall(prose):
            if ref not in own_ns:
                raise SkillManifestQuarantineError(
                    f"manifest {manifest.name!r} field {fname!r} references "
                    f"foreign capability {ref!r}; manifests may describe only "
                    f"themselves"
                )

        # 2. Imperative sequencing directives: reject.
        if IMPERATIVE_PATTERN.search(prose):
            raise SkillManifestQuarantineError(
                f"manifest {manifest.name!r} field {fname!r} contains "
                f"imperative/sequencing language; move guidance to a "
                f"non-rendered 'docs' field"
            )

        # 3. Length cap: bound the context budget a single manifest may claim.
        if len(prose) > 600:
            raise SkillManifestQuarantineError(
                f"manifest {manifest.name!r} field {fname!r} exceeds 600 chars"
            )


def admit_batch(manifests: Iterable[SkillManifest], trusted_keys: dict) -> dict:
    """Admission returns only the admitted set; quarantined manifests are
    excluded from the index so they cannot re-poison the next cold start."""
    admitted, quarantined = {}, {}
    for m in manifests:
        try:
            admit_manifest(m, trusted_keys)
            admitted[m.name] = m
        except SkillManifestQuarantineError as exc:
            quarantined[m.name] = str(exc)
    return {"admitted": admitted, "quarantined": quarantined}
