# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-signed-capability-manifest-as-insufficient-and-demand-runtime-attestation-of-the-loaded-skill-body.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-a-signed-capability-manifest-as-insufficient-and-demand-runtime-attestation-of-the-loaded-skill-body.warrant.json
# Markdown SHA-256:   0d958cf4536e51cac4fb08e0d5741352764c79c764055440b76ca10b1d955ea6
# Code AST SHA-256:   9fc922767a811ca5635c9baf517bcefa7faa51b967e8cf5dd8f3c999b9e9ca57
# Verified Classes:   AttestationMismatch, UndeclaredCapability, Manifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass


class AttestationMismatch(RuntimeError):
    """Raised when a resolved skill body does not match its signed manifest."""


class UndeclaredCapability(RuntimeError):
    """Raised when a loaded skill exposes a tool not covered by declared scopes."""


@dataclass(frozen=True)
class Manifest:
    skill_id: str
    version: str
    body_hash: str          # "sha256:<hex>"
    declared_scopes: frozenset[str]
    declared_tools: frozenset[str]


def attest_and_register(manifest: Manifest, resolved_bytes: bytes,
                        loaded_tools: dict[str, str]) -> dict[str, str]:
    # 1. Re-bind signature to bytes in-process. Never trust an upstream
    #    "integrity: verified" header or a channel pointer here.
    actual = "sha256:" + hashlib.sha256(resolved_bytes).hexdigest()
    if actual != manifest.body_hash:
        raise AttestationMismatch(
            f"{manifest.skill_id}@{manifest.version}: body digest {actual} "
            f"!= manifest body_hash {manifest.body_hash}"
        )

    # 2. Scope enforcement reads the *verified* manifest, and is applied to
    #    the loaded symbol table, not the manifest text.
    for tool_name, required_scope in loaded_tools.items():
        if tool_name not in manifest.declared_tools:
            raise UndeclaredCapability(
                f"{manifest.skill_id}: tool {tool_name!r} not in declared_tools"
            )
        if required_scope not in manifest.declared_scopes:
            raise UndeclaredCapability(
                f"{manifest.skill_id}: tool {tool_name!r} requires "
                f"{required_scope!r} not in declared_scopes"
            )

    # 3. Register only after both checks pass; key cache on body digest.
    return {"skill_id": manifest.skill_id, "body_digest": actual,
            "tools": tuple(loaded_tools)}
