A pane beside the session that Claude talks to you through: the task, what it is doing, the notes it files, the questions it went on without, and manual tests…

A Claude Code mod that keeps a pane beside the session. Claude talks to you through it without stopping, and you can switch worktrees and pick up where you left off.
Claude uses its own ask dialog only when it can't go on without you. Otherwise it writes Open question: Which TTL? [5m | 1h] (assuming 5m) and keeps working on the assumption. The question shows in the pane as soon as Claude writes it. You answer with a button or a typed reply whenever you like, and no new turn starts:
Mods need Claude Code 2.1.287 or later.
/plugin marketplace add crockalet/claude-mods
/plugin install breadcrumbs@claude-mods
/plugin install breadcrumbs-launcher@claude-mods
/whereami shows or hides the pane. It opens by itself at 144+ columns.
When you need to run tests by hand, Claude lists them in a second pane (/tests) with their steps, adding each as soon as the piece it covers is ready, so they wait there until you get to them. Start tester hands one test to a tester subagent that walks you through it, follows the logs while you go, and sends its final report to the main session, so the main agent stays the orchestrator.
With breadcrumbs-launcher installed, Start launches the tester at once, even mid-turn. Without it, Start asks Claude to spawn the tester, which waits until Claude is free. (An agent a mod spawns skips that mod's own hooks, so breadcrumbs can't answer its own tester's tools. A second mod's spawn doesn't have that problem.)
Notes live outside your repos, one folder per session:
~/.agents/notes/<repo>/<worktree>/
index.md one line per session
<date>-<task>-<id>/
context.md the pane as a file
NN-<title>.md notes
state.json restores the pane on resume
~/.agents/notes/<repo>/_pinned/ pinned notes
Session folders are archived after 30 days, or as soon as their worktree is gone, and deleted 60 days after that. /whereami clean shows what would go and asks first. Both periods, the side-pass model, the testers' model (Sonnet unless a test asks for another) and when the pane opens are settings in /plugin.
claude --plugin-dir plugins/breadcrumbs # hot-reloads on save
claude plugin validate plugins/breadcrumbs
claude plugin test plugins/breadcrumbshooks/register.tsx 1983 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, SessionMessage } from 'claude-code'
3
4import type { Answer, Ask, Crumbs, Entry, ManualTest, Note, Repo, TestRun, TestStatus, TestsView, View, Wait, Where } from '../types'
5import { contextMarkdown, repoState } from './markdown'
6import { normalize } from './state'
7import { ICON, LAUNCHER_ALIVE_MS, LAUNCH_DIR, LAUNCH_GRACE_MS, STATUSES, TESTER, TESTER_PROMPT, TESTS_GUIDANCE, TESTS_PANE, TOOL, WAIT_LIMIT_MS, isLive, listOf, openWait, pastables, settleNeeds, str, testOf, unmet } from './tests'
8import type { Saved } from './markdown'
9import { richLines, type Line } from './rich'
10import { MAX_ASKS, ago, asks, basename, cdTarget, clip, day, doneOf, head, narrowTables, openQuestions, parseObject, parseStatus, slug, stamp, strings, toolLabel } from './text'
11
12const PANE = 'breadcrumbs'
13const PAD = 1
14// Below this many columns per cell a wrapped table reads worse than the same rows as a list.
15const MIN_CELL = 10
16
17// The terminal's own Markdown draws flat; there the pane lays markdown out itself in the theme's colors.
18const drawRich = (el: ReturnType<$['ui']['resolve']>, lines: Line[], dim = false) => {
19 const { Box, Text, Link } = el
20 return (
21 <Box flexDirection="column">
22 {lines.map(line => (
23 <Text wrap="truncate-end">
24 {line.length === 0
25 ? ' '
26 : line.map(s => {
27 const text = (
28 <Text {...s.style} dimColor={dim || undefined}>
29 {s.text}
30 </Text>
31 )
32 return s.href ? <Link href={s.href}>{text}</Link> : text
33 })}
34 </Text>
35 ))}
36 </Box>
37 )
38}
39const SAVE_NOTE = 'mcp__breadcrumbs__save_note'
40const EDIT_NOTE = 'mcp__breadcrumbs__edit_note'
41
42const crumbs = atom({ plugin: 'breadcrumbs', key: 'crumbs' } as const, normalize({}))
43const where = atom({ plugin: 'breadcrumbs', key: 'where' } as const, null)
44const VIEW: View = {
45 openNote: null,
46 isShowingPrompts: false,
47 isShowingMore: false,
48 isShowingStatus: false,
49 openDone: null,
50 typed: {},
51}
52const view = atom({ plugin: 'breadcrumbs', key: 'view' } as const, VIEW)
53const pending = atom({ plugin: 'breadcrumbs', key: 'pending' } as const, null)
54const testRun = atom({ plugin: 'breadcrumbs', key: 'tests' } as const, { brief: '', tests: [], waits: [], unreported: [] })
55const testsView = atom({ plugin: 'breadcrumbs', key: 'testsView' } as const, { expanded: null, typed: {} })
56
57const COMPANION_GUIDANCE = [
58 'The user keeps a "breadcrumbs" pane open beside this session; it is how you reach them without stopping.',
59 'Write explanations, summaries and walkthroughs in your reply as usual: the pane files them as notes by itself.',
60 `Call ${SAVE_NOTE} only on purpose: to post something the user should see now while you keep working (a finding, a heads-up), a document they will come back to (a plan, a handoff, a decision record) that you keep current with ${EDIT_NOTE} (its id and only the text that changes), or when they ask you to save something. Never for status updates, and never to repeat what your reply says.`,
61 'When you cannot go on without an answer, use AskUserQuestion.',
62 'When you can go on with a sensible default, write the question on its own line as "Open question: <question> [option | option] (assuming <what you go with>)", the options optional, and keep working on that assumption.',
63 'The user answers in the pane when they get to it; the answer reaches you after one of your tool calls or with their next prompt, so adjust then if it changes anything, and do not ask it again meanwhile.',
64].join(' ')
65
66type $ = EngineInterface
67
68// Session state outlives reloads, so it can predate fields added since; every access goes through normalize.
69const readCrumbs = async ($: $): Promise<Crumbs> => normalize(await read($, crumbs))
70
71const mutate = ($: $, fn: (c: Crumbs) => Crumbs) => update($, crumbs, c => fn(normalize(c)))
72
73const notesRoot = async ($: $): Promise<string> =>
74 `${(await $.env.get('HOME')) ?? '~'}/.agents/notes`
75
76const git = async ($: $, cwd: string, ...args: string[]): Promise<string | null> => {
77 try {
78 const run = await $.process.run(['git', ...args], { cwd, timeoutMs: 3000 })
79
80 return run.exitCode === 0 ? run.stdout : null
81 } catch {
82 return null
83 }
84}
85
86const locate = async ($: $): Promise<Where> => {
87 const cwd = await $.session.cwd()
88 const repo = await $.session.repo()
89 const worktree = (await git($, cwd, 'rev-parse', '--show-toplevel'))?.trim() || cwd
90
91 return {
92 repo: repo ? basename(repo.root) : basename(worktree),
93 branch: (await git($, cwd, 'branch', '--show-current'))?.trim() ?? '',
94 worktree,
95 }
96}
97
98const refreshRepos = async ($: $) => {
99 const c = await readCrumbs($)
100 const place = await read($, where)
101 const places = new Set([...c.touched, ...c.edited.map(f => f.slice(0, f.lastIndexOf('/')))])
102 if (place) places.add(place.worktree)
103 const roots = new Set<string>()
104 for (const dir of places) {
105 const root = (await git($, dir, 'rev-parse', '--show-toplevel'))?.trim()
106 if (root) roots.add(root)
107 }
108 const repos: Repo[] = []
109 for (const root of roots) {
110 const status = await git($, root, 'status', '--porcelain=v1', '-b')
111 if (status !== null) repos.push({ root, ...parseStatus(status) })
112 }
113 await mutate($, old => ({ ...old, repos }))
114}
115
116const worktreeDir = (root: string, where: Where) =>
117 `${root}/${where.repo}/${basename(where.worktree)}`
118
119const readSaved = async ($: $, dir: string): Promise<Saved | null> => {
120 try {
121 return JSON.parse(await $.fs.read(`${dir}/state.json`)) as Saved
122 } catch {
123 return null
124 }
125}
126
127const writeIndex = async ($: $, wtDir: string) => {
128 let entries
129 try {
130 entries = await $.fs.list(wtDir)
131 } catch {
132 return
133 }
134 const rows: { at: number; line: string }[] = []
135 for (const entry of entries) {
136 if (entry.kind !== 'dir') continue
137 const saved = await readSaved($, `${wtDir}/${entry.name}`)
138 if (!saved) continue
139 const task = clip(saved.tasks[0]?.title ?? 'No task yet', 70)
140 const notes = saved.notes.length === 1 ? '1 note' : `${saved.notes.length} notes`
141 const waiting = asks(saved.needsYou).length > 0 ? ' · needs you' : ''
142 rows.push({
143 at: saved.updatedAt,
144 line: `- ${task}${waiting} · ${notes} · ${stamp(saved.updatedAt)} → [${entry.name}/](${entry.name}/context.md)`,
145 })
146 }
147 if (rows.length === 0) return
148 rows.sort((a, b) => b.at - a.at)
149 await $.fs.write(`${wtDir}/index.md`, `# ${basename(wtDir)}\n\n${rows.map(r => r.line).join('\n')}\n`)
150}
151
152const persist = async ($: $, dir: string, saved: Saved, where: Where, status: string) => {
153 await $.fs.write(`${dir}/state.json`, JSON.stringify(saved, null, 2))
154 await $.fs.write(`${dir}/context.md`, contextMarkdown(saved, where, status))
155 await writeIndex($, dir.slice(0, dir.lastIndexOf('/')))
156}
157
158type CleanPlan = {
159 archive: { from: string; to: string }[]
160 remove: string[]
161 touched: string[]
162}
163
164type CleanOptions = { now: number; retentionDays: number; archiveDays: number; isArchiving: boolean; keep: string }
165
166const DAY = 86_400_000
167
168const dirs = async ($: $, path: string) => {
169 try {
170 return (await $.fs.list(path)).filter(e => e.kind === 'dir' && !e.name.startsWith('.'))
171 } catch {
172 return []
173 }
174}
175
176const planClean = async ($: $, root: string, o: CleanOptions): Promise<CleanPlan> => {
177 const plan: CleanPlan = { archive: [], remove: [], touched: [] }
178 for (const repo of await dirs($, root)) {
179 if (repo.name.startsWith('_')) continue
180 for (const wt of await dirs($, `${root}/${repo.name}`)) {
181 if (wt.name.startsWith('_')) continue
182 const wtDir = `${root}/${repo.name}/${wt.name}`
183 for (const session of await dirs($, wtDir)) {
184 const dir = `${wtDir}/${session.name}`
185 if (dir === o.keep) continue
186 const saved = await readSaved($, dir)
187 const updatedAt = saved?.updatedAt ?? (await $.fs.stat(dir)).mtimeMs
188 const isGone = saved !== null && !(await $.fs.exists(saved.worktree))
189 const isOld = o.now - updatedAt > o.retentionDays * DAY
190 if (!isGone && !isOld) continue
191 if (o.isArchiving) {
192 plan.archive.push({ from: dir, to: `${root}/_archive/${repo.name}/${wt.name}--${session.name}` })
193 } else {
194 plan.remove.push(dir)
195 }
196 if (!plan.touched.includes(wtDir)) plan.touched.push(wtDir)
197 }
198 }
199 }
200 for (const repo of await dirs($, `${root}/_archive`)) {
201 for (const entry of await dirs($, `${root}/_archive/${repo.name}`)) {
202 const dir = `${root}/_archive/${repo.name}/${entry.name}`
203 let archivedAt: number
204 try {
205 archivedAt = Number(await $.fs.read(`${dir}/.archived-at`))
206 } catch {
207 archivedAt = (await $.fs.stat(dir)).mtimeMs
208 }
209 if (o.now - archivedAt > o.archiveDays * DAY) plan.remove.push(dir)
210 }
211 }
212
213 return plan
214}
215
216const applyClean = async ($: $, root: string, plan: CleanPlan, now: number) => {
217 // Every path came from listing `root`, but a bad join must never reach rm.
218 const isInside = (p: string) => p.startsWith(`${root}/`) && !p.includes('/../')
219 for (const { from, to } of plan.archive) {
220 if (!isInside(from) || !isInside(to)) continue
221 await $.process.run(['mkdir', '-p', to.slice(0, to.lastIndexOf('/'))])
222 const moved = await $.process.run(['mv', from, to])
223 if (moved.exitCode === 0) await $.fs.write(`${to}/.archived-at`, String(now))
224 }
225 for (const dir of plan.remove) {
226 if (isInside(dir)) await $.process.run(['rm', '-rf', dir])
227 }
228 for (const wtDir of plan.touched) {
229 if ((await dirs($, wtDir)).length === 0) {
230 await $.process.run(['rm', '-rf', wtDir])
231 } else {
232 await writeIndex($, wtDir)
233 }
234 }
235}
236
237const cfg = { model: 'haiku', testerModel: 'sonnet', retentionDays: 30, archiveDays: 60, isArchiving: true }
238
239let sessionId = ''
240let dir: string | null = null
241// Identifies the conversation across a resume, which starts it under a new session id but keeps its transcript.
242let transcript: string | null = null
243let turnTools: string[] = []
244let hasSavedNote = false
245
246const ensureDir = async ($: $, title: string): Promise<string> => {
247 if (dir) return dir
248 const place = (await read($, where)) ?? (await locate($))
249 const now = await $.clock.now()
250 dir = `${worktreeDir(await notesRoot($), place)}/${day(now)}-${slug(title, 32)}-${sessionId.slice(0, 6)}`
251 await $.store.set(`dir:${sessionId}`, dir)
252
253 return dir
254}
255
256const save = async ($: $, status: string) => {
257 const state = await readCrumbs($)
258 const place = await read($, where)
259 if (!place || (state.tasks.length === 0 && state.notes.length === 0)) return
260 const target = await ensureDir($, state.tasks[0]?.title ?? 'session')
261 const saved: Saved = { ...state, session: sessionId, worktree: place.worktree, updatedAt: await $.clock.now(), ...(transcript ? { transcript } : {}) }
262 await persist($, target, saved, place, status)
263}
264
265const clean = async ($: $) => {
266 const root = await notesRoot($)
267 const now = await $.clock.now()
268 const plan = await planClean($, root, { ...cfg, now, keep: dir ?? '' })
269
270 return { root, now, plan }
271}
272
273// `transcript` set means a one-off catch-up over a session that predates the mod; `isPartial`, a pass while the turn still runs.
274// `said` is what Claude wrote earlier in the turn that no pass has read yet.
275type Turn = { answer: string; hasSavedNote: boolean; tools: string[]; transcript?: string; turnId?: string; said?: string; isPartial?: boolean }
276
277// Each turn's done entry, so later passes over the same turn rewrite it instead of adding rows.
278const doneAt = new Map<string, number>()
279
280const sidePass = async ($: $, { answer, hasSavedNote, tools, transcript, turnId, said, isPartial }: Turn) => {
281 const cap = transcript ? 6 : 3
282 const state = await readCrumbs($)
283 const prompt = state.prompts.at(-1)?.text ?? ''
284 const recorded = [...state.decided.slice(-6), ...state.tried.slice(-6).map(t => t.text)]
285 const request = [
286 'You keep a running log of a coding session for a developer who switches between many sessions.',
287 transcript
288 ? 'Read this transcript of the session so far and answer with one JSON object and nothing else. It is a catch-up: read "this turn" below as "the session so far", and allow up to 6 decisions, attempts and done items.'
289 : isPartial
290 ? 'The assistant is still working on this turn. Read what it has written so far and answer with one JSON object and nothing else; read "this turn" below as "this turn so far":'
291 : 'Read the latest exchange and answer with one JSON object and nothing else:',
292 '{"task": string, "isNewTask": boolean, "decisions": string[], "attempts": [{"text": string, "isOk": boolean}], "done": {"title": string, "items": string[]} | null, "note": {"title": string, "markdown": string | null} | null}',
293 '- task: the overall goal of the whole session in under 60 characters, imperative ("Fix websocket reconnect loop"), judged from all the recent prompts, not just this turn\'s step. Keep the current task\'s wording unless it is wrong or too narrow: when the prompts show the current task is one step of a bigger goal, widen it to that goal ("Verify the restart" becomes "Build the breadcrumbs mod").',
294 '- isNewTask: true only when the user clearly moved on to a different goal, not a follow-up.',
295 '- decisions: design or approach choices the assistant made on its own this turn where another option was reasonable and the user did not specify it ("Capped backoff at 30s instead of 60s"). Not actions taken, checks run or instructions given to the user. At most 3, under 90 characters each. Usually empty.',
296 '- done: what this turn changed outside the conversation, from the assistant reply and tools used. Not reads, checks, explanations or plans; null when nothing changed. title: the turn\'s outcome in under 40 characters, past tense ("Added the secrets mod", "Pushed main"). items: the concrete results behind it, naming what changed ("Pushed main to crockalet/breadcrumbs", "Fixed reconnect race in socket.ts"), at most 3, under 90 characters each; empty when the title says it all.',
297 '- attempts: approaches tried this turn, isOk false when one failed or was abandoned (at most 3). Empty when none.',
298 '- note: when the reply explains, summarizes, walks through or compares something at a paragraph or more (not a one-line answer, not a progress report), and it was not saved already. title: under 60 characters. markdown: null when the whole reply is the explanation, as it usually is; otherwise only the explanation, in the reply\'s own words. Otherwise note is null.',
299 '',
300 `Current task: ${state.tasks[0]?.title ?? '(none yet)'}`,
301 `Earlier prompts, oldest first (context for the task only; already handled): ${state.prompts.slice(0, -1).map(p => JSON.stringify(clip(p.text, 200))).join(' | ') || 'none'}`,
302 `Claude posted a note itself this turn: ${hasSavedNote} (only skip the reply's explanation when that note already holds it)`,
303 `Notes saved earlier (reuse a title exactly to update that note instead of adding one): ${state.notes.map(n => JSON.stringify(n.title)).join(', ') || 'none'}`,
304 `Tools used this turn: ${tools.slice(-30).join('; ') || 'none'}`,
305 `Decisions and attempts already recorded (never repeat one): ${recorded.map(r => JSON.stringify(r)).join(', ') || 'none'}`,
306 ...(isPartial ? ['- note mid-turn: only a finding or explanation the developer would want now, with its markdown; null for narration of steps.'] : []),
307 '',
308 ...(transcript
309 ? ['<transcript>', transcript, '</transcript>']
310 : [
311 '<user_prompt>',
312 clip(prompt, 4000),
313 '</user_prompt>',
314 ...(said ? ['<assistant_earlier_in_turn>', said.slice(-16000), '</assistant_earlier_in_turn>'] : []),
315 ...(answer ? [isPartial ? '<assistant_latest>' : '<assistant_reply>', answer.slice(0, 24000), isPartial ? '</assistant_latest>' : '</assistant_reply>'] : []),
316 ]),
317 ].join('\n')
318
319 const asked = sessionId
320 const reply = await $.model.complete({ model: cfg.model, prompt: request, maxTokens: 8000, effort: 'low', timeoutMs: 60_000 })
321 // A /clear while Haiku was answering means this reply belongs to the session before it.
322 if (sessionId !== asked) return false
323 if (!reply.isAnswered) {
324 $.ui.log(`side pass skipped (${reply.reason})`)
325 return false
326 }
327 const out = parseObject(reply.text)
328 if (!out) {
329 $.ui.log(`side pass: unparseable reply (${clip(reply.text, 120)})`, { to: 'debug' })
330 return false
331 }
332
333 const now = await $.clock.now()
334 const task = typeof out.task === 'string' ? clip(out.task, 70) : ''
335 const attempts = Array.isArray(out.attempts)
336 ? out.attempts
337 .filter((a): a is { text: string; isOk?: unknown } => typeof a?.text === 'string')
338 .slice(0, cap)
339 .map(a => ({ text: clip(a.text, 100), isOk: a.isOk !== false }))
340 : []
341 const at = (turnId && doneAt.get(turnId)) || now
342 await mutate($, c => {
343 let tasks = c.tasks
344 // A turn starts at most one new task, however many passes read it.
345 const isNew = out.isNewTask === true && !(turnId && doneAt.has(turnId))
346 if (task && (tasks.length === 0 || isNew)) {
347 tasks = [{ title: task, at: now }, ...tasks].slice(0, 6)
348 } else if (task && tasks[0]) {
349 tasks = [{ ...tasks[0], title: task }, ...tasks.slice(1)]
350 }
351
352 const done = Array.isArray(out.done)
353 ? doneOf(null, strings(out.done, cap, 90), at)
354 : doneOf((out.done as { title?: unknown } | null)?.title, strings((out.done as { items?: unknown } | null)?.items, cap, 90), at)
355 const kept = c.done.filter(d => d.at !== at)
356 const seen = new Set([...c.decided, ...c.tried.map(t => t.text)])
357
358 return {
359 ...c,
360 tasks,
361 decided: [...c.decided, ...strings(out.decisions, cap, 90).filter(d => !seen.has(d))].slice(-20),
362 tried: [...c.tried, ...attempts.filter(a => !seen.has(a.text))].slice(-20),
363 done: done ? [...kept, done].slice(-30) : c.done,
364 }
365 })
366 if (turnId) {
367 doneAt.set(turnId, at)
368 if (doneAt.size > 20) doneAt.delete(doneAt.keys().next().value ?? '')
369 }
370
371 const note = out.note as { title?: unknown; markdown?: unknown } | null
372 // A catch-up's answer is only the last message, and a partial one is mostly narration, so neither files the whole of it.
373 const body = typeof note?.markdown === 'string' ? note.markdown : transcript || isPartial ? '' : answer
374 const markdown = body.split('\n').filter(line => openQuestions(line).length === 0).join('\n')
375 // Claude's own saves are posts and documents, not this reply, so they don't stop it being filed; Haiku sees their titles.
376 if (note && typeof note.title === 'string' && markdown.trim()) {
377 await saveNote($, note.title, markdown)
378 }
379 return true
380}
381
382// Passes run one at a time, so the end-of-turn pass reads what a mid-turn one wrote.
383let passes: Promise<void> = Promise.resolve()
384let isPassing = false
385
386const queuePass = ($: $, run: () => Promise<void>) => {
387 passes = passes.then(async () => {
388 isPassing = true
389 try {
390 await run()
391 } catch (error) {
392 // A timer callback's rejection is otherwise swallowed without a trace.
393 $.ui.log(`side pass failed: ${error instanceof Error ? error.message : String(error)}`)
394 } finally {
395 isPassing = false
396 }
397 })
398 return passes
399}
400
401// Pending lives in session state, so a reload (which drops timers) can pick the pass back up.
402const runPending = ($: $) =>
403 queuePass($, async () => {
404 const raw = await read($, pending)
405 if (raw === null) return
406 await update($, pending, () => null)
407 if (await sidePass($, JSON.parse(raw) as Turn)) await save($, 'idle')
408 })
409
410let live = { turnId: '', said: [] as string[], toolsRead: 0, lastPass: 0 }
411const MID_PASS_MS = 90_000
412// Until the session has a task, the first pass comes sooner so the pane isn't blank through a long first turn.
413const FIRST_PASS_MS = 20_000
414
415const midPass = async ($: $, turnId: string, text: string) => {
416 const now = await $.clock.now()
417 if (live.turnId !== turnId) live = { turnId, said: [], toolsRead: turnTools.length, lastPass: now }
418 if (text) live.said.push(text)
419 if (isPassing) return
420 const hasTask = (await readCrumbs($)).tasks.length > 0
421 const isFresh = live.said.join('\n').length >= 300 || turnTools.length - live.toolsRead >= 3
422 if (!isFresh || now - live.lastPass < (hasTask ? MID_PASS_MS : FIRST_PASS_MS)) return
423 const turn: Turn = { answer: live.said.join('\n\n'), hasSavedNote, tools: [...turnTools], turnId, isPartial: true }
424 live = { turnId, said: [], toolsRead: turnTools.length, lastPass: now }
425 $.clock.after(0, () =>
426 queuePass($, async () => {
427 if (await sidePass($, turn)) await save($, 'working')
428 }),
429 )
430}
431
432const noteFile = (title: string, task: string, markdown: string) =>
433 `---\ntitle: ${title.replace(/\n/g, ' ')}\ntask: ${task}\nsession: ${sessionId}\n---\n\n# ${title}\n\n${markdown.trim()}\n`
434
435const FRONTMATTER = /^---\n[\s\S]*?\n---\n+/
436
437// A rewritten note moves to the top of the list but keeps its file and number.
438const touchNote = async ($: $, id: string) => {
439 const now = await $.clock.now()
440 const pinned = (await readCrumbs($)).notes.find(n => n.id === id && n.isPinned)
441 if (pinned) await copyPinned($, pinned)
442 await mutate($, c => {
443 const note = c.notes.find(n => n.id === id)
444 return note ? { ...c, notes: [...c.notes.filter(n => n.id !== id), { ...note, at: now }] } : c
445 })
446 await save($, 'working')
447}
448
449const saveNote = async ($: $, title: string, markdown: string): Promise<Note> => {
450 const state = await readCrumbs($)
451 const task = state.tasks[0]?.title ?? ''
452 // Saving under a title already used replaces that note rather than listing a second copy.
453 const same = state.notes.find(n => slug(n.title) === slug(title))
454 if (same) {
455 await $.fs.write(same.file, noteFile(title, task, markdown))
456 await touchNote($, same.id)
457 return same
458 }
459 const target = await ensureDir($, task || title)
460 const now = await $.clock.now()
461 const number = String(state.notes.length + 1).padStart(2, '0')
462 const file = `${target}/${number}-${slug(title)}.md`
463 await $.fs.write(file, noteFile(title, task, markdown))
464 const note: Note = { id: `${now}-${number}`, title: clip(title, 80), file, at: now, isPinned: false }
465 await mutate($, c => ({ ...c, notes: [...c.notes, note] }))
466 await save($, 'working')
467
468 return note
469}
470
471type NoteEdit = { old: string; new: string }
472
473const editNote = async ($: $, ref: string, edits: NoteEdit[], markdown: string): Promise<{ note: Note } | { error: string }> => {
474 const { notes } = await readCrumbs($)
475 const note = notes.find(n => n.id === ref) ?? [...notes].reverse().find(n => slug(n.title) === slug(ref))
476 if (!note) return { error: `No note "${ref}". Notes: ${notes.map(n => `${n.id} (${n.title})`).join(', ') || 'none'}.` }
477 let text: string
478 try {
479 text = await $.fs.read(note.file)
480 } catch {
481 return { error: `The file for "${note.title}" is gone; save it again with save_note.` }
482 }
483 const header = FRONTMATTER.exec(text)?.[0] ?? ''
484 let body = markdown.trim() ? `# ${note.title}\n\n${markdown.trim()}\n` : text.slice(header.length)
485 for (const edit of edits) {
486 const count = body.split(edit.old).length - 1
487 if (count !== 1) {
488 return { error: `"${clip(edit.old, 60)}" appears ${count} times in "${note.title}"; ${count === 0 ? 'copy it exactly from the note' : 'include more of the text around it'}. Nothing was changed.` }
489 }
490 body = body.replace(edit.old, () => edit.new)
491 }
492 await $.fs.write(note.file, `${header}${body}`)
493 await touchNote($, note.id)
494
495 return { note }
496}
497
498const copyPinned = async ($: $, note: Note): Promise<boolean> => {
499 const place = await read($, where)
500 if (!place) return false
501 await $.fs.write(`${await notesRoot($)}/${place.repo}/_pinned/${basename(note.file)}`, await $.fs.read(note.file))
502 return true
503}
504
505const pin = async ($: $, note: Note) => {
506 if (!(await copyPinned($, note))) return
507 await mutate($, c => ({ ...c, notes: c.notes.map(n => (n.id === note.id ? { ...n, isPinned: true } : n)) }))
508 await save($, 'working')
509 $.ui.toast(`Pinned "${note.title}"`)
510}
511
512const track = async ($: $, e: Record<string, unknown>) => {
513 const file = typeof e.file_path === 'string' ? e.file_path : typeof e.notebook_path === 'string' ? e.notebook_path : ''
514 if ((e.tool === 'Edit' || e.tool === 'Write' || e.tool === 'NotebookEdit') && file) {
515 await mutate($, c => ({ ...c, edited: [...c.edited.filter(f => f !== file), file].slice(-50) }))
516 }
517 if (e.tool === 'Bash' && typeof e.command === 'string') {
518 const dir = cdTarget(e.command, (await $.env.get('HOME')) ?? '')
519 if (dir) await mutate($, c => ({ ...c, touched: [...c.touched.filter(d => d !== dir), dir].slice(-20) }))
520 }
521}
522
523const isTyped = (m: SessionMessage) =>
524 m.role === 'user' && m.text.trim() !== '' && !m.toolResults?.length && !m.text.trimStart().startsWith('<')
525
526// The newest session folder in this worktree that holds the same conversation, by its transcript.
527const findResumed = async ($: $, wtDir: string, path: string): Promise<string | null> => {
528 let best: { dir: string; at: number } | null = null
529 for (const entry of await dirs($, wtDir)) {
530 const saved = await readSaved($, `${wtDir}/${entry.name}`)
531 if (saved?.transcript === path && (!best || saved.updatedAt > best.at)) best = { dir: `${wtDir}/${entry.name}`, at: saved.updatedAt }
532 }
533
534 return best?.dir ?? null
535}
536
537const restoreFrom = async ($: $, from: string) => {
538 const current = await readCrumbs($)
539 const saved = await readSaved($, from)
540 if (saved && current.tasks.length === 0 && current.notes.length === 0) {
541 const { session: _s, worktree: _w, updatedAt: _u, transcript: _t, ...restored } = saved
542 await mutate($, () => ({ ...normalize(restored), activity: null, asking: null, isWorking: false }))
543 }
544 // Restored on its own: on a reload the breadcrumbs state can survive while the test list doesn't.
545 const savedTests = await readTests($, from)
546 if (savedTests && (await read($, testRun)).tests.length === 0) {
547 // A tester or a waiting step doesn't outlive its session.
548 await update($, testRun, () => ({
549 brief: savedTests.brief ?? '',
550 tests: savedTests.tests.map(t => ({ ...t, status: t.status === 'running' ? 'todo' : t.status, agentId: null, asking: null })),
551 waits: [],
552 unreported: savedTests.unreported,
553 }))
554 }
555}
556
557// A resumed conversation starts under a new session id, so its folder is found by its transcript.
558const adoptResumed = async ($: $, path: string) => {
559 transcript = path
560 const place = (await read($, where)) ?? (await locate($))
561 const found = dir ? null : await findResumed($, worktreeDir(await notesRoot($), place), path)
562 if (!found) return
563 dir = found
564 await $.store.set(`dir:${sessionId}`, found)
565 await restoreFrom($, found)
566}
567
568const begin = async ($: $) => {
569 sessionId = await $.session.id()
570 transcript = null
571 turnTools = []
572 hasSavedNote = false
573 live = { turnId: '', said: [], toolsRead: 0, lastPass: 0 }
574 const place = await locate($)
575 await update($, where, () => place)
576
577 const known = await $.store.get(`dir:${sessionId}`)
578 dir = typeof known === 'string' ? known : null
579 if (dir) await restoreFrom($, dir)
580 // A reload restarts the module but not the session's state, so answers still waiting come back from it.
581 outbox = (await readCrumbs($)).outbox
582}
583
584// A session that was running before the mod was installed has history but no breadcrumbs yet.
585const backfill = async ($: $) => {
586 const current = await readCrumbs($)
587 if (current.tasks.length > 0 || current.prompts.length > 0) return
588 let rows: readonly SessionMessage[]
589 try {
590 rows = await $.session.messages()
591 } catch {
592 return
593 }
594 if (!rows.some(isTyped)) return
595
596 const now = await $.clock.now()
597 const home = (await $.env.get('HOME')) ?? ''
598 const edited: string[] = []
599 const touched: string[] = []
600 const lines: string[] = []
601 for (const m of rows) {
602 if (isTyped(m)) lines.push(`User: ${clip(m.text, 1500)}`)
603 if (m.role !== 'assistant') continue
604 if (m.text.trim()) lines.push(`Claude: ${clip(m.text, 2500)}`)
605 for (const use of m.toolUses) {
606 lines.push(` [${toolLabel(use.tool, use.input)}]`)
607 if (use.isError) continue
608 const file = use.input.file_path ?? use.input.notebook_path
609 if ((use.tool === 'Edit' || use.tool === 'Write' || use.tool === 'NotebookEdit') && typeof file === 'string') edited.push(file)
610 const dir = use.tool === 'Bash' && typeof use.input.command === 'string' ? cdTarget(use.input.command, home) : null
611 if (dir) touched.push(dir)
612 }
613 }
614 const lastSaid = [...rows].reverse().find(m => m.role === 'assistant' && m.text.trim())
615 await mutate($, c => ({
616 ...c,
617 prompts: rows.filter(isTyped).slice(-5).map(m => ({ text: m.text.trim(), at: now })),
618 lastSaid: lastSaid ? { text: head(lastSaid.text.trim(), 600), at: now } : c.lastSaid,
619 edited: [...new Set(edited)].slice(-50),
620 touched: [...new Set(touched)].slice(-20),
621 }))
622 await refreshRepos($)
623 await sidePass($, { answer: lastSaid?.text ?? '', hasSavedNote: true, tools: [], transcript: lines.join('\n').slice(-30_000) })
624 await save($, 'idle')
625}
626
627const dropAsk = ($: $, question: string) =>
628 mutate($, c => ({ ...c, needsYou: c.needsYou.filter(a => a.question !== question) }))
629
630const setView = ($: $, fn: (v: View) => View) => update($, view, old => fn({ ...VIEW, ...old }))
631
632// The source of truth for answers Claude hasn't read: a hook's state read can miss a write made while it runs.
633let outbox: Answer[] = []
634
635// Questions Claude can go on without wait in the pane; their answers queue rather than start a turn.
636const addAsks = ($: $, found: Ask[]) =>
637 mutate($, c => {
638 const fresh = found.filter(a => !c.asked.includes(a.question))
639 if (fresh.length === 0) return c
640 return { ...c, needsYou: [...c.needsYou, ...fresh].slice(-MAX_ASKS), asked: [...c.asked, ...fresh.map(a => a.question)].slice(-50) }
641 })
642
643const answerAsk = async ($: $, ask: Ask, answer: string) => {
644 const text = answer.trim()
645 if (!text) return
646 outbox = [...outbox.filter(a => a.question !== ask.question), { question: ask.question, answer: text, at: await $.clock.now() }]
647 await mutate($, c => ({ ...c, outbox, needsYou: c.needsYou.filter(a => a.question !== ask.question) }))
648 await setView($, v => ({ ...v, typed: Object.fromEntries(Object.entries(v.typed).filter(([q]) => q !== ask.question)) }))
649}
650
651const typeAsk = ($: $, ask: Ask, text: string) =>
652 setView($, v => ({ ...v, typed: { ...v.typed, [ask.question]: text } }))
653
654const takeOutbox = async ($: $): Promise<string | null> => {
655 const taken = outbox
656 if (taken.length === 0) return null
657 outbox = []
658 await mutate($, c => ({ ...c, outbox }))
659 const [only] = taken
660
661 return taken.length === 1 && only
662 ? `The user answered your open question "${only.question}" in the breadcrumbs pane: ${only.answer}`
663 : ['The user answered your open questions in the breadcrumbs pane:', ...taken.map(a => `- "${a.question}" — ${a.answer}`)].join('\n')
664}
665
666// Answers ride on the next tool result Claude reads, so they reach it mid-turn without a turn of their own.
667const withAnswers = async <R extends { deny?: string; context?: readonly string[] }>($: $, ran: R): Promise<R> => {
668 if (ran.deny !== undefined || outbox.length === 0) return ran
669 const text = await takeOutbox($)
670
671 return text ? ({ ...ran, context: [...(ran.context ?? []), text] } as R) : ran
672}
673
674// A surface without an input box answers in the prompt instead, as a turn of its own.
675const draftAsk = async ($: $, ask: Ask) => {
676 await $.prompt.fill({ text: `Re: "${ask.question}" — `, mode: 'insert' })
677 $.ui.toast('Finish your answer in the prompt box')
678}
679
680// While Claude works the answers reach it after its next tool call; idle, this starts the turn.
681const sendNow = async ($: $) => {
682 const text = await takeOutbox($)
683 if (text) await $.prompt.submit({ text, asUser: true })
684}
685
686// A run saved before the brief existed has none.
687const readRun = async ($: $): Promise<TestRun> => {
688 const r = await read($, testRun)
689 return { ...r, brief: r.brief ?? '' }
690}
691
692// Kept in its own file and written only when a test changes, so a turn's save never rewrites it from an empty live list.
693const mutateTests = async ($: $, fn: (r: TestRun) => TestRun) => {
694 const now = await $.clock.now()
695 await update($, testRun, r => settleNeeds(fn(r), now))
696 const state = await readCrumbs($)
697 const target = await ensureDir($, state.tasks[0]?.title ?? 'tests')
698 await $.fs.write(`${target}/tests.json`, JSON.stringify(await read($, testRun), null, 2))
699}
700
701const readTests = async ($: $, dir: string): Promise<TestRun | null> => {
702 try {
703 return JSON.parse(await $.fs.read(`${dir}/tests.json`)) as TestRun
704 } catch {
705 return null
706 }
707}
708
709const setTestsView = ($: $, fn: (v: TestsView) => TestsView) => update($, testsView, fn)
710
711const patchTest = ($: $, id: string, fn: (t: ManualTest) => ManualTest) =>
712 mutateTests($, r => ({ ...r, tests: r.tests.map(t => (t.id === id ? fn(t) : t)) }))
713
714const logTest = async ($: $, id: string, from: Entry['from'], text: string) => {
715 const at = await $.clock.now()
716 await patchTest($, id, t => ({ ...t, log: [...t.log, { from, text: clip(text, 400), at }].slice(-30) }))
717}
718
719const showWaiting = async ($: $) => {
720 const open = (await readRun($)).waits.filter(w => w.answer === null).length
721 $.ui.status(open > 0 ? `⏳ ${open} test step${open > 1 ? 's' : ''} waiting on you` : undefined)
722}
723
724const STATUS_COLOR: Record<TestStatus, 'claude' | 'success' | 'error' | 'warning' | undefined> = {
725 todo: undefined,
726 running: 'claude',
727 passed: 'success',
728 failed: 'error',
729 blocked: 'warning',
730 retest: 'warning',
731}
732
733const copyText = async ($: $, text: string, surface: Parameters<$['ui']['copy']>[0]['surface']) => {
734 const copied = await $.ui.copy({ text, surface })
735 $.ui.toast(copied.isCopied ? `Copied ${clip(text, 40)}` : 'Could not copy here; select the text instead')
736}
737
738// A hook's own state reads don't see writes made while it runs, so a waiting step polls this instead.
739const answered = new Map<string, string>()
740
741const answerWait = async ($: $, waitId: string, answer: string) => {
742 answered.set(waitId, answer)
743 await mutateTests($, r => ({ ...r, waits: r.waits.map(w => (w.id === waitId ? { ...w, answer } : w)) }))
744 await showWaiting($)
745}
746
747// Where a message about a test goes: the step it is waiting on, its live tester, or the main agent.
748const routeTest = async ($: $, t: ManualTest, message: string, forMain: string) => {
749 const r = await readRun($)
750 const wait = openWait(r, t.id)
751 if (wait) return answerWait($, wait.id, message)
752 if (isLive(t) && t.agentId) {
753 await $.session.send({ to: { agentId: t.agentId }, text: message })
754 return
755 }
756 await $.prompt.submit({ text: forMain, asUser: true })
757}
758
759const replyTest = async ($: $, t: ManualTest, typed: string) => {
760 const message = typed.trim()
761 if (!message) return
762 await logTest($, t.id, 'you', message)
763 await setTestsView($, v => ({ ...v, typed: { ...v.typed, [t.id]: '' } }))
764 await routeTest($, t, message, `[manual test ${t.id} · ${t.title}] ${message}`)
765}
766
767// Testers the person stopped: every later tool call is refused but a cleanup kill and the hand-back that reports and ends the run.
768const stopped = new Map<string, string>()
769
770const isWrapUp = (e: Record<string, unknown>) =>
771 e.tool === 'SubagentHandback' || e.tool === 'TaskStop' || e.tool === 'KillShell' || (e.tool === 'Bash' && /^\s*p?kill\b/.test(str(e.command)))
772
773const stopDeny = (e: Record<string, unknown> & { agentId?: string }) =>
774 e.agentId !== undefined && stopped.has(e.agentId) && !isWrapUp(e) ? { deny: stopped.get(e.agentId) ?? '' } : null
775
776const stopTester = async ($: $, t: ManualTest, verdict: 'passed' | 'failed' | null, why: string) => {
777 if (!t.agentId) return
778 const said = verdict ? `The person marked this test ${verdict}${why ? `: ${why}` : ''}.` : 'The person stopped this test.'
779 const note = `${said} Run no more steps and do not change its status: kill the background processes you started, then end your turn now with one line on what you saw before the stop.`
780 await patchTest($, t.id, old => ({ ...old, status: verdict ?? 'todo', asking: null, ...(t.asking ? { agentId: null } : {}) }))
781 await logTest($, t.id, 'you', verdict ? `${ICON[verdict]} ${verdict}${why ? `: ${why}` : ''}` : '■ stopped the tester')
782 // A tester paused on the planner has ended its turn; a message would only wake it.
783 if (t.asking) return
784 stopped.set(t.agentId, note)
785 const wait = openWait(await readRun($), t.id)
786 if (wait) await answerWait($, wait.id, note)
787 else await $.session.send({ to: { agentId: t.agentId }, text: note })
788}
789
790const markTest = async ($: $, t: ManualTest, status: 'passed' | 'failed', typed: string) => {
791 const why = typed.trim()
792 await setTestsView($, v => ({ ...v, typed: { ...v.typed, [t.id]: '' } }))
793 if (isLive(t)) return stopTester($, t, status, why)
794 await patchTest($, t.id, old => ({ ...old, status }))
795 await logTest($, t.id, 'you', `${status === 'passed' ? '✓ passed' : '✗ failed'}${why ? `: ${why}` : ''}`)
796 const line = `${ICON[status]} test ${t.id} ${t.title}${why ? `: ${why}` : ''}`
797 const r = await readRun($)
798 if (openWait(r, t.id)) {
799 await routeTest($, t, `The person marked this test ${status}${why ? `: ${why}` : ''}. Wrap up.`, line)
800 return
801 }
802 // A pass with nothing to logTest waits for the next prompt instead of costing a turn.
803 if (status === 'passed' && !why) {
804 await mutateTests($, old => ({ ...old, unreported: [...old.unreported, line] }))
805 return
806 }
807 await $.prompt.submit({ text: `[manual test ${t.id} ${ICON[status]}] ${t.title}${why ? `: ${why}` : ''}`, asUser: true })
808}
809
810const startTester = async ($: $, t: ManualTest) => {
811 const { brief } = await readRun($)
812 const prompt = [
813 `Test ${t.id}: ${t.title}`,
814 brief ? `Brief from the planner:\n${brief}` : '',
815 t.steps.length > 0 ? `Steps:\n${t.steps.map((s, i) => `${i + 1}. ${s}`).join('\n')}` : '',
816 t.expect ? `Expected: ${t.expect}` : '',
817 t.trigger ? `Trigger: ${t.trigger}` : '',
818 (t.assumes ?? []).length > 0 ? `Assumes:\n${(t.assumes ?? []).map(a => `- ${a}`).join('\n')}` : '',
819 t.watch ? `Follow along with: ${t.watch}` : '',
820 // Framed as past runs: a restarted tester once read an earlier "■ stopped" line as its own stop and quit at once.
821 t.log.length > 0
822 ? `Earlier runs of this test (history only; this is a fresh run, so start the steps):\n${t.log.map(l => `- ${l.from}: ${l.text}`).join('\n')}`
823 : '',
824 ]
825 .filter(Boolean)
826 .join('\n\n')
827 const description = clip(`Test ${t.id}: ${t.title}`, 40)
828 await patchTest($, t.id, old => ({ ...old, status: 'running', agentId: null }))
829 await setTestsView($, v => ({ ...v, expanded: t.id }))
830 // An agent this plugin spawned would skip all of its hooks, leaving the tester's tools unanswered; the launcher mod's spawn doesn't.
831 if (await hasLauncher($)) {
832 const request = `${await launchDir($)}/${await $.clock.now()}-${slug(t.id, 12)}.json`
833 await $.fs.write(request, JSON.stringify({ subagentType: TESTER, description, prompt }))
834 $.clock.after(LAUNCH_GRACE_MS, async () => {
835 if (!(await $.fs.exists(request))) return
836 await $.process.run(['rm', '-f', request])
837 await askMainToStart($, t, description, prompt)
838 })
839 return
840 }
841 await askMainToStart($, t, description, prompt)
842}
843
844const askMainToStart = ($: $, t: ManualTest, description: string, prompt: string) =>
845 $.prompt.submit({
846 text: [
847 `Start the tester for manual test ${t.id}: call the Agent tool with subagent_type "${TESTER}", run_in_background true, description "${description}" and exactly this prompt. Then end your turn without walking the user through the test yourself.`,
848 '',
849 prompt,
850 ].join('\n'),
851 })
852
853const launchDir = async ($: $) => `${await notesRoot($)}/${LAUNCH_DIR}/${sessionId}`
854
855// The launcher stamps `ready` while it runs, so a stale stamp means it was removed or stopped.
856const hasLauncher = async ($: $) => {
857 try {
858 return (await $.clock.now()) - Number(await $.fs.read(`${await launchDir($)}/ready`)) < LAUNCHER_ALIVE_MS
859 } catch {
860 return false
861 }
862}
863
864// Links a tester the launcher or the main agent spawned to its test, by the "Test <id>:" line its prompt opens with.
865const bindTester = async ($: $, prompt: string, agentId: string) => {
866 const id = /^Test (\S+):/.exec(prompt.trim())?.[1]
867 if (!id) return
868 await patchTest($, id, old => ({ ...old, status: 'running', agentId }))
869}
870
871const planTests = async ($: $, e: Record<string, unknown>) => {
872 const raw = Array.isArray(e.tests) ? (e.tests as Record<string, unknown>[]) : []
873 // Tests arrive a few at a time as pieces get ready, so a call adds to the list unless it asks to start over.
874 const isAppending = e.mode !== 'replace'
875 const r = await readRun($)
876 const kept = isAppending ? r.tests : []
877 const given = raw.filter(t => str(t?.title))
878 // A later batch often numbers its tests from 1 again; those get the next free ids, and its needs follow them.
879 const taken = new Set(kept.map(t => t.id))
880 const renamed = new Map<string, string>()
881 let next = kept.reduce((n, t) => Math.max(n, Number(t.id) || 0), kept.length)
882 const assigned = given.map(t => {
883 const id = str(t.id)
884 if (id && !taken.has(id)) {
885 taken.add(id)
886 renamed.set(id, id)
887 return id
888 }
889 while (taken.has(String(++next)));
890 taken.add(String(next))
891 if (id && !renamed.has(id)) renamed.set(id, String(next))
892 return String(next)
893 })
894 const incoming: ManualTest[] = given
895 .map((t, i) => ({
896 id: assigned[i] ?? String(i + 1),
897 title: clip(str(t.title), 60),
898 steps: listOf(t.steps),
899 expect: str(t.expect),
900 watch: str(t.watch),
901 trigger: str(t.trigger),
902 assumes: listOf(t.assumes),
903 needs: listOf(t.needs).map(id => renamed.get(id) ?? id),
904 ...(str(t.model) ? { model: str(t.model) } : {}),
905 status: 'todo',
906 agentId: null,
907 log: [],
908 }))
909 if (incoming.length === 0) return { deny: 'test_plan needs at least one test with a title.' }
910 const untriggered = incoming.filter(t => t.expect && !t.trigger)
911 if (untriggered.length > 0) {
912 return {
913 deny: `Give tests ${untriggered.map(t => t.id).join(', ')} a trigger: the code that produces the expected signal and what decides whether it fires, checked against the code. Write "none: <why>" when no code path is involved.`,
914 }
915 }
916 const ids = new Set(incoming.map(t => t.id))
917 const brief = str(e.brief)
918 await mutateTests($, old => ({
919 ...old,
920 brief: brief || (isAppending ? old.brief ?? '' : ''),
921 tests: [...kept.filter(t => !ids.has(t.id)), ...incoming],
922 waits: isAppending ? old.waits : [],
923 unreported: isAppending ? old.unreported : [],
924 }))
925 void $.ui.open({ id: TESTS_PANE, title: 'tests' })
926 $.ui.toast(`${incoming.length} manual test${incoming.length > 1 ? 's' : ''} ready in /tests`)
927
928 return {
929 result: [
930 `Added ${incoming.length} test(s) to the tests pane (/tests): ${incoming.map(t => `${t.id} ${t.title}`).join('; ')}.`,
931 'Use these ids with test_update. The user runs them when they get to them, each with a tester subagent whose final report reaches you; carry on with your work meanwhile.',
932 ].join(' '),
933 }
934}
935
936const updateTest = async ($: $, e: Record<string, unknown> & { agentId?: string }) => {
937 const brief = str(e.brief)
938 if (brief) await mutateTests($, r => ({ ...r, brief }))
939 const t = testOf(await readRun($), e)
940 if (!t) return brief && e.id === undefined ? { result: 'Updated the brief.' } : { deny: 'No such test: pass the id from test_plan.' }
941 const status = STATUSES.find(s => s === e.status)
942 const note = str(e.note)
943 const steps = listOf(e.steps)
944 const expect = str(e.expect)
945 const reply = str(e.reply)
946 const trigger = str(e.trigger)
947 const assumes = listOf(e.assumes)
948 await patchTest($, t.id, old => ({
949 ...old,
950 status: status ?? old.status,
951 steps: steps.length > 0 ? steps : old.steps,
952 expect: expect || old.expect,
953 trigger: trigger || old.trigger,
954 assumes: assumes.length > 0 ? assumes : old.assumes,
955 needs: Array.isArray(e.needs) ? listOf(e.needs) : old.needs,
956 model: str(e.model) || old.model,
957 }))
958 if (note || status) await logTest($, t.id, e.agentId === undefined ? 'claude' : 'tester', `${status && status !== t.status ? `${ICON[status]} ` : ''}${note || status}`)
959 if (!reply) return { result: `Updated test ${t.id}.` }
960 await logTest($, t.id, 'claude', `↩ ${reply}`)
961 if (!t.asking || !t.agentId) return { result: `Test ${t.id}'s tester is not waiting on a question; the reply is only in the pane log.` }
962 await patchTest($, t.id, old => ({ ...old, asking: null }))
963 const text = [
964 `The planner answered: ${reply}`,
965 steps.length > 0 ? `Steps are now:\n${steps.map((s, i) => `${i + 1}. ${s}`).join('\n')}` : '',
966 expect ? `Expected now: ${expect}` : '',
967 ]
968 .filter(Boolean)
969 .join('\n\n')
970
971 // A tester the plugin resumes from inside this hook gets no answer from this hook again, so the main agent sends it.
972 return { result: `Now resume test ${t.id}'s tester: call SendMessage with to "${t.agentId}" and exactly this message:\n\n${text}` }
973}
974
975const awaitUser = async ($: $, e: Record<string, unknown> & { agentId?: string }, signal: AbortSignal) => {
976 const instruction = str(e.instruction)
977 // Not clipped: the pane wraps steps, and a cut command can't be pasted.
978 const steps = listOf(e.steps)
979 if (!instruction && steps.length === 0) return { deny: 'await_user needs an instruction or steps.' }
980 const t = testOf(await readRun($), e)
981 const now = await $.clock.now()
982 const wait: Wait = {
983 id: `${now}-${Math.random().toString(36).slice(2, 7)}`,
984 testId: t?.id ?? null,
985 step: typeof e.step === 'number' ? e.step : null,
986 instruction,
987 steps,
988 options: listOf(e.options).slice(0, 4).map(o => clip(o, 30)),
989 at: now,
990 answer: null,
991 }
992 await mutateTests($, r => ({ ...r, waits: [...r.waits.filter(w => w.answer === null || w.testId !== wait.testId), wait] }))
993 if (t) await setTestsView($, v => ({ ...v, expanded: t.id }))
994 await showWaiting($)
995 $.ui.toast(t ? `Test ${t.id} is waiting on you` : 'A test step is waiting on you')
996
997 // Waiting on a button inside the hook counts against its budget; time inside a $ call does not.
998 let answer: string | null = null
999 while (answer === null && !signal.aborted && (await $.clock.now()) - now < WAIT_LIMIT_MS) {
1000 await $.process.run(['sleep', '1'])
1001 answer = answered.get(wait.id) ?? null
1002 }
1003 answered.delete(wait.id)
1004 await mutateTests($, r => ({ ...r, waits: r.waits.filter(w => w.id !== wait.id) }))
1005 await showWaiting($)
1006 if (answer === null) {
1007 return { result: signal.aborted ? 'Interrupted before the person answered.' : 'No answer after 30 minutes. Ask again, or end the test as blocked.' }
1008 }
1009
1010 return { result: `The person answered: ${answer}` }
1011}
1012
1013// The question reaches the main agent as the tester's hand-back; a reply resumes the same tester.
1014const askPlanner = async ($: $, e: Record<string, unknown> & { agentId?: string }) => {
1015 const question = str(e.question)
1016 if (!question) return { deny: 'ask_planner needs a question.' }
1017 const t = testOf(await readRun($), e)
1018 if (!t) return { deny: 'No such test: pass the id from the brief.' }
1019 await patchTest($, t.id, old => ({ ...old, asking: clip(question, 200) }))
1020 await logTest($, t.id, 'tester', `? ${question}`)
1021
1022 return {
1023 result: [
1024 `Your question is with the planner. End your turn now, with this as your whole final message: "[tester asks · manual test ${t.id} · ${t.title}] ${question}".`,
1025 'Leave your background captures running: the planner fixes what it can and its reply resumes you in this same run.',
1026 ].join(' '),
1027 }
1028}
1029
1030const testerDone = async ($: $, agentId: string, answer: string, isAborted: boolean) => {
1031 stopped.delete(agentId)
1032 const t = (await readRun($)).tests.find(x => x.agentId === agentId)
1033 if (!t) return
1034 // Stopped to ask the planner: still this test's tester, resumed by the reply.
1035 if (t.asking && !isAborted) return
1036 const status: TestStatus = t.status === 'running' ? 'todo' : t.status
1037 await patchTest($, t.id, old => ({ ...old, status, agentId: null, asking: null }))
1038 await mutateTests($, r => ({ ...r, waits: r.waits.filter(w => w.testId !== t.id || w.answer !== null) }))
1039 await showWaiting($)
1040 // Claude Code hands the tester's final report to the main agent itself; the pane just records it.
1041 await logTest($, t.id, 'tester', answer || (isAborted ? 'stopped before it reported' : 'ended without a summary'))
1042}
1043
1044const TEST_TOOLS = [TOOL('test_plan'), TOOL('test_update'), TOOL('await_user'), TOOL('ask_planner')]
1045
1046const testTool = async ($: $, e: Record<string, unknown> & { tool: unknown; agentId?: string }, signal: AbortSignal) => {
1047 if (e.tool === TOOL('test_plan')) return planTests($, e)
1048 if (e.tool === TOOL('test_update')) return updateTest($, e)
1049 if (e.tool === TOOL('ask_planner')) return askPlanner($, e)
1050
1051 return awaitUser($, e, signal)
1052}
1053
1054const OWN_TOOLS = [SAVE_NOTE, EDIT_NOTE, ...TEST_TOOLS]
1055
1056const briefInput = (tool: string, input: unknown): Record<string, string> | null => {
1057 const i = (input ?? {}) as Record<string, unknown>
1058 if (tool === SAVE_NOTE) return { title: str(i.title) }
1059 if (tool === EDIT_NOTE) {
1060 const n = Array.isArray(i.edits) ? i.edits.length : 0
1061 return { note: str(i.id), ...(str(i.markdown) ? { markdown: 'rewritten' } : { edits: `${n} edit${n === 1 ? '' : 's'}` }) }
1062 }
1063 if (tool === TOOL('test_plan')) {
1064 const n = Array.isArray(i.tests) ? i.tests.length : 0
1065 return { tests: `${n} test${n === 1 ? '' : 's'}`, ...(i.mode === 'replace' ? { mode: 'replace' } : {}) }
1066 }
1067 if (tool === TOOL('test_update')) {
1068 const text = str(i.reply) || str(i.note)
1069 const changed = ['steps', 'expect', 'brief'].filter(k => i[k] !== undefined)
1070 return {
1071 ...(str(i.id) ? { id: str(i.id) } : {}),
1072 ...(str(i.status) ? { status: str(i.status) } : {}),
1073 ...(text ? { [str(i.reply) ? 'reply' : 'note']: clip(text, 60) } : {}),
1074 ...(changed.length > 0 ? { changed: changed.join(', ') } : {}),
1075 }
1076 }
1077 if (tool === TOOL('ask_planner')) return { question: clip(str(i.question), 60) }
1078 return null
1079}
1080
1081// Results end with a note to the model that the person needn't read.
1082const firstSentence = (output: unknown): unknown => {
1083 const cut = (s: string) => s.match(/^[\s\S]*?\.(?=\s|$)/)?.[0] ?? s
1084 if (typeof output === 'string') return cut(output)
1085 if (Array.isArray(output))
1086 return output.map(b => (b && typeof b === 'object' && typeof b.text === 'string' ? { ...b, text: cut(b.text) } : b))
1087 return output
1088}
1089
1090// Passes with nothing to say ride along with the next prompt instead of costing a turn each.
1091const takePasses = async ($: $): Promise<string | null> => {
1092 const { unreported } = await readRun($)
1093 if (unreported.length === 0) return null
1094 await mutateTests($, r => ({ ...r, unreported: [] }))
1095
1096 return `Manual tests the user passed since your last turn:\n${unreported.join('\n')}`
1097}
1098
1099export const register: Register = (on, options) => {
1100 cfg.model = String(options.model ?? 'haiku')
1101 cfg.testerModel = String(options.testerModel ?? 'sonnet')
1102 cfg.retentionDays = Number(options.retentionDays ?? 30)
1103 cfg.archiveDays = Number(options.archiveDays ?? 60)
1104 cfg.isArchiving = options.archive !== false
1105
1106 on('session.start', async ($, e, next) => {
1107 const started = await next(e)
1108 await begin($)
1109
1110 await $.command.register({
1111 name: 'whereami',
1112 description: 'Show or hide the breadcrumbs pane; `/whereami clean` tidies old session notes',
1113 })
1114 await $.tool.register({
1115 name: 'save_note',
1116 description:
1117 'Post a markdown note to the user\'s breadcrumbs pane: something they should see now while you keep working, or a document they will come back to (a plan, a handoff, a decision record). Explanations in your reply are filed as notes without it. The pane reflows notes to its width, tables included; only code and diagram lines are cut, so keep those short.',
1118 inputSchema: {
1119 type: 'object',
1120 properties: {
1121 title: { type: 'string', description: 'A short title, under 60 characters' },
1122 markdown: { type: 'string', description: 'The note in markdown' },
1123 },
1124 required: ['title', 'markdown'],
1125 },
1126 })
1127 await $.tool.register({
1128 name: 'edit_note',
1129 description:
1130 'Change a note saved with save_note in place, sending only the text that changes. Each edit replaces one exact, unique piece of the note; markdown instead replaces the whole body.',
1131 inputSchema: {
1132 type: 'object',
1133 properties: {
1134 id: { type: 'string', description: 'The id save_note returned, or the note\'s title' },
1135 edits: {
1136 type: 'array',
1137 items: {
1138 type: 'object',
1139 properties: {
1140 old: { type: 'string', description: 'Text in the note, exactly as written and found once' },
1141 new: { type: 'string', description: 'What replaces it' },
1142 },
1143 required: ['old', 'new'],
1144 },
1145 },
1146 markdown: { type: 'string', description: 'A whole new body, for a rewrite' },
1147 },
1148 required: ['id'],
1149 },
1150 })
1151 await $.command.register({ name: 'tests', description: 'Show or hide the manual tests pane' })
1152 try {
1153 await $.agent.register({
1154 name: 'tester',
1155 description: 'Guides the person through one manual end-to-end test. Spawn it only when the tests pane asks you to, with the prompt it gives.',
1156 prompt: TESTER_PROMPT,
1157 })
1158 } catch (error) {
1159 // Without the tester the rest of the pane still works; Start reports the missing agent.
1160 $.ui.log(`breadcrumbs: tester agent not registered (${error instanceof Error ? error.message : String(error)})`)
1161 }
1162 await $.tool.register({
1163 name: 'test_plan',
1164 description: 'Add manual or end-to-end tests the user has to run by hand to their tests pane, each with its steps, as soon as the change they cover is ready to try. The user starts each test from the pane whenever they get to it.',
1165 inputSchema: {
1166 type: 'object',
1167 properties: {
1168 brief: {
1169 type: 'string',
1170 description: 'Read by every tester before its test: the change, the environment, how to observe results, what is already verified',
1171 },
1172 tests: {
1173 type: 'array',
1174 items: {
1175 type: 'object',
1176 properties: {
1177 id: { type: 'string', description: 'Short id, e.g. "1"; defaults to its position' },
1178 title: { type: 'string', description: 'Under 40 characters' },
1179 steps: { type: 'array', items: { type: 'string' }, description: 'What the person does, each short; a command or text to paste goes whole in backticks' },
1180 expect: { type: 'string', description: 'What should happen' },
1181 watch: { type: 'string', description: 'Logs or watchers to follow along with' },
1182 trigger: {
1183 type: 'string',
1184 description: 'The code that produces the expected signal and what decides whether it fires, e.g. "sent by completeRide() in rides.ts, driver app only"; required with expect',
1185 },
1186 assumes: { type: 'array', items: { type: 'string' }, description: 'What the plan relies on that the code cannot show' },
1187 needs: { type: 'array', items: { type: 'string' }, description: 'Ids of tests that must pass first' },
1188 model: { type: 'string', description: 'The tester\'s model for this test, e.g. opus; leave out for the default' },
1189 },
1190 required: ['title'],
1191 },
1192 },
1193 mode: { type: 'string', enum: ['append', 'replace'], description: 'append (default) adds to the tests already listed; replace starts a new list' },
1194 },
1195 required: ['tests'],
1196 },
1197 })
1198 await $.tool.register({
1199 name: 'test_update',
1200 description:hooks/markdown.ts 56 lines1import type { Crumbs, Where } from '../types'
2import type { Repo } from '../types'
3import { asks, basename, dones, stamp } from './text'
4
5export type Saved = Crumbs & { session: string; worktree: string; updatedAt: number; transcript?: string }
6
7export const repoState = (r: Repo): string => {
8 const parts: string[] = []
9 if (r.changed > 0) parts.push(`${r.changed} uncommitted`)
10 if (!r.hasUpstream) parts.push('no upstream')
11 else if (r.ahead > 0) parts.push(`↑${r.ahead} unpushed`)
12 if (r.behind > 0) parts.push(`↓${r.behind} behind`)
13
14 return parts.length > 0 ? parts.join(' · ') : '✓ pushed'
15}
16
17export const contextMarkdown = (saved: Saved, where: Where, status: string): string => {
18 const task = saved.tasks[0]?.title ?? 'No task yet'
19 const lines = [
20 '---',
21 `session: ${saved.session}`,
22 `worktree: ${saved.worktree}`,
23 `repo: ${where.repo}`,
24 `branch: ${where.branch}`,
25 `status: ${status}`,
26 `updated: ${stamp(saved.updatedAt)}`,
27 '---',
28 '',
29 `# ${task}`,
30 '',
31 ]
32 if (saved.tasks.length > 1) {
33 lines.push('Earlier in this session:', ...saved.tasks.slice(1).map(t => `- ${t.title}`), '')
34 }
35 const waiting = asks(saved.needsYou)
36 if (waiting.length > 0) lines.push('## Needs you', '', ...waiting.map(a => `- [ ] ${a.question}`), '')
37 const done = dones(saved.done)
38 if (done.length > 0) lines.push('## Done', '', ...done.flatMap(d => [`- ${d.title}`, ...d.items.map(i => ` - ${i}`)]), '')
39 const repos = saved.repos ?? []
40 if (repos.length > 0) {
41 lines.push('## Repos', '', ...repos.map(r => `- ${basename(r.root)} · ${r.branch} · ${repoState(r)}`), '')
42 }
43 const prompt = saved.prompts.at(-1)
44 if (prompt) lines.push('## You asked', '', ...prompt.text.split('\n').map(l => `> ${l}`), '')
45 if (saved.lastSaid) lines.push('## Claude last said', '', saved.lastSaid.text, '')
46 if (saved.notes.length > 0) {
47 lines.push('## Notes', '', ...saved.notes.map(n => `- [${n.title}](${basename(n.file)})`), '')
48 }
49 if (saved.decided.length > 0) lines.push('## Decided', '', ...saved.decided.map(d => `- ${d}`), '')
50 if (saved.tried.length > 0) {
51 lines.push('## Tried', '', ...saved.tried.map(t => `- ${t.isOk ? '✓' : '✗'} ${t.text}`), '')
52 }
53
54 return lines.join('\n')
55}
56hooks/state.ts 28 lines1import type { Crumbs } from '../types'
2import { asks, dones } from './text'
3
4const list = <T>(value: T[] | undefined): T[] => (Array.isArray(value) ? value : [])
5
6export const normalize = (value: Partial<Crumbs> | null | undefined): Crumbs => {
7 const c = value ?? {}
8
9 return {
10 tasks: list(c.tasks),
11 prompts: list(c.prompts),
12 activity: c.activity ?? null,
13 lastSaid: c.lastSaid ?? null,
14 notes: list(c.notes),
15 decided: list(c.decided),
16 tried: list(c.tried),
17 needsYou: asks(c.needsYou),
18 done: dones(c.done),
19 edited: list(c.edited),
20 touched: list(c.touched),
21 repos: list(c.repos),
22 asking: c.asking ?? null,
23 outbox: list(c.outbox),
24 asked: list(c.asked),
25 isWorking: c.isWorking === true,
26 }
27}
28hooks/tests.ts 84 lines1import type { ManualTest, TestRun, TestStatus } from '../types'
2
3// Prompts, tool schemas and pure helpers for the manual tests pane; everything that touches $ is in register.tsx.
4export const TESTS_PANE = 'tests'
5export const TOOL = (name: string) => `mcp__breadcrumbs__${name}`
6export const TESTER = 'breadcrumbs:tester'
7export const WAIT_LIMIT_MS = 30 * 60_000
8// Shared with the breadcrumbs-launcher mod: `<notes root>/.launch/<session id>/` holds its `ready` stamp and spawn requests.
9export const LAUNCH_DIR = '.launch'
10export const LAUNCHER_ALIVE_MS = 90_000
11export const LAUNCH_GRACE_MS = 15_000
12
13export const TESTS_GUIDANCE = [
14 `When the user needs to run manual or end-to-end tests that you cannot run yourself, list them with the ${TOOL('test_plan')} tool instead of writing the steps in your reply.`,
15 'Add them as soon as each piece is ready to try by hand, while you go on with the rest, rather than all at the end: each call adds to the list (mode "replace" starts over), and the brief you pass replaces the one before, so pass the whole brief or leave it out.',
16 'The user starts each test from their tests pane whenever they get to it, where a tester subagent guides them through it and sends you its final report when it finishes.',
17 'You are the planner. Give test_plan a brief that every tester reads first and trusts without re-checking: what the change does, the environment (devices, builds, servers and how to reach them), how to observe results (log tags, commands, signals known to mislead) and what is already verified.',
18 'Before listing, make sure every step can actually happen, checked against the code and the setup; testers do not re-check. Do the preconditions you can check yourself (builds, deploys, registrations) instead of making them a test.',
19 'For each test, trigger names the code that produces the expected signal and what decides whether it fires ("ride_ended is sent by completeRide() in rides.ts, from the driver app only"), so a step never takes a path that skips it; assumes lists what you could not check in the code (one ride per driver at a time, how another agent will behave); needs lists ids of tests that must pass first. Testers run on a fast default model; set model "opus" on a test only when the tester will have to diagnose something subtle.',
20 'Group by physical setup: one setup such as a single ride can verify several behaviours, so prefer fewer, longer tests. Steps are only what the person does by hand; checks you or the tester run go in expect or watch, and each expect names a signal that tells a pass from a fail.',
21 'After each tester report, revise the tests still to run with test_update: new steps or expect, status blocked with the reason when one can no longer be done or failed when an earlier result already decides it, and new facts added to the brief.',
22 'A tester may hand back a question instead of a report ("[tester asks · manual test …] …"). It is paused with its setup still running, so fix what it needs if you can (rebuild, restart a server, sync data), then answer with test_update: its id and reply, plus new steps or expect if they change, and send the message it gives you to the tester with SendMessage, which resumes it. Reply "end the test" when it should stop.',
23 'Testers usually start without you; when the tests pane asks you to start one, spawn it exactly as asked and end your turn. Act on testers\' reports as the orchestrator: fix what failed, then mark the test for a retest with test_update. Do not walk the user through a listed test yourself unless they ask.',
24 'The pane can be narrow: keep titles under 40 characters and steps short, but write a command or text to paste whole, in backticks; the pane wraps it and gives it a copy button.',
25].join(' ')
26
27export const TESTER_PROMPT = [
28 'You guide a person through one manual end-to-end test. You cannot see their screen or device; they do every step by hand.',
29 '- The planner wrote the brief and the test and already checked the steps can be done. Trust the brief: do not re-verify the environment, tooling or facts it states; start the test straight away and read code only to explain a result.',
30 `- When a step turns out to be impossible, the setup breaks (a watcher or server dies, data or config is missing) or a result fails in a way the planner could fix, call ${TOOL('ask_planner')} with what you saw and what you need, then end your turn as it says. The planner fixes things or revises the steps, and its reply resumes you in the same run with the same setup.`,
31 '- Do not swap in a different path to the same end on your own. End the test as blocked or failed only when the planner says to or does not answer.',
32 '- Before the first step, start one background capture of the logs or watchers named in the test and note its PID. Check it at checkpoints and analyse it in full at the end.',
33 `- Hand the person steps with ${TOOL('await_user')}. Put a run of steps they can do without stopping in one call (steps, step = the first one's number), and stop only at a checkpoint: where the result decides whether the remaining steps still make sense, or where only the person can see the result (screen, notification tray).`,
34 '- Put each command or text the person has to paste in backticks, whole, never shortened: the pane wraps it and gives it a copy button.',
35 '- When you ask the person something, put the question in instruction and give 2 to 4 short answer options ("Gone", "Still there", "Not sure"). Leave options out for plain actions; they then get Done and Can\'t.',
36 `- Post short observations with ${TOOL('test_update')} (note), so the person sees what you saw.`,
37 '- When an expected signal does not show, check the test\'s trigger first: say whether the steps reached that code path, and if an assumption turned out wrong, say which.',
38 '- Do not edit code or config. Diagnose and propose; the main agent decides on fixes.',
39 '- Before your final report, kill every background process you started; keep them while you wait on ask_planner.',
40 '- When the test is settled, call test_update with status passed, failed or blocked and a one-line note, then end with at most five lines: the result, the evidence, the likely cause if it failed, and anything you learned that affects the tests still to run.',
41].join('\n')
42
43export const ICON: Record<TestStatus, string> = { todo: '·', running: '●', passed: '✓', failed: '✗', blocked: '⊘', retest: '⟳' }
44
45export const STATUSES: readonly TestStatus[] = ['todo', 'running', 'passed', 'failed', 'blocked', 'retest']
46
47export const listOf = (value: unknown): string[] =>
48 Array.isArray(value) ? value.filter((s): s is string => typeof s === 'string' && s.trim() !== '').map(s => s.trim()) : []
49
50export const str = (value: unknown) => (typeof value === 'string' ? value.trim() : '')
51
52// What a step asks the person to paste: its backticked spans, else what follows "run:" or "paste:".
53export const pastables = (text: string): string[] => {
54 const spans = [...text.matchAll(/`([^`\n]+)`/g)].map(m => (m[1] ?? '').trim()).filter(Boolean)
55 if (spans.length > 0) return spans
56 const after = /\b(?:run|paste)\s*:\s*(.+)$/i.exec(text)?.[1]?.trim()
57
58 return after ? [after] : []
59}
60
61export const testOf = (r: TestRun, e: { id?: unknown; agentId?: string }) =>
62 r.tests.find(t => (typeof e.id === 'string' && e.id ? t.id === e.id : e.agentId !== undefined && t.agentId === e.agentId))
63
64// Ids this test needs that have not passed yet.
65export const unmet = (r: TestRun, t: ManualTest): string[] =>
66 (t.needs ?? []).filter(id => r.tests.find(x => x.id === id)?.status !== 'passed')
67
68// A test whose prerequisite failed or was blocked cannot run either.
69export const settleNeeds = (r: TestRun, at: number): TestRun => ({
70 ...r,
71 tests: r.tests.map(t => {
72 if (t.status !== 'todo' && t.status !== 'retest') return t
73 const dead = r.tests.find(x => (t.needs ?? []).includes(x.id) && (x.status === 'failed' || x.status === 'blocked'))
74 if (!dead) return t
75 const text = `${ICON.blocked} needs test ${dead.id}, which ${dead.status === 'failed' ? 'failed' : 'is blocked'}`
76 return { ...t, status: 'blocked', log: [...t.log, { from: 'claude' as const, text, at }].slice(-30) }
77 }),
78})
79
80export const isLive = (t: ManualTest) => t.status === 'running' && t.agentId !== null
81
82export const openWait = (r: TestRun, testId: string) => r.waits.find(w => w.testId === testId && w.answer === null)
83
84hooks/rich.ts 464 lines1// Lays markdown out as styled, pre-wrapped lines for the terminal pane, which has no Markdown element of its own worth reading.
2
3export type Style = {
4 color?: string
5 bold?: boolean
6 italic?: boolean
7 underline?: boolean
8 strikethrough?: boolean
9}
10export type Span = { text: string; style: Style; href?: string }
11export type Line = Span[]
12
13// Theme keys, not raw colors, so the pane follows whichever theme the person picked.
14const S = {
15 text: { color: 'text' },
16 h1: { color: 'claude', bold: true, underline: true },
17 h2: { color: 'claude', bold: true },
18 h3: { color: 'suggestion', bold: true },
19 h4: { color: 'text', bold: true },
20 strong: { bold: true },
21 em: { italic: true },
22 del: { color: 'inactive', strikethrough: true },
23 code: { color: 'permission' },
24 link: { color: 'suggestion', underline: true },
25 bullet: { color: 'claude' },
26 number: { color: 'claude' },
27 done: { color: 'success' },
28 todo: { color: 'inactive' },
29 quote: { color: 'subtle', italic: true },
30 bar: { color: 'subtle' },
31 rule: { color: 'subtle' },
32 th: { color: 'claude', bold: true },
33 block: { color: 'text' },
34 lang: { color: 'inactive', italic: true },
35} satisfies Record<string, Style>
36
37const CODE = {
38 comment: { color: 'inactive', italic: true },
39 string: { color: 'success' },
40 number: { color: 'warning' },
41 keyword: { color: 'merged' },
42 call: { color: 'suggestion' },
43 type: { color: 'claude' },
44 operator: { color: 'permission' },
45} satisfies Record<string, Style>
46
47// MARK: Blocks
48
49type Align = 'left' | 'center' | 'right'
50type Item = { marker: string; task?: boolean; blocks: Block[] }
51type Block =
52 | { kind: 'heading'; level: number; text: string }
53 | { kind: 'paragraph'; text: string }
54 | { kind: 'code'; lang: string; lines: string[] }
55 | { kind: 'quote'; blocks: Block[] }
56 | { kind: 'list'; ordered: boolean; items: Item[] }
57 | { kind: 'table'; header: string[]; align: Align[]; rows: string[][] }
58 | { kind: 'rule' }
59
60const FENCE = /^ {0,3}(`{3,}|~{3,})\s*([\w+#.-]*)/
61const HEADING = /^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/
62const RULE = /^ {0,3}([-*_])(\s*\1){2,}\s*$/
63const ITEM = /^(\s*)([-*+]|\d{1,9}[.)])\s+(.*)$/
64const QUOTE = /^ {0,3}>\s?(.*)$/
65const TABLE_RULE = /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/
66
67const cells = (row: string) =>
68 row
69 .trim()
70 .replace(/^\||(?<!\\)\|$/g, '')
71 .split(/(?<!\\)\|/)
72 .map(c => c.trim().replace(/\\\|/g, '|'))
73
74const startsBlock = (line: string, next: string | undefined) =>
75 FENCE.test(line) ||
76 HEADING.test(line) ||
77 RULE.test(line) ||
78 QUOTE.test(line) ||
79 ITEM.test(line) ||
80 (line.includes('|') && next !== undefined && TABLE_RULE.test(next) && next.includes('-'))
81
82const indentOf = (line: string) => (/^\s*/.exec(line)?.[0] ?? '').replace(/\t/g, ' ').length
83
84export const parse = (markdown: string): Block[] => {
85 const lines = markdown.replace(/\r\n?/g, '\n').split('\n')
86 const blocks: Block[] = []
87 let i = 0
88 while (i < lines.length) {
89 const line = lines[i] ?? ''
90 if (!line.trim()) {
91 i++
92 continue
93 }
94 const fence = FENCE.exec(line)
95 if (fence) {
96 const close = new RegExp(`^ {0,3}${fence[1]?.[0] === '`' ? '`' : '~'}{${fence[1]?.length ?? 3},}\\s*$`)
97 const body: string[] = []
98 i++
99 while (i < lines.length && !close.test(lines[i] ?? '')) body.push(lines[i++] ?? '')
100 i++
101 blocks.push({ kind: 'code', lang: fence[2] ?? '', lines: body })
102 continue
103 }
104 const heading = HEADING.exec(line)
105 if (heading) {
106 blocks.push({ kind: 'heading', level: heading[1]?.length ?? 1, text: heading[2] ?? '' })
107 i++
108 continue
109 }
110 if (RULE.test(line)) {
111 blocks.push({ kind: 'rule' })
112 i++
113 continue
114 }
115 if (QUOTE.test(line)) {
116 const body: string[] = []
117 while (i < lines.length && (lines[i] ?? '').trim() && QUOTE.test(lines[i] ?? '')) body.push(QUOTE.exec(lines[i++] ?? '')?.[1] ?? '')
118 blocks.push({ kind: 'quote', blocks: parse(body.join('\n')) })
119 continue
120 }
121 const next = lines[i + 1]
122 if (line.includes('|') && next !== undefined && TABLE_RULE.test(next) && next.includes('-')) {
123 const header = cells(line)
124 const align = cells(next).map((c): Align => (c.endsWith(':') ? (c.startsWith(':') ? 'center' : 'right') : 'left'))
125 const rows: string[][] = []
126 i += 2
127 while (i < lines.length && (lines[i] ?? '').includes('|') && (lines[i] ?? '').trim()) rows.push(cells(lines[i++] ?? ''))
128 blocks.push({ kind: 'table', header, align, rows })
129 continue
130 }
131 const item = ITEM.exec(line)
132 if (item) {
133 const base = indentOf(line)
134 const ordered = /\d/.test(item[2] ?? '')
135 const items: Item[] = []
136 while (i < lines.length) {
137 const head = ITEM.exec(lines[i] ?? '')
138 if (!head || indentOf(lines[i] ?? '') !== base || /\d/.test(head[2] ?? '') !== ordered) break
139 const body = [head[3] ?? '']
140 const contentIndent = base + (head[2]?.length ?? 1) + 1
141 i++
142 while (i < lines.length) {
143 const l = lines[i] ?? ''
144 if (!l.trim()) {
145 const after = lines[i + 1] ?? ''
146 if (after.trim() && indentOf(after) >= contentIndent) {
147 body.push('')
148 i++
149 continue
150 }
151 break
152 }
153 if (indentOf(l) < contentIndent && (ITEM.test(l) || startsBlock(l, lines[i + 1]))) break
154 body.push(indentOf(l) >= contentIndent ? l.replace(/\t/g, ' ').slice(contentIndent) : l.trim())
155 i++
156 }
157 const task = /^\[([ xX])\]\s+/.exec(body[0] ?? '')
158 if (task) body[0] = (body[0] ?? '').slice(task[0].length)
159 items.push({ marker: head[2] ?? '-', task: task ? task[1] !== ' ' : undefined, blocks: parse(body.join('\n')) })
160 while (i < lines.length && !(lines[i] ?? '').trim() && ITEM.test(lines[i + 1] ?? '') && indentOf(lines[i + 1] ?? '') === base) i++
161 }
162 blocks.push({ kind: 'list', ordered, items })
163 continue
164 }
165 const text = [line.trim()]
166 i++
167 while (i < lines.length && (lines[i] ?? '').trim() && !startsBlock(lines[i] ?? '', lines[i + 1])) text.push((lines[i++] ?? '').trim())
168 blocks.push({ kind: 'paragraph', text: text.join(' ') })
169 }
170
171 return blocks
172}
173
174// MARK: Inline
175
176const merge = (a: Style, b: Style): Style => ({ ...a, ...b })
177
178export const inline = (text: string, base: Style): Span[] => {
179 const out: Span[] = []
180 const push = (t: string, style: Style, href?: string) => {
181 if (!t) return
182 const last = out.at(-1)
183 if (last && !href && !last.href && JSON.stringify(last.style) === JSON.stringify(style)) last.text += t
184 else out.push(href ? { text: t, style, href } : { text: t, style })
185 }
186 let i = 0
187 while (i < text.length) {
188 const rest = text.slice(i)
189 const ch = rest[0] ?? ''
190 if (ch === '\\' && /^\\[\\`*_{}[\]()#+\-.!|~<>]/.test(rest)) {
191 push(rest[1] ?? '', base)
192 i += 2
193 continue
194 }
195 if (ch === '`') {
196 const run = /^`+/.exec(rest)?.[0] ?? '`'
197 const end = rest.indexOf(run, run.length)
198 if (end > 0) {
199 push(rest.slice(run.length, end).trim(), merge(base, S.code))
200 i += end + run.length
201 continue
202 }
203 }
204 const link = /^\[((?:[^\]\\]|\\.)*)\]\(\s*<?([^)\s>]*)>?(?:\s+"[^"]*")?\s*\)/.exec(rest)
205 if (link) {
206 for (const s of inline(link[1] ?? '', merge(base, S.link))) push(s.text, s.style, link[2] || undefined)
207 i += link[0].length
208 continue
209 }
210 const auto = /^<(https?:\/\/[^>\s]+)>/.exec(rest) ?? /^(https?:\/\/[^\s<]*[^\s<.,;:!?)'"])/.exec(rest)
211 if (auto && (i === 0 || /[\s(]/.test(text[i - 1] ?? ''))) {
212 push(auto[1] ?? '', merge(base, S.link), auto[1])
213 i += auto[0].length
214 continue
215 }
216 const strike = /^~~(?=\S)([\s\S]*?\S)~~/.exec(rest)
217 if (strike) {
218 for (const s of inline(strike[1] ?? '', merge(base, S.del))) push(s.text, s.style, s.href)
219 i += strike[0].length
220 continue
221 }
222 const strong = /^(\*\*|__)(?=\S)([\s\S]*?\S)\1/.exec(rest)
223 if (strong && (ch === '*' || !/\w/.test(text[i - 1] ?? ''))) {
224 for (const s of inline(strong[2] ?? '', merge(base, S.strong))) push(s.text, s.style, s.href)
225 i += strong[0].length
226 continue
227 }
228 const em = /^([*_])(?=[^\s*_])([\s\S]*?[^\s\\])\1(?![*_])/.exec(rest)
229 if (em && (ch === '*' || !/\w/.test(text[i - 1] ?? ''))) {
230 for (const s of inline(em[2] ?? '', merge(base, S.em))) push(s.text, s.style, s.href)
231 i += em[0].length
232 continue
233 }
234 const plain = /^[^\\`[<h~*_]+/.exec(rest)?.[0] ?? ch
235 push(plain, base)
236 i += plain.length
237 }
238
239 return out
240}
241
242// MARK: Wrapping
243
244const width = (spans: Span[]) => spans.reduce((n, s) => n + s.text.length, 0)
245
246const pad = (n: number, style: Style = {}): Span => ({ text: ' '.repeat(Math.max(0, n)), style })
247
248// Greedy word wrap across spans; `first` and `rest` prefix the first and later lines and count toward `max`.
249export const wrap = (spans: Span[], max: number, first: Span[] = [], rest: Span[] = first): Line[] => {
250 const lines: Line[] = []
251 let line: Line = [...first]
252 let used = width(first)
253 let room = Math.max(4, max - used)
254 const flush = () => {
255 const last = line.at(-1)
256 if (last) last.text = last.text.replace(/ +$/, '')
257 lines.push(line)
258 line = [...rest]
259 used = width(rest)
260 room = Math.max(4, max - used)
261 }
262 const add = (text: string, span: Span) => {
263 const last = line.at(-1)
264 if (last && last.style === span.style && last.href === span.href) last.text += text
265 else line.push({ ...span, text })
266 used += text.length
267 }
268 for (const span of spans) {
269 for (const token of span.text.match(/\s+|\S+/g) ?? []) {
270 if (/^\s/.test(token)) {
271 if (used > width(lines.length === 0 ? first : rest) && used < max) add(' ', span)
272 continue
273 }
274 let word = token
275 while (word.length > 0) {
276 const left = max - used
277 if (word.length <= left) {
278 add(word, span)
279 word = ''
280 } else if (word.length > room) {
281 if (left <= 0) flush()
282 const cut = Math.max(1, max - used)
283 add(word.slice(0, cut), span)
284 word = word.slice(cut)
285 if (word) flush()
286 } else {
287 flush()
288 }
289 }
290 }
291 }
292 if (line.length > rest.length || lines.length === 0) flush()
293
294 return lines
295}
296
297// MARK: Code
298
299const KEYWORDS = new Set(
300 (
301 'abstract as async await break case catch class const continue def default defer del delete do elif else enum export extends ' +
302 'false final finally fn for from func function go if impl implements import in interface is lambda let loop match mod mut new nil ' +
303 'none null package pass private protected pub public raise return self static struct super switch this throw true try type typeof ' +
304 'undefined unless until use val var void when where while with yield local then end fi done esac echo'
305 ).split(' '),
306)
307
308const TOKEN =
309 /(\/\/.*|#(?![!\[]).*|--\s.*)|("(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`(?:[^`\\]|\\.)*`?)|(\b0x[\da-f]+\b|\b\d[\d_.]*\b)|([A-Za-z_$][\w$]*)(?=\s*\()|([A-Za-z_$][\w$]*)|([^\w\s"'`]+)|(\s+)/gi
310
311const highlight = (line: string, lang: string): Span[] => {
312 const spans: Span[] = []
313 const hashComments = /^(sh|bash|zsh|shell|py|python|rb|ruby|ya?ml|toml|conf|ini|dockerfile|make|r)$/i.test(lang)
314 for (const m of line.matchAll(TOKEN)) {
315 const [text, comment, str, num, call, word, punct] = m
316 let style: Style = S.block
317 if (comment && (comment.startsWith('//') || hashComments || comment.startsWith('--'))) style = CODE.comment
318 else if (str) style = CODE.string
319 else if (num) style = CODE.number
320 else if (call) style = KEYWORDS.has(call) ? CODE.keyword : CODE.call
321 else if (word && KEYWORDS.has(word)) style = CODE.keyword
322 else if (word && /^[A-Z]/.test(word)) style = CODE.type
323 else if (punct && /[=<>!+\-*/%&|^?:]/.test(punct)) style = CODE.operator
324 spans.push({ text, style })
325 }
326
327 return spans
328}
329
330const codeBlock = (lang: string, body: string[], max: number): Line[] => {
331 const bar: Span = { text: '▎ ', style: S.bar }
332 const inner = Math.max(4, max - 2)
333 const out: Line[] = lang ? [[bar, { text: lang.slice(0, inner), style: S.lang }]] : []
334 for (const raw of body.length > 0 ? body : ['']) {
335 // Code keeps its indentation, so it is cut into rows rather than word-wrapped.
336 let row: Span[] = []
337 let used = 0
338 const rows: Span[][] = []
339 for (const s of highlight(raw.replace(/\t/g, ' '), lang)) {
340 let t = s.text
341 while (t.length > 0) {
342 const take = t.slice(0, inner - used)
343 row.push({ ...s, text: take })
344 used += take.length
345 t = t.slice(take.length)
346 if (used >= inner) {
347 rows.push(row)
348 row = []
349 used = 0
350 }
351 }
352 }
353 if (row.length > 0 || rows.length === 0) rows.push(row)
354 out.push(...rows.map(r => [bar, ...r]))
355 }
356
357 return out
358}
359
360// MARK: Tables
361
362const fit = (natural: number[], max: number): number[] => {
363 const widths = natural.map(n => Math.max(1, n))
364 const budget = max - (widths.length - 1) * 3 - 2
365 while (widths.reduce((a, b) => a + b, 0) > budget) {
366 const big = widths.indexOf(Math.max(...widths))
367 if ((widths[big] ?? 0) <= 3) break
368 widths[big] = (widths[big] ?? 0) - 1
369 }
370
371 return widths
372}
373
374const table = (header: string[], align: Align[], rows: string[][], max: number): Line[] => {
375 const columns = Math.max(header.length, ...rows.map(r => r.length))
376 const head = Array.from({ length: columns }, (_, k) => inline(header[k] ?? '', S.th))
377 const body = rows.map(r => Array.from({ length: columns }, (_, k) => inline(r[k] ?? '', S.text)))
378 const widths = fit(
379 Array.from({ length: columns }, (_, k) => Math.max(width(head[k] ?? []), ...body.map(r => width(r[k] ?? [])))),
380 max,
381 )
382 const sep: Span = { text: ' │ ', style: S.bar }
383 const row = (cellsOf: Span[][]): Line[] => {
384 const wrapped = cellsOf.map((c, k) => wrap(c, widths[k] ?? 1))
385 const height = Math.max(1, ...wrapped.map(w => w.length))
386 return Array.from({ length: height }, (_, y) => {
387 const line: Line = [pad(1)]
388 wrapped.forEach((w, k) => {
389 if (k > 0) line.push(sep)
390 const cell = w[y] ?? []
391 const gap = (widths[k] ?? 1) - width(cell)
392 const a = align[k] ?? 'left'
393 const left = a === 'right' ? gap : a === 'center' ? Math.floor(gap / 2) : 0
394 line.push(pad(left), ...cell, pad(gap - left))
395 })
396 return line
397 })
398 }
399 const rule: Line = [{ text: `─${widths.map(w => '─'.repeat(w)).join('─┼─')}─`, style: S.rule }]
400
401 return [...row(head), rule, ...body.flatMap(row)]
402}
403
404// MARK: Layout
405
406const indent = (lines: Line[], first: Span[], rest: Span[]): Line[] => lines.map((l, i) => [...(i === 0 ? first : rest), ...l])
407
408const headingStyle = (level: number): Style => (level === 1 ? S.h1 : level === 2 ? S.h2 : level === 3 ? S.h3 : S.h4)
409
410const layoutBlocks = (blocks: Block[], max: number, base: Style, tight = false): Line[] => {
411 const out: Line[] = []
412 blocks.forEach((b, n) => {
413 if (n > 0 && !tight) out.push([])
414 out.push(...layoutBlock(b, max, base))
415 })
416
417 return out
418}
419
420const layoutBlock = (b: Block, max: number, base: Style): Line[] => {
421 switch (b.kind) {
422 case 'heading':
423 return wrap(
424 inline(b.text, headingStyle(b.level)).map(s => ({ ...s, style: { ...s.style, ...headingStyle(b.level) } })),
425 max,
426 [{ text: `${'#'.repeat(b.level)} `, style: { ...headingStyle(b.level), bold: false, underline: false } }],
427 [pad(b.level + 1)],
428 )
429 case 'paragraph':
430 return wrap(inline(b.text, base), max)
431 case 'rule':
432 return [[{ text: '─'.repeat(max), style: S.rule }]]
433 case 'code':
434 return codeBlock(b.lang, b.lines, max)
435 case 'table':
436 return table(b.header, b.align, b.rows, max)
437 case 'quote': {
438 const bar: Span = { text: '│ ', style: S.bar }
439 return indent(layoutBlocks(b.blocks, max - 2, S.quote), [bar], [bar])
440 }
441 case 'list': {
442 const loose = b.items.some(it => it.blocks.length > 1 && it.blocks.some(x => x.kind === 'paragraph') && it.blocks.filter(x => x.kind === 'paragraph').length > 1)
443 const out: Line[] = []
444 b.items.forEach((it, n) => {
445 if (n > 0 && loose) out.push([])
446 const marker: Span[] =
447 it.task !== undefined
448 ? [{ text: it.task ? '✓ ' : '☐ ', style: it.task ? S.done : S.todo }]
449 : b.ordered
450 ? [{ text: `${it.marker} `, style: S.number }]
451 : [{ text: '• ', style: S.bullet }]
452 const w = width(marker)
453 const itemBase = it.task ? { ...base, ...S.del } : base
454 const lines = layoutBlocks(it.blocks, max - w, itemBase, true)
455 out.push(...indent(lines.length > 0 ? lines : [[]], marker, [pad(w)]))
456 })
457 return out
458 }
459 }
460}
461
462/** The lines a markdown text draws as, each at most `max` columns wide. */
463export const richLines = (markdown: string, max: number): Line[] => layoutBlocks(parse(markdown), Math.max(12, max), S.text)
464hooks/text.ts 233 lines1export const slug =(text: string, max = 40): string =>
2 text
3 .toLowerCase()
4 .replace(/[^a-z0-9]+/g, '-')
5 .replace(/^-+|-+$/g, '')
6 .slice(0, max)
7 .replace(/-+$/, '') || 'untitled'
8
9export const clip = (text: string, max: number): string => {
10 const flat = text.replace(/\s+/g, ' ').trim()
11
12 return flat.length <= max ? flat : `${flat.slice(0, max - 1).trimEnd()}…`
13}
14
15// Unlike clip, keeps newlines so a markdown preview still renders as markdown.
16export const head = (text: string, max: number): string =>
17 text.length <= max ? text : `${text.slice(0, max - 1).trimEnd()}…`
18
19const cells = (row: string) =>
20 row
21 .trim()
22 .replace(/^\||\|$/g, '')
23 .split(/(?<!\\)\|/)
24 .map(c => c.trim())
25
26const isRule = (row: string) => /^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/.test(row) && row.includes('-')
27
28// A table wider than the pane wraps into an unreadable grid, so the preview restacks it as a list.
29// With `minCell`, the drawing wraps cells itself, so only a table that can't give each column that much is restacked.
30export const narrowTables = (markdown: string, width: number, minCell?: number): string => {
31 const lines = markdown.split('\n')
32 const out: string[] = []
33 let isFenced = false
34 for (let i = 0; i < lines.length; i++) {
35 const line = lines[i] ?? ''
36 if (/^\s*(```|~~~)/.test(line)) isFenced = !isFenced
37 if (isFenced || !line.includes('|') || !isRule(lines[i + 1] ?? '')) {
38 out.push(line)
39 continue
40 }
41 let end = i + 2
42 while (end < lines.length && (lines[end] ?? '').includes('|') && (lines[end] ?? '').trim()) end++
43 const header = cells(line)
44 const rows = lines.slice(i + 2, end).map(cells)
45 const widths = header.map((h, k) => Math.max(h.length, ...rows.map(r => (r[k] ?? '').length)))
46 if (widths.reduce((sum, w) => sum + (minCell ? Math.min(w, minCell) : w) + 3, 1) <= width) {
47 out.push(...lines.slice(i, end))
48 } else {
49 for (const row of rows) {
50 out.push(`- ${row[0] ?? ''}`)
51 for (let k = 1; k < header.length; k++) if (row[k]) out.push(` - *${header[k]}*: ${row[k]}`)
52 }
53 }
54 i = end - 1
55 }
56
57 return out.join('\n')
58}
59
60export const ago =(at: number, now: number): string => {
61 const seconds = Math.max(0, Math.round((now - at) / 1000))
62 if (seconds < 45) return 'now'
63 const minutes = Math.round(seconds / 60)
64 if (minutes < 60) return `${minutes}m ago`
65 const hours = Math.round(minutes / 60)
66 if (hours < 24) return `${hours}h ago`
67
68 return `${Math.round(hours / 24)}d ago`
69}
70
71const pad = (n: number) => String(n).padStart(2, '0')
72
73export const day = (at: number): string => {
74 const d = new Date(at)
75
76 return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`
77}
78
79export const stamp = (at: number): string => {
80 const d = new Date(at)
81
82 return `${day(at)} ${pad(d.getHours())}:${pad(d.getMinutes())}`
83}
84
85export const basename = (path: string): string => path.replace(/\/+$/, '').split('/').pop() ?? path
86
87// Models wrap JSON in fences or prose often enough that a strict parse loses turns.
88export const parseObject = (text: string): Record<string, unknown> | null => {
89 const start = text.indexOf('{')
90 const end = text.lastIndexOf('}')
91 if (start < 0 || end <= start) return null
92 try {
93 const value: unknown = JSON.parse(text.slice(start, end + 1))
94
95 return value !== null && typeof value === 'object' && !Array.isArray(value)
96 ? (value as Record<string, unknown>)
97 : null
98 } catch {
99 return null
100 }
101}
102
103export const strings = (value: unknown, max: number, each = 100): string[] =>
104 Array.isArray(value)
105 ? value.filter((v): v is string => typeof v === 'string' && v.trim() !== '').map(v => clip(v, each)).slice(0, max)
106 : []
107
108const str = (value: unknown): string => (typeof value === 'string' ? value : '')
109
110// Older state.json files stored needs-you items as bare strings.
111type RawAsk = { question: string; context?: unknown; options?: unknown; optionNotes?: unknown; assumption?: unknown }
112type RawOption = { label: string; description?: unknown }
113
114const text = (value: unknown, max: number) => (typeof value === 'string' ? clip(value, max) : '')
115
116export const MAX_ASKS = 6
117
118// Accepts every shape this has had: bare strings, string options, and {label, description} options.
119export const asks = (value: unknown): { question: string; context: string; options: string[]; optionNotes: string[]; assumption: string }[] =>
120 Array.isArray(value)
121 ? value
122 .map(v => (typeof v === 'string' ? { question: v } : v))
123 .filter((v): v is RawAsk => typeof v?.question === 'string' && v.question.trim() !== '')
124 .slice(-MAX_ASKS)
125 .map(v => {
126 const notes = Array.isArray(v.optionNotes) ? v.optionNotes : []
127 const options = (Array.isArray(v.options) ? v.options : [])
128 .map((o, i): RawOption | null =>
129 typeof o === 'string' ? { label: o, description: notes[i] } : typeof o?.label === 'string' ? o : null,
130 )
131 .filter((o): o is RawOption => o !== null && o.label.trim() !== '')
132 .slice(0, 4)
133 return {
134 question: clip(v.question, 160),
135 context: text(v.context, 400),
136 options: options.map(o => clip(o.label, 80)),
137 optionNotes: options.map(o => text(o.description, 160)),
138 assumption: text(v.assumption, 160),
139 }
140 })
141 : []
142
143const OPEN = /^\s*(?:[-*>]\s+)?(?:\*\*|__)?open question\b(?:\*\*|__)?\s*:(?:\*\*|__)?\s*(.+)$/i
144
145// `Open question: Which TTL? [5m | 1h] (assuming 5m)`, options and assumption both optional.
146export const openQuestions = (reply: string) => {
147 let isFenced = false
148 return asks(
149 reply.split('\n').flatMap(line => {
150 if (/^\s*(```|~~~)/.test(line)) isFenced = !isFenced
151 const body = isFenced ? undefined : OPEN.exec(line)?.[1]
152 if (!body) return []
153 let rest = body.replace(/\*\*|__/g, '').trim()
154 const assumed = /\(\s*assum(?:e|es|ing)\s*:?\s*(.+?)\s*\)\s*\.?$/i.exec(rest)
155 if (assumed) rest = rest.slice(0, assumed.index).trim()
156 const choices = /\[([^\]]*\|[^\]]*)\]\s*$/.exec(rest)
157 if (choices) rest = rest.slice(0, choices.index).trim()
158 const options = choices?.[1]?.split('|').map(o => o.trim()).filter(Boolean) ?? []
159 return rest ? [{ question: rest, options, assumption: assumed?.[1] ?? '' }] : []
160 }),
161 )
162}
163
164export const DONE_TITLE = 40
165
166// One turn's results as a done entry; a single result short enough to be the title needs no list under it.
167export const doneOf = (title: unknown, items: string[], at: number): { title: string; items: string[]; at: number } | null => {
168 const named = typeof title === 'string' ? clip(title, DONE_TITLE) : ''
169 const first = items[0]
170 if (!named && first === undefined) return null
171 if (!named && items.length === 1 && first !== undefined && first.length <= DONE_TITLE) return { title: first, items: [], at }
172
173 return { title: named || clip(first ?? '', DONE_TITLE), items, at }
174}
175
176// Older state.json files stored one {text, at} per result.
177export const dones = (value: unknown): { title: string; items: string[]; at: number }[] =>
178 Array.isArray(value)
179 ? value.flatMap(v => {
180 const at = typeof v?.at === 'number' ? v.at : 0
181 const done = typeof v?.text === 'string' ? doneOf(null, [clip(v.text, 100)], at) : doneOf(v?.title, strings(v?.items, 6, 100), at)
182 return done ? [done] : []
183 })
184 : []
185
186export const parseStatus =(out: string) => {
187 const [first = '', ...rest] = out.split('\n')
188 const header = first.replace(/^## /, '')
189 const [branchPart = '', trackPart = ''] = header.split('...')
190 const branch = branchPart.replace(/^No commits yet on /, '').replace(/ \[.*$/, '')
191
192 return {
193 branch: branch === 'HEAD (no branch)' ? 'detached' : branch,
194 hasUpstream: trackPart !== '',
195 ahead: Number(/ahead (\d+)/.exec(header)?.[1] ?? 0),
196 behind: Number(/behind (\d+)/.exec(header)?.[1] ?? 0),
197 changed: rest.filter(line => line.trim() !== '').length,
198 }
199}
200
201// `cd <dir> && …` is how most commands reach another repo, so it marks that repo as touched.
202export const cdTarget = (command: string, home: string): string | null => {
203 const match = /^\s*cd\s+("([^"]+)"|'([^']+)'|(\S+))/.exec(command)
204 const raw = match?.[2] ?? match?.[3] ?? match?.[4]
205 if (!raw) return null
206 const dir = raw.replace(/^~(?=\/|$)/, home).replace(/\/+$/, '')
207
208 return dir.startsWith('/') ? dir : null
209}
210
211export const toolLabel = (tool: string, input: Record<string, unknown>): string => {
212 const file = str(input.file_path) || str(input.notebook_path)
213 switch (tool) {
214 case 'Bash':
215 return `Bash: ${clip(str(input.description) || str(input.command), 48)}`
216 case 'Read':
217 case 'Edit':
218 case 'Write':
219 case 'NotebookEdit':
220 return `${tool} ${basename(file)}`
221 case 'Grep':
222 case 'Glob':
223 return `${tool} ${clip(str(input.pattern), 40)}`
224 case 'Agent':
225 return `Agent: ${clip(str(input.description), 44)}`
226 case 'WebFetch':
227 case 'WebSearch':
228 return `${tool} ${clip(str(input.url) || str(input.query), 40)}`
229 default:
230 return tool.startsWith('mcp__') ? tool.split('__').slice(1).join(' ') : tool
231 }
232}
233types/index.d.ts 119 lines1export type Note = {
2 id: string
3 title: string
4 file: string
5 at: number
6 isPinned: boolean
7}
8
9export type Task = { title: string; at: number }
10
11export type Attempt = { text: string; isOk: boolean }
12
13// What Claude went ahead with while the question waits; '' when it named nothing.
14export type Ask = { question: string; context: string; options: string[]; optionNotes: string[]; assumption: string }
15
16// An answer from the pane that Claude has not read yet.
17export type Answer = { question: string; answer: string; at: number }
18
19export type Repo = {
20 root: string
21 branch: string
22 changed: number
23 ahead: number
24 behind: number
25 hasUpstream: boolean
26}
27
28export type Stamped = { text: string; at: number }
29
30// One per turn: a one-line title, with what changed listed under it.
31export type Done = { title: string; items: string[]; at: number }
32
33export type Crumbs = {
34 tasks: Task[]
35 prompts: Stamped[]
36 activity: string | null
37 lastSaid: Stamped | null
38 notes: Note[]
39 decided: string[]
40 tried: Attempt[]
41 needsYou: Ask[]
42 done: Done[]
43 edited: string[]
44 touched: string[]
45 repos: Repo[]
46 asking: string | null
47 outbox: Answer[]
48 // Open questions already shown, so one repeated in a later reply isn't asked again.
49 asked: string[]
50 isWorking: boolean
51}
52
53export type Where = {
54 repo: string
55 branch: string
56 worktree: string
57}
58
59export type View = {
60 openNote: string | null
61 isShowingPrompts: boolean
62 isShowingMore: boolean
63 isShowingStatus: boolean
64 openDone: number | null
65 typed: Record<string, string>
66}
67
68export type TestStatus = 'todo' | 'running' | 'passed' | 'failed' | 'blocked' | 'retest'
69
70export type Entry = { from: 'you' | 'tester' | 'claude'; text: string; at: number }
71
72export type ManualTest = {
73 id: string
74 title: string
75 steps: string[]
76 expect: string
77 watch: string
78 status: TestStatus
79 agentId: string | null
80 log: Entry[]
81 // The tester's open question to the planner; absent on tests saved before it existed.
82 asking?: string | null
83 // What makes the expected signal happen; absent on older tests, as are the two below.
84 trigger?: string
85 assumes?: string[]
86 needs?: string[]
87 // The tester's model for this test, over the testerModel setting.
88 model?: string
89}
90
91export type Wait = {
92 id: string
93 testId: string | null
94 step: number | null
95 instruction: string
96 // Absent on waits from before these fields existed.
97 steps?: string[]
98 options?: string[]
99 at: number
100 answer: string | null
101}
102
103export type TestRun = { brief: string; tests: ManualTest[]; waits: Wait[]; unreported: string[] }
104
105export type TestsView = { expanded: string | null; typed: Record<string, string> }
106
107declare module 'claude-code' {
108 interface PluginState {
109 breadcrumbs: {
110 crumbs: Crumbs
111 where: Where | null
112 view: View
113 pending: string | null
114 tests: TestRun
115 testsView: TestsView
116 }
117 }
118}
119