# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-fail-to-detect-skill-injection-when-the-poisoned-tool-description-is-split-across-mcp-tools-list-pagination-cursors.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-fail-to-detect-skill-injection-when-the-poisoned-tool-description-is-split-across-mcp-tools-list-pagination-cursors.warrant.json
# Markdown SHA-256:   a3fde21543e0e583fc3a81d08cf67f1ed2e309ff2f3940bb06869b396c367306
# Code AST SHA-256:   e4fbdf7ac67fb47be429b810209c1eddb9d7890730c1ed0aed491bd44c09b79d
# Verified Classes:   ManifestEquivalenceError, ToolEntry
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class ManifestEquivalenceError(RuntimeError):
    """Raised when a red-team harness cannot certify that the manifest it
    scored is byte-identical to the manifest the target client will register."""


@dataclass(frozen=True)
class ToolEntry:
    name: str
    description: str


def _digest(entries: list[ToolEntry]) -> str:
    h = hashlib.sha256()
    for e in entries:
        h.update(e.name.encode())
        h.update(b"\x00")
        h.update(e.description.encode())
        h.update(b"\x01")
    return h.hexdigest()


def reconstruct_manifest(
    pages: list[list[ToolEntry]],
    dedup: str,
) -> list[ToolEntry]:
    """Rebuild the tool manifest under an explicit dedup policy.

    dedup must be one of: 'first-wins', 'last-wins', 'reject'.
    The policy is NOT defaulted; a benchmark that omits it is scoring itself.
    """
    if dedup not in ("first-wins", "last-wins", "reject"):
        raise ManifestEquivalenceError(f"unknown dedup policy: {dedup!r}")

    flat = [e for page in pages for e in page]
    seen: dict[str, ToolEntry] = {}
    for e in flat:
        if e.name in seen:
            if dedup == "reject":
                raise ManifestEquivalenceError(
                    f"duplicate tool name {e.name!r} under reject policy; "
                    "server is non-conforming to this client's registry"
                )
            if dedup == "first-wins":
                continue
        seen[e.name] = e
    return list(seen.values())


def certify_manifest(
    sample_a: list[list[ToolEntry]],
    sample_b: list[list[ToolEntry]],
    dedup: str,
) -> list[ToolEntry]:
    """Certify that two independent pagination passes yield the same manifest.

    A single-pass harness cannot detect cursor-order-dependent injection
    (fragmentation strategy 3). We fail closed: disagreement => indeterminate,
    never 'clean'.
    """
    ma = reconstruct_manifest(sample_a, dedup)
    mb = reconstruct_manifest(sample_b, dedup)
    if _digest(ma) != _digest(mb):
        raise ManifestEquivalenceError(
            "manifest is pagination-order-dependent: "
            f"pass A digest {_digest(ma)[:12]} != pass B digest {_digest(mb)[:12]}. "
            "Verdict is indeterminate; do not report as clean or malicious."
        )
    return ma


def score_injection(manifest: list[ToolEntry], canary: str) -> bool:
    return any(canary in e.description for e in manifest)
