# Why Exit Scripts Are Too Late: Stopping Post-Compaction Retry Spirals in Coding Agents

> Source: <https://dev.to/tomzafred/why-exit-scripts-are-too-late-stopping-post-compaction-retry-spirals-in-coding-agents-41le>
> Published: 2026-11-26 14:11:32+00:00

**Recommendation:** Split agent governance into two planes: a watchdog that detects compaction and re-anchors invariants before the next edit, and a separate pre-mutation plus exit gate for mechanical enforcement.
More in the playbook "Working with AI coding agents": <https://wpnews.pro/playbooks/coding-agents>

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`](https://dev.to/dannwaneri/dont-write-markdown-files-for-your-coding-agent-write-scripts-j00) 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**.

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](https://dev.to/tomzafred/the-pink-elephant-in-the-token-window-why-transformer-self-attention-hates-your-do-not-rules-569a); 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:

`stderr` reports symptoms, not architecture.`FAIL: raw string interpolation in query.js:84` tells 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.
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.

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.

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.

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%](https://dev.to/tomzafred/cutting-coding-agent-token-burn-by-65-a-two-stage-discussion-lock-and-2-turn-mcp-execution-loop-49e3)) 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.

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:

`"CHECKPOINT"` or `"compact_boundary"`. Naturally, the first time the agent read `JSON.parse()` strictly on hits to verify top-level fields.`string.length` (UTF-16 code units) works fine until someone types a pound sign, em-dash, or emoji - after which `fs.readSync` lands mid-object and goes deaf. Mid-flush reads can also tear a 4-byte UTF-8 character in half, and an unbounded `Buffer.allocUnsafe(delta)` risks a memory spike if a tool dumps a 40 MB log. `fs.fstatSync(fd)` (closing the `stat -> open` rename race), read in bounded 1 MiB chunks, decode only through the last raw `0x0a` byte, advance in raw bytes, and fast-skip >1 MiB single-line blobs.`st.size < cursor.offset` catches truncation, yet misses an atomic `renameSync` swap onto a `st.ino` (degrading cleanly where filesystems report `0`) 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:

``` python
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:

`acknowledgeReanchor` in a 100-entry LRU file) so each compaction re-anchors once.`EPERM`/` EBUSY``input_tokens + cache_read_tokens` on the same delta pass
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):

`JSON.parse` every turn (`150` runs):`11.17ms` p50 / `16.82ms` p95`scanCompactionDelta` (`1,000` steady-state turns):`0.072ms` p50 / `0.091ms` p95`156.2x` speedup`9.38ms` cold prime, `15/15` adversarial vectors passing, 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.

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.

`session-guard` v2.5.0 (RFC-002)
