# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/what-structural-signals-indicate-syscall-level-taint-propagation-has-been-defeated-by-taint-laundering-through-agent-generated-helper-binaries.md
# Remnant Warrant:    https://corpusfetch.com/c/what-structural-signals-indicate-syscall-level-taint-propagation-has-been-defeated-by-taint-laundering-through-agent-generated-helper-binaries.warrant.json
# Markdown SHA-256:   352c8414ad6aff82a884445e9c79f706497507ec83b0e9f6408c0c4372c193ba
# Code AST SHA-256:   77d58fc16a574856f9cf17ac494252c2a5a109276c98dfc08ec244a196b519d9
# Verified Classes:   TaintLedgerImbalance, TaintLedger
# Defensive Guards:   3 fail-closed invariants (zero external deps)

from dataclasses import dataclass, field


class TaintLedgerImbalance(RuntimeError):
    """Raised when tainted-byte flux across the sandbox boundary is not conserved
    and no explicit declassification record explains the discrepancy."""


@dataclass
class TaintLedger:
    taint_in: int = 0
    taint_out: int = 0
    declassified: int = 0
    process_tree_mutations: list = field(default_factory=list)

    def record_ingress(self, nbytes: int) -> None:
        self.taint_in += nbytes

    def record_egress(self, nbytes: int, tainted: bool) -> None:
        if tainted:
            self.taint_out += nbytes

    def record_declassify(self, nbytes: int, reason: str) -> None:
        if not reason:
            raise TaintLedgerImbalance("declassification requires a logged reason")
        self.declassified += nbytes

    def record_tree_mutation(self, kind: str, path: str | None = None) -> None:
        # fork/execve/clone/unshare all risk resetting per-process label maps.
        self.process_tree_mutations.append((kind, path))

    def assert_conserved(self) -> None:
        imbalance = self.taint_in - self.taint_out - self.declassified
        if imbalance != 0:
            raise TaintLedgerImbalance(
                f"taint flux unbalanced by {imbalance} bytes "
                f"(in={self.taint_in}, out={self.taint_out}, "
                f"declassified={self.declassified}); "
                f"tree mutations={self.process_tree_mutations}. "
                f"Suspect laundering via execve label reset, zero-copy "
                f"(splice/sendfile/io_uring), or helper-binary provenance gap."
            )
        # Even a balanced ledger is suspect if an agent-authored binary was
        # exec'd: labels may have been reset and re-derived inconsistently.
        for kind, path in self.process_tree_mutations:
            if kind == "execve" and path and path.startswith("/tmp/"):
                raise TaintLedgerImbalance(
                    f"execve of agent-authored binary {path!r} without "
                    f"tainted-by-descent re-arming; conservation is unverifiable."
                )


def audit_sandbox_exit(ledger: TaintLedger) -> None:
    ledger.assert_conserved()
