# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-a-re-signed-skill-manifest-whose-declared-capabilities-have-drifted-from-the-capabilities-the-skill-actually-exercises-at.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-a-re-signed-skill-manifest-whose-declared-capabilities-have-drifted-from-the-capabilities-the-skill-actually-exercises-at.warrant.json
# Markdown SHA-256:   05736ddec4fa47d439354561c44107bab9f5382aea0ae22feec55c6f0407974e
# Code AST SHA-256:   f8d3b5a0510b0431b50039a8ec51b3f05363c634d506803f98e97d797ffa5a65
# Verified Classes:   CapabilityDriftError, Manifest, LoadIdentity
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field
from typing import Set, Tuple


class CapabilityDriftError(RuntimeError):
    """Raised when a skill's observed effect exceeds its signed declaration."""


@dataclass(frozen=True)
class Manifest:
    skill_id: str
    declared: Set[str]          # e.g. {"fs.read:/data/in", "http.get:api.internal"}
    signature: bytes
    body_hash: str              # hash of the signed body; ties observation to this declaration


@dataclass
class LoadIdentity:
    manifest: Manifest
    observed: Set[str] = field(default_factory=set)
    aborted: bool = False


def canonicalize_path(path: str) -> str:
    # resolve symlinks and .. before capability comparison
    import os
    return os.path.realpath(path)


def capability_covers(declared: Set[str], observed: str) -> bool:
    kind, _, target = observed.partition(":")
    for cap in declared:
        dkind, _, dtarget = cap.partition(":")
        if dkind != kind:
            continue
        if kind.startswith("fs."):
            # resolve both sides; prefix match only on canonical roots
            if canonicalize_path(target) == canonicalize_path(dtarget) or \
               canonicalize_path(target).startswith(canonicalize_path(dtarget).rstrip("/") + "/"):
                return True
        elif target == dtarget:
            return True
    return False


def record_effect(ident: LoadIdentity, effect: str, reversible: bool) -> None:
    """Called by the sandbox shim on every intercepted syscall/effect."""
    if ident.aborted:
        raise CapabilityDriftError(
            f"skill {ident.manifest.skill_id} already aborted; refusing effect {effect}"
        )
    ident.observed.add(effect)
    if capability_covers(ident.manifest.declared, effect):
        return  # admitted

    # undeclared effect: decide by reversibility
    if not reversible:
        ident.aborted = True
        raise CapabilityDriftError(
            f"skill {ident.manifest.skill_id} (manifest {ident.manifest.body_hash[:12]}) "
            f"emitted irreversible undeclared effect {effect!r}; "
            f"declared={sorted(ident.manifest.declared)}; aborting and revoking load identity"
        )
    # reversible: quarantine, do not execute further until re-signed
    raise CapabilityDriftError(
        f"skill {ident.manifest.skill_id} (manifest {ident.manifest.body_hash[:12]}) "
        f"emitted reversible undeclared effect {effect!r}; quarantining for re-signing"
    )


def verify_signature(manifest: Manifest, trusted_key_check) -> bool:
    # stand-in for real pubkey verification; the point is that this passing
    # does NOT imply the declaration is true of the code.
    return trusted_key_check(manifest.signature, manifest.body_hash)
