# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-tool-manifest-in-dynamic-skill-injection-surfaces.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-a-poisoned-tool-manifest-in-dynamic-skill-injection-surfaces.warrant.json
# Markdown SHA-256:   23d233e562d188f3d50aa3c92fc6131dee48314907dce2670cf957503663bd5a
# Code AST SHA-256:   f174d50e690996839a8c0dcd339d18827209831b6e4e5371f58b97e66073b8f9
# Verified Classes:   ManifestQuarantineError, ManifestVerdict
# Defensive Guards:   1 fail-closed invariants (zero external deps)

import hashlib
import re
from dataclasses import dataclass, field

IMPERATIVE_RE = re.compile(
    r"\b(call|first|always|never|do not|ignore|before|must|you should|instead)\b",
    re.IGNORECASE,
)


class ManifestQuarantineError(RuntimeError):
    """Raised when a dynamically loaded manifest crosses the trust boundary."""


@dataclass
class ManifestVerdict:
    name: str
    clean: bool
    reasons: list[str] = field(default_factory=list)
    digest: str = ""


def structural_scan(manifest: dict, catalog_names: set[str], median_len: int) -> ManifestVerdict:
    name = manifest.get("name", "<unnamed>")
    desc = manifest.get("description", "") or ""
    reasons: list[str] = []

    if len(desc.split()) > max(10 * median_len, 400):
        reasons.append(f"description length {len(desc.split())} exceeds catalog median bound")

    hits = IMPERATIVE_RE.findall(desc)
    if hits:
        reasons.append(f"imperative tokens in declarative field: {sorted(set(hits))}")

    named_siblings = {n for n in catalog_names if n != name and n in desc}
    if named_siblings:
        reasons.append(f"description references sibling tools: {sorted(named_siblings)}")

    digest = hashlib.sha256(desc.encode("utf-8")).hexdigest()[:16]
    return ManifestVerdict(name=name, clean=not reasons, reasons=reasons, digest=digest)


def load_catalog(manifests: list[dict]) -> list[dict]:
    names = {m.get("name", "") for m in manifests}
    lens = sorted(len((m.get("description") or "").split()) for m in manifests)
    median_len = lens[len(lens) // 2] if lens else 0

    admitted: list[dict] = []
    quarantined: list[ManifestVerdict] = []
    for m in manifests:
        v = structural_scan(m, names, median_len)
        if not v.clean:
            quarantined.append(v)
            continue
        admitted.append(m)

    if quarantined:
        # Sticky quarantine: refuse to load the catalog with the poisoned
        # descriptions still present in the selection context.
        detail = "; ".join(f"{v.name}: {', '.join(v.reasons)}" for v in quarantined)
        raise ManifestQuarantineError(
            f"{len(quarantined)} manifest(s) crossed the trust boundary: {detail}"
        )
    return admitted
