# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-provenance-attestation-drift-when-a-skill-s-prompt-template-is-silently-re-signed-across-a-manifest-boundary.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-provenance-attestation-drift-when-a-skill-s-prompt-template-is-silently-re-signed-across-a-manifest-boundary.warrant.json
# Markdown SHA-256:   d2a54e97a195be98beb7871239c261246a929e1f50fd24cd5cf6c19475d7bf79
# Code AST SHA-256:   4f380c4a76d185363717de91bcbd0c2143f133c8955d392a69803e0f68bb30b8
# Verified Classes:   ProvenanceContinuityError, Attestation, ExecutionSlot
# Defensive Guards:   5 fail-closed invariants (zero external deps)

import hashlib
import json
from dataclasses import dataclass


class ProvenanceContinuityError(RuntimeError):
    """Raised when an attestation is valid but provenance continuity is broken."""


@dataclass(frozen=True)
class Attestation:
    name: str
    semver: str
    subject_digest: str          # SHA-256 of prompt+manifest bytes
    capability_set: frozenset   # declared authorized tools
    signature_valid: bool


@dataclass(frozen=True)
class ExecutionSlot:
    cache_key: str               # MUST be subject_digest, not (name, semver)
    capability_fingerprint: frozenset


def _extract_prompt_tool_refs(prompt_bytes: bytes) -> frozenset:
    """Static extraction of tool-call tokens from a prompt template.

    In production this is a tokenizer-aware scan for structured tool-call
    spans and example blocks. Here we approximate with a marker convention.
    """
    text = prompt_bytes.decode("utf-8", errors="replace")
    refs = set()
    for line in text.splitlines():
        if line.strip().startswith("TOOL:"):
            refs.add(line.split("TOOL:", 1)[1].strip())
    return frozenset(refs)


def admit_skill(
    att: Attestation,
    prompt_bytes: bytes,
    manifest_capabilities: frozenset,
    slot: ExecutionSlot | None,
    registry: dict,              # (name, semver) -> set of digests
) -> ExecutionSlot:
    # Precondition: envelope integrity.
    if not att.signature_valid:
        raise ProvenanceContinuityError(
            f"signature invalid for {att.name}@{att.semver}"
        )

    actual_digest = hashlib.sha256(prompt_bytes).hexdigest()
    if actual_digest != att.subject_digest:
        raise ProvenanceContinuityError(
            f"artifact digest {actual_digest} != attested {att.subject_digest}"
        )

    # Registry immutability: one digest per (name, semver).
    key = (att.name, att.semver)
    seen = registry.setdefault(key, set())
    seen.add(att.subject_digest)
    if len(seen) > 1:
        raise ProvenanceContinuityError(
            f"immutability violated: {key} bound to multiple digests {seen}"
        )

    # Declared capability set must equal the manifest's, not just be present.
    if att.capability_set != manifest_capabilities:
        raise ProvenanceContinuityError(
            f"attestation capabilities {att.capability_set} != "
            f"manifest {manifest_capabilities}"
        )

    # The signal no signature sees: prompt tool refs must be a subset
    # of the authorized capability set.
    prompt_refs = _extract_prompt_tool_refs(prompt_bytes)
    unauthorized = prompt_refs - att.capability_set
    if unauthorized:
        raise ProvenanceContinuityError(
            f"prompt references unauthorized tools {sorted(unauthorized)}; "
            f"authorized={sorted(att.capability_set)}. "
            f"Likely silent re-sign of {att.name}@{att.semver}."
        )

    # Slot continuity: cache key must be the attestation digest.
    if slot is not None and slot.cache_key != att.subject_digest:
        # Stale slot: invalidate and re-resolve, do not reject artifact.
        slot = None

    if slot is None:
        slot = ExecutionSlot(
            cache_key=att.subject_digest,
            capability_fingerprint=att.capability_set,
        )

    return slot
