Compacts the main conversation to a near-clear at each /loop /auto iteration boundary (a turn ending with an iteration outcome line), with one ledger row per…

A hooks-only mod that compacts the main conversation to a near-clear at each /loop /auto iteration boundary, so every iteration starts at the session's fixed floor instead of carrying the previous iterations' context. /auto keeps its cross-iteration state in tmp/auto-state-<runKey>.json and Linear, which is what makes the near-clear loss-free.
A boundary is a main-loop turn that ended with one of /auto's iteration outcome lines (SHIPPED-MERGE, SHIPPED-PR, DEFERRED-MERGE, SKIPPED-*, BLOCKED-ON-REVIEW, AUTO-CONTINUE, NO-CANDIDATES, AUTO-HALTED), in a session that is looping — a /loop prompt was typed or dispatched, a scheduled-trigger wakeup arrived, or a ScheduleWakeup call armed the next iteration — on a loop prompt that begins with a configured prefix (/auto).
Never compacted: a turn with no outcome line (the fallback heartbeat's status check with delegated work in flight, or a stalled turn), any turn in a session running no loop, the turn whose ScheduleWakeup ends the loop, an aborted or errored turn, and every subagent conversation. Each passed-through looping turn gets a pass ledger row with its reason.
The compaction is called from turn.complete, the one site the engine accepts it from (the probe's result is in mods/loop-boundary-probe/README.md); the mod's own session.compact hook answers that compaction with one message naming the outcome line, the run key and the run-state file, so no summarizer request is made.
Installed mod, claude --bg /loop 1m on sonnet with the loop prompt configured as a prefix, each reply ending in an outcome line: the first boundary took the next request from 72,791 to 45,813 tokens, and the second iteration's last request was 45,813 again — the floor held, nothing accumulated. In a fleet session the floor is the ~108k fixed overhead doc/compacting-investigation.md measured.
userConfig: enabled (kill switch), loop_prefixes (comma-separated, default /auto), min_context_percent (below it a boundary is logged, not compacted; default 0), ledger.
<checkout>/tmp/loop-boundary-<sessionId>.jsonl, where the checkout is the one that owns the session root — a linked worktree resolves to its main checkout, so a session resumed inside one keeps writing where fleet-metrics.py reads (the three 2026-10-10 fleet sessions, resumed at 14:22Z, split their ledgers into the worktrees until this resolution):
{"ts":"...","session":"...","event":"boundary","accepted":true,"outcome":"SHIPPED-MERGE: BF-1","tokensBefore":480210,"tokensAfter":112340,"path":"turn-complete","nearClear":true,"turnId":"...","loopPrompt":"/auto"}
{"ts":"...","session":"...","event":"pass","reason":"no-outcome","turnId":"...","loopPrompt":"/auto"}
tokensBefore is the context of the last request before the boundary; tokensAfter is the context of the next iteration's first request, filled in when it answers (null until then, and on a session that ends first). The retro reads it: fleet-metrics.py reports a Boundary compactions line and boundary_compactions in its JSON.
Installed user-wide by update.sh from the repo's marketplace and loaded in place from this folder; fleet-launch.sh and fleet-sequence.sh refuse to dispatch where it is not enabled (scripts/mod-enabled.sh loop-boundary), since they no longer add an --autocompact cap. claude --plugin-dir ~/.claude/mods/loop-boundary loads it for one session on a machine without the install.
claude plugin validate mods/loop-boundary && claude plugin test mods/loop-boundary && mods/typecheck.sh mods/loop-boundaryhooks/register.ts 153 lines1import type { Register } from 'claude-code'
2import { boundaryMessage, dotGitOf, loopPromptOf, matchesPrefix, outcomeLineOf, owningCheckout, readOptions, requestTokensOf, wakeupPromptOf } from './boundary'
3
4let sessionId = ''
5let runKey = ''
6let root = ''
7let ledgerPath = ''
8let rows: string[] = []
9let loopPrompt: string | null = null
10let loopEnding = false
11let stepOutcome: string | null = null
12let rearmed = false
13let compacting: { outcome: string; tokensBefore: number | null } | null = null
14let nearClear = false
15let pendingAfter: number | null = null
16
17type Writer = { readonly fs: { readonly write: (path: string, text: string) => Promise<void> } }
18
19async function flush($: Writer): Promise<void> {
20 await $.fs.write(ledgerPath, rows.join('\n') + '\n')
21}
22
23async function record($: Writer, row: Record<string, unknown>, ledger: boolean): Promise<number> {
24 if (!ledger) return -1
25 rows.push(JSON.stringify({ ts: new Date().toISOString(), session: sessionId, ...row }))
26 await flush($)
27 return rows.length - 1
28}
29
30export const register: Register = (on, options) => {
31 const opts = readOptions(options)
32
33 on('session.start', async ($, e, next) => {
34 sessionId = await $.session.id()
35 runKey = sessionId.split('-')[0] ?? sessionId
36 const reported = await $.session.root()
37 root = owningCheckout(reported, await dotGitOf((path) => $.fs.read(path), reported))
38 if (opts.enabled && opts.ledger) {
39 ledgerPath = `${root}/tmp/loop-boundary-${sessionId}.jsonl`
40 if (await $.fs.exists(ledgerPath)) rows = (await $.fs.read(ledgerPath)).split('\n').filter((line) => line !== '')
41 }
42 return next(e)
43 })
44
45 // A session is looping once a /loop prompt is typed (or dispatched, as a fleet session's first prompt) or a loop
46 // wakeup arrives; the loop prompt is what the prefix list is matched against.
47 on('prompt.submit', async ($, e, next) => {
48 const typed = loopPromptOf(e.text)
49 if (typed !== null) loopPrompt = typed
50 else if (e.origin.kind === 'scheduled-trigger') loopPrompt = e.text.trim()
51 return next(e)
52 })
53
54 on('turn.start', async ($, e, next) => {
55 loopEnding = false
56 stepOutcome = null
57 rearmed = false
58 return next(e)
59 })
60
61 // The ScheduleWakeup call that arms the next iteration carries the loop prompt; stop:true ends the loop.
62 // The first request after a boundary measures what the compaction left: its context is the boundary's tokensAfter.
63 on('turn.step', async function* ($, e, next) {
64 if (e.agentId !== undefined || !opts.enabled) return yield* next(e)
65 const result = yield* next(e)
66 const wake = wakeupPromptOf(result.toolUses)
67 if (wake.stop) loopEnding = true
68 else if (wake.prompt !== null) {
69 loopPrompt = wake.prompt
70 rearmed = true
71 }
72 stepOutcome = outcomeLineOf(result.answer) ?? stepOutcome
73 if (pendingAfter !== null && opts.ledger) {
74 const after = requestTokensOf(result.usage)
75 const row = rows[pendingAfter]
76 if (row !== undefined && after !== null) {
77 rows[pendingAfter] = JSON.stringify({ ...(JSON.parse(row) as Record<string, unknown>), tokensAfter: after })
78 await flush($)
79 $.ui.log(`loop-boundary: next iteration's first request carried ${after.toLocaleString()} tokens`)
80 }
81 pendingAfter = null
82 }
83 return result
84 })
85
86 on('turn.complete', async ($, e, next) => {
87 const result = await next(e)
88 if (e.agentId !== undefined || !opts.enabled || loopPrompt === null) return result
89 const base = { turnId: e.turnId, loopPrompt }
90 if (!matchesPrefix(loopPrompt, opts.prefixes)) {
91 await record($, { event: 'pass', reason: 'prefix', ...base }, opts.ledger)
92 return result
93 }
94 if (e.reason !== 'answer') {
95 await record($, { event: 'pass', reason: e.reason, ...base }, opts.ledger)
96 return result
97 }
98 // The outcome line usually closes the turn, but /auto sometimes emits its tag mid-turn, re-arms, and ends on a prose summary:
99 // 10 of the 2026-10-12 fleet's 48 shipping turns did, and each next iteration started at ~470k instead of ~83k. A tag from an
100 // earlier step counts only in a turn that also re-armed the loop — the shape of an iteration that ended, not one in flight.
101 const outcome = outcomeLineOf(e.answer) ?? (rearmed ? stepOutcome : null)
102 if (outcome === null) {
103 await record($, { event: 'pass', reason: 'no-outcome', ...base }, opts.ledger)
104 return result
105 }
106 if (loopEnding) {
107 await record($, { event: 'pass', reason: 'loop-ended', outcome, ...base }, opts.ledger)
108 return result
109 }
110 const context = (await $.session.usage()).context
111 if (opts.minContextPercent > 0 && (context.percent ?? 0) < opts.minContextPercent) {
112 await record($, { event: 'pass', reason: 'below-floor', outcome, contextPercent: context.percent ?? null, ...base }, opts.ledger)
113 return result
114 }
115 const tokensBefore = context.tokens ?? null
116 compacting = { outcome, tokensBefore }
117 nearClear = false
118 let row: Record<string, unknown>
119 try {
120 const compacted = await $.session.compact()
121 row =
122 compacted.skip !== undefined
123 ? { event: 'boundary', accepted: false, skipped: compacted.skip, outcome, tokensBefore, tokensAfter: null, path: 'turn-complete', nearClear, ...base }
124 : { event: 'boundary', accepted: true, outcome, tokensBefore: compacted.tokensBefore ?? tokensBefore, tokensAfter: null, path: 'turn-complete', nearClear, ...base }
125 } catch (err) {
126 row = { event: 'boundary', accepted: false, error: String(err), outcome, tokensBefore, tokensAfter: null, path: 'turn-complete', nearClear: false, ...base }
127 }
128 compacting = null
129 const index = await record($, row, opts.ledger)
130 if (row.accepted === true) {
131 pendingAfter = index >= 0 ? index : null
132 $.ui.log(`loop-boundary: compacted at the iteration boundary after \`${outcome}\` — the last request carried ${tokensBefore === null ? 'an unmeasured number of' : tokensBefore.toLocaleString()} tokens`)
133 } else {
134 $.ui.log(`loop-boundary: boundary after \`${outcome}\` not compacted (${String(row.skipped ?? row.error)})`)
135 }
136 return result
137 })
138
139 // The compaction this mod triggered is answered here with the one boundary message, so no summarizer runs. The
140 // in-flight flag is the key: it is set just before the call and cleared just after, and the engine stamps the event
141 // `trigger: plugin` (the plugin test harness stamps nothing). Every other compaction — the engine's threshold, a typed
142 // /compact, a subagent's — passes through untouched.
143 on('session.compact', async ($, e, next) => {
144 if (e.agentId !== undefined || compacting === null) return next(e)
145 nearClear = true
146 const statePath = `${root}/tmp/auto-state-${runKey}.json`
147 const text = boundaryMessage({ outcome: compacting.outcome, runKey, statePath, stateExists: await $.fs.exists(statePath) })
148 return compacting.tokensBefore === null
149 ? { messages: [{ role: 'user', text, toolUses: [] }] }
150 : { messages: [{ role: 'user', text, toolUses: [] }], tokensBefore: compacting.tokensBefore }
151 })
152}
153hooks/boundary.ts 109 lines1export type ToolUse = { readonly name: string; readonly input: unknown }
2
3// The lines /auto ends an iteration with (skills/auto/SKILL.md). A heartbeat status check and a stalled turn end with
4// none of them, which is what keeps an in-flight iteration's context intact.
5const OUTCOME_LINE = /^[\s>*_`#-]*(SHIPPED-MERGE|SHIPPED-PR|DEFERRED-MERGE|SKIPPED-[A-Z]+(?:-[A-Z]+)*|BLOCKED-ON-REVIEW|AUTO-CONTINUE|NO-CANDIDATES|AUTO-HALTED)\b.*$/m
6
7export function outcomeLineOf(answer: string): string | null {
8 const m = OUTCOME_LINE.exec(answer)
9 if (m === null) return null
10 return m[0].replace(/^[\s>*_`#-]+/, '').replace(/[*_`]+/g, '').trim().slice(0, 200)
11}
12
13// `/loop 5m /auto epic:BF-1` re-fires `/auto epic:BF-1`; `/loop /auto` re-fires `/auto`. Anything else is its own prompt.
14const LOOP_PROMPT = /^\/loop(?:\s+\d+(?:\.\d+)?\s*(?:s|m|h|d|sec|secs|min|mins|minutes?|seconds?|hours?|days?))?\s+([\s\S]*)$/i
15
16export function loopPromptOf(text: string): string | null {
17 const m = LOOP_PROMPT.exec(text.trim())
18 return m === null ? null : (m[1] ?? '').trim()
19}
20
21export function matchesPrefix(prompt: string, prefixes: readonly string[]): boolean {
22 const p = prompt.trim()
23 return prefixes.some((prefix) => p === prefix || p.startsWith(`${prefix} `))
24}
25
26function inputOf(use: ToolUse): Record<string, unknown> {
27 return typeof use.input === 'object' && use.input !== null ? (use.input as Record<string, unknown>) : {}
28}
29
30// The loop prompt a ScheduleWakeup call carries forward, or null when the call ends the loop or there is no such call. /auto re-arms
31// with its whole `/loop /auto …` command, so the prompt is stripped the same way a typed one is before the prefix list sees it.
32export function wakeupPromptOf(uses: readonly ToolUse[]): { prompt: string | null; stop: boolean } {
33 let prompt: string | null = null
34 let stop = false
35 for (const use of uses) {
36 if (use.name !== 'ScheduleWakeup') continue
37 const input = inputOf(use)
38 if (input.stop === true) stop = true
39 else if (typeof input.prompt === 'string') prompt = loopPromptOf(input.prompt) ?? input.prompt.trim()
40 }
41 return { prompt, stop }
42}
43
44export function requestTokensOf(usage: unknown): number | null {
45 if (typeof usage !== 'object' || usage === null) return null
46 const u = usage as Record<string, unknown>
47 const parts = [u.input_tokens, u.cache_read_input_tokens, u.cache_creation_input_tokens].filter((v): v is number => typeof v === 'number')
48 return parts.length === 0 ? null : parts.reduce((a, b) => a + b, 0)
49}
50
51export function boundaryMessage(args: { outcome: string; runKey: string; statePath: string; stateExists: boolean }): string {
52 const state = args.stateExists ? `run state in ${args.statePath}` : `no run-state file at ${args.statePath} yet`
53 return [
54 `Loop boundary: the previous /auto iteration ended with \`${args.outcome}\`.`,
55 `Run key ${args.runKey}; ${state}. The conversation before this point was compacted away at the iteration boundary by the loop-boundary mod; /auto re-reads its state from that file and from Linear, and nothing from the earlier iteration is needed here.`,
56 ].join('\n')
57}
58
59export type Options = {
60 readonly enabled: boolean
61 readonly prefixes: readonly string[]
62 readonly minContextPercent: number
63 readonly ledger: boolean
64}
65
66// The checkout a ledger belongs to. A session resumed inside a /start wt worktree reports the worktree as its root — measured
67// 2026-10-10: three fleet sessions resumed at 14:22Z wrote their later rows under <worktree>/tmp, where /finish deletes them and
68// fleet-metrics.py never looked — so a linked worktree (its `.git` is a file naming the owning repo's worktrees dir) resolves to
69// the checkout that owns it. Anything else, a main checkout's `.git` directory included, keeps the root as reported.
70export function owningCheckout(root: string, dotGit: string | null): string {
71 const target = /^gitdir:\s*(.+?)\s*$/m.exec(dotGit ?? '')?.[1]
72 if (target === undefined) return root
73 const gitdir = (/^(?:\/|[A-Za-z]:[\\/])/.test(target) ? target : `${root}/${target}`).replace(/\\/g, '/')
74 const at = gitdir.indexOf('/.git/worktrees/')
75 if (at === -1) return root
76 const out: string[] = []
77 for (const seg of gitdir.slice(0, at).split('/')) {
78 if (seg === '..') out.pop()
79 else if (seg !== '.' && (seg !== '' || out.length === 0)) out.push(seg)
80 }
81 return out.join('/')
82}
83
84// A main checkout's `.git` is a directory, which the read rejects; a linked worktree's is a one-line file.
85export async function dotGitOf(read: (path: string) => Promise<string>, root: string): Promise<string | null> {
86 try {
87 return await read(`${root}/.git`)
88 } catch {
89 return null
90 }
91}
92
93export function readOptions(raw: Readonly<Record<string, unknown>>): Options {
94 const prefixes =
95 typeof raw.loop_prefixes === 'string'
96 ? raw.loop_prefixes
97 .split(/[,\s]+/)
98 .map((p) => p.trim())
99 .filter((p) => p !== '')
100 : []
101 const min = raw.min_context_percent
102 return {
103 enabled: raw.enabled !== false,
104 prefixes: prefixes.length > 0 ? prefixes : ['/auto'],
105 minContextPercent: typeof min === 'number' && min > 0 ? Math.min(100, min) : 0,
106 ledger: raw.ledger !== false,
107 }
108}
109