A few months ago, I briefly thought I had solved coding-agent governance in twenty minutes.
I binned half of a bloated 3,000-word rules file and replaced it with a strict post-edit verification script. Any forbidden SQL pattern, stray dependency, or missing boundary check tripped a blocking non-zero exit (exit 1 in POSIX wrappers; exit 2 in Claude Code hooks). No begging in system prompts - just deterministic checks. Twelve minutes later, I came back expecting a clean diff and found the agent on Turn 14 of a remarkably polite loop with the shell: failing, apologising, leaving half-patched files on disk, renaming a local variable, and walking straight back into the same error. The annoying part? The exit script was working flawlessly.
The shift toward deterministic tooling - argued sharply on here by @dannwaneri in his case for scripts, Makefile targets, and codemods over vague Markdown prose - gets half the physics right. When a script executes a mechanical transform (like ast-grep or a formatter), it removes agent judgment altogether. Where things break down is relying on post-write validation hooks (PostToolUse or Stop hooks) as your only safety net, because an agent's short-term memory quietly evaporates forty minutes before the exit hook ever runs.
1. The Amnesia Trap: When a Good Hook Turns Into a Retry Spiral
On Turn 1, a coding agent usually grasps why a boundary exists. Your instructions sit near the top of the prompt, and the surrounding files are in view.
Then real debugging happens. You chase stack traces, inspect six modules, and cross Turn 28. Quietly, the host harness runs automatic context compaction, replacing the first twenty-seven turns with a tidy summary paragraph so the chat stays inside its window.
Compaction summaries are good at remembering tasks ("refactoring invoice export; two tests left"). They are ruthlessly efficient at composting constraints and the architectural reasons behind them. I wrote earlier about why bare negative prose rules backfire under self-attention in The Pink Elephant in the Token Window; compaction finishes the job by physically evicting the original wording from the prompt.
Now watch an amnesiac model meet a bare post-write exit hook:
- Disk is already dirty. Post-edit hooks fire after the write has landed. Hit Cancel in frustration, and you inherit a half-rewritten working tree.
-
Exit
stderrreports symptoms, not architecture. PrintingFAIL: raw string interpolation in query.js:84tells the agent what annoyed the regex, not the database contract it forgot twenty turns ago. So it improvises a workaround that trips the next check, or weakens the code to appease the linter. - Every blind retry compounds the bill. Each failed patch appends another diff, traceback, and polite apology onto an already bloated window, shoving the session straight toward a second compaction cliff.
In the comments on his post, @dannwaneri put his finger directly on the weak spot in most rule-compression talk: shrinking an instruction file by 75% measures size, not compliance. He was dead right. Compacting rules buys you nothing if mid-session compaction sweeps them off the desk and leaves an exit script shouting into an empty room.
2. Two Planes Instead of One
An exit script is a fire alarm. Fire alarms are non-negotiable, yet nobody expects the sprinkler system to remind the chef where the oven gloves live.
Once I stopped asking one mechanism to serve as both short-term memory and building inspector, the setup split cleanly into two independent planes:
[Session Transcript (.jsonl)]
|
v (sub-0.1ms byte-offset delta scan)
+---------------------------------------------------------+
| PLANE 1: PROACTIVE MEMORY (Context Watchdog) |
| Detects genuine compaction event -> re-anchors active |
| invariants ONCE via a persistent monotonic watermark. |
+---------------------------------------------------------+
| (constraints restored BEFORE next edit)
v
+---------------------------------------------------------+
| PLANE 2: MECHANICAL ENFORCEMENT (Pre-Tool + Exit Gate) |
| Pre-mutation hook rejects illegal writes before disk |
| I/O and locks its own config; exit script stays in CI. |
+---------------------------------------------------------+
Plane 1 does not replace Plane 2; it stops the agent walking into Plane 2 blindfolded.
What Plane 1 Injects (~140 Tokens)
Do not re-inject a 3,000-word handbook after compaction. Re-inject a tiny contract holding only the active session's hard invariants:
[RE-ANCHOR | POST-COMPACTION INVARIANTS]
- DB: Parameterised queries only via db.execParam(); never interpolate SQL strings.
- UI: Pure Vanilla JS; zero jQuery or external runtime imports.
- SCOPE: Edit only files in src/billing/ and tests/billing/.
- LOCK: Hook and policy configs (.claude/, scripts/gates/) are read-only.
That block costs ~140 tokens for a dozen rules - less than one wasted tool call - and restores the why before the model drafts its next edit.
What Plane 2 Stops Before Disk I/O
Moving checks from a post-edit script to a Pre-Tool Gate (a Claude Code PreToolUse hook or an MCP write lock, like the two-stage discussion lock in Cutting Coding Agent Token Burn by 65%) rejects bad edits before disk is touched.
Crucially - echoing a sharp point @dannwaneri raised in his own comments - the gate must also protect its own hook configuration, or a creative agent can edit the settings file to reach exit 0:
// Minimal Claude Code PreToolUse gate (reads JSON on stdin, blocks before disk I/O).
import fs from 'node:fs';
const { tool_name, tool_input = {} } = JSON.parse(fs.readFileSync(0, 'utf8'));
const target = String(tool_input.file_path || '');
const content = String(tool_input.content || tool_input.new_string || '');
const command = String(tool_input.command || '');
const PROTECTED_PATH = /(^|[\\/\s"'])(\.claude|scripts[\\/]gates)([\\/\s"']|$)/i;
const deny = (reason) => {
process.stdout.write(JSON.stringify({
hookSpecificOutput: {
hookEventName: 'PreToolUse',
permissionDecision: 'deny',
permissionDecisionReason: reason,
},
}));
process.exit(0); // Exit 0 + stdout JSON applies permissionDecision; plain stderr uses exit 2.
};
if (/^(Write|Edit|MultiEdit)$/.test(tool_name)) {
if (PROTECTED_PATH.test(target)) {
deny('Policy boundary: hook configs are immutable during agent runs.');
}
if (/SELECT\s+.*\$\{/i.test(content)) {
deny('Database contract: use db.execParam() with bind parameters, not template SQL.');
}
}
if (tool_name === 'Bash' && PROTECTED_PATH.test(command)) {
deny('Policy boundary: shell edits to hook configs are blocked (enforce OS read-only perms too).');
}
Disk stays spotless, the gate cannot be self-disabled, and the denial hands back the architectural contract rather than a cryptic regex line number.
3. Three Embarrassing Bugs in a Naive Watchdog (And the Tested Fix)
Building Plane 1 looks simple: tail the .jsonl transcript, spot a compaction marker, and inject the re-anchor block. Here are the three rakes I personally stepped on so you can walk straight past them:
-
The Phantom Compaction Comedy. My first prototype scanned appended lines for
"CHECKPOINT"or"compact_boundary". Naturally, the first time the agent read the watchdog's own source file, the transcript logged a tool result containing those strings and set off the alarm on Turn 2. Fix: keep a fast substring pre-filter so ~99.9% of lines allocate nothing, thenJSON.parse()strictly on hits to verify top-level fields. -
UTF-8 Cursor Drift, Partial Flushes, and Giant Blobs. Advancing an offset by JavaScript
string.length(UTF-16 code units) works fine until someone types a pound sign, em-dash, or emoji - after whichfs.readSynclands mid-object and goes deaf. Mid-flush reads can also tear a 4-byte UTF-8 character in half, and an unboundedBuffer.allocUnsafe(delta)risks a memory spike if a tool dumps a 40 MB log. Fix: open the descriptor first and callfs.fstatSync(fd)(closing thestat -> openrename race), read in bounded 1 MiB chunks, decode only through the last raw0x0abyte, advance in raw bytes, and fast-skip >1 MiB single-line blobs. -
Atomic Log-Rotation Blindness. Checking only
st.size < cursor.offsetcatches truncation, yet misses an atomicrenameSyncswap onto a larger file unless you also comparest.ino(degrading cleanly where filesystems report0) and reset the watermark with the offset.
Here is the complete, zero-dependency Node.js watchdog core - supporting both Antigravity (SYSTEM/CHECKPOINT) and Claude Code (type: "system" / subtype: "compact_boundary") markers out of the box, with a pluggable matcher for any other harness:
import fs from 'node:fs';
const MAX_CHUNK = 1024 * 1024; // Cap per-read allocation at 1 MiB.
const DEFAULT_HINTS = ['CHECKPOINT', 'CONTEXT_SUMMARY', 'compact_boundary'];
export function makeCursor() {
return {
offset: 0, ino: 0, linesSeen: 0,
lastCheckpointStep: -1, reanchoredStep: -1, skipToNl: false,
};
}
export function acknowledgeReanchor(cursor, step) {
if (step > cursor.reanchoredStep) cursor.reanchoredStep = step;
}
export function defaultIsCompaction(ev) {
if (!ev || typeof ev !== 'object') return false;
if (ev.source === 'SYSTEM' && (ev.type === 'CHECKPOINT' || ev.type === 'CONTEXT_SUMMARY')) return true;
if (ev.type === 'system' && ev.subtype === 'compact_boundary') return true;
return false;
}
export function scanCompactionDelta(
filePath,
cursor,
{ isCompaction = defaultIsCompaction, hints = DEFAULT_HINTS } = {},
) {
const fd = fs.openSync(filePath, 'r');
let compacted = false;
try {
const st = fs.fstatSync(fd); // Stat the open fd to eliminate stat->open rename races.
if (st.size < cursor.offset || (cursor.ino && st.ino !== cursor.ino)) {
Object.assign(cursor, {
offset: 0, ino: st.ino, linesSeen: 0,
lastCheckpointStep: -1, reanchoredStep: -1, skipToNl: false,
});
}
cursor.ino = st.ino;
while (cursor.offset < st.size) {
const toRead = Math.min(st.size - cursor.offset, MAX_CHUNK);
const buf = Buffer.allocUnsafe(toRead);
const n = fs.readSync(fd, buf, 0, toRead, cursor.offset);
if (n <= 0) break;
const view = buf.subarray(0, n);
if (cursor.skipToNl) {
const firstNl = view.indexOf(0x0a);
if (firstNl === -1) { cursor.offset += n; continue; }
cursor.offset += firstNl + 1;
cursor.linesSeen += 1;
cursor.skipToNl = false;
continue;
}
// Advance only to the last raw 0x0a ('\n') byte so UTF-8 and partial flushes stay intact.
const lastNl = view.lastIndexOf(0x0a);
if (lastNl === -1) {
if (cursor.offset + n < st.size) { cursor.offset += n; cursor.skipToNl = true; continue; }
break; // Incomplete trailing line at EOF; wait for next flush.
}
const chunk = view.subarray(0, lastNl + 1).toString('utf8');
cursor.offset += lastNl + 1;
for (const rawLine of chunk.split('\n')) {
const line = rawLine.endsWith('\r') ? rawLine.slice(0, -1) : rawLine;
if (!line) continue;
cursor.linesSeen += 1;
if (hints.length > 0 && !hints.some((h) => line.includes(h))) continue;
try {
const ev = JSON.parse(line);
if (isCompaction(ev)) {
const step = Number.isInteger(ev.step_index) ? ev.step_index : cursor.linesSeen;
if (step > cursor.reanchoredStep) {
cursor.lastCheckpointStep = step;
compacted = true;
}
}
} catch {
// Ignore malformed lines without advancing the watermark.
}
}
}
} finally {
fs.closeSync(fd);
}
return { compacted, step: cursor.lastCheckpointStep };
}
In production (session-guard v2.5.0), three small hardening details keep this boring:
-
Persist a monotonic watermark (
acknowledgeReanchorin a 100-entry LRU file) so each compaction re-anchors once. -
Retry atomic renames on
EPERM/EBUSYon Windows, because Defender loves grabbing transient rename locks at the exact worst millisecond. -
Track
input_tokens + cache_read_tokenson the same delta pass so even on harnesses that hide compaction markers completely, you still catch sudden prompt drops, mid-session KV-cache collapses, and approaching context ceilings before amnesia ever starts.
4. Measured I/O Latency and Replay Arithmetic
Engineering write-ups stay honest when they separate what was timed on metal from deterministic cost arithmetic.
Timed on Node.js v24.22.1 across a synthetic 4.76 MB (4,996,438-byte), 300-step JSONL transcript containing decoy payloads, multi-byte UTF-8 text, and 1,000 steady-state appended turns (~1.5 KB each):
-
Naive full re-read +
JSON.parseevery turn (150runs):11.17msp50 /16.82msp95 -
Upgraded
scanCompactionDelta(1,000steady-state turns):0.072msp50 /0.091msp95 (156.2xspeedup,9.38mscold prime,15/15adversarial vectors passing,0false positives)
Switching from statSync + openSync to openSync + fstatSync(fd) did not merely fix a rename race - dropping the duplicate path lookup shaved ~20 microseconds off every turn.
Deterministic replay arithmetic for 4 constrained edits remaining after a compaction that leaves 27,000 tokens in context (+2,200 tok/turn when diffs and stderr pile up; +1,600 tok/turn when blocked pre-write):
| Governance Architecture | Turn Breakdown | Dirty Disk Writes | Cumulative Input Tokens Replayed | End Context |
|---|---|---|---|---|
| Exit Script Only |
16 (4 edits x (1 miss + 3 repairs)) |
4 |
696,000 |
62,200 |
| Pre-Tool Gate Only |
9 (4 blind catches + 4 fixes + 1 final pass) |
0 |
300,600 (-56.8%) |
41,400 |
Two-Plane (+140 tok re-anchor + Pre-Tool Gate) |
5 (4 clean edits + 1 residual catch) |
0 |
151,700 (-78.2%) |
35,140 |
What about KV prompt caching? Even a 90% cache-read discount on the stable prefix does not rescue the top row: compaction itself invalidates the cached prefix (forcing a fresh cache write), every newly appended failure diff and generated output token (billed at 5x-10x input rates) is uncached, and eleven wasted repair turns still burn minutes of wall-clock latency while inflating the window (35k -> 62k) toward a second compaction cliff.
Keep the Fire Alarm, Give the Agent Its Glasses Back
Do not bin your exit scripts. Keep them strict, deterministic, and immune to flattery - just stop asking a post-write hook to moonlight as a pre-write firewall and a short-term memory clinic at the same time.
If you want to adopt this on Monday without boiling the ocean, start in order: move one painful check from post-write to a PreToolUse gate (locking its own config path), make the denial explain the architectural contract rather than just a regex line, and then wire the 0.07ms compaction watchdog so active invariants come back once after every summary.
-
Open-Source Reference Runtime (MIT):
session-guardv2.5.0 (RFC-002) - zero-dependency Node.js context watchdog and post-compaction re-anchor extracted from my regulated laboratory software work at Biomed Systems Limited (UK).
Top comments (0)