Multi-agent loop for Claude Code: Fable/Opus plans, Codex challenges, Opus builds (effort medium), cheap OpenCode models (free ones first) do the rote parts…

hooks/review-status.tsx 203 lines1// review-status — a band above the prompt while a codex-review or grunt-run lane runs in the background, and the last
2// result for ten minutes after it ends. Reads the status files the plugin's scripts write under
3// ${XDG_STATE_HOME:-~/.local/state}/ai-loop (active/<pid>.json while a lane runs, last.json when one ends); no process is
4// started and nothing is sent anywhere.
5// 0.16.0: a context row from AI_CONTEXT_WARN tokens (300k; red from 5/3 of it), and the work rules below added to every session's
6// system prompt (prompt.compose). 0.19.0: the parked plugins line.
7// 0.20.0: compaction keeps the details. Every compaction (auto, /compact, a subagent's) tells the summarizer what to
8// keep (COMPACT_KEEP). After it, a short state note read from disk goes back into the session (classic SessionStart,
9// source compact): branch, uncommitted files, open review findings, newest task notes, loop worktrees.
10import type { Register } from 'claude-code'
11
12import type { LaneRow, LastRow } from '../types'
13
14const POLL_MS = 4000
15const STALE_S = 3 * 3600 // an active file older than this belongs to a lane that died without cleaning up
16const SHOW_LAST_S = 10 * 60 // how long the last result stays on the band
17
18// 10–17 Oct 2026 transcripts: 817 sleep/poll calls (17.8 h), 2,238 test runs, 40 general-purpose subagents at the session's effort.
19const WORK_RULES = [
20 'Work rules from the ai plugin:',
21 '- New tests: write one only for a bug reproducer or a check the spec\'s "Done means" names, e2e or integration first. No tests for refactors, UI layout, copy or config. Never add a test that repeats an existing one or a flow an e2e test covers.',
22 '- Tests: while you work, run only the tests for the code you changed. Run the full suite once, before you report or commit. A run that reports zero tests, or stops before it loads the test files, is a failure.',
23 '- Waiting: never poll with sleep loops or repeated status checks. Run a long command in the foreground with a timeout, or in the background and wait for its exit notice. Watch CI the same way (`gh run watch <id> --exit-status` in the background).',
24 '- Delegation: routine read-only checks (device or simulator QA, screenshot and store-listing reviews, audits) go to the ai `checker` agent, builds to the `implementer`, not to `general-purpose`.',
25 '- Parked plugins (installed, turned off to keep every request small): agent-skills (spec, review, performance and security workflows), superset (orchestration), claude-api (Claude API and SDK work, the prompt audit at each model release), typescript-lsp (type-aware code navigation), image-view (images in the terminal). When a task fits one, name it to the user and say it is off in /plugin. Do not work around it.',
26].join('\n')
27
28// What a summary must keep. The rest (file contents, command output) can be read again.
29const COMPACT_KEEP = [
30 'The ai plugin asks the summary to keep these, word for word where wording matters:',
31 '- what the user asked, answered and decided, in their words, and approaches tried and dropped, with the reason.',
32 '- the repo, branch, base and worktree, and the paths of the spec, plan, handoff and task notes in use.',
33 '- exact error messages, failing commands and test names, with their last result.',
34 '- open review findings and open questions for the user.',
35 '- what is done, what is in progress, and the next step.',
36 'Leave out file contents and command output that can be read again: give their paths instead.',
37].join('\n')
38
39// Read after a compaction, in the session's directory. Paths only: the model reads what it needs.
40const STATE_SH = [
41 'git rev-parse --is-inside-work-tree >/dev/null 2>&1 || exit 0',
42 'b=$(git branch --show-current)',
43 'echo "Branch: ${b:-detached HEAD} in $(git rev-parse --show-toplevel)"',
44 's=$(git status --short | head -25); [ -n "$s" ] && printf "Uncommitted:\\n%s\\n" "$s"',
45 'f="docs/tasks/review-notes/$(printf %s "$b" | sed -E "s/[^A-Za-z0-9._-]+/-/g").md"',
46 '[ -n "$b" ] && [ -f "$f" ] && echo "Open review findings: $f"',
47 'n=$(ls -t docs/tasks/*.md 2>/dev/null | head -5); [ -n "$n" ] && printf "Newest task notes:\\n%s\\n" "$n"',
48 'w=$(git worktree list | grep "/.claude/worktrees/" | head -8); [ -n "$w" ] && printf "Loop worktrees:\\n%s\\n" "$w"',
49 'exit 0',
50].join('\n')
51
52const dur = (s: number): string => {
53 if (s < 60) return `${s}s`
54 if (s < 3600) return `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
55 return `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`
56}
57
58export const register: Register = on => {
59 let stateDir = ''
60 let warnAt = 300_000
61
62 on('session.start', async ($, e, next) => {
63 const xdg = await $.env.get('XDG_STATE_HOME')
64 const home = await $.env.get('HOME')
65 stateDir = `${xdg || `${home ?? ''}/.local/state`}/ai-loop`
66 const w = Number(await $.env.get('AI_CONTEXT_WARN'))
67 if (Number.isFinite(w) && w > 0) warnAt = w
68
69 const poll = async () => {
70 const now = Math.floor((await $.clock.now()) / 1000)
71 const rows: LaneRow[] = []
72 try {
73 const entries = await $.fs.list(`${stateDir}/active`)
74 for (const entry of entries) {
75 if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
76 try {
77 const text = await $.fs.read(`${stateDir}/active/${entry.name}`)
78 const j = JSON.parse(text) as Partial<LaneRow> & { started?: number }
79 const started = Number(j.started ?? 0)
80 if (!started || now - started > STALE_S) continue
81 rows.push({
82 tool: String(j.tool ?? ''),
83 lane: String(j.lane ?? ''),
84 detail: String(j.detail ?? ''),
85 repo: String(j.repo ?? ''),
86 started,
87 elapsed: dur(Math.max(0, now - started)),
88 })
89 } catch {
90 // a file mid-write or already gone: skip it this round
91 }
92 }
93 } catch {
94 // no active/ directory yet: nothing runs
95 }
96 rows.sort((a, b) => a.started - b.started)
97 await $.state.set({ plugin: 'ai', key: 'lanes' }, rows)
98
99 let recent: LastRow | null = null
100 try {
101 const j = JSON.parse(await $.fs.read(`${stateDir}/last.json`)) as Partial<LastRow> & { finished?: number }
102 const finished = Number(j.finished ?? 0)
103 if (finished && now - finished <= SHOW_LAST_S) {
104 recent = {
105 tool: String(j.tool ?? ''),
106 lane: String(j.lane ?? ''),
107 result: String(j.result ?? ''),
108 detail: String(j.detail ?? ''),
109 repo: String(j.repo ?? ''),
110 finished,
111 ago: dur(Math.max(0, now - finished)),
112 }
113 }
114 } catch {
115 // no last.json yet
116 }
117 await $.state.set({ plugin: 'ai', key: 'last' }, recent)
118
119 let ctx = 0
120 try {
121 ctx = (await $.session.usage()).context.tokens ?? 0
122 } catch {
123 // no reading yet
124 }
125 await $.state.set({ plugin: 'ai', key: 'ctx' }, ctx)
126 }
127
128 void poll()
129 $.clock.every(POLL_MS, () => {
130 void poll()
131 })
132
133 return next(e)
134 })
135
136 on('prompt.compose', async ($, e, next) => {
137 const r = await next(e)
138 return { sections: [...r.sections, { id: 'ai:work-rules', text: WORK_RULES, scope: 'session' as const }] }
139 })
140
141 on('session.compact', async ($, e, next) =>
142 next({ ...e, instructions: e.instructions ? `${e.instructions}\n\n${COMPACT_KEEP}` : COMPACT_KEEP }),
143 ).catch(() => undefined) // a failure leaves the compaction as the engine does it
144
145 on('classic.SessionStart', async ($, e, next) => {
146 const r = await next(e)
147 if (e.source !== 'compact') return r
148 try {
149 const { stdout } = await $.process.run(['sh', '-c', STATE_SH], { cwd: e.cwd, timeoutMs: 10_000 })
150 const note = stdout.trim()
151 if (!note) return r
152 const text = `State after compaction, read from disk by the ai plugin (paths only, read what you need):\n${note}`
153 return { ...r, additionalContext: [...(r.additionalContext ?? []), text] }
154 } catch {
155 return r
156 }
157 }).catch(() => undefined)
158
159 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
160 const heldLanes = await $.state.get({ plugin: 'ai', key: 'lanes' })
161 const heldLast = await $.state.get({ plugin: 'ai', key: 'last' })
162 const running: LaneRow[] = heldLanes?.value ?? []
163 const recent: LastRow | null = heldLast?.value ?? null
164 const ctx: number = (await $.state.get({ plugin: 'ai', key: 'ctx' }))?.value ?? 0
165 const isBig = ctx >= warnAt
166 if (e.props.hasSurvey || (running.length === 0 && recent === null && !isBig)) {
167 return next(e)
168 }
169
170 const { Box, Text } = $.ui.resolve(e)
171
172 const isBad = recent !== null && (recent.result.includes('BLOCK') || recent.result.startsWith('no '))
173
174 return (
175 <Box flexDirection="column">
176 {running.map(row => (
177 <Box key={`${row.tool}-${row.started}`}>
178 <Text color="yellow">{'⟳ '}</Text>
179 <Text bold>{row.tool}</Text>
180 <Text dimColor>
181 {` · ${row.lane}${row.detail ? ` (${row.detail})` : ''} · ${row.elapsed}${row.repo ? ` · ${row.repo}` : ''}`}
182 </Text>
183 </Box>
184 ))}
185 {running.length === 0 && recent !== null && (
186 <Box key="last">
187 <Text color={isBad ? 'red' : 'green'}>{isBad ? '✗ ' : '✓ '}</Text>
188 <Text bold>{recent.tool}</Text>
189 <Text dimColor>{` · ${recent.lane} · ${recent.result} · ${recent.ago} ago${recent.repo ? ` · ${recent.repo}` : ''}`}</Text>
190 </Box>
191 )}
192 {isBig && (
193 <Box key="ctx">
194 <Text color={ctx >= (warnAt * 5) / 3 ? 'red' : 'yellow'}>{'⚠ '}</Text>
195 <Text bold>{`context ${Math.round(ctx / 1000)}k`}</Text>
196 <Text dimColor>{' · every call re-reads it · finish this step, run /ai:handoff, start a new session'}</Text>
197 </Box>
198 )}
199 </Box>
200 )
201 })
202}
203types/index.d.ts 9 lines1export type LaneRow = { tool: string; lane: string; detail: string; repo: string; started: number; elapsed: string }
2export type LastRow = { tool: string; lane: string; result: string; detail: string; repo: string; finished: number; ago: string }
3
4declare module 'claude-code' {
5 interface PluginState {
6 ai: { lanes: LaneRow[]; last: LastRow | null; ctx: number }
7 }
8}
9