# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-capability-scoped-tool-sandboxing-as-a-two-phase-invariant-rather-than-a-single-syscall-confinement-check.md
# Remnant Warrant:    https://corpusfetch.com/c/in-what-scenarios-must-an-instance-treat-mcp-capability-scoped-tool-sandboxing-as-a-two-phase-invariant-rather-than-a-single-syscall-confinement-check.warrant.json
# Markdown SHA-256:   9c7826ad86466a4b7d88734fb90b5e7188503a9f45c2d9a336e146b09666515c
# Code AST SHA-256:   3111007423e28ebd6dbe7a0368e292cdb0375f50824d12eb9c92be9c6d73039f
# Verified Classes:   ConfinementSnapshotMismatch
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class ConfinementSnapshotMismatch(RuntimeError):
    """Raised when admission-time capability/ruleset snapshots diverge from
    the live namespace at the terminal syscall boundary."""
    pass


def admit_tool_call(tool_manifest: dict, live_namespace: dict,
                    capability_token: dict) -> str:
    """Two-phase admission. Returns 'single_phase' or 'two_phase'.
    Raises ConfinementSnapshotMismatch if the call cannot be safely
    admitted under either model."""
    write_verbs = {"fs.write", "fs.rename", "fs.unlink", "fs.mkdir"}
    caps = set(capability_token.get("capabilities", []))

    needs_two_phase = (
        bool(caps & write_verbs)
        or tool_manifest.get("opaque", False)
        or capability_token.get("scope_kind") == "path_prefix"
        or tool_manifest.get("invocation_count", 0) > 0
    )

    if not needs_two_phase:
        return "single_phase"

    # Two-phase requires the live namespace to match the ruleset snapshot.
    ruleset_snapshot = tool_manifest.get("ruleset_snapshot", {})
    staged = live_namespace.get("staging_symlinks", [])
    snapshot_symlinks = set(ruleset_snapshot.get("symlinks", []))

    new_symlinks = set(staged) - snapshot_symlinks
    if new_symlinks:
        raise ConfinementSnapshotMismatch(
            f"namespace mutated since ruleset load: {sorted(new_symlinks)} "
            f"present in staging but absent from ruleset snapshot; "
            f"terminal syscall target cannot be re-resolved safely"
        )

    if capability_token.get("scope_kind") == "path_prefix":
        # Prefix scopes cannot be re-resolved against live inodes;
        # require an explicit rebuild before two-phase admission.
        raise ConfinementSnapshotMismatch(
            "capability scope is a path prefix; symlink-following can escape "
            "the prefix and the ruleset cannot re-resolve it. Rebuild ruleset "
            "against resolved inodes before admitting a write tool."
        )

    return "two_phase"


def execute_with_revalidation(tool_call, live_namespace, capability_token):
    mode = admit_tool_call(tool_call.manifest, live_namespace, capability_token)
    if mode == "single_phase":
        return tool_call.invoke()

    # Two-phase: hook the terminal syscall and re-resolve target.
    def terminal_syscall_hook(syscall_name: str, resolved_inode: int):
        live_scope = capability_token.resolve_live_scope()
        if resolved_inode not in live_scope:
            raise ConfinementSnapshotMismatch(
                f"terminal syscall {syscall_name} resolved inode {resolved_inode} "
                f"outside live capability scope {live_scope}; "
                f"admission-time snapshot was stale"
            )

    return tool_call.invoke_with_hook(terminal_syscall_hook)
