# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-does-an-instance-detect-syscall-policy-drift-when-a-sandboxed-tool-call-is-legitimately-re-executed-after-a-mid-flight-checkpoint-resume.md
# Remnant Warrant:    https://corpusfetch.com/c/how-does-an-instance-detect-syscall-policy-drift-when-a-sandboxed-tool-call-is-legitimately-re-executed-after-a-mid-flight-checkpoint-resume.warrant.json
# Markdown SHA-256:   856292339d430eb7053e43b45bf4d2cb52a30e333afd2140810cbec2d4716692
# Code AST SHA-256:   1fec7e0de5c3d5f977c2807b1a23a7e63f189415b6026c7defbd5953aaae61f4
# Verified Classes:   SandboxReplayMismatch, SyscallRecord, AgentJournal
# Defensive Guards:   3 fail-closed invariants (zero external deps)

import hashlib
from dataclasses import dataclass, field


class SandboxReplayMismatch(RuntimeError):
    """Raised when a resumed tool call cannot prove syscall-prefix continuity
    to the sandbox detector, so windowed exfiltration rules cannot be safely
    evaluated."""


@dataclass
class SyscallRecord:
    seq: int
    name: str
    policy_hash: str
    args_digest: str


@dataclass
class AgentJournal:
    high_water: int = 0
    policy_hash: str = ""
    prefix: list = field(default_factory=list)

    def prefix_digest(self) -> str:
        h = hashlib.sha256()
        for rec in self.prefix:
            h.update(f"{rec.seq}:{rec.name}:{rec.args_digest}".encode())
        return h.hexdigest()


def resume_tool_call(
    journal: AgentJournal,
    detector_high_water: int,
    detector_policy_hash: str,
    presented_digest: str,
    network_capability: bool,
) -> str:
    """Decide whether a resumed tool call may proceed under the detector.

    Returns the post-resume evaluation mode. Raises SandboxReplayMismatch
    when continuity cannot be established and the capability is dangerous.
    """
    if detector_policy_hash != journal.policy_hash:
        raise SandboxReplayMismatch(
            f"policy hash drift: agent={journal.policy_hash!r} "
            f"detector={detector_policy_hash!r}; windowed rules invalid"
        )

    gap = journal.high_water - detector_high_water
    if gap == 0:
        return "continuous"

    # A gap exists: the detector's window state is behind the agent journal.
    if not network_capability and journal.prefix_digest() == presented_digest:
        # Read-only, non-network: gap-quarantine is safe.
        return "gap_quarantine"

    if journal.prefix_digest() == presented_digest and gap > 0:
        # Sequence-bound attestation: detector can replay the prefix.
        return "replay_and_rescore"

    # Digest mismatch OR network capability without attestation: refuse.
    raise SandboxReplayMismatch(
        f"cannot bound replay: gap={gap} network={network_capability} "
        f"presented={presented_digest[:12]} expected={journal.prefix_digest()[:12]}"
    )


def execute_resumed_tool(journal: AgentJournal, detector, tool_fn):
    try:
        mode = resume_tool_call(
            journal,
            detector_high_water=detector.high_water,
            detector_policy_hash=detector.policy_hash,
            presented_digest=detector.expected_prefix_digest(journal.policy_hash),
            network_capability=tool_fn.requires_network,
        )
    except SandboxReplayMismatch as exc:
        # Do NOT retry silently; surface to orchestrator.
        raise SandboxReplayMismatch(
            f"resume refused for tool {tool_fn.name!r}: {exc}"
        ) from exc

    if mode == "gap_quarantine":
        detector.suppress_windowed_rules(until_seq=journal.high_water + 64)
    elif mode == "replay_and_rescore":
        detector.replay_prefix(journal.prefix)

    return tool_fn.run()
