# CorpusFetch Method Slice (Zero-Prose Python Stdlib Reference)
# Canonical Residual: https://corpusfetch.com/c/why-does-an-instance-drift-past-its-enforced-tool-budget-when-ebpf-interception-counts-syscalls-instead-of-semantic-tool-invocations.md
# Remnant Warrant:    https://corpusfetch.com/c/why-does-an-instance-drift-past-its-enforced-tool-budget-when-ebpf-interception-counts-syscalls-instead-of-semantic-tool-invocations.warrant.json
# Markdown SHA-256:   383e33b40daa389ce903d38c215343964532e29070dec7ac807a45297a4806d0
# Code AST SHA-256:   fe7fab4bc8d3ebe07888d1790372706cb76029a1fbe0efb605ff77fe599d6070
# Verified Classes:   SemanticBudgetMeter, FramingViolation, SemanticBudgetExceeded
# Defensive Guards:   3 fail-closed invariants (zero external deps)

class SemanticBudgetMeter:
    """
    Reassembles length-prefixed memory records from fragment writes before
    charging the semantic budget. Falls closed on framing errors.
    """

    def __init__(self, max_semantic_commits: int, max_record_bytes: int = 1 << 20):
        self.max_semantic_commits = max_semantic_commits
        self.max_record_bytes = max_record_bytes
        self.semantic_commits = 0
        self._buf = bytearray()
        self._expected_len = None

    def on_write(self, fragment: bytes) -> int:
        # fragment is one intercepted write(2) payload on the memory fd
        self._buf.extend(fragment)
        commits = 0
        while True:
            if self._expected_len is None:
                if len(self._buf) < 4:
                    return commits
                self._expected_len = int.from_bytes(self._buf[:4], "big")
                if self._expected_len > self.max_record_bytes:
                    raise FramingViolation(
                        f"declared record length {self._expected_len} exceeds "
                        f"cap {self.max_record_bytes}; refusing to meter mechanically"
                    )
                del self._buf[:4]
            if len(self._buf) < self._expected_len:
                return commits
            # one complete semantic record reassembled
            del self._buf[: self._expected_len]
            self._expected_len = None
            commits += 1
            self.semantic_commits += 1
            if self.semantic_commits > self.max_semantic_commits:
                raise SemanticBudgetExceeded(
                    f"semantic commits {self.semantic_commits} exceeded grant "
                    f"{self.max_semantic_commits} (mechanical fragments were not counted)"
                )


class FramingViolation(RuntimeError):
    pass


class SemanticBudgetExceeded(RuntimeError):
    pass


def enforce(meter: SemanticBudgetMeter, intercepted_writes: list[bytes]) -> int:
    total = 0
    for frag in intercepted_writes:
        total += meter.on_write(frag)
    # invariant check: a dangling partial record means the agent was killed
    # mid-record; the next resume must NOT inherit a half-charged budget.
    if meter._expected_len is not None or meter._buf:
        raise FramingViolation(
            "task ended with an unreassembled partial record; "
            "checkpoint must be discarded, not resumed"
        )
    return total
