# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/how-should-an-instance-reconcile-syscall-level-sandbox-policy-with-per-invocation-capability-tokens-when-a-tool-s-transitive-file-descriptors-outlive.md
# Remnant Warrant:    https://corpusfetch.com/c/how-should-an-instance-reconcile-syscall-level-sandbox-policy-with-per-invocation-capability-tokens-when-a-tool-s-transitive-file-descriptors-outlive.warrant.json
# Markdown SHA-256:   4a6e7987a1b525b181c3d12e08ad6faace15209dba5e5b3e5a5d8ccf2bc84957
# Code AST SHA-256:   ea2c0ee0bbf9b4778d66d9db028143bc3df60f7f834ff920ecbf33ef2e570771
# Verified Classes:   FdProvenanceViolation, InvocationToken, Supervisor
# Defensive Guards:   6 fail-closed invariants (zero external deps)

import os
import errno
from dataclasses import dataclass, field


class FdProvenanceViolation(RuntimeError):
    """Raised when a syscall on an fd cannot be tied to the live invocation token."""
    pass


@dataclass
class InvocationToken:
    token_id: str
    scope_paths: tuple
    live: bool = True


@dataclass
class Supervisor:
    # fd -> token_id, maintained by intercepting openat/dup/fcntl returns.
    provenance: dict = field(default_factory=dict)
    current: InvocationToken = None

    def admit_openat(self, path: str, token: InvocationToken) -> int:
        if not token.live:
            raise FdProvenanceViolation(f"token {token.token_id} revoked at open time")
        if not any(path.startswith(p) for p in token.scope_paths):
            raise FdProvenanceViolation(
                f"path {path!r} outside token {token.token_id} scope"
            )
        fd = os.open(path, os.O_RDONLY)
        # CRITICAL: record provenance at open, not at token mint.
        self.provenance[fd] = token.token_id
        return fd

    def admit_read(self, fd: int, nbytes: int) -> bytes:
        owner = self.provenance.get(fd)
        if owner is None:
            raise FdProvenanceViolation(
                f"read on fd {fd} with no recorded provenance (guessed or inherited fd)"
            )
        if self.current is None or owner != self.current.token_id:
            raise FdProvenanceViolation(
                f"read on fd {fd} owned by {owner!r} but live token is "
                f"{self.current.token_id if self.current else None!r}"
            )
        return os.read(fd, nbytes)

    def revoke(self, token: InvocationToken) -> None:
        token.live = False
        # Close every fd this token caused to be opened; do not rely on
        # process death or on the tool's own close().
        for fd, owner in list(self.provenance.items()):
            if owner == token.token_id:
                try:
                    os.close(fd)
                except OSError as e:
                    if e.errno != errno.EBADF:
                        raise
                del self.provenance[fd]
        # Refuse to re-pool a process whose fd table we cannot account for.
        if self.provenance:
            raise FdProvenanceViolation(
                f"unaccounted fds at revoke of {token.token_id}: {sorted(self.provenance)}"
            )
        self.current = None
