# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/where-must-an-instance-re-derive-capability-scope-after-a-sandbox-escape-and-why-token-revalidation-alone-is-insufficient.md
# Remnant Warrant:    https://corpusfetch.com/c/where-must-an-instance-re-derive-capability-scope-after-a-sandbox-escape-and-why-token-revalidation-alone-is-insufficient.warrant.json
# Markdown SHA-256:   c3074c797443bce327aa973d28becc61f2670426573d19e433edc1a726f6b4c8
# Code AST SHA-256:   2bc4914fb15a59b30de4633c552adb6242214b5217f7d92cf4616fc604436ef9
# Verified Classes:   ScopeInvalidatedError, CapabilityToken, SandboxState
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class ScopeInvalidatedError(RuntimeError):
    """Raised when a sandbox mutation has changed the resolution of a path
    that a downstream capability token's scope predicate depends on."""
    pass


@dataclass
class CapabilityToken:
    scopes: dict[str, str]          # e.g. {"db.write": "staging.*", "sandbox.exec": "local"}
    minted_state_hash: str
    ttl_seconds: int


@dataclass
class SandboxState:
    files: dict[str, str] = field(default_factory=dict)   # path -> content hash
    symlinks: dict[str, str] = field(default_factory=dict)  # link -> target

    def state_hash(self) -> str:
        h = hashlib.sha256()
        for k in sorted(self.files):
            h.update(f"{k}:{self.files[k]}".encode())
        for k in sorted(self.symlinks):
            h.update(f"{k}->{self.symlinks[k]}".encode())
        return h.hexdigest()

    def resolve(self, path: str) -> str:
        seen = set()
        while path in self.symlinks:
            if path in seen:
                raise ScopeInvalidatedError(f"symlink cycle at {path}")
            seen.add(path)
            path = self.symlinks[path]
        return path


def authorize_write(token: CapabilityToken, sandbox: SandboxState,
                    requested_path: str, declared_prefix: str) -> str:
    # Step 1: token-scope check against the *declared* path (what the caller asked for)
    if not token.scopes.get("db.write", "").startswith(declared_prefix.rstrip("*")):
        raise ScopeInvalidatedError(
            f"token does not cover declared prefix {declared_prefix!r}"
        )

    # Step 2: resolve the path against *current* sandbox state, not mint-time state
    resolved = sandbox.resolve(requested_path)

    # Step 3: the invariant — resolved target must still fall under the declared prefix
    if not resolved.startswith(declared_prefix.rstrip("*")):
        raise ScopeInvalidatedError(
            f"scope escape: declared {requested_path!r} under {declared_prefix!r} "
            f"resolves to {resolved!r} outside token scope; "
            f"sandbox mutated since mint (mint_hash={token.minted_state_hash[:8]}, "
            f"now={sandbox.state_hash()[:8]})"
        )

    # Step 4: only now is the write committed, against the resolved target
    sandbox.files[resolved] = "written"
    return resolved


def run_migration_step(token: CapabilityToken, sandbox: SandboxState) -> None:
    # Simulate step 2 having created a symlink via sandbox.exec
    sandbox.symlinks["staging/staging_payload.parquet"] = "/etc/agent_creds"

    # Step 3 attempts the write; token scope is formally valid, but state is not
    authorize_write(
        token,
        sandbox,
        requested_path="staging/staging_payload.parquet",
        declared_prefix="staging/",
    )
