Safety and review of Claude's output. Mods: blast-radius, secret-sentry, reflect (/reflect-queue, /reflect-pause), assumption-tracker (/assumptions)…

Safety and review of Claude's output. Needs Claude Code 2.1.287+.
/plugin marketplace add bharath-gp/ai-harness
/plugin install guardrails@ai-harness
| Mod | What it does | Trigger | Commands |
|---|---|---|---|
blast-radius | Asks before destructive shell commands run (rm -r, git push --force, git reset --hard, DROP TABLE, ...) and shows what they would hit | Bash tool call | none |
secret-sentry | Blocks API keys and private keys from being written into files | Write, Edit, NotebookEdit | none |
reflect | Spots corrections in your prompts and saves them as rules in CLAUDE.md | every prompt | /reflect-queue, /reflect-pause |
assumption-tracker | Lists the assumptions Claude made and sends fixes for the ones you mark wrong | end of each turn | /assumptions |
self-critique | Reviews Claude's last answer, with one-click fixes | on demand, or each turn | /critique |
prompt-coach | Rewrites your first prompt so Claude grills you about the open questions first | first prompt of a session | /sharpen |
merge-sweep | After a PR you opened is merged, offers to remove its worktree, local branch and remote branch; never forces | gh pr create, then end of each turn | none |
Every mod is on by default. Turn one off in the plugin config menu: blastRadius, secretSentry, reflect, assumptionTracker, selfCritique, promptCoach, mergeSweep. The plugin reloads.
| Option | Default | Meaning |
|---|---|---|
palette | theme | theme follows your Claude Code theme; pastel uses fixed colours for dark terminals |
motion | while-active | off keeps animations still |
merge-sweep needs gh signed in and assumes the remote is origin. Mods are not sandboxed: read hooks/register.tsx first. Install reflect or the Python claude-reflect plugin, not both.
hooks/register.tsx 892 lines1import type { Register } from 'claude-code'
2import { band, paneHeader } from './band'
3import { textCard } from './kit'
4import { C, P, type Tone, below, fmtSize, gauge, parsePorcelain, DECK, usePalette } from './ui'
5
6// ===== shared drawing =====
7// After a surface module faults on a surface, it is drawn there without animation; other surfaces keep theirs.
8const faulted = new Set<string>()
9
10// A rail that carries packets while `active` (claude-flightdeck's connector), a still faint line otherwise or where the
11// surface cannot run a surface module. The module path must be a literal in this file.
12export function rail(ui: any, e: any, key: string, active: boolean, color: string, width: number) {
13 const { Text } = ui
14 if (!DECK.motion || !('Client' in ui) || faulted.has(`${e.surface}:rail.tsx`))
15 return <Text color={C.faint} mono>{'─'.repeat(Math.max(1, width))}</Text>
16 return <ui.Client key={key} module="./rail.tsx" width={width} height={1} props={{ active, width, color, dim: C.faint, marks: [], isMerge: false }} />
17}
18
19// ===== blast-radius =====
20// Destructive shell patterns worth a human look: [pattern, what it does].
21export const RISKY: [RegExp, string][] = [
22 [/\brm\s+((-[a-zA-Z]*[rRf][a-zA-Z]*|--recursive|--force)\s+)+/, 'delete'],
23 [/\bgit\s+push\b[^\n;&|]*(--force\b|--force-with-lease\b|\s-f\b|\s\+\S|--delete\b)/, 'force-push'],
24 [/\bgit\s+reset\s+--hard\b/, 'discard'],
25 [/\bgit\s+clean\s+-[a-zA-Z]*f/, 'discard'],
26 [/\bgit\s+(checkout|restore)\s+(--\s+)?\.(\s|$)/, 'discard'],
27 [/\bgit\s+branch\s+-D\b/, 'force-delete a branch'],
28 [/\b(mkfs|dd\s+if=)/, 'overwrite a device'],
29 [/\bfind\b[^\n]*\s-delete\b/, 'delete'],
30 [/\bDROP\s+(TABLE|DATABASE)\b/i, 'drop a database object'],
31]
32
33type File = { path: string; size: number; tracked: boolean }
34type Impact = { cmd: string; verb: string; project: string; files: File[]; total: number; untracked: number; note: string }
35
36let pending: Impact | undefined
37
38const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}`
39
40// Every file under `path`, with sizes (capped: a node_modules rm should not take a minute).
41async function collect($: any, path: string, out: File[]) {
42 const st = await $.fs.stat(path).catch(() => undefined)
43 if (!st) return
44 if (st.kind !== 'dir') {
45 out.push({ path, size: st.size, tracked: false })
46 return
47 }
48 for (const x of await $.fs.list(path).catch(() => [])) {
49 if (out.length >= 3000) return
50 if (x.kind === 'dir') await collect($, `${path}/${x.name}`, out)
51 else out.push({ path: `${path}/${x.name}`, size: x.size, tracked: false })
52 }
53}
54
55// `rm -rf build dist` -> ['build', 'dist']; no globbing or quoting tricks, just the plain case.
56const rmTargets = (cmd: string) => {
57 const m = /\brm\s+(?:-[a-zA-Z-]+\s+)+([^;&|\n]+)/.exec(cmd)
58 return (m?.[1] ?? '').split(/\s+/).map(t => t.replace(/^['"]|['"]$/g, '')).filter(t => t && !t.startsWith('-'))
59}
60
61async function assess($: any, cmd: string, verb: string) {
62 const cwd: string = await $.session.cwd()
63 const impact: Impact = { cmd, verb, project: cwd.slice(cwd.lastIndexOf('/') + 1), files: [], total: 0, untracked: 0, note: '' }
64 if (verb === 'delete' && /\brm\b/.test(cmd)) {
65 for (const t of rmTargets(cmd)) await collect($, t.startsWith('/') ? t : `${cwd}/${t}`, impact.files)
66 const tracked = await $.process.run(['git', 'ls-files', '-z'], { cwd, timeoutMs: 8000 }).catch(() => undefined)
67 const set = new Set<string>((tracked?.stdout ?? '').split('\0').filter(Boolean).map((p: string) => `${cwd}/${p}`))
68 for (const f of impact.files) f.tracked = set.has(f.path)
69 } else if (verb === 'discard') {
70 const st = await $.process.run(['git', 'status', '--porcelain', '-z'], { cwd, timeoutMs: 5000 }).catch(() => undefined)
71 for (const row of parsePorcelain(st?.stdout ?? '')) {
72 const p = `${cwd}/${row.path}`
73 const s = await $.fs.stat(p).catch(() => undefined)
74 impact.files.push({ path: p, size: s?.size ?? 0, tracked: false }) // uncommitted work is not saved anywhere
75 }
76 }
77 impact.total = impact.files.reduce((n, f) => n + f.size, 0)
78 impact.untracked = impact.files.filter(f => !f.tracked).length
79 impact.note =
80 impact.files.length === 0
81 ? verb === 'force-push' ? 'This rewrites history on the remote. Others who pulled it will have to recover.' : 'This cannot be undone from inside the session.'
82 : impact.untracked === 0
83 ? 'All of these are tracked by git: you can restore them with git checkout.'
84 : impact.untracked === impact.files.length
85 ? "None of these are tracked by git, so they can't be restored."
86 : `${plural(impact.untracked, 'file')} of these are not tracked by git, so they can't be restored.`
87 return impact
88}
89
90// Group files by folder, biggest folder first.
91const groups = (files: File[], project: string) => {
92 const by = new Map<string, File[]>()
93 for (const f of files) {
94 const dir = f.path.slice(0, f.path.lastIndexOf('/'))
95 by.set(dir, [...(by.get(dir) ?? []), f])
96 }
97 const rel = (d: string) => (d.includes(`/${project}/`) ? d.slice(d.indexOf(`/${project}/`) + project.length + 2) : d)
98 return [...by.entries()]
99 .map(([dir, fs]) => ({ dir: `${rel(dir)}/`, files: fs.sort((a, b) => b.size - a.size), size: fs.reduce((n, f) => n + f.size, 0) }))
100 .sort((a, b) => b.size - a.size)
101}
102
103// The dialog takes at most 12 rows, the engine's own included (Claude Code 2.1.300 holds the desktop to 12 too),
104// and no size or place: so on every surface the card is flightdeck's borderless mini form, three flex rows. The
105// dialog's own question already names the command.
106const drawCard = (ui: any, i: Impact) => {
107 const { Box, Text } = ui
108 const n = i.files.length
109 const big = groups(i.files, i.project)[0]
110 const folders = new Set(i.files.map(f => f.path.slice(0, f.path.lastIndexOf('/')))).size
111 const act = i.verb === 'delete' ? 'will delete' : i.verb === 'discard' ? 'will discard' : `will ${i.verb}`
112 const g6 = big ? gauge(i.total ? (big.size / i.total) * 100 : 0, 6) : null
113 const row = (key: string, left: unknown, right: string, m: unknown) => (
114 <Box key={key} flexDirection="row" columnGap={1}>
115 <Box flexGrow={1} flexShrink={1}>{left}</Box>
116 <Box flexShrink={0}><Text dimColor>{right}</Text></Box>
117 {m ? <Box flexShrink={0}>{m}</Box> : null}
118 </Box>
119 )
120 return (
121 <Box flexDirection="column">
122 {row('t', <Text color={C.warn} bold wrap="truncate">{`BLAST RADIUS · ${act}`}</Text>, n > 0 ? `${plural(n, 'file')} · ${fmtSize(i.total)}` : `in ${i.project}`, null)}
123 <Text color={C.amber} wrap="truncate">{`⛨ ${i.note}`}</Text>
124 {big && g6
125 ? row(
126 'g',
127 <Text wrap="truncate"><Text color={C.agent}>■ </Text><Text bold>{big.dir}</Text><Text dimColor>{` ${big.files[0].path.slice(big.files[0].path.lastIndexOf('/') + 1)}${folders > 1 ? ` · +${plural(folders - 1, 'folder')}` : ''}`}</Text></Text>,
128 `${plural(big.files.length, 'file')} ${fmtSize(big.size)}`,
129 <Text><Text color={C.warn}>{g6.on}</Text><Text color={C.faint}>{g6.off}</Text></Text>,
130 )
131 : null}
132 </Box>
133 )
134}
135
136// Chained into the bundle's one Bash tool.call hook in `register`.
137export async function blastRadiusBash($: any, e: any, next: any) {
138 const hit = RISKY.find(([re]) => re.test(e.command))
139 if (!hit) return next(e)
140
141 pending = await assess($, e.command.trim(), hit[1])
142 const n = pending.files.length
143 const proceed = n > 0 ? `${hit[1] === 'delete' ? 'Delete' : 'Discard'} ${plural(n, 'file')}` : 'Proceed'
144 let answer: string
145 try {
146 answer = await $.ui.ask(`Blast Radius is holding this command: ${e.command.slice(0, 200)}`, { header: 'Blast Radius', options: [proceed, 'Cancel'] })
147 } finally {
148 pending = undefined
149 }
150 return answer === proceed ? next(e) : { deny: `${$.plugin.name}: user cancelled (${hit[1]}).` }
151}
152
153export const blastRadius: Register = on => {
154 // The impact card goes above the engine's own dialog, which keeps its Delete / Cancel buttons.
155 on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {
156 const q = (e.props.questions as { header?: string }[] | undefined)?.[0]
157if (!pending || q?.header !== 'Blast Radius') return next(e)
158 const { Box } = $.ui.resolve(e)
159 return (
160 <Box flexDirection="column">
161 {drawCard($.ui.resolve(e), pending)}
162 {await next(e)}
163 </Box>
164 )
165 })
166}
167
168// ===== secret-sentry =====
169const SECRETS: [RegExp, string][] = [
170 [/AKIA[0-9A-Z]{16}/, 'AWS access key'],
171 [/sk-ant-[A-Za-z0-9_-]{20,}/, 'Anthropic API key'],
172 [/sk-[A-Za-z0-9]{32,}/, 'OpenAI-style API key'],
173 [/gh[pousr]_[A-Za-z0-9]{36,}/, 'GitHub token'],
174 [/xox[abprs]-[A-Za-z0-9-]{10,}/, 'Slack token'],
175 [/-----BEGIN (RSA |EC |OPENSSH |DSA |PGP )?PRIVATE KEY-----/, 'private key'],
176 [/(api[_-]?key|secret|token|passwd|password)["']?\s*[:=]\s*["'][A-Za-z0-9/+_=-]{20,}["']/i, 'hard-coded credential'],
177]
178
179// .env files are where secrets belong; example files hold placeholders.
180const ALLOWED_PATH = /(^|\/)\.env(\.|$)|\.example$|\.sample$/
181
182const scan = (text: string) => SECRETS.find(([re]) => re.test(text))?.[1]
183
184let blocked = 0
185
186function guard($: any, path: string, text: string) {
187 if (ALLOWED_PATH.test(path)) return undefined
188 const kind = scan(text)
189 if (!kind) return undefined
190 blocked += 1
191 $.ui.status(`secret-sentry · ${blocked} blocked`)
192 $.ui.toast(`Secret Sentry blocked a ${kind} in ${path.split('/').pop()}`)
193 return { deny: `${$.plugin.name}: refused to write a ${kind} into ${path}. Read it from an env var instead.` }
194}
195
196export const secretSentry: Register = on => {
197 on('tool.call', { tool: 'Write' }, ($, e, next) => guard($, e.file_path, e.content) ?? next(e)).catch(
198 ($, e, next) => (next.called ? next(e) : { deny: `${$.plugin.name}: guard failed.` }),
199 )
200
201 on('tool.call', { tool: 'Edit' }, ($, e, next) => guard($, e.file_path, e.new_string) ?? next(e)).catch(
202 ($, e, next) => (next.called ? next(e) : { deny: `${$.plugin.name}: guard failed.` }),
203 )
204
205 on('tool.call', { tool: 'NotebookEdit' }, ($, e, next) => guard($, e.notebook_path, e.new_source ?? '') ?? next(e)).catch(
206 ($, e, next) => (next.called ? next(e) : { deny: `${$.plugin.name}: guard failed.` }),
207 )
208}
209
210// ===== reflect =====
211const START = '<!-- reflect:start -->'
212const END = '<!-- reflect:end -->'
213const SKIP = /^(ok|okay|yes|no|y|n|continue|go on|thanks|thank you|go|sure|proceed)\W*$/i
214
215const reflectPROMPT = (text: string) =>
216 `The user sent this message to a coding assistant. Does it state a reusable, durable preference or correction (a rule to follow in future sessions, e.g. "use pnpm not npm", "never mock the db")? One-off task instructions are NOT rules. Any language. Reply with only JSON: {"rule":"<imperative rule in English>"|null,"scope":"global"|"repo"}.\n\n<message>\n${text}\n</message>`
217
218type Found = { rule: string; scope: 'global' | 'repo'; count: number }
219
220const reflectParse = (text: string): { rule: string; scope: 'global' | 'repo' } | undefined => {
221 try {
222 const j = JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1))
223 return typeof j.rule === 'string' && j.rule ? { rule: j.rule, scope: j.scope === 'global' ? 'global' : 'repo' } : undefined
224 } catch {
225 return undefined
226 }
227}
228
229let queue: Found[] = []
230let paused = false
231
232function add($: any, rule: string, scope: Found['scope']) {
233 const hit = queue.find(q => q.rule.toLowerCase() === rule.toLowerCase())
234 if (hit) hit.count += 1
235 else queue = [...queue, { rule, scope, count: 1 }]
236 $.ui.invalidate('ui.render')
237}
238
239async function save($: any, f: Found, scope: Found['scope']) {
240 const path = scope === 'global' ? '~/.claude/CLAUDE.md' : `${await $.session.root()}/CLAUDE.md`
241 const file = scope === 'global' ? `${await $.env.get('HOME')}/.claude/CLAUDE.md` : path
242 const old: string = (await $.fs.exists(file)) ? await $.fs.read(file) : ''
243 const bullet = `- ${f.rule}`
244 let next: string
245 if (old.includes(START) && old.includes(END)) next = old.replace(END, () => `${bullet}\n${END}`) // a function: `$&` in a rule must stay literal
246 else next = `${old.trimEnd()}${old ? '\n\n' : ''}## Learned rules\n${START}\n${bullet}\n${END}\n`
247 await $.fs.write(file, next)
248 queue = queue.filter(q => q !== f)
249 $.ui.invalidate('ui.render')
250 $.ui.toast(`Saved to ${scope === 'global' ? '~/.claude/CLAUDE.md' : './CLAUDE.md'}`)
251}
252
253export async function reflectSessionStart($: any, e: any, next: any) {
254 await $.command.register({ name: 'reflect-queue', description: 'List rules reflect found in your prompts' })
255 await $.command.register({ name: 'reflect-pause', description: 'Pause or resume reflect' })
256 return next(e)
257}
258
259export function reflectCommandRunReflectQueue() {
260 return { text: queue.length ? queue.map(q => `- ${q.rule} (${q.scope}, x${q.count})`).join('\n') : 'Nothing queued.' }
261}
262
263export function reflectCommandRunReflectPause() {
264 paused = !paused
265 return { text: paused ? 'reflect paused.' : 'reflect resumed.' }
266}
267
268export async function reflectPromptSubmit($: any, e: any, next: any) {
269 const t = e.text.trim()
270 if (e.origin.kind === 'plugin' || paused || t.startsWith('/')) return next(e)
271
272 const explicit = /^remember:\s*(.+)$/is.exec(t)
273 if (explicit) add($, explicit[1].trim(), 'repo')
274 else if (t.length <= 500 && !SKIP.test(t)) {
275 void $.model
276 .complete({ model: 'haiku', prompt: reflectPROMPT(t), maxTokens: 150, effort: 'low', timeoutMs: 15_000 })
277 .then(r => {
278 const found = r.isAnswered ? reflectParse(r.text) : undefined
279 if (found) add($, found.rule, found.scope)
280 })
281 }
282 return next(e)
283}
284
285export async function reflectUiRenderAbovePrompt($: any, e: any, next: any) {
286 if (e.props.hasSurvey || queue.length === 0) return next(e)
287 const f = queue[0]
288 const other = f.scope === 'global' ? 'repo' : 'global'
289 const more = queue.length > 1 ? [`+${queue.length - 1} more`] : []
290 return band($.ui.resolve(e), e, await below(next, e), {
291 title: 'Rule found',
292 tone: 'purple',
293 detail: f.rule,
294 chips: [f.scope, ...(f.count > 1 ? [`×${f.count}`] : []), ...more],
295 buttons: [
296 { key: 'save', label: 'Save', onPress: () => save($, f, f.scope) },
297 { key: 'other', label: other === 'global' ? 'Global instead' : 'This repo instead', onPress: () => save($, f, other) },
298 { key: 'skip', label: 'Skip', plain: true, onPress: () => { queue = queue.filter(q => q !== f); $.ui.invalidate('ui.render') } },
299 ],
300 })
301}
302
303// ===== assumption-tracker =====
304type Item = { text: string; verdict: 'right' | 'wrong' | undefined }
305
306const assumptionTrackerPROMPT = (task: string, answer: string) =>
307 `List the assumptions the assistant made that the user did not explicitly specify (defaults chosen, ambiguities resolved silently, scope decisions). Max 8, one short sentence each. Reply with only a JSON array of strings, [] if none.\n\n<user_request>\n${task.slice(0, 2000)}\n</user_request>\n<assistant_reply>\n${answer.slice(0, 6000)}\n</assistant_reply>`
308
309const assumptionTrackerParse = (text: string): string[] => {
310 try {
311 const arr = JSON.parse(text.slice(text.indexOf('['), text.lastIndexOf(']') + 1))
312 return Array.isArray(arr) ? arr.filter((s): s is string => typeof s === 'string').slice(0, 8) : []
313 } catch {
314 return []
315 }
316}
317
318let items: Item[] = []
319let task = ''
320let assumptionGen = 0 // a late reply for an older prompt is ignored
321
322function redraw($: any) { return $.ui.invalidate('ui.render') }
323
324export async function assumptionTrackerSessionStart($: any, e: any, next: any) {
325 await $.command.register({ name: 'assumptions', description: 'Review the assumptions Claude made last turn' })
326 return next(e)
327}
328
329export async function assumptionTrackerCommandRunAssumptions($: any) {
330 if (items.length === 0) return { text: 'No assumptions recorded for the last turn.' }
331 await $.ui.open({ id: 'assumptions', title: 'Assumptions', focus: true, closeOnEscape: true })
332 return { text: 'Assumptions opened.' }
333}
334
335export function assumptionTrackerPromptSubmit($: any, e: any, next: any) {
336 if (e.origin.kind !== 'plugin') task = e.text // fix prompts we send must not overwrite the task
337 assumptionGen += 1
338 return next(e)
339}
340
341export async function assumptionTrackerTurnComplete($: any, e: any, next: any) {
342 if (e.agentId === undefined && e.reason === 'answer' && task) {
343 const gen = assumptionGen
344 void $.model
345 .complete({ model: 'haiku', prompt: assumptionTrackerPROMPT(task, e.answer), maxTokens: 600, effort: 'low', timeoutMs: 20_000 })
346 .then(r => {
347 if (gen !== assumptionGen) return
348 items = r.isAnswered ? assumptionTrackerParse(r.text).map(text => ({ text, verdict: undefined })) : []
349 redraw($)
350 })
351 }
352 return next(e)
353}
354
355export async function assumptionTrackerUiRenderAbovePrompt($: any, e: any, next: any) {
356 if (e.props.hasSurvey || items.length === 0) return next(e)
357 const reviewed = items.filter(i => i.verdict).length
358 return band($.ui.resolve(e), e, await below(next, e), {
359 title: `Claude made ${items.length} assumption${items.length > 1 ? 's' : ''}`,
360 tone: 'warn',
361 detail: `${reviewed}/${items.length} reviewed`,
362 pct: (reviewed / items.length) * 100,
363 buttons: [
364 { key: 'review', label: 'Review', hotkey: '0', onPress: () => $.ui.open({ id: 'assumptions', title: 'Assumptions', focus: true, closeOnEscape: true }) },
365 { key: 'skip', label: '×', plain: true, onPress: () => { items = []; redraw($) } },
366 ],
367 })
368}
369
370export function assumptionTrackerUiRenderPaneAssumptions($: any, e: any) {
371 const ui = $.ui.resolve(e)
372 const { Box, Text, Button } = ui
373 const wrong = items.filter(i => i.verdict === 'wrong')
374 const set = (i: number, v: Item['verdict']) => {
375 items = items.map((it, j) => (j === i ? { ...it, verdict: v } : it))
376 redraw($)
377 }
378 const reviewed = items.filter(i => i.verdict).length
379 return (
380 <Box flexDirection="column" gap={1}>
381 {paneHeader(ui, e, { title: 'Assumptions', sub: `${reviewed}/${items.length} reviewed · ${wrong.length} wrong`, pct: items.length ? (reviewed / items.length) * 100 : 0, tone: 'warn' })}
382 {items.length === 0 && <Text dimColor>Nothing to review.</Text>}
383 {items.length > 0 && <Text dimColor>{`1-${items.length} cycle right / wrong${wrong.length ? ' · f send the fixes' : ''}`}</Text>}
384 {items.map((it, i) => {
385 const color = it.verdict === 'wrong' ? P.err : it.verdict === 'right' ? P.ok : P.warn // amber until reviewed
386 const mark = it.verdict === 'wrong' ? '✗ wrong' : it.verdict === 'right' ? '✓ right' : '◇ unreviewed'
387 return textCard(ui, {
388 key: `r${i}`,
389 color,
390 text: it.text,
391 children: (
392 <Box flexDirection="row" columnGap={1}>
393 <Button key={`cy${i}`} plain hotkey={String(i + 1)} label={`${i + 1} ${mark}`} onPress={() => set(i, it.verdict === undefined ? 'right' : it.verdict === 'right' ? 'wrong' : undefined)} />
394 <Box flexGrow={1} />
395 <Button key={`ok${i}`} label="Right" variant={it.verdict === 'right' ? 'primary' : 'secondary'} onPress={() => set(i, 'right')} />
396 <Button key={`no${i}`} label="Wrong" variant={it.verdict === 'wrong' ? 'primary' : 'secondary'} onPress={() => set(i, 'wrong')} />
397 </Box>
398 ),
399 })
400 })}
401 {wrong.length > 0 && (
402 <Button
403 key="send"
404 variant="primary"
405 hotkey="f"
406 label={`Fix ${wrong.length} wrong`}
407 onPress={async () => {
408 const keep = items.filter(i => i.verdict === 'right').map(i => `- ${i.text}`)
409 const text =
410 `These assumptions you made were wrong. Fix only the parts that depend on them:\n${wrong.map(i => `- ${i.text}`).join('\n')}` +
411 (keep.length ? `\n\nThese were right, keep them:\n${keep.join('\n')}` : '')
412 items = []
413 await $.ui.close({ id: 'assumptions' })
414 void $.prompt.submit({ text })
415 }}
416 />
417 )}
418 </Box>
419 )
420}
421
422// ===== self-critique =====
423type Critique = {
424 verdict: 'strong' | 'mixed' | 'weak'
425 summary: string
426 strengths: string[]
427 flaws: { issue: string; fix: string }[]
428}
429
430const MODELS = ['session', 'opus', 'sonnet', 'haiku'] as const
431
432const selfCritiquePROMPT = (answer: string) =>
433 `Critique the assistant reply below. Reply with only JSON: {"verdict":"strong|mixed|weak","summary":"one sentence","strengths":["..."],"flaws":[{"issue":"...","fix":"one-line instruction to repair it"}]}. Be specific; at most 4 strengths and 5 flaws.\n\n<reply>\n${answer.slice(0, 12000)}\n</reply>`
434
435const selfCritiqueParse = (text: string): Critique | undefined => {
436 try {
437 const c = JSON.parse(text.slice(text.indexOf('{'), text.lastIndexOf('}') + 1))
438 return Array.isArray(c.flaws) && Array.isArray(c.strengths) ? c : undefined
439 } catch {
440 return undefined
441 }
442}
443
444let result: Critique | undefined
445let status = 'No critique yet. Run /critique.'
446let model: (typeof MODELS)[number] = 'session'
447let auto = false
448let lastAnswer = ''
449
450async function run($: any, answer: string) {
451 if (!answer) {
452 status = 'Nothing to critique yet.'
453 return
454 }
455 status = 'Critiquing…'
456 $.ui.invalidate('ui.render')
457 const m = model === 'session' ? await $.session.model() : model
458 const r = await $.model.complete({ model: m, prompt: selfCritiquePROMPT(answer), maxTokens: 1500, timeoutMs: 60_000 })
459 result = r.isAnswered ? selfCritiqueParse(r.text) : undefined
460 status = result ? '' : `Critique failed${r.isAnswered ? ' (unparseable reply)' : `: ${r.reason}`}`
461 $.ui.invalidate('ui.render')
462}
463
464export async function selfCritiqueSessionStart($: any, e: any, next: any) {
465 await $.command.register({ name: 'critique', description: 'Critique the last answer: /critique [auto|opus|sonnet|haiku|session]' })
466 return next(e)
467}
468
469export async function selfCritiqueCommandRunCritique($: any, e: any) {
470 const arg = (e.args ?? "").trim()
471 if (arg === 'auto') {
472 auto = !auto
473 return { text: `Auto-critique ${auto ? 'on' : 'off'}.` }
474 }
475 if ((MODELS as readonly string[]).includes(arg)) model = arg as typeof model
476 await $.ui.open({ id: 'critique', title: 'Critique' })
477 void run($, lastAnswer)
478 return { text: `Critiquing with ${model}.` }
479}
480
481export async function selfCritiqueTurnComplete($: any, e: any, next: any) {
482 if (e.agentId === undefined && e.reason === 'answer') {
483 lastAnswer = e.answer
484 if (auto) {
485 await $.ui.open({ id: 'critique', title: 'Critique' })
486 void run($, e.answer)
487 }
488 }
489 return next(e)
490}
491
492export function selfCritiqueUiRenderPaneCritique($: any, e: any) {
493 const ui = $.ui.resolve(e)
494 const { Box, Text, Button } = ui
495 const tone: Tone = result?.verdict === 'strong' ? 'ok' : result?.verdict === 'weak' ? 'err' : 'warn'
496 const score = result ? { strong: 90, mixed: 55, weak: 20 }[result.verdict] : undefined
497 return (
498 <Box flexDirection="column" gap={1}>
499 {paneHeader(ui, e, { title: 'Critique', sub: status || `${result?.flaws.length ?? 0} flaws · model: ${model}`, pct: score, tone: result ? tone : 'purple' })}
500 {rail(ui, e, 'critique-busy', status === 'Critiquing…', C.arch, Math.max(10, (e.props.bodyColumns ?? 40) - 1))}
501 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
502 <Button key="rerun" label="Rerun" hotkey="r" variant="primary" onPress={() => void run($, lastAnswer)} />
503 <Button key="auto" label={`Auto ${auto ? 'on' : 'off'}`} hotkey="a" onPress={() => { auto = !auto; $.ui.invalidate('ui.render') }} />
504 <Button key="model" label={`Model: ${model}`} hotkey="m" onPress={() => { model = MODELS[(MODELS.indexOf(model) + 1) % MODELS.length]; $.ui.invalidate('ui.render') }} />
505 </Box>
506 {result && (
507 <>
508 {textCard(ui, { key: 'verdict', color: P[tone], text: `${result.verdict.toUpperCase()}: ${result.summary}` })}
509 {result.strengths.map((s, i) => textCard(ui, { key: `s${i}`, color: P.ok, text: s }))}
510 {result.flaws.map((f, i) => (
511 <Box key={`f${i}`} flexDirection="column">
512 {textCard(ui, { key: `fc${i}`, color: P.err, text: f.issue, sub: `fix: ${f.fix}` })}
513 <Button key={`fix${i}`} label={`${i + 1} Make this fix`} hotkey={String(i + 1)} onPress={() => void $.prompt.submit({ text: `Fix this issue in your last answer: ${f.issue}. ${f.fix}` })} />
514 </Box>
515 ))}
516 </>
517 )}
518 </Box>
519 )
520}
521
522// ===== prompt-coach =====
523type Coach = {
524 original: string
525 ctx: string
526 draft?: string
527 changes?: string
528 asking: boolean // the "request changes" box is open
529 busy: string
530 err: string
531 tipOnly?: boolean // the prompt carries attachments: it was sent as typed, the improved text is only offered
532 fromSubmit?: boolean // the session's first prompt, held until the user picks Use Prompt or Dismiss
533}
534
535let coach: Coach | undefined
536// Per-session "offered" flag in $.state (survives hot reload); only the session's first prompt is auto-coached, /sharpen coaches any.
537const coachedRef = { plugin: 'guardrails', key: 'coached' } as const
538
539// A prompt that opens with /command or a skill keeps that first line verbatim in front of the reworded text.
540const coachCommandLine = (text: string) => (text.startsWith('/') ? text.split('\n')[0].trim() : '')
541
542const coachDraftPROMPT = (c: Coach) => {
543 const cmd = coachCommandLine(c.original)
544 return (
545 `Rewrite the user's prompt below as one better prompt for a coding assistant, following prompting best practices. Write it to the assistant in second person. Use these sections, omitting any with nothing to say: Role (persona), Goal (intent and why), Context, Requirements, Constraints, Out of scope, Acceptance criteria, Output format. Never invent requirements the user did not state. Always include a section "Before you start" instructing the assistant to grill the user, before doing any work, about every ambiguity, missing requirement and unstated assumption in the request: ask one question at a time, give options with a recommendation, look at the project itself for anything it can answer, and wait for the answers before starting. The assistant does the questioning, you do not ask anything. ` +
546 (cmd
547 ? `The prompt opens with the slash command or skill line ${JSON.stringify(cmd)}; take what that skill does into account. Do not repeat that line and do not quote the original: reply with only the text that follows it.`
548 : 'End with an "Original request" section quoting the original prompt verbatim.') +
549 ` Reply with only the prompt text, no preamble and no code fences.\n\n<project_context>\n${c.ctx}\n</project_context>\n<original_prompt>\n${c.original}\n</original_prompt>` +
550 (c.changes ? `\n<previous_draft>\n${c.draft}\n</previous_draft>\n<requested_changes>\n${c.changes}\n</requested_changes>` : '')
551 )
552}
553
554async function coachContext($: any): Promise<string> {
555 try {
556 const root = await $.session.root()
557 const md = `${root}/CLAUDE.md`
558 const doc: string = (await $.fs.exists(md)) ? await $.fs.read(md) : ''
559 const names = (await $.fs.list(root)).map((f: any) => (f.kind === 'dir' ? `${f.name}/` : f.name))
560 return `${doc.slice(0, 4000)}\n\nTop-level files: ${names.slice(0, 60).join(', ')}`
561 } catch {
562 return ''
563 }
564}
565
566async function coachDraft($: any, c: Coach) {
567 c.busy = 'Writing your prompt…'
568 c.err = ''
569 redraw($)
570 if (!c.ctx) c.ctx = await coachContext($)
571 const r = await $.model.complete({ model: await $.session.model(), prompt: coachDraftPROMPT(c), maxTokens: 2500, timeoutMs: 90_000 })
572 if (coach !== c) return
573 c.busy = ''
574 const body = r.isAnswered ? r.text.trim() : ''
575 if (body) {
576 const cmd = coachCommandLine(c.original)
577 c.draft = cmd ? `${cmd}\n\n${body}` : body
578 c.changes = undefined
579 c.asking = false
580 } else c.err = `Could not write the prompt${r.isAnswered ? '' : `: ${r.reason}`}`
581 redraw($)
582}
583
584// text: the original to send on (Dismiss), or nothing.
585async function coachClose($: any, text?: string) {
586 coach = undefined
587 await $.ui.close({ id: 'coach' })
588 if (text) void $.prompt.submit({ text, asUser: true })
589}
590
591// Sends the improved prompt as the user's own; a held first prompt is replaced by it.
592async function coachUse($: any, c: Coach) {
593 await coachClose($, c.draft)
594}
595
596// Opens the pane and writes the draft; false when no surface draws a pane (the prompt then goes through unchanged).
597async function coachStart($: any, text: string, fromSubmit = false, tipOnly = false): Promise<boolean> {
598 const c: Coach = { fromSubmit, tipOnly, original: text, ctx: '', asking: false, busy: 'Writing your prompt…', err: '' }
599 coach = c
600 const r = await $.ui.open({ id: 'coach', title: 'Prompt coach', focus: true })
601 if (!r.isPlaced) {
602 coach = undefined
603 return false
604 }
605 void coachDraft($, c)
606 return true
607}
608
609export async function promptCoachSessionStart($: any, e: any, next: any) {
610 await $.command.register({ name: 'sharpen', description: 'Rewrite a prompt so the main session grills you first: /sharpen [prompt] (defaults to the prompt box, then your last message)' })
611 return next(e)
612}
613
614export async function promptCoachCommandRunSharpen($: any, e: any) {
615 let text = (e.args ?? '').trim()
616 if (!text) text = ((await $.prompt.read()).text ?? '').trim()
617 if (!text) {
618 const last = (await $.session.messages()).filter((m: any) => m.role === 'user' && (m.text ?? '').trim()).at(-1)
619 text = (last?.text ?? '').trim()
620 }
621 if (!text) return { text: 'Usage: /sharpen <prompt>' }
622 return { text: (await coachStart($, text)) ? 'Prompt coach opened.' : 'No pane available here.' }
623}
624
625export async function promptCoachPromptSubmit($: any, e: any, next: any) {
626 const t = e.text.trim()
627 if (e.origin?.kind === 'plugin' || e.command || !t) return next(e)
628 const member = { ...coachedRef, id: await $.session.id() }
629 if ((await $.state.get(member)).value) return next(e)
630 await $.state.set(member, true) // set on the first prompt whether or not it is coached: nothing later is auto-coached
631 // Attachments can't be re-sent with a rewritten prompt, so such a prompt goes through as typed and the pane only offers the improved text.
632 const tipOnly = !!e.attachments?.length
633 if (!(await coachStart($, t, true, tipOnly)) || tipOnly) return next(e)
634 return { drop: 'prompt-coach: review the improved prompt, then pick Use Prompt or Dismiss.' }
635}
636
637export function promptCoachUiRenderPaneCoach($: any, e: any) {
638 const ui = $.ui.resolve(e)
639 const { Box, Text, Button, Input } = ui
640 const c = coach
641 if (!c) return <Text dimColor>No prompt being coached.</Text>
642 const dismiss = <Button key="dismiss" hotkey="d" label={c.tipOnly || !c.fromSubmit ? 'Dismiss' : 'Dismiss (send original)'} onPress={() => void coachClose($, c.tipOnly || !c.fromSubmit ? undefined : c.original)} />
643 return (
644 <Box flexDirection="column" gap={1}>
645 {paneHeader(ui, e, { title: 'Prompt coach', sub: c.draft ? 'Review your prompt' : c.busy || 'Could not write the prompt', pct: c.draft ? 100 : 0, tone: 'purple' })}
646 {c.tipOnly && <Text dimColor>Your prompt and its attachments were already sent. Use the improved version next time.</Text>}
647 {c.err && textCard(ui, { key: 'err', color: P.err, text: c.err })}
648 {rail(ui, e, 'coach-busy', Boolean(c.busy), C.arch, Math.max(10, (e.props.bodyColumns ?? 40) - 1))}
649 {c.busy && <Text dimColor>{c.busy}</Text>}
650 {c.draft && !c.busy && (
651 <>
652 {textCard(ui, { key: 'draft', color: C.main, text: c.draft })}
653 {c.asking && (
654 <Input
655 key="changes"
656 autoFocus
657 placeholder="What should change?"
658 submitLabel="regenerate"
659 onSubmit={(v: string) => {
660 if (!v.trim()) return
661 c.changes = v.trim()
662 void coachDraft($, c)
663 }}
664 />
665 )}
666 <Box flexDirection="row" columnGap={1} flexWrap="wrap">
667 {!c.tipOnly && <Button key="use" label="Use Prompt" hotkey="u" variant="primary" onPress={() => void coachUse($, c)} />}
668 <Button key="copy" label="Copy" hotkey="c" onPress={async () => { $.ui.toast((await $.ui.copy({ text: c.draft, surface: e.surface })).isCopied ? 'Copied' : 'Copy failed') }} />
669 <Button key="change" label="Request changes" hotkey="e" onPress={() => { c.asking = !c.asking; redraw($) }} />
670 {dismiss}
671 </Box>
672 </>
673 )}
674 {c.err && !c.busy && (
675 <Box flexDirection="row" columnGap={1}>
676 <Button key="retry" label="Retry" hotkey="r" variant="primary" onPress={() => void coachDraft($, c)} />
677 {!c.draft && dismiss}
678 </Box>
679 )}
680 </Box>
681 )
682}
683
684// ===== merge-sweep =====
685// PRs this session opened with `gh pr create`, kept per session id in $.state (survives hot reload).
686const sweepPrsRef = { plugin: 'guardrails', key: 'prs' } as const
687const SWEEP_CREATE = /\bgh\s+pr\s+create\b/
688const SWEEP_PR_URL = /https:\/\/[^\s"')]+\/pull\/\d+/
689
690export async function mergeSweepBash($: any, e: any, next: any) {
691 if (!SWEEP_CREATE.test(e.command)) return next(e)
692 const ran = await next(e)
693 if (ran.deny !== undefined || ran.isError) return ran
694 const url = SWEEP_PR_URL.exec(ran.text ?? '')?.[0]
695 if (url) {
696 const member = { ...sweepPrsRef, id: await $.session.id() }
697 const prs: string[] = (await $.state.get(member)).value ?? []
698 if (!prs.includes(url)) await $.state.set(member, [...prs, url])
699 }
700 return ran
701}
702
703// Merged PRs waiting for an answer, rebuilt by the poll after a reload; a PR leaves the state list once cleaned or dismissed.
704type SweepPr = { url: string; head: string; oid: string; base: string; isFork: boolean }
705let sweepReady: SweepPr[] = []
706let sweepBusy = false
707
708const sweepRun = ($: any, argv: string[], cwd?: string) =>
709 $.process.run(argv, { cwd, timeoutMs: 30_000 }).catch((err: unknown) => ({ exitCode: 1, stdout: '', stderr: String(err) }))
710
711const sweepWhy = (r: { stderr: string }) => r.stderr.trim().split('\n')[0].slice(0, 120)
712
713export const sweepWorktrees = (text: string) =>
714 text
715 .split('\n\n')
716 .map(b => ({ path: /^worktree (.+)$/m.exec(b)?.[1] ?? '', branch: /^branch refs\/heads\/(.+)$/m.exec(b)?.[1] }))
717 .filter(w => w.path)
718
719async function sweepForget($: any, url: string) {
720 const member = { ...sweepPrsRef, id: await $.session.id() }
721 const prs: string[] = (await $.state.get(member)).value ?? []
722 await $.state.set(member, prs.filter(u => u !== url))
723 sweepReady = sweepReady.filter(p => p.url !== url)
724 $.ui.invalidate('ui.render')
725}
726
727async function sweepPoll($: any) {
728 const prs: string[] = (await $.state.get({ ...sweepPrsRef, id: await $.session.id() })).value ?? []
729 for (const url of prs) {
730 if (sweepReady.some(p => p.url === url)) continue
731 const r = await sweepRun($, ['gh', 'pr', 'view', url, '--json', 'state,headRefName,headRefOid,baseRefName,isCrossRepository'])
732 if (r.exitCode !== 0) continue // offline or not signed in: ask again next turn
733 try {
734 const j = JSON.parse(r.stdout)
735 if (j.state === 'MERGED') sweepReady = [...sweepReady, { url, head: j.headRefName, oid: j.headRefOid, base: j.baseRefName, isFork: !!j.isCrossRepository }]
736 } catch {}
737 }
738 $.ui.invalidate('ui.render')
739}
740
741// Never forces: a dirty worktree, a branch with later commits or a moved remote is kept and reported.
742// shortcut: the remote is assumed to be `origin`, upgrade when a PR's head lives on another remote.
743export async function sweepClean($: any, p: SweepPr) {
744 sweepBusy = true
745 $.ui.invalidate('ui.render')
746 const done: string[] = []
747 const kept: string[] = []
748 try {
749 const cwd = await $.session.root()
750 const git = (...a: string[]) => sweepRun($, ['git', ...a], cwd)
751 const wts = sweepWorktrees((await git('worktree', 'list', '--porcelain')).stdout)
752 const main = wts[0]
753 const here = (await git('rev-parse', '--show-toplevel')).stdout.trim()
754 if (!main || p.head === p.base) kept.push(`${p.head}: nothing to clean`)
755 else {
756 let blocked = false // the branch is still checked out somewhere
757 const wt = wts.find(w => w.branch === p.head)
758 if (wt === main) {
759 const r = await sweepRun($, ['git', 'switch', p.base], main.path)
760 if (r.exitCode === 0) {
761 main.branch = p.base
762 done.push(`switched to ${p.base}`)
763 } else {
764 blocked = true
765 kept.push(`switch to ${p.base} failed: ${sweepWhy(r)}`)
766 }
767 } else if (wt) {
768 if (wt.path === here) {
769 blocked = true
770 kept.push(`worktree ${wt.path} is the current directory: later run git worktree remove ${wt.path} && git branch -D ${p.head}`)
771 } else {
772 const r = await git('worktree', 'remove', wt.path)
773 if (r.exitCode === 0) done.push('worktree removed')
774 else {
775 blocked = true
776 kept.push(`worktree ${wt.path}: ${sweepWhy(r)}`)
777 }
778 }
779 }
780 if (main.branch === p.base) {
781 const r = await sweepRun($, ['git', 'pull', '--ff-only'], main.path)
782 if (r.exitCode === 0) done.push(`pulled ${p.base}`)
783 else kept.push(`pull ${p.base} failed: ${sweepWhy(r)}`)
784 } else kept.push(`${p.base} not pulled: main checkout is on ${main.branch ?? 'a detached head'}`)
785
786 if (!blocked) {
787 const tip = (await git('rev-parse', '--verify', '--quiet', `refs/heads/${p.head}`)).stdout.trim()
788 if (tip === p.oid) {
789 const r = await git('branch', '-D', p.head)
790 if (r.exitCode === 0) done.push('local branch deleted')
791 else kept.push(`local ${p.head}: ${sweepWhy(r)}`)
792 } else if (tip) kept.push(`local ${p.head} has commits after the merged ${p.oid.slice(0, 7)}`)
793 }
794
795 if (p.isFork) kept.push('remote branch: the PR is from a fork')
796 else {
797 const line = (await git('ls-remote', '--heads', 'origin', `refs/heads/${p.head}`)).stdout.split('\n').find(l => l.endsWith(`\trefs/heads/${p.head}`))
798 const sha = line?.split('\t')[0]
799 if (sha === p.oid) {
800 const r = await git('push', 'origin', '--delete', p.head)
801 if (r.exitCode === 0) done.push('remote branch deleted')
802 else kept.push(`remote ${p.head}: ${sweepWhy(r)}`)
803 } else if (sha) kept.push(`remote ${p.head} moved past the merged commit`)
804 else if ((await git('branch', '-dr', `origin/${p.head}`)).exitCode === 0) done.push('stale origin ref pruned') // remote already deleted; a missing ref just fails
805 }
806 }
807 } catch (err) {
808 kept.push(`failed: ${String(err).slice(0, 120)}`)
809 } finally {
810 sweepBusy = false
811 }
812 await sweepForget($, p.url)
813 $.ui.toast(`Cleanup: ${done.join(', ') || 'nothing removed'}${kept.length ? ` | kept: ${kept.join('; ')}` : ''}`)
814}
815
816export function mergeSweepTurnComplete($: any, e: any, next: any) {
817 void sweepPoll($).catch(() => {})
818 return next(e)
819}
820
821export async function mergeSweepUiRenderAbovePrompt($: any, e: any, next: any) {
822 if (e.props.hasSurvey || sweepReady.length === 0) return next(e)
823 const p = sweepReady[0]
824 return band($.ui.resolve(e), e, await below(next, e), {
825 title: `PR #${/\/pull\/(\d+)/.exec(p.url)?.[1]} merged`,
826 tone: 'ok',
827 busy: sweepBusy,
828 detail: sweepBusy ? 'cleaning up' : `clean up ${p.head}?`,
829 chips: sweepReady.length > 1 ? [`+${sweepReady.length - 1} more`] : [],
830 buttons: sweepBusy
831 ? []
832 : [
833 { key: 'clean', label: 'Clean up', hotkey: 'c', onPress: () => void sweepClean($, p) },
834 { key: 'skip', label: 'Dismiss', hotkey: 'd', plain: true, onPress: () => void sweepForget($, p.url) },
835 ],
836 })
837}
838
839// Each mod is on unless its userConfig flag is false (toggle in the config menu; the module reloads).
840export const register: Register = (on, options) => {
841 usePalette(options.palette, options.motion)
842 on('ui.fault', ($, e, next) => {
843 const key = `${e.surface}:${e.module.split(/[\\/]/).pop()}`
844 if (!faulted.has(key)) {
845 faulted.add(key)
846 $.ui.log(`guardrails: ${e.module} faulted on ${e.surface} (${e.phase}: ${e.reason}); drawing it without animation`)
847 $.ui.invalidate('ui.render')
848 }
849 return next(e)
850 })
851 if (options.blastRadius !== false) blastRadius(on)
852 // blast-radius and merge-sweep share the one Bash tool.call hook; merge-sweep is outermost so it sees the final result.
853 on('tool.call', { tool: 'Bash' }, ($, e, next) => {
854 const n = (x: any) => (options.blastRadius === false ? next(x) : blastRadiusBash($, x, next))
855 return options.mergeSweep === false ? n(e) : mergeSweepBash($, e, n)
856 }).catch(($, e, next) =>
857 // ask rejects when nobody can answer (-p run): refuse rather than run it
858 next.called || options.blastRadius === false ? next(e) : { deny: `${$.plugin.name}: could not confirm a destructive command.` },
859 )
860 if (options.secretSentry !== false) secretSentry(on)
861 on('session.start', ($, e, next) => {
862 const n4 = (x: any) => next(x)
863 const n3 = (x: any) => (options.promptCoach === false ? n4(x) : promptCoachSessionStart($, x, n4))
864 const n2 = (x: any) => (options.selfCritique === false ? n3(x) : selfCritiqueSessionStart($, x, n3))
865 const n1 = (x: any) => (options.assumptionTracker === false ? n2(x) : assumptionTrackerSessionStart($, x, n2))
866 return options.reflect === false ? n1(e) : reflectSessionStart($, e, n1)
867 })
868 if (options.reflect !== false) on('command.run', { command: 'reflect-queue' }, reflectCommandRunReflectQueue)
869 if (options.reflect !== false) on('command.run', { command: 'reflect-pause' }, reflectCommandRunReflectPause)
870 on('prompt.submit', ($, e, next) => {
871 const n2 = (x: any) => (options.promptCoach === false ? next(x) : promptCoachPromptSubmit($, x, next)) // last, so reflect and assumption-tracker see the original first
872 const n1 = (x: any) => (options.assumptionTracker === false ? n2(x) : assumptionTrackerPromptSubmit($, x, n2))
873 return options.reflect === false ? n1(e) : reflectPromptSubmit($, e, n1)
874 })
875 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
876 const n2 = (x: any) => (options.mergeSweep === false ? next(x) : mergeSweepUiRenderAbovePrompt($, x, next))
877 const n1 = (x: any) => (options.assumptionTracker === false ? n2(x) : assumptionTrackerUiRenderAbovePrompt($, x, n2))
878 return options.reflect === false ? n1(e) : reflectUiRenderAbovePrompt($, e, n1)
879 })
880 if (options.assumptionTracker !== false) on('command.run', { command: 'assumptions' }, assumptionTrackerCommandRunAssumptions)
881 on('turn.complete', ($, e, next) => {
882 const n2 = (x: any) => (options.mergeSweep === false ? next(x) : mergeSweepTurnComplete($, x, next))
883 const n1 = (x: any) => (options.selfCritique === false ? n2(x) : selfCritiqueTurnComplete($, x, n2))
884 return options.assumptionTracker === false ? n1(e) : assumptionTrackerTurnComplete($, e, n1)
885 })
886 if (options.assumptionTracker !== false) on('ui.render', { component: 'Pane', requestId: 'assumptions' }, assumptionTrackerUiRenderPaneAssumptions)
887 if (options.selfCritique !== false) on('command.run', { command: 'critique' }, selfCritiqueCommandRunCritique)
888 if (options.selfCritique !== false) on('ui.render', { component: 'Pane', requestId: 'critique' }, selfCritiqueUiRenderPaneCritique)
889 if (options.promptCoach !== false) on('command.run', { command: 'sharpen' }, promptCoachCommandRunSharpen)
890 if (options.promptCoach !== false) on('ui.render', { component: 'Pane', requestId: 'coach' }, promptCoachUiRenderPaneCoach)
891}
892hooks/band.tsx 194 lines1// Shared band and pane pieces, so every mod looks the same: claude-flightdeck's look (MIT, see THIRD_PARTY_NOTICES.md).
2// Single source: scripts/sync-ui.sh copies it to plugins/*/hooks/band.tsx. `$` never crosses an import, so every
3// piece takes `ui` (= $.ui.resolve(e)) and `e`. Animated pieces (rails, clocks) are drawn in each register.tsx:
4// a surface module's path must be a literal in the hooks module itself.
5import { C, P, gauge, type Tone } from './ui'
6
7export type Btn = { key: string; label: string; onPress: () => unknown; hotkey?: string; plain?: boolean }
8export type RowBtn = { key: string; label: string; hint?: string; hotkey?: string; onPress: () => unknown }
9export type BandSpec = {
10 title: string
11 tone: Tone
12 detail?: string
13 pct?: number // 0-100: a ▰▱ gauge
14 bars?: { pct: number; label: string; tone?: Tone }[] // several gauges in one band, instead of pct
15 pctLabel?: string // text before the gauge, e.g. "Review 3/4"
16 ring?: boolean // kept for callers: drawn as the same gauge
17 busy?: boolean // ◐ instead of ● while live
18 chips?: string[]
19 right?: string
20 buttons?: Btn[]
21 rows?: RowBtn[] // one clickable line each, under the band
22 maxW?: number
23}
24
25// ---- lines of coloured pieces (flightdeck's `line`)
26// A Text nesting coloured Texts truncates as one line in a terminal, but the desktop app wraps each nested piece on its
27// own and collapses runs of spaces. So pieces sit `gap` cells apart, each keeps its width, and pieces that don't fit in
28// `room` are left out from the end; a piece marked `fill` truncates to what the others leave.
29export type Span = { text: string; color?: string; dim?: boolean; bold?: boolean }
30export type Piece = { spans: Span[]; lead?: number; fill?: boolean; key?: string }
31const styleOf = (s: Span) => ({ ...(s.color ? { color: s.color } : {}), ...(s.dim ? { dimColor: true } : {}), ...(s.bold ? { bold: true } : {}) })
32const widthOf = (p: Piece) => p.spans.reduce((n, s) => n + [...s.text].length, 0)
33export const fits = (pieces: Piece[], room: number, gap: number) => {
34 let used = 0
35 for (let i = 0; i < pieces.length; i += 1) {
36 const next = used + (i > 0 ? gap : 0) + (pieces[i].lead ?? 0) + widthOf(pieces[i])
37 if (next > room) return i
38 used = next
39 }
40 return pieces.length
41}
42export const line = (ui: any, pieces: (Piece | null | false | undefined)[], room: number, gap = 1, justify?: 'center' | 'space-between') => {
43 const { Box, Text } = ui
44 const all = pieces.filter((p): p is Piece => Boolean(p))
45 const shown = all.some(p => p.fill) ? all : all.slice(0, Math.max(1, fits(all, room, gap)))
46 return (
47 <Box width={Math.max(1, room)} columnGap={gap} overflow="hidden" {...(justify ? { justifyContent: justify } : {})}>
48 {shown.map((p, i) => {
49 if (p.fill) return <Box key={p.key ?? `p${i}`} flexShrink={1}>{p.spans.length === 1 ? <Text {...styleOf(p.spans[0])} wrap="truncate">{p.spans[0].text}</Text> : <Text wrap="truncate">{p.spans.map(s => <Text {...styleOf(s)}>{s.text}</Text>)}</Text>}</Box>
50 return (
51 <Box key={p.key ?? `p${i}`} flexShrink={0} {...(p.lead ? { marginLeft: p.lead } : {})}>
52 {p.spans.length === 1 ? <Text {...styleOf(p.spans[0])}>{p.spans[0].text}</Text> : <Text>{p.spans.map(s => <Text {...styleOf(s)}>{s.text}</Text>)}</Text>}
53 </Box>
54 )
55 })}
56 </Box>
57 )
58}
59
60// A ▰▱ gauge as spans: coloured fill, faint track, then the percent.
61export const gaugeSpans = (pct: number, width: number, color: string, label = ''): Span[] => {
62 const g = gauge(pct, width)
63 return [...(label ? [{ text: `${label} `, dim: true }] : []), { text: g.on, color }, { text: g.off, color: C.faint }, { text: ` ${Math.round(pct)}%`, bold: true }]
64}
65
66// ---- boxes
67// A flightdeck panel: rounded border in the role's colour, a "TITLE · state" row with a dim right side, then the body.
68export const box = (ui: any, o: { key?: string; color: string; title: string; state?: string; right?: string; w?: number; dim?: boolean; children?: unknown }) => {
69 const { Box, Text } = ui
70 return (
71 <Box key={o.key} flexDirection="column" borderStyle="round" borderColor={o.color} borderDimColor={o.dim} paddingX={1} {...(o.w ? { width: o.w } : {})}>
72 <Box justifyContent="space-between">
73 <Text color={o.color} bold wrap="truncate">{o.state ? `${o.title} · ${o.state}` : o.title}</Text>
74 {o.right ? <Box flexShrink={0}><Text dimColor>{o.right}</Text></Box> : null}
75 </Box>
76 {o.children}
77 </Box>
78 )
79}
80
81const width = (e: any, maxW?: number) => Math.max(24, Math.min(maxW ?? 400, (e?.props?.bodyColumns ?? e?.viewport?.columns ?? 80) - 1))
82
83// ---- bands above the prompt
84// A mod that needs attention: one flightdeck box, same anatomy in every mod. `nested` is `await below(next, e)` (the bands
85// beneath), `ui` is `$.ui.resolve(e)`: `$` never crosses an import, so the mod passes both in.
86export const band = (ui: any, e: any, nested: unknown, s: BandSpec) => {
87 const { Box, Text, Button } = ui
88 const color = P[s.tone]
89 const W = width(e, s.maxW)
90 const bars = s.bars ?? (s.pct !== undefined ? [{ pct: s.pct, label: s.pctLabel ?? '', tone: undefined }] : [])
91 const meter = bars.length || s.chips?.length || s.right
92 return (
93 <Box flexDirection="column">
94 <Box flexDirection="column" borderStyle="round" borderColor={color} paddingX={1} width={W}>
95 <Box flexDirection="row" alignItems="center" columnGap={1}>
96 <Box flexShrink={1} flexGrow={1}>
97 {line(ui, [{ spans: [{ text: `${s.busy ? '◐' : '●'} ${s.title}`, color, bold: true }] }, s.detail ? { spans: [{ text: `· ${s.detail}`, dim: true }], fill: true } : null], W - 4 - (s.buttons?.length ?? 0) * 12)}
98 </Box>
99 {(s.buttons ?? []).map(b => <Button key={b.key} label={b.label} hotkey={b.hotkey} plain={b.plain} onPress={b.onPress} />)}
100 </Box>
101 {meter
102 ? line(
103 ui,
104 [
105 ...bars.map((b, i): Piece => ({ key: `b${i}`, spans: gaugeSpans(b.pct, 10, b.tone ? P[b.tone] : color, b.label) })),
106 ...(s.chips ?? []).map((c, i): Piece => ({ key: `c${i}`, spans: [{ text: `· ${c}`, dim: true }] })),
107 s.right ? { key: 'r', spans: [{ text: s.right, dim: true }], lead: 1 } : null,
108 ],
109 W - 4,
110 2,
111 )
112 : null}
113 {(s.rows ?? []).map(r => (
114 <Button key={r.key} plain hotkey={r.hotkey} onPress={r.onPress}>
115 <Text color={color}>{r.hotkey ? '' : '› '}</Text>
116 <Text>{r.label}</Text>
117 <Text dimColor>{r.hint ? ` ${r.hint}` : ''}</Text>
118 </Button>
119 ))}
120 </Box>
121 {nested}
122 </Box>
123 )
124}
125
126// Calm state: a mod adds a short segment to one shared summary line instead of drawing its own band.
127export type Seg = { key: string; text: string; tone?: Tone; spec?: BandSpec; more?: BandSpec[]; onPress?: () => unknown }
128let segs: Seg[] = []
129export const beginPass = () => {
130 segs = []
131}
132// Bands are drawn inner-first, so a new segment goes to the front to keep the outermost mod on the left.
133export const quiet = (s: Seg) => {
134 segs.unshift(s)
135}
136export const quietSegs = () => segs
137
138// The one summary line above the prompt, flightdeck's inline "mini" look: NAME · every calm segment · an Open button.
139// `nested` is what the bands beneath drew.
140export const quietLine = (ui: any, e: any, nested: unknown, o: { name: string; open?: () => unknown; label?: string }) => {
141 if (!segs.length) return nested
142 const { Box, Text, Button } = ui
143 return (
144 <Box flexDirection="column">
145 <Box flexDirection="row" alignItems="center" columnGap={1} width={width(e)}>
146 <Text bold color={C.main}>{o.name}</Text>
147 {segs.map(s => {
148 const label = <Text color={s.tone ? P[s.tone] : undefined} dimColor={!s.tone}>{`· ${s.text}`}</Text>
149 return s.onPress ? <Button key={s.key} plain onPress={s.onPress}>{label}</Button> : <Box key={s.key} flexShrink={0}>{label}</Box>
150 })}
151 <Box flexGrow={1} />
152 {o.open ? <Button key="open" plain label={o.label ?? 'Open'} onPress={o.open} /> : null}
153 </Box>
154 {nested}
155 </Box>
156 )
157}
158
159// ---- panes
160// A pane's header, flightdeck's: "TITLE · state" in the tone's colour, a dim right side or a gauge.
161export const paneHeader = (ui: any, e: any, o: { title: string; sub?: string; pct?: number; tone?: Tone; right?: string }) => {
162 const color = P[o.tone ?? 'accent']
163 const W = width(e)
164 return line(
165 ui,
166 [
167 { spans: [{ text: o.title.toUpperCase(), color, bold: true }] },
168 o.sub ? { spans: [{ text: `· ${o.sub}`, bold: true }], fill: true } : null,
169 o.pct !== undefined ? { spans: gaugeSpans(o.pct, 8, color), lead: 1 } : null,
170 o.right ? { spans: [{ text: o.right, dim: true }], lead: 1 } : null,
171 ],
172 W,
173 )
174}
175
176const GLYPH: Record<Tone, string> = { accent: '◐', ok: '✓', warn: '◐', err: '✗', info: '●', purple: '●' }
177
178// One row in a pane list: status glyph, title, a dim chip and a right-hand meta; an optional dim line under it.
179export const item = (ui: any, e: any, o: { key: string; tone: Tone; title: string; sub?: string; chip?: string; meta?: string; glyph?: string }) => {
180 const { Box, Text } = ui
181 const color = P[o.tone]
182 return (
183 <Box key={o.key} flexDirection="column">
184 <Box columnGap={1}>
185 <Text color={color}>{o.glyph ?? GLYPH[o.tone]}</Text>
186 <Box flexShrink={1} flexGrow={1}><Text wrap="truncate">{o.title}</Text></Box>
187 {o.chip ? <Box flexShrink={0}><Text color={color}>{o.chip}</Text></Box> : null}
188 {o.meta ? <Box flexShrink={0}><Text dimColor>{o.meta}</Text></Box> : null}
189 </Box>
190 {o.sub ? <Text dimColor wrap="truncate">{` ${o.sub}`}</Text> : null}
191 </Box>
192 )
193}
194hooks/kit.tsx 67 lines1// Card pieces shared by the pane mods: pills, file badges, folder marks, stat tiles, section labels, text cards.
2// Single source: scripts/sync-ui.sh copies it to plugins/*/hooks/kit.tsx. Mono text in theme colours on every surface,
3// as claude-flightdeck draws (MIT, see THIRD_PARTY_NOTICES.md). Every piece takes `ui` (= $.ui.resolve(e)) and `e`.
4import { C, P } from './ui'
5
6const EXT: Record<string, [string, keyof typeof P]> = {
7 js: ['JS', 'warn'], jsx: ['JSX', 'warn'], mjs: ['JS', 'warn'], ts: ['TS', 'info'], tsx: ['TSX', 'info'],
8 json: ['JSON', 'warn'], md: ['MD', 'muted'], pdf: ['PDF', 'err'], csv: ['CSV', 'ok'], py: ['PY', 'ok'],
9 sh: ['SH', 'accent'], html: ['HTML', 'err'], css: ['CSS', 'purple'], yml: ['YML', 'purple'], yaml: ['YML', 'purple'],
10 go: ['GO', 'teal'], rs: ['RS', 'accent'], txt: ['TXT', 'muted'], png: ['PNG', 'teal'], jpg: ['JPG', 'teal'],
11 svg: ['SVG', 'teal'], map: ['MAP', 'muted'], lock: ['LOCK', 'muted'], toml: ['TOML', 'accent'],
12}
13
14// "client.test.js" -> ["JS", colour]; no extension -> a plain file mark.
15export const extBadge = (name: string): [string, string] => {
16 const dot = name.lastIndexOf('.')
17 const ext = dot > 0 ? name.slice(dot + 1).toLowerCase() : name.startsWith('.') ? name.slice(1).toLowerCase() : ''
18 const hit = EXT[ext]
19 return hit ? [hit[0], P[hit[1]]] : [ext ? ext.slice(0, 4).toUpperCase() : 'FILE', P.muted]
20}
21
22export const fileBadge = (ui: any, _e: any, name: string) => {
23 const [label, color] = extBadge(name)
24 return <ui.Text color={color}>{`${label.padEnd(4)} `}</ui.Text>
25}
26
27export const folderIcon = (ui: any, _e: any, color: string = P.info) => <ui.Text color={color}>{'■ '}</ui.Text>
28
29// A small bracketed tag: "reading", "edited", "committed".
30export const pill = (ui: any, _e: any, label: string, color: string) => <ui.Text color={color} bold>{`[${label}]`}</ui.Text>
31
32// A glyph mark, the "RIGHT NOW" / trash icon.
33export const iconTile = (ui: any, _e: any, glyph: string, color: string) => <ui.Text color={color} bold>{`${glyph} `}</ui.Text>
34
35// Stat tile: a dim label and a bold value (Cost, Tokens, Time).
36export const tile = (ui: any, _e: any, label: string, value: string) => (
37 <ui.Text>
38 <ui.Text dimColor>{`${label} `}</ui.Text>
39 <ui.Text bold>{value}</ui.Text>
40 </ui.Text>
41)
42
43// "CLAUDE TOUCHED 1 FILE": dim caps label left, dim count right.
44export const sectionLabel = (ui: any, left: string, right?: string) => (
45 <ui.Box flexDirection="row">
46 <ui.Text bold dimColor>{left.toUpperCase()}</ui.Text>
47 <ui.Box flexGrow={1} />
48 <ui.Text dimColor>{right ? right.toUpperCase() : ''}</ui.Text>
49 </ui.Box>
50)
51
52// Rounded bordered panel in the faint colour, or the one given.
53export const panel = (ui: any, children: unknown, o: { color?: string } = {}) => (
54 <ui.Box flexDirection="column" borderStyle="round" borderColor={o.color ?? C.faint} paddingX={1}>
55 {children}
56 </ui.Box>
57)
58
59// A card whose text wraps in full (no truncation): a rounded border in the card's colour, text, an optional dim line and actions.
60export const textCard = (ui: any, o: { key: string; color: string; text: string; sub?: string; children?: unknown }) => (
61 <ui.Box key={o.key} flexDirection="column" borderStyle="round" borderColor={o.color} paddingX={1}>
62 <ui.Text wrap="wrap">{o.text}</ui.Text>
63 {o.sub ? <ui.Text wrap="wrap" dimColor>{o.sub}</ui.Text> : null}
64 {o.children}
65 </ui.Box>
66)
67hooks/ui.ts 114 lines1// Shared drawing kit. Single source: scripts/sync-ui.sh copies it to plugins/*/hooks/ui.ts.
2// The look follows claude-flightdeck (MIT, see THIRD_PARTY_NOTICES.md): mono text in rounded, role-coloured boxes,
3// ▰▱ gauges, colours named after the person's Claude Code theme so light, dark and colour-blind themes all read.
4
5// Roles, as flightdeck names them: main (Claude's own), agent, gate, cleared, arch(itect), amber, warn, dim, faint, text.
6type Role = 'main' | 'agent' | 'gate' | 'cleared' | 'arch' | 'amber' | 'warn' | 'dim' | 'faint' | 'text'
7const THEME: Record<Role, string> = {
8 main: 'claude', agent: 'suggestion', gate: 'success', cleared: 'permission', arch: 'merged',
9 amber: 'warning', warn: 'error', dim: 'inactive', faint: 'subtle', text: 'text',
10}
11// Fixed hex tuned for dark terminals: the `palette: pastel` option.
12const PASTEL: Record<Role, string> = {
13 main: '#7dd3fc', agent: '#93c5fd', gate: '#86efac', cleared: '#5eead4', arch: '#c4b5fd',
14 amber: '#fcd34d', warn: '#fca5a5', dim: '#6b7280', faint: '#3f4654', text: '#e5e7eb',
15}
16
17// The live palette every mod reads. `usePalette` swaps it in place at register time, so imports stay valid.
18export const C: Record<Role, string> = { ...THEME }
19export type Tone = 'accent' | 'ok' | 'warn' | 'err' | 'info' | 'purple'
20// A mod's tone, as a role colour: accent is Claude's own, info an agent's, purple the architect's.
21export const P: Record<Tone | 'teal' | 'muted' | 'faint' | 'text', string> = { ...toneColors() }
22// Motion and palette options, set once per load by the bundle's register.
23export const DECK = { motion: true, palette: 'theme' as 'theme' | 'pastel' }
24
25function toneColors() {
26 return { accent: C.main, ok: C.gate, warn: C.amber, err: C.warn, info: C.agent, purple: C.arch, teal: C.cleared, muted: C.dim, faint: C.faint, text: C.text }
27}
28
29export const usePalette = (palette: unknown, motion: unknown) => {
30 DECK.palette = palette === 'pastel' ? 'pastel' : 'theme'
31 DECK.motion = motion !== 'off'
32 Object.assign(C, DECK.palette === 'pastel' ? PASTEL : THEME)
33 Object.assign(P, toneColors())
34}
35
36// SVG cannot name theme keys: mid-tone colours that read on light and dark backgrounds (the desktop time axis).
37export const SVG_COLORS = { running: '#3b82f6', done: '#16a34a', failed: '#dc2626', other: '#8b5cf6', label: '#6b7280' }
38export const MONO = "ui-monospace, 'SF Mono', Menlo, Consolas, monospace"
39
40export const esc = (s: string) => s.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c] as string)
41
42export const fmtTok = (n: number) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)}M` : n >= 1e3 ? `${Math.round(n / 1e3)}k` : `${n}`)
43export const fmtSize = (n: number) => (n < 1024 ? `${n} B` : n < 1048576 ? `${(n / 1024).toFixed(n < 10240 ? 1 : 0)} KB` : `${(n / 1048576).toFixed(1)} MB`)
44
45// `git status --porcelain -z` output (no header) -> rows. A rename or copy carries its old path as an extra field: skipped.
46export const parsePorcelain = (out: string) => {
47 const parts = out.split('\0')
48 const rows: { st: string; path: string }[] = []
49 for (let i = 0; i < parts.length; i++) {
50 const l = parts[i]
51 if (l.length < 4) continue
52 rows.push({ st: l.slice(0, 2), path: l.slice(3) })
53 if (/[RC]/.test(l.slice(0, 2))) i++
54 }
55 return rows
56}
57
58export const fmtCost = (usd: number) => (usd < 0.01 ? '<$0.01' : usd < 10 ? `$${usd.toFixed(2)}` : `$${Math.round(usd)}`)
59export const fmtDur = (ms: number) => {
60 const s = Math.max(0, Math.round(ms / 1000))
61 return s < 60 ? `${s}s` : s < 3600 ? `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s` : `${Math.floor(s / 3600)}h${String(Math.floor((s % 3600) / 60)).padStart(2, '0')}m`
62}
63// A running clock as flightdeck's cards draw it: m:ss, or XhYY past an hour.
64export const fmtTimer = (ms: number) => {
65 const s = Math.max(0, Math.floor(ms / 1000))
66 const m = Math.floor(s / 60)
67 return m < 60 ? `${m}:${String(s % 60).padStart(2, '0')}` : `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
68}
69export const fmtClock = (ms: number) => (ms > 0 ? new Date(ms).toTimeString().slice(0, 8) : '--:--:--')
70export const plural = (n: number, w: string) => `${n} ${w}${n === 1 ? '' : 's'}`
71export const shorten = (s: string, n: number) => {
72 const one = s.replace(/\s+/g, ' ').trim()
73 return n <= 0 ? '' : one.length > n ? `${one.slice(0, Math.max(0, n - 1)).trimEnd()}…` : one
74}
75
76// Green below `warnAt`, amber below `errAt`, red above (percent scales).
77export const zone = (pct: number, warnAt = 60, errAt = 85) => (pct >= errAt ? C.warn : pct >= warnAt ? C.amber : C.gate)
78export const zoneTone = (pct: number, warnAt = 60, errAt = 85): Tone => (pct >= errAt ? 'err' : pct >= warnAt ? 'warn' : 'ok')
79
80// A gauge of `width` cells: ▰ filled, ▱ empty.
81export const gauge = (pct: number, width: number) => {
82 const full = Math.max(0, Math.min(width, Math.round((pct / 100) * width)))
83 return { on: '▰'.repeat(full), off: '▱'.repeat(width - full) }
84}
85
86// "claude-opus-5-5[1m]" -> "Opus 5.5 1M"; anything else as given, cut to 22.
87export const prettyModel = (id: string) => {
88 if (!id) return '—'
89 const cap = (f: string) => f.charAt(0).toUpperCase() + f.slice(1)
90 const big = /\[1m\]|-1m\b/i.test(id) ? ' 1M' : ''
91 const now = /claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(?![\d])/i.exec(id)
92 if (now?.[1] && !/^\d/.test(now[1])) return `${cap(now[1].toLowerCase())} ${now[2]}${now[3] ? `.${now[3]}` : ''}${big}`
93 const old = /claude-(\d+)(?:-(\d))?-([a-z]+)/i.exec(id)
94 if (old?.[3]) return `${cap(old[3].toLowerCase())} ${old[1]}${old[2] ? `.${old[2]}` : ''}${big}`
95 return shorten(id, 22)
96}
97
98// The desktop and mobile draw Svg; the terminal's element table carries a stub that draws nothing: test the surface too.
99export const isRich = (ui: object, e: { surface: string }) => e.surface !== 'terminal' && 'Svg' in ui
100
101// AbovePrompt is one strip shared by every mod: a hook that returns a tree hides the mods beneath it
102// unless it nests what `next(e)` drew. Call this first, put the result in your column. Claude Code's
103// own placeholder ({ type: 'engine' }) is never nested: the desktop drops a band that nests it.
104export const below = async (next: (e: any) => unknown, e: unknown) => {
105 const drawn = await Promise.resolve(next(e)).catch(() => null)
106 return drawn && typeof drawn === 'object' && (drawn as { type?: string }).type !== 'engine' ? drawn : null
107}
108
109// Age in a few characters, as the filetree draws it: now, 12m, 3h, 5d.
110export const age = (ms: number) => {
111 const m = Math.floor(ms / 60_000)
112 return m < 1 ? 'now' : m < 60 ? `${m}m` : m < 1440 ? `${Math.floor(m / 60)}h` : `${Math.floor(m / 1440)}d`
113}
114hooks/rail.tsx 87 lines1// From claude-flightdeck (https://github.com/scasella/claude-flightdeck, commit f9c3c52), MIT, Copyright (c) 2026
2// Stephen Casella; see THIRD_PARTY_NOTICES.md. Single source: scripts/sync-ui.sh copies it to plugins/*/hooks/rail.tsx.
3// A connector drawn on the surface's own frame clock: packets travel along it while `active`,
4// and it rests as a plain dim line otherwise. Only this region redraws; the pane does not.
5import type { ClientModule, RenderChildren } from 'claude-code'
6
7type Props = {
8 active: boolean
9 width: number
10 color: string
11 dim: string
12 /** Cells where a branch drops (┬); the rest of the line is ─. */
13 marks: number[]
14 /** Draw ┴ instead of ┬ at the marks: a merge into what is below. */
15 isMerge: boolean
16}
17
18type Ref = { phase: number; active: boolean }
19type State = { ref: Ref }
20
21const STEP_MS = 110
22/** Dashes drawn past the line's end and clipped by its box, so the right end is the box's edge. */
23const SPARE = 4
24
25const Rail: ClientModule<Props, State> = (props, surface) => {
26 const { Box, Text } = surface.elements
27 const ref = surface.state?.ref ?? { phase: 0, active: props.active }
28 ref.active = props.active
29 if (surface.state === undefined) {
30 surface.setState({ ref })
31 surface.every(STEP_MS, () => {
32 if (ref.active) {
33 ref.phase += 1
34 surface.setState({ ref })
35 }
36 })
37 }
38
39 const width = Math.max(1, surface.columns || props.width)
40 const cells = Array.from({ length: width + SPARE }, () => '─')
41 for (const m of props.marks) if (m >= 0 && m < width) cells[m] = props.isMerge ? '┴' : '┬'
42
43 // A graphical surface draws text in a proportional face, where ─ ● • and bold differ in width, so as
44 // the packets moved the line's length changed and its right end jittered. Drawn in the surface's
45 // monospaced face (whose advance is what a cell is there) each glyph is one cell, and the line sits in
46 // a box of its width that clips the spare dashes: its right end is that edge, every frame.
47 const line = (children: RenderChildren) => (
48 <Box width={width} overflow="hidden">
49 <Box flexShrink={0}>{children}</Box>
50 </Box>
51 )
52
53 if (!props.active) {
54 return line(
55 <Text color={props.dim} mono>
56 {cells.join('')}
57 </Text>,
58 )
59 }
60
61 // Two packets per 24 cells, a bright head and a trailing dot, moving left to right.
62 const lit = new Map<number, string>()
63 for (let base = 0; base < width + 24; base += 24) {
64 const head = (base + ref.phase) % (width + 24)
65 if (head < width) lit.set(head, '●')
66 if (head - 1 >= 0 && head - 1 < width) lit.set(head - 1, '•')
67 }
68 // Runs, not cells: consecutive cells of one kind share a Text, a handful of nodes per frame.
69 const runs: { text: string; isLit: boolean }[] = []
70 cells.forEach((ch, i) => {
71 const isLit = lit.has(i)
72 const last = runs[runs.length - 1]
73 const glyph = lit.get(i) ?? ch
74 if (last && last.isLit === isLit) last.text += glyph
75 else runs.push({ text: glyph, isLit })
76 })
77 return line(
78 runs.map(r => (
79 <Text color={r.isLit ? props.color : props.dim} bold={r.isLit} mono>
80 {r.text}
81 </Text>
82 )),
83 )
84}
85
86export default Rail
87types/index.d.ts 10 lines1export type GuardrailsCoached = boolean
2
3declare module 'claude-code' {
4 interface PluginState {
5 // merge-sweep: PR URLs this session opened (one list per session id)
6 // prompt-coach: has this session's first prompt been coached (one value per session id)
7 guardrails: { coached: StateFamily<GuardrailsCoached>; prs: StateFamily<string[]> }
8 }
9}
10