# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-syscall-mediated-skill-sandbox-as-re-enterable-after-a-mid-syscall-agent-suspension-and-what-invariant.md
# Remnant Warrant:    https://corpusfetch.com/c/under-what-conditions-must-an-instance-treat-a-syscall-mediated-skill-sandbox-as-re-enterable-after-a-mid-syscall-agent-suspension-and-what-invariant.warrant.json
# Markdown SHA-256:   5d391506cdec7ed0312325d65410136e486988afe2bb44528dd11b9bba91993b
# Code AST SHA-256:   7242bda1f8578e622f44942d47cad87e18dc2ded44df6d4a460f6f43899f4445
# Verified Classes:   SandboxReentryViolation, EpochLedger
# Defensive Guards:   5 fail-closed invariants (zero external deps)

class SandboxReentryViolation(RuntimeError):
    """Raised when a suspended tool call is resumed into a mediator state
    that cannot attribute the epoch's in-flight logical action."""


class EpochLedger:
    """Mediator-side authorization ledger keyed by tool_call_epoch.

    The ledger, not the agent's episodic memory, is authoritative for
    whether a suspended tool call may continue.
    """

    def __init__(self) -> None:
        self._inflight: dict[str, dict] = {}
        self._attributed_fds: dict[str, set[int]] = {}

    def begin_logical_action(self, epoch: str, action: str, fds: set[int]) -> None:
        self._inflight[epoch] = {"action": action, "fds": fds, "committed": False}
        self._attributed_fds.setdefault(epoch, set()).update(fds)

    def commit_logical_action(self, epoch: str) -> None:
        record = self._inflight.get(epoch)
        if record is None:
            raise SandboxReentryViolation(
                f"commit for unknown epoch {epoch!r}; ledger was flushed mid-action"
            )
        record["committed"] = True

    def resume_epoch(self, epoch: str, carried_fds: set[int]) -> dict:
        record = self._inflight.get(epoch)
        if record is None:
            # Suspension landed inside a logical action whose authorization
            # state was not serialized with the process image. Re-entry is
            # unsound; the runtime must abort and reissue under a new epoch.
            raise SandboxReentryViolation(
                f"resume of epoch {epoch!r} with no in-flight record: "
                f"carried fds {sorted(carried_fds)} have no mediator provenance; "
                f"abort tool call and reissue under fresh epoch"
            )
        unattributed = carried_fds - self._attributed_fds.get(epoch, set())
        if unattributed:
            raise SandboxReentryViolation(
                f"epoch {epoch!r} resumed with unattributed fds {sorted(unattributed)}; "
                f"refusing to permit further syscalls on this epoch"
            )
        if record["committed"]:
            raise SandboxReentryViolation(
                f"epoch {epoch!r} already committed logical action "
                f"{record['action']!r}; replay would double-apply"
            )
        return record


def resume_suspended_tool_call(
    ledger: EpochLedger,
    epoch: str,
    carried_fds: set[int],
    checkpoint_phase: str,
) -> str:
    """Runtime-side resume path. Returns 'continue' or 'reissue'.

    The checkpoint_phase is agent-layer state and is deliberately not
    trusted to decide re-entry; only the mediator's ledger is.
    """
    try:
        record = ledger.resume_epoch(epoch, carried_fds)
    except SandboxReentryViolation:
        # Conservative default: not re-enterable. Close fds, drop the
        # agent's partial episodic record, reissue from the top.
        return "reissue"
    if record["action"] == "write_rename" and checkpoint_phase != "post_commit":
        # Suspension landed between write and renameat2; the mediator
        # holds an uncommitted logical action. Continuing would let the
        # skill re-issue renameat2 against a temp file it no longer owns.
        raise SandboxReentryViolation(
            f"epoch {epoch!r} suspended mid write_rename at phase "
            f"{checkpoint_phase!r}; renameat2 must not be reissued"
        )
    return "continue"
