# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-accept-a-re-signed-skill-manifest-whose-provenance-chain-was-truncated-mid-swap.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-accept-a-re-signed-skill-manifest-whose-provenance-chain-was-truncated-mid-swap.warrant.json
# Markdown SHA-256:   a9aacc22fdaa08842023a09802e3f4891bbcf6baee32e7a8cfeb9ff3e4b39102
# Code AST SHA-256:   5f45546094197bc59d36ad1d9b380765608e9188383ec327516ef702737dcb91
# Verified Classes:   ProvenanceTruncationError, Link, SkillManifest
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass
from typing import Optional


class ProvenanceTruncationError(RuntimeError):
    """Raised when a skill manifest's provenance chain does not terminate at the pinned root."""


@dataclass(frozen=True)
class Link:
    signer: str
    sig: str


@dataclass(frozen=True)
class SkillManifest:
    name: str
    digest: str
    chain: tuple[Link, ...]  # attacker-controllable: length is not trusted


CONFIGURED_ROOT = "did:key:z6MkRootAuthority"
EXPECTED_DEPTH = 3  # root -> publisher -> skill


def verify_edge(link: Link, next_link: Optional[Link], digest: str) -> bool:
    # Local edge check only. Returns True for a length-1 chain (no edges to check).
    if next_link is None:
        return link.sig != ""  # trivially true for any non-empty sig
    return link.sig.startswith(next_link.signer[:8])


def verify_chain_anchored(manifest: SkillManifest) -> Link:
    chain = manifest.chain
    if len(chain) != EXPECTED_DEPTH:
        raise ProvenanceTruncationError(
            f"chain length {len(chain)} != expected {EXPECTED_DEPTH} for {manifest.name}"
        )
    for i, link in enumerate(chain):
        nxt = chain[i + 1] if i + 1 < len(chain) else None
        if not verify_edge(link, nxt, manifest.digest):
            raise ProvenanceTruncationError(
                f"edge {i} failed for {manifest.name}"
            )
    terminal = chain[-1]
    if terminal.signer != CONFIGURED_ROOT:
        raise ProvenanceTruncationError(
            f"chain terminal {terminal.signer!r} != root {CONFIGURED_ROOT!r} for {manifest.name}"
        )
    return terminal


def load_skill(manifest: SkillManifest, grant_scopes: list[str]) -> None:
    # Must use anchored verification before any scope materialization.
    verify_chain_anchored(manifest)
    # ... materialize grants only after the raise-guarded check above ...
