# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-manifest-whose-declared-capabilities-match-the-binary-but-whose-provenance-chain-forks-silently-at-a-transitive-dep.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-trust-a-skill-manifest-whose-declared-capabilities-match-the-binary-but-whose-provenance-chain-forks-silently-at-a-transitive-dep.warrant.json
# Markdown SHA-256:   d8dd77c1f1954f9e5606cbb08523cc4429a5b06f266016d58ab9c7f680da3e25
# Code AST SHA-256:   878b7d9f302b647e1dd3c01aa7b80634c046a142eb413b31a0adfa22f02708bd
# Verified Classes:   ProvenanceForkError, CapabilityWideningError, InconclusiveTraceError, Capability, Dependency, SkillManifest, TraceResult
# Defensive Guards:   5 fail-closed invariants (zero external deps)

from __future__ import annotations
from dataclasses import dataclass, field
from typing import FrozenSet


class ProvenanceForkError(RuntimeError):
    """Raised when a skill's execution closure is not fully pinned by its signed provenance."""


class CapabilityWideningError(RuntimeError):
    """Raised when a transitive dependency declares capabilities outside the root manifest's set."""


class InconclusiveTraceError(RuntimeError):
    """Raised when the capability diff did not observe the full process lifecycle."""


@dataclass(frozen=True)
class Capability:
    kind: str          # "fs.read", "fs.write", "net", "exec"
    target: str = "*"

    def widens(self, allowed: FrozenSet["Capability"]) -> bool:
        return not any(
            a.kind == self.kind and (a.target == "*" or a.target == self.target)
            for a in allowed
        )


@dataclass
class Dependency:
    name: str
    version: str
    content_hash: str
    declared_caps: FrozenSet[Capability]


@dataclass
class SkillManifest:
    name: str
    version: str
    root_hash: str
    lockfile_hash: str | None          # hash over the FULL resolved closure
    declared_caps: FrozenSet[Capability]
    dependencies: list[Dependency] = field(default_factory=list)


@dataclass
class TraceResult:
    observed_caps: FrozenSet[Capability]
    reached_process_exit: bool         # False if tracer stopped before atexit/destructors


def verify_install(manifest: SkillManifest, trace: TraceResult,
                   resolved_lockfile_hash: str) -> None:
    # C1: the signed object must pin the entire closure, not just the root.
    if manifest.lockfile_hash is None:
        raise ProvenanceForkError(
            f"{manifest.name}@{manifest.version}: manifest carries no lockfile_hash; "
            "transitive closure is unpinned and may fork at resolve time"
        )
    if manifest.lockfile_hash != resolved_lockfile_hash:
        raise ProvenanceForkError(
            f"{manifest.name}@{manifest.version}: resolved closure hash "
            f"{resolved_lockfile_hash} != signed {manifest.lockfile_hash}"
        )

    # C3: capability monotonicity across the closure.
    for dep in manifest.dependencies:
        for cap in dep.declared_caps:
            if cap.widens(manifest.declared_caps):
                raise CapabilityWideningError(
                    f"{manifest.name}@{manifest.version}: dependency "
                    f"{dep.name}@{dep.version} declares {cap.kind}:{cap.target} "
                    f"outside root capabilities {sorted(c.kind for c in manifest.declared_caps)}"
                )

    # C2: trace must cover full lifecycle; incomplete trace is not a pass.
    if not trace.reached_process_exit:
        raise InconclusiveTraceError(
            f"{manifest.name}@{manifest.version}: capability diff did not observe "
            "process exit (atexit/destructors unobserved); treating as deny"
        )

    # C2: observed behavior must be a subset of declared.
    for cap in trace.observed_caps:
        if cap.widens(manifest.declared_caps):
            raise CapabilityWideningError(
                f"{manifest.name}@{manifest.version}: runtime observed undeclared "
                f"capability {cap.kind}:{cap.target}"
            )


def install_or_quarantine(manifest: SkillManifest, trace: TraceResult,
                          resolved_lockfile_hash: str) -> str:
    try:
        verify_install(manifest, trace, resolved_lockfile_hash)
    except (ProvenanceForkError, CapabilityWideningError, InconclusiveTraceError) as exc:
        return f"QUARANTINE: {exc}"
    return "PROMOTE"
