SLOPSHOPPER

brief

Dotfiles – (neo)vim, tmux and zsh configuration

bandspinnerrowsguardcommandprompt
v?no licenseupdated 2026-10-19rcliao/dotfiles/dot_claude/mods/brief
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · brief
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /brief No goal set (brief_note). in progress since 0s 3 file edits ctx 49% ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Command output
No goal set (brief_note). in progress since 0s 3 file edits ctx 49%
README

Eric's Dotfiles

Managed with chezmoi. Shell, terminals, editors, git, and the Claude Code setup I actually work in.

Set up a new machine

brew install chezmoi
chezmoi init --apply rcliao

That prompts for three things and writes them to ~/.config/chezmoi/chezmoi.toml, which stays local to the machine and is never committed:

PromptWhy it is per-machine
Full namegit author name
Git emailso a work laptop and a personal box can share this repo without cross-signing commits
Ghost hookssee Ghost below

Re-running chezmoi init later is non-interactive — it keeps whatever is already set. To change an answer, edit ~/.config/chezmoi/chezmoi.toml and chezmoi apply. For an unattended install, chezmoi init --apply --promptDefaults takes the personal identity with Ghost off.

The first apply runs brew bundle for everything below. A package failure warns rather than aborting, so the dotfiles land either way.

Day to day

chezmoi diff                 # what would change
chezmoi apply                # everything
chezmoi apply ~/.zshrc       # just one target
chezmoi add ~/.tmux.conf     # pull a local edit back into the repo
chezmoi update               # git pull + apply

This repo is edited from more than one machine, so read chezmoi diff before applying. Whichever machine committed last is not automatically the machine that is more correct.

What is in here

Shell — .zshrc (zsh, pure prompt, shared history across panes, cached compinit), .gitconfig (delta pager, zdiff3 conflicts, rerere, auto-set upstream on push), .config/git/ignore, .ssh/config (keychain-backed agent loading — this is what replaces the ssh-add -A that used to run on every shell start).

Terminals — ghostty.

Multiplexers — herdr (primary, keys mapped to match tmux muscle memory), tmux as the fallback. The old zellij config is kept under archive/, which is not deployed.

Editors — neovim (0.12+: one init.lua, plugins via the built-in vim.pack, LSP for Go, TypeScript, Rust, Python and Terraform from Brewfile-installed servers), emacs.

Runtimes — mise, activated at the end of .zshrc so it wins over the PATH exports above it. Homebrew still provides the global node, go, and python; mise only takes over inside a directory that pins a version in mise.toml or .tool-versions.

Window management — aerospace.

Claude Code — CLAUDE.md, settings.json, and the hook scripts under .claude/hooks. settings.json is a template: hooks belonging to tools that may not be installed (herdr, Zero) are only wired in when their script is actually present, so a machine never ends up pointing at a hook that does not exist.

Other — bat, yazi.

Ghost memory hooks (opt-in)

The ghost-* hooks drive the Ghost MCP memory server. A machine without Ghost has no use for them, so they are off by default: neither the scripts nor their settings.json entries are installed.

To turn them on, set ghost = true in ~/.config/chezmoi/chezmoi.toml and chezmoi apply. To turn them off again, flip it back and apply.

aerospace

Homebrew refuses casks from untrusted taps, and trusting one is a decision worth making deliberately, so the bundle does not install aerospace:

brew trust --cask nikitabobko/tap/aerospace   # this one cask, not the whole tap
brew install --cask nikitabobko/tap/aerospace

What is deliberately not tracked

Anything regenerated, tool-managed, or machine-specific — Claude Code session transcripts and caches, plugin directories, herdr's own integration hook, and ~/.config/chezmoi/chezmoi.toml itself. See .chezmoiignore, which lists each exclusion explicitly so chezmoi add ~/.claude can never sweep one in.

This repo is public, so nothing employer-specific goes in it.

Source 4 files
hooks/register.tsx 773 lines
1// The brief: a band of at most two lines above the prompt (activity between turns, the armed ask nearest the
2// prompt), a step count on the spinner, a /brief snapshot in the transcript, and a notification for blocking
3// asks. The agent writes through brief_ask, brief_note and brief_read; everything else is observed by hooks.
4import { atom, read, update } from 'claude-code'
5import type { EngineInterface, Register } from 'claude-code'
6
7import type { Changes, Check, Cron, DoneItem, Job, Pending, Question, SnapLine, Step } from '../types'
8import { activity, askSpec, fitAsk, stepCount, UNDO_MS } from './band'
9import {
10  APPROVAL_HINT,
11  ASK_DESCRIPTION,
12  answerRow,
13  applyMet,
14  parseAnswerRows,
15  checkPrompt,
16  defaultQuestion,
17  driftQuestion,
18  expired,
19  mergeRows,
20  NEEDS_APPROVAL,
21  openQuestions,
22  parseCheck,
23  pickArmed,
24  MAX_CHECK,
25  readText,
26  RULE,
27  snapshot,
28  validateAsk,
29  validateNote,
30} from './model'
31import type { BriefView } from './model'
32
33const goalAtom = atom({ plugin: 'brief', key: 'goal' } as const, null as string | null)
34const doneWhenAtom = atom({ plugin: 'brief', key: 'doneWhen' } as const, [] as DoneItem[])
35const assumptionsAtom = atom({ plugin: 'brief', key: 'assumptions' } as const, [] as string[])
36const questionsAtom = atom({ plugin: 'brief', key: 'questions' } as const, [] as Question[])
37const armedAtom = atom({ plugin: 'brief', key: 'armed' } as const, null as string | null)
38const pendingAtom = atom({ plugin: 'brief', key: 'pending' } as const, null as Pending | null)
39const nextIdAtom = atom({ plugin: 'brief', key: 'nextId' } as const, 1)
40const stepsAtom = atom({ plugin: 'brief', key: 'steps' } as const, [] as Step[])
41const hasTaskToolAtom = atom({ plugin: 'brief', key: 'hasTaskTool' } as const, false)
42const jobsAtom = atom({ plugin: 'brief', key: 'jobs' } as const, [] as Job[])
43const cronsAtom = atom({ plugin: 'brief', key: 'crons' } as const, [] as Cron[])
44const workingAtom = atom({ plugin: 'brief', key: 'isWorking' } as const, false)
45const startedAtom = atom({ plugin: 'brief', key: 'startedAt' } as const, 0)
46const endedAtom = atom({ plugin: 'brief', key: 'endedAt' } as const, 0)
47const turnAtom = atom({ plugin: 'brief', key: 'turn' } as const, 0)
48const checkAtom = atom({ plugin: 'brief', key: 'check' } as const, null as Check | null)
49const changesAtom = atom({ plugin: 'brief', key: 'changes' } as const, { since: 0, done: [], asks: 0, answers: 0, edits: 0 } as Changes)
50const outboxAtom = atom({ plugin: 'brief', key: 'outbox' } as const, [] as string[])
51const snapshotAtom = atom({ plugin: 'brief', key: 'snapshot' } as const, [] as SnapLine[])
52const unreadAtom = atom({ plugin: 'brief', key: 'unread' } as const, null as string | null)
53const keptAtom = atom({ plugin: 'brief', key: 'kept' } as const, [] as string[])
54const sidAtom = atom({ plugin: 'brief', key: 'sid' } as const, null as string | null)
55
56const ASK_TOOL = 'mcp__brief__brief_ask'
57const NOTE_TOOL = 'mcp__brief__brief_note'
58const READ_TOOL = 'mcp__brief__brief_read'
59const TICK_MS = 15_000
60const FLUSH_MS = 300
61const EDIT_TOOLS = new Set(['Edit', 'Write', 'NotebookEdit'])
62const SAVE_MS = 500
63// One file per session, not the plugin store: the store is one JSON file every session writes, so panes saving
64// at once could drop each other's keys. A session only ever writes its own file.
65const SAVE_DIR = '/.claude/mods-data/brief/sessions'
66const SAVE_TTL_MS = 14 * 86_400_000
67// Typed at the terminal, Remote Control, and an SDK host's turn (claude -p, the eval harness).
68const PERSON_ORIGINS = new Set(['composer', 'bridge', 'sdk'])
69
70// Module variables reset on a hot reload; each only skips one check or merges one row less.
71let toolsThisTurn = false
72let checking = false
73let flushTimer: { cancel: () => void } | undefined
74let undoTimer: { cancel: () => void } | undefined
75let saveTimer: { cancel: () => void } | undefined
76// The last save written, so the 15 s tick's redraw does not rewrite an unchanged brief.
77let lastSaved = ''
78// sid after session.end: the next entry point loads the new id's save. null means never set (a fresh process,
79// or a hot reload from before sid existed).
80const ENDED = '(ended)'
81
82// Every change redraws; the same moment schedules the session's save, so a resume finds the brief as it was.
83const redraw = ($: EngineInterface): void => {
84  $.ui.invalidate('ui.render')
85  saveTimer?.cancel()
86  saveTimer = $.clock.after(SAVE_MS, () => {
87    void save($).catch(() => undefined)
88  })
89}
90
91// --- the brief across a resume: what the person has yet to answer, one file per session ---
92
93async function saveDir($: EngineInterface): Promise<string | undefined> {
94  const home = await $.env.get('HOME')
95  return home === undefined ? undefined : `${home}${SAVE_DIR}`
96}
97
98// Session ids are UUIDs; anything else is not used in a path.
99const savePath = (dir: string, sid: string): string | undefined => (/^[A-Za-z0-9-]{1,80}$/.test(sid) ? `${dir}/${sid}.json` : undefined)
100
101/** What a resumed session gets back. Jobs, steps and the turn's flags are re-observed; an answer in its undo window is not kept. */
102type Saved = {
103  at: number
104  goal: string | null
105  doneWhen: DoneItem[]
106  assumptions: string[]
107  questions: Question[]
108  armed: string | null
109  nextId: number
110  kept: string[]
111  startedAt: number
112  check: Check | null
113  turn: number
114  outbox: string[]
115}
116
117async function save($: EngineInterface): Promise<void> {
118  const sid = await read($, sidAtom)
119  if (sid === null || sid === ENDED) return
120  const pending = await read($, pendingAtom)
121  // An answer still undoable did not go out: on a resume its ask is open again.
122  const questions = (await read($, questionsAtom)).map(q => (pending !== null && q.id === pending.id ? { ...q, status: 'open' as const, answer: undefined } : q))
123  const saved: Saved = {
124    at: await $.clock.now(),
125    goal: await read($, goalAtom),
126    doneWhen: await read($, doneWhenAtom),
127    assumptions: await read($, assumptionsAtom),
128    questions: questions.slice(-40),
129    armed: await read($, armedAtom),
130    nextId: await read($, nextIdAtom),
131    kept: await read($, keptAtom),
132    startedAt: await read($, startedAtom),
133    check: await read($, checkAtom),
134    turn: await read($, turnAtom),
135    outbox: await read($, outboxAtom),
136  }
137  // Nothing to keep: no file, so idle sessions leave nothing behind.
138  if (saved.goal === null && saved.doneWhen.length === 0 && saved.questions.length === 0 && saved.outbox.length === 0) return
139  const body = JSON.stringify({ ...saved, at: 0 })
140  if (body === lastSaved) return
141  // The session may have ended while this was reading: never write one session's state under another.
142  if ((await read($, sidAtom)) !== sid) return
143  const dir = await saveDir($)
144  const path = dir === undefined ? undefined : savePath(dir, sid)
145  if (path === undefined) return
146  await $.fs.write(path, JSON.stringify(saved))
147  lastSaved = body
148}
149
150async function load($: EngineInterface, sid: string): Promise<void> {
151  const dir = await saveDir($)
152  const path = dir === undefined ? undefined : savePath(dir, sid)
153  if (path === undefined || !(await $.fs.exists(path))) return
154  let v: Partial<Saved> | undefined
155  try {
156    v = JSON.parse(await $.fs.read(path)) as Partial<Saved>
157  } catch {
158    return
159  }
160  if (v === undefined || v === null || typeof v !== 'object' || !Array.isArray(v.questions)) return
161  await update($, goalAtom, () => (typeof v.goal === 'string' ? v.goal : null))
162  await update($, doneWhenAtom, () => (Array.isArray(v.doneWhen) ? v.doneWhen : []))
163  await update($, assumptionsAtom, () => (Array.isArray(v.assumptions) ? v.assumptions : []))
164  await update($, questionsAtom, () => v.questions as Question[])
165  await update($, nextIdAtom, () => (typeof v.nextId === 'number' ? v.nextId : 1))
166  await update($, keptAtom, () => (Array.isArray(v.kept) ? v.kept : []))
167  await update($, checkAtom, () => v.check ?? null)
168  await update($, turnAtom, () => (typeof v.turn === 'number' ? v.turn : 0))
169  if (typeof v.startedAt === 'number' && v.startedAt > 0) await update($, startedAtom, () => v.startedAt as number)
170  if (Array.isArray(v.outbox) && v.outbox.length > 0) {
171    await update($, outboxAtom, () => v.outbox as string[])
172    flushTimer = $.clock.after(FLUSH_MS, () => {
173      void flush($)
174    })
175  }
176  const qs = v.questions as Question[]
177  await update($, armedAtom, () => pickArmed(qs, typeof v.armed === 'string' ? v.armed : null))
178}
179
180/**
181 * The state belongs to one session id. A /clear or a resume moves the process to another id without a
182 * session.start, so each entry point checks: a new id resets the state and loads that session's save.
183 */
184async function ensureSession($: EngineInterface): Promise<void> {
185  const sid = await $.session.id()
186  const held = await read($, sidAtom)
187  if (held === sid) return
188  // A mod loaded over a running session (a deploy) finds state but no sid: it is this session's, keep it.
189  if (held === null && (await read($, startedAtom)) !== 0) {
190    await update($, sidAtom, () => sid)
191    return
192  }
193  lastSaved = ''
194  await resetSession($)
195  await update($, sidAtom, () => sid)
196  await load($, sid)
197}
198
199async function sweepSaves($: EngineInterface): Promise<void> {
200  const dir = await saveDir($)
201  if (dir === undefined || !(await $.fs.exists(dir))) return
202  const now = await $.clock.now()
203  for (const f of await $.fs.list(dir)) {
204    if (f.kind === 'file' && f.name.endsWith('.json') && now - f.mtimeMs > SAVE_TTL_MS) await removeSave($, `${dir}/${f.name}`)
205  }
206}
207
208async function removeSave($: EngineInterface, path: string): Promise<void> {
209  await $.process.run(['rm', '-f', path], { timeoutMs: 3_000 }).catch(() => undefined)
210}
211
212const freshChanges = (since: number): Changes => ({ since, done: [], asks: 0, answers: 0, edits: 0 })
213
214async function newId($: EngineInterface): Promise<string> {
215  // One update, so two callers at once never share an id.
216  const n = await update($, nextIdAtom, v => v + 1)
217  return `D${n - 1}`
218}
219
220async function rearm($: EngineInterface): Promise<void> {
221  const qs = await read($, questionsAtom)
222  await update($, armedAtom, prev => pickArmed(qs, prev ?? null))
223}
224
225async function noteDone($: EngineInterface, texts: readonly string[]): Promise<void> {
226  if (texts.length > 0) await update($, changesAtom, c => ({ ...(c ?? freshChanges(0)), done: [...(c?.done ?? []), ...texts].slice(-6) }))
227}
228
229// --- delivery: one row per step, mid-turn as a user row, idle as a prompt ---
230
231async function flush($: EngineInterface): Promise<void> {
232  flushTimer = undefined
233  const rows = await read($, outboxAtom)
234  if (rows.length === 0) return
235  await update($, outboxAtom, () => [])
236  const text = mergeRows(rows)
237  try {
238    if (await read($, workingAtom)) {
239      const sent = await $.session.append({ message: { type: 'user', content: [{ type: 'text', text }] } })
240      if ('deny' in sent && sent.deny !== undefined) $.ui.log(`brief: answer not delivered (${sent.deny})`)
241      // Read at the agent's next request; if the turn ends first, turn.complete sends it again as a prompt.
242      else await update($, unreadAtom, prev => (prev === null || prev === undefined ? text : `${prev}\n${text}`))
243    } else {
244      await $.prompt.submit({ text })
245    }
246  } catch (err) {
247    $.ui.log(`brief: answer not delivered (${String(err)})`)
248  }
249}
250
251async function send($: EngineInterface, row: string): Promise<void> {
252  await update($, outboxAtom, prev => [...(prev ?? []), row])
253  // Rows that land together go as one; a timer, so a press or a command never submits from inside its own hook.
254  flushTimer?.cancel()
255  flushTimer = $.clock.after(FLUSH_MS, () => {
256    void flush($)
257  })
258}
259
260// --- answers: held UNDO_MS, then sent ---
261
262async function commit($: EngineInterface, id: string): Promise<void> {
263  undoTimer = undefined
264  const pending = await read($, pendingAtom)
265  if (pending === null || pending.id !== id) return
266  await update($, pendingAtom, () => null)
267  const q = (await read($, questionsAtom)).find(x => x.id === id)
268  if (q !== undefined) {
269    await settle($, q, pending.option)
270    const row = answerRow(q, pending.option)
271    if (row !== undefined) await send($, row)
272  }
273  await rearm($)
274  redraw($)
275}
276
277/** What an answer does to the brief, however it arrived (a band press or a row from another channel). */
278async function settle($: EngineInterface, q: Question, option: string): Promise<void> {
279  // A kept drift becomes a done-when check of its own.
280  if (q.kind === 'drift' && option === 'keep') {
281    const what = q.question.replace(/ isn't in done-when$/, '')
282    await update($, doneWhenAtom, prev => [...(prev ?? []), { text: what.slice(0, MAX_CHECK), met: false }])
283    await update($, keptAtom, prev => [...(prev ?? []), what.toLowerCase()])
284  }
285  await update($, questionsAtom, prev => (prev ?? []).map(x => (x.id === q.id ? { ...x, status: 'answered' as const, answer: option } : x)))
286  await update($, changesAtom, c => ({ ...(c ?? freshChanges(0)), answers: (c?.answers ?? 0) + 1 }))
287}
288
289async function answer($: EngineInterface, id: string, option: string): Promise<void> {
290  const now = await $.clock.now()
291  // A press that lands after the ask closed (a default applied a moment ago) answers nothing.
292  if (!openQuestions(await read($, questionsAtom)).some(q => q.id === id) || (await read($, pendingAtom)) !== null) return
293  await update($, questionsAtom, prev => (prev ?? []).map(q => (q.id === id && q.status === 'open' ? { ...q, status: 'answered' as const, answer: option } : q)))
294  await update($, pendingAtom, () => ({ id, option, at: now }))
295  undoTimer?.cancel()
296  undoTimer = $.clock.after(UNDO_MS, () => {
297    void commit($, id)
298  })
299  redraw($)
300}
301
302async function undo($: EngineInterface): Promise<void> {
303  const pending = await read($, pendingAtom)
304  if (pending === null) return
305  undoTimer?.cancel()
306  undoTimer = undefined
307  await update($, pendingAtom, () => null)
308  await update($, questionsAtom, prev => (prev ?? []).map(q => (q.id === pending.id ? { ...q, status: 'open' as const, answer: undefined } : q)))
309  // The same ask, the same hotkeys.
310  await update($, armedAtom, () => pending.id)
311  redraw($)
312}
313
314// --- the clock: defaults apply; meta times move ---
315
316async function tick($: EngineInterface): Promise<void> {
317  const now = await $.clock.now()
318  const due = expired(await read($, questionsAtom), now)
319  if (due.length > 0) {
320    const raised: Question[] = []
321    for (const q of due) raised.push(defaultQuestion(await newId($), q, now))
322    await update($, questionsAtom, prev => [
323      ...(prev ?? []).map(q => (due.some(d => d.id === q.id) ? { ...q, status: 'defaulted' as const, answer: q.options[0] } : q)),
324      ...raised,
325    ])
326    await rearm($)
327  }
328  redraw($)
329}
330
331// --- the direction check: one forked completion over the session's own transcript ---
332
333async function directionCheck($: EngineInterface, turn: number): Promise<void> {
334  const goal = await read($, goalAtom)
335  const doneWhen = await read($, doneWhenAtom)
336  // Nothing to judge against without done-when checks: no fork.
337  if (goal === null || doneWhen.length === 0 || checking) return
338  if (openQuestions(await read($, questionsAtom)).some(q => q.kind === 'drift')) return
339  checking = true
340  try {
341    const session = await read($, startedAtom)
342    const reply = await $.model.fork({ prompt: checkPrompt(goal, doneWhen) })
343    // A /clear while the fork ran: the verdict is the old conversation's.
344    if (!reply.isAnswered || (await read($, startedAtom)) !== session) return
345    const check = parseCheck(reply.text, turn)
346    if (check === undefined) return
347    await update($, checkAtom, () => check)
348    const kept = await read($, keptAtom)
349    const what = check.unplanned.find(u => !doneWhen.some(d => d.text.toLowerCase() === u.toLowerCase()) && !kept.includes(u.toLowerCase()))
350    if (what !== undefined) {
351      const q = driftQuestion(await newId($), what, turn, await $.clock.now())
352      await update($, questionsAtom, prev => [...(prev ?? []), q])
353      await rearm($)
354    }
355    redraw($)
356  } finally {
357    checking = false
358  }
359}
360
361// --- the views ---
362
363async function view($: EngineInterface): Promise<BriefView> {
364  const usage = await $.session.usage().catch(() => undefined)
365  return {
366    goal: await read($, goalAtom),
367    doneWhen: await read($, doneWhenAtom),
368    questions: await read($, questionsAtom),
369    steps: await read($, stepsAtom),
370    check: await read($, checkAtom),
371    changes: await read($, changesAtom),
372    ctxPercent: usage?.context.percent,
373    assumptions: await read($, assumptionsAtom),
374    now: await $.clock.now(),
375  }
376}
377
378async function resetSession($: EngineInterface): Promise<void> {
379  undoTimer?.cancel()
380  flushTimer?.cancel()
381  const now = await $.clock.now()
382  await update($, goalAtom, () => null)
383  await update($, doneWhenAtom, () => [])
384  await update($, assumptionsAtom, () => [])
385  await update($, questionsAtom, () => [])
386  await update($, armedAtom, () => null)
387  await update($, pendingAtom, () => null)
388  await update($, stepsAtom, () => [])
389  await update($, jobsAtom, () => [])
390  await update($, cronsAtom, () => [])
391  await update($, checkAtom, () => null)
392  await update($, outboxAtom, () => [])
393  await update($, unreadAtom, () => null)
394  await update($, keptAtom, () => [])
395  await update($, snapshotAtom, () => [])
396  await update($, turnAtom, () => 0)
397  await update($, endedAtom, () => 0)
398  await update($, startedAtom, () => now)
399  await update($, changesAtom, () => freshChanges(now))
400}
401
402export const register: Register = on => {
403  on('session.start', async ($, e, next) => {
404    // Tools first, each on its own: a refused registration (a taken name) must not skip the others.
405    const tools = [
406      {
407        name: 'brief_ask',
408        description: ASK_DESCRIPTION,
409        isDeferred: false,
410        inputSchema: {
411          type: 'object',
412          properties: {
413            question: { type: 'string', description: 'At most 60 characters' },
414            short: { type: 'string', description: 'The question in at most 24 characters, for narrow screens' },
415            options: { type: 'array', items: { type: 'string' }, description: '2 to 4 choices of at most 12 characters; your default (or the safe choice, when blocking) first' },
416            blocking: { type: 'boolean', description: "true only when you stop until they answer: a step that can't be undone or that others will see" },
417          },
418          required: ['question', 'short', 'options'],
419        },
420      },
421      {
422        name: 'brief_note',
423        description: 'Record the goal and 2-8 done-when checks when you start (the list replaces the last; "[x] text" marks one met), tick checks with met as you finish them, or note an assumption you made.',
424        isDeferred: true,
425        inputSchema: {
426          type: 'object',
427          properties: {
428            goal: { type: 'string' },
429            doneWhen: { type: 'array', items: { type: 'string' } },
430            met: { type: 'array', items: { type: 'string' }, description: 'Done-when checks now met, by their text' },
431            assumption: { type: 'string' },
432          },
433        },
434      },
435      {
436        name: 'brief_read',
437        description: 'The brief as the person sees it: goal, status, done-when (one check per line), open asks, recent answers, health.',
438        isDeferred: true,
439        inputSchema: { type: 'object', properties: {} },
440      },
441    ]
442    for (const spec of tools) await $.tool.register(spec).catch(err => $.ui.log(`brief: could not register ${spec.name} (${String(err)})`))
443    await $.command
444      .register({ name: 'brief', description: 'Show the brief: goal, done-when, open asks, what changed, health', immediate: true })
445      .catch(err => $.ui.log(`brief: could not register /brief (${String(err)})`))
446    // A hot reload keeps the state (same id); a fresh process or a resume loads the session's save.
447    await ensureSession($)
448    await sweepSaves($).catch(() => undefined)
449    // A reload drops timers: an answer still in its undo window goes out when the window would have closed.
450    const pending = await read($, pendingAtom)
451    if (pending !== null) {
452      const left = Math.max(0, pending.at + UNDO_MS - (await $.clock.now()))
453      undoTimer = $.clock.after(left, () => {
454        void commit($, pending.id)
455      })
456    }
457    // ...and rows queued for the agent go out.
458    if ((await read($, outboxAtom)).length > 0) {
459      flushTimer = $.clock.after(FLUSH_MS, () => {
460        void flush($)
461      })
462    }
463    $.clock.every(TICK_MS, () => {
464      void tick($)
465    })
466    return next(e)
467  })
468
469  on('session.end', async ($, e, next) => {
470    // Save what is open before the state goes: a resume of this session gets it back. /clear starts over.
471    saveTimer?.cancel()
472    if (e.reason === 'clear') {
473      const dir = await saveDir($)
474      const path = dir === undefined ? undefined : savePath(dir, e.sessionId)
475      if (path !== undefined) await removeSave($, path)
476    }
477    else {
478      // Always write: another session's sweep may have removed a long-idle file whose body never changed.
479      lastSaved = ''
480      await save($).catch(() => undefined)
481    }
482    await update($, sidAtom, () => ENDED)
483    await resetSession($)
484    return next(e)
485  })
486
487  on('turn.start', async ($, e, next) => {
488    if (e.agentId === undefined) {
489      await ensureSession($)
490      toolsThisTurn = false
491      await update($, workingAtom, () => true)
492      redraw($)
493    }
494    return next(e)
495  })
496
497  // A model request of the main loop reads every row appended before it.
498  on('turn.step', async function* ($, e, next) {
499    if (e.agentId === undefined) await update($, unreadAtom, () => null)
500    return yield* next(e)
501  })
502
503  on('turn.complete', async ($, e, next) => {
504    const done = await next(e)
505    if (e.agentId !== undefined) return done
506    await update($, workingAtom, () => false)
507    const ended = await $.clock.now()
508    await update($, endedAtom, () => ended)
509    // An answer appended after the turn's last request would wait for the person's next prompt: send it now.
510    const unread = await read($, unreadAtom)
511    if (unread !== null) {
512      await update($, unreadAtom, () => null)
513      $.clock.after(FLUSH_MS, () => {
514        void $.prompt.submit({ text: unread }).catch(err => $.ui.log(`brief: answer not delivered (${String(err)})`))
515      })
516    }
517    const turn = (await read($, turnAtom)) + 1
518    await update($, turnAtom, () => turn)
519    if (toolsThisTurn && !e.isAborted) void directionCheck($, turn).catch(err => $.ui.log(`brief: direction check failed (${String(err)})`))
520    redraw($)
521    return done
522  })
523
524  // Jobs and wakeups, as Claude Code reports them when the main loop stops.
525  on('classic.Stop', async ($, e, next) => {
526    const now = await $.clock.now()
527    const tasks = (e.background_tasks ?? []).filter(t => t.status === 'running' || t.status === 'pending')
528    await update($, jobsAtom, prev =>
529      tasks.map(t => ({ id: t.id, label: (t.description || t.command || t.type).slice(0, 30), since: (prev ?? []).find(j => j.id === t.id)?.since ?? now })),
530    )
531    await update($, cronsAtom, prev =>
532      (e.session_crons ?? []).map(c => ({ id: c.id, schedule: c.schedule, recurring: c.recurring, seenAt: (prev ?? []).find(x => x.id === c.id)?.seenAt ?? now })),
533    )
534    redraw($)
535    return next(e)
536  }).catch(($, e, next) => next(e))
537
538  on('tool.call', async ($, e, next) => {
539    // A plain string: the laid MCP types list a fixed set of names, so comparing e.tool narrows e to never.
540    const name: string = e.tool
541    if ([ASK_TOOL, NOTE_TOOL, READ_TOOL].includes(name)) await ensureSession($)
542    if (name === ASK_TOOL) {
543      if (e.agentId !== undefined) return { result: 'Not queued: only the main session asks the person.' }
544      const checked = validateAsk(e)
545      if (!checked.ok) return { isError: true, result: checked.error, text: checked.error }
546      const id = await newId($)
547      const q: Question = { id, kind: 'agent', ...checked.value, at: await $.clock.now(), status: 'open' }
548      await update($, questionsAtom, prev => [...(prev ?? []), q])
549      await update($, changesAtom, c => ({ ...(c ?? freshChanges(0)), asks: (c?.asks ?? 0) + 1 }))
550      await rearm($)
551      redraw($)
552      if (q.blocking) {
553        const sent = await $.ui.notify(`${q.question}  ${q.options.join(' / ')}`).catch(() => undefined)
554        if (sent !== undefined && !sent.isSent) $.ui.log(`brief: notification not sent (${sent.reason})`)
555      }
556      return { result: JSON.stringify({ id }) }
557    }
558    if (name === NOTE_TOOL) {
559      const checked = validateNote(e)
560      if (!checked.ok) return { isError: true, result: checked.error, text: checked.error }
561      const { goal, doneWhen, met, assumption } = checked.value
562      if (goal !== undefined) {
563        if ((await read($, goalAtom)) === null) {
564          const started = await $.clock.now()
565          await update($, startedAtom, () => started)
566        }
567        await update($, goalAtom, () => goal)
568      }
569      if (doneWhen !== undefined) {
570        const prev = await read($, doneWhenAtom)
571        await noteDone($, doneWhen.filter(d => d.met && !prev.some(p => p.text === d.text && p.met)).map(d => d.text))
572        await update($, doneWhenAtom, () => doneWhen)
573      }
574      if (met !== undefined) {
575        const prev = await read($, doneWhenAtom)
576        const { items, unmatched } = applyMet(prev, met)
577        if (unmatched.length > 0) {
578          const error = prev.length === 0 ? 'no done-when checks yet: brief_note doneWhen first' : `no check matches ${unmatched.map(u => `"${u}"`).join(', ')}; the checks are: ${prev.map(d => d.text).join('; ')}`
579          return { isError: true, result: error, text: error }
580        }
581        await noteDone($, items.filter((d, i) => d.met && !(prev[i] as DoneItem).met).map(d => d.text))
582        await update($, doneWhenAtom, () => items)
583      }
584      if (assumption !== undefined) await update($, assumptionsAtom, prev => [...(prev ?? []), assumption].slice(-5))
585      redraw($)
586      // The current checks, so the agent knows what is left without a brief_read.
587      const list = await read($, doneWhenAtom)
588      return { result: list.length === 0 ? 'ok' : `ok; done when ${list.map(d => `[${d.met ? 'x' : ' '}] ${d.text}`).join('  ')}` }
589    }
590    if (name === READ_TOOL) return { result: readText(await view($)) }
591
592    if (e.agentId === undefined) toolsThisTurn = true
593    const ran = await next(e)
594    if (ran.isError === true && e.agentId === undefined && NEEDS_APPROVAL.test(ran.text ?? '')) return { ...ran, context: [...(ran.context ?? []), APPROVAL_HINT] }
595    if (ran.deny !== undefined || ran.isError === true || e.agentId !== undefined) return ran
596
597    // Steps, from the agent's own task list.
598    if (e.tool === 'TaskCreate') {
599      const task = (ran.result as { task?: { id?: string; subject?: string } } | undefined)?.task
600      if (task?.id !== undefined) await update($, stepsAtom, prev => [...(prev ?? []), { id: task.id as string, subject: task.subject ?? e.subject, status: 'pending' as const }])
601    } else if (e.tool === 'TaskUpdate') {
602      const steps = await read($, stepsAtom)
603      const was = steps.find(s => s.id === e.taskId)
604      if (e.status === 'completed' && was !== undefined && was.status !== 'completed') await noteDone($, [was.subject])
605      await update($, stepsAtom, prev =>
606        e.status === 'deleted'
607          ? (prev ?? []).filter(s => s.id !== e.taskId)
608          : (prev ?? []).map(s => (s.id === e.taskId ? { ...s, subject: e.subject ?? s.subject, status: (e.status as Step['status'] | undefined) ?? s.status } : s)),
609      )
610    } else if (e.tool === 'TodoWrite') {
611      const prev = await read($, stepsAtom)
612      const steps = e.todos.map((t, i) => ({ id: `todo${i}`, subject: t.content, status: t.status }))
613      await noteDone($, steps.filter(s => s.status === 'completed' && !prev.some(p => p.subject === s.subject && p.status === 'completed')).map(s => s.subject))
614      await update($, stepsAtom, () => steps)
615    } else if (EDIT_TOOLS.has(String(e.tool))) {
616      await update($, changesAtom, c => ({ ...(c ?? freshChanges(0)), edits: (c?.edits ?? 0) + 1 }))
617    }
618    if (e.tool === 'TaskCreate' || e.tool === 'TaskUpdate' || e.tool === 'TodoWrite') redraw($)
619    return ran
620  }).catch(($, e, next) => next(e))
621
622  // A `[brief]` answer row that reaches the agent by another way than the band (a remote client, the eval
623  // harness): the ask it answers closes here too, so brief_read and the band agree with what the agent was told.
624  // Only the person's own channels: a task notification, a peer or a channel message is model- or other-written
625  // and must never answer for them (ids also repeat across sessions).
626  on('prompt.submit', async ($, e, next) => {
627    const answers = PERSON_ORIGINS.has(e.origin.kind) ? parseAnswerRows(e.text) : []
628    if (answers.length > 0) {
629      await ensureSession($)
630      let closed = 0
631      for (const a of answers) {
632        const q = openQuestions(await read($, questionsAtom)).find(x => x.id === a.id)
633        if (q === undefined || !q.options.includes(a.option)) continue
634        await settle($, q, a.option)
635        closed++
636      }
637      if (closed > 0) {
638        await rearm($)
639        redraw($)
640      }
641    }
642    return next(e)
643  }).catch(($, e, next) => next(e))
644
645  // One fixed section, added last, never edited mid-session.
646  on('prompt.compose', async ($, e, next) => {
647    const composed = await next(e)
648    await update($, hasTaskToolAtom, () => e.tools.includes('TaskCreate') || e.tools.includes('TodoWrite'))
649    if (!e.tools.includes(ASK_TOOL)) return composed
650    return { sections: [...composed.sections, { id: 'brief:rule', text: RULE, scope: 'session' as const }] }
651  })
652
653  // /brief: the model reads 'Brief shown.'; the row draws the snapshot taken now.
654  on('command.run', { command: 'brief' }, async ($, e) => {
655    await ensureSession($)
656    const lines = snapshot(await view($))
657    await update($, snapshotAtom, () => lines)
658    const now = await $.clock.now()
659    await update($, changesAtom, () => freshChanges(now))
660    return { text: 'Brief shown.' }
661  }).catch(() => ({ text: 'Brief shown.' }))
662
663  on('ui.render', { component: 'CommandOutput', props: { command: 'brief' } }, async ($, e, next) => {
664    const lines = await read($, snapshotAtom)
665    if (lines.length === 0 || e.props.isErrored) return next(e)
666    const { Box, Text } = $.ui.resolve(e)
667    return (
668      <Box flexDirection="column">
669        {lines.map((l, i) =>
670          l.tone === 'warning' ? (
671            <Text key={`s${i}`} color="warning" wrap="truncate-end">{l.text}</Text>
672          ) : l.tone === 'dim' ? (
673            <Text key={`s${i}`} dimColor wrap="truncate-end">{l.text}</Text>
674          ) : (
675            <Text key={`s${i}`} wrap="truncate-end">{l.text}</Text>
676          ),
677        )}
678      </Box>
679    )
680  })
681
682  // The spinner: the step count after Claude Code's own ellipsis; its word and message stay Claude Code's.
683  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
684    const count = stepCount(await read($, stepsAtom), await read($, doneWhenAtom))
685    if (count === undefined) return next(e)
686    return next({ ...e, props: { ...e.props, suffix: `${e.props.suffix} ${count.k}/${count.n}` } })
687  })
688
689  // The band: activity between turns, then the armed ask (or its undo window) nearest the prompt.
690  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
691    if (e.props.hasSurvey) return next(e)
692    const now = await $.clock.now()
693    const columns = e.props.bodyColumns
694    const act = e.props.isWorking
695      ? undefined
696      : activity(
697          {
698            steps: await read($, stepsAtom),
699            doneWhen: await read($, doneWhenAtom),
700            jobs: await read($, jobsAtom),
701            crons: await read($, cronsAtom),
702            startedAt: await read($, startedAtom),
703            endedAt: await read($, endedAtom),
704            now,
705          },
706          columns,
707        )
708    const pending = await read($, pendingAtom)
709    const qs = await read($, questionsAtom)
710    const open = openQuestions(qs)
711    const armedId = await read($, armedAtom)
712    const armed = pending === null ? open.find(q => q.id === armedId) ?? open.find(q => q.id === pickArmed(qs, armedId)) : undefined
713    if (act === undefined && pending === null && armed === undefined) return next(e)
714
715    const { Box, Text, Button } = $.ui.resolve(e)
716    const actRow =
717      act === undefined ? null : act.kind === 'done' ? (
718        <Box key="act" flexDirection="row">
719          <Text>{`${act.count} `}</Text>
720          <Text color="success">done</Text>
721          {act.doneWhen === '' ? null : <Text>{`  ${act.doneWhen}`}</Text>}
722          {act.time === '' ? null : <Text dimColor>{`  ${act.time}`}</Text>}
723        </Box>
724      ) : (
725        <Box key="act" flexDirection="row">
726          <Text wrap="truncate-end">{[act.count, act.step].filter(s => s !== '').join(' ')}</Text>
727          {act.state === '' ? null : <Text dimColor>{`${act.count === '' && act.step === '' ? '' : '  '}${act.state}`}</Text>}
728        </Box>
729      )
730    let askRow = null
731    if (pending !== null) {
732      askRow = (
733        <Box key="ask" flexDirection="row" gap={2}>
734          <Box flexDirection="row" flexShrink={0}>
735            <Text dimColor>sent: </Text>
736            <Text>{pending.option}</Text>
737          </Box>
738          <Box flexShrink={0}>
739            <Button plain hotkey="0" label="undo" onPress={() => undo($)} />
740          </Box>
741        </Box>
742      )
743    } else if (armed !== undefined) {
744      const spec = askSpec(armed, open.length - 1, now)
745      const fit = fitAsk(spec, columns)
746      const tone = armed.blocking ? 'warning' : undefined
747      askRow = (
748        <Box key="ask" flexDirection="row">
749          <Text color={tone} wrap="truncate-end">{`${spec.sigil} ${fit.question}`}</Text>
750          <Box flexShrink={0} gap={2} marginLeft={2}>
751            {armed.options.map((o, i) => (
752              <Button key={`${armed.id}:${i + 1}`} plain hotkey={String(i + 1)} label={o} onPress={() => answer($, armed.id, o)} />
753            ))}
754          </Box>
755          <Box flexGrow={1} />
756          {fit.meta === '' ? null : (
757            <Box flexShrink={0} marginLeft={2}>
758              <Text dimColor>{fit.meta}</Text>
759            </Box>
760          )}
761        </Box>
762      )
763    }
764    return (
765      <Box flexDirection="column">
766        {actRow}
767        {askRow}
768      </Box>
769    )
770  })
771}
772
773
hooks/band.ts 196 lines
1// The band's two lines, laid out by hand: flex layout wraps a line it cannot fit, so each line's length is
2// computed here and the first form that fits bodyColumns is drawn. Pure functions only, for the fit tests.
3import type { Cron, DoneItem, Job, Question, Step } from '../types'
4
5/** A non-blocking ask's default applies after this long without an answer. */
6export const DEFAULT_MS = 10 * 60_000
7/** An answer is held this long, undoable, before it goes to the agent. */
8export const UNDO_MS = 3_000
9
10export const isAscii = (s: string): boolean => /^[\x20-\x7e]*$/.test(s)
11
12/** Elapsed time as a job shows it: 45s, 1m12s, 22m, 1h05. */
13export const duration = (ms: number): string => {
14  const s = Math.max(0, Math.round(ms / 1000))
15  if (s < 60) return `${s}s`
16  if (s < 600) return s % 60 === 0 ? `${s / 60}m` : `${Math.floor(s / 60)}m${String(s % 60).padStart(2, '0')}s`
17  const m = Math.round(s / 60)
18  if (m < 60) return `${m}m`
19  return `${Math.floor(m / 60)}h${String(m % 60).padStart(2, '0')}`
20}
21
22/** A coarse time for meta: 30s, 4m, 2h. */
23export const mins = (ms: number): string => {
24  const s = Math.max(0, Math.round(ms / 1000))
25  if (s < 60) return `${s}s`
26  const m = Math.round(s / 60)
27  return m < 60 ? `${m}m` : `${Math.round(m / 60)}h`
28}
29
30const optionsWidth = (options: readonly string[]): number => options.reduce((n, o, i) => n + 2 + `${i + 1}: ${o}`.length, 0)
31
32export type AskSpec = {
33  sigil: '!' | '?'
34  question: string
35  short: string
36  options: readonly string[]
37  /** the other open asks, drawn as `+n` */
38  plus: number
39  /** meta's time part, full and short (`default in 4m`, `4m`) */
40  time: string
41  timeShort: string
42}
43
44export type AskFit = { form: 1 | 2 | 3 | 4 | 5 | 6; question: string; meta: string }
45
46const join = (parts: readonly string[], sep: string): string => parts.filter(p => p !== '').join(sep)
47
48export const askLength = (question: string, options: readonly string[], meta: string): number =>
49  2 + question.length + optionsWidth(options) + (meta === '' ? 0 : 2 + meta.length)
50
51/** The first form that fits `columns`; past the fifth, the short question alone, cut by Claude Code. */
52export const fitAsk = (spec: AskSpec, columns: number): AskFit => {
53  const plus = spec.plus > 0 ? `+${spec.plus}` : ''
54  const full = join([plus, spec.time], '  ')
55  const short = join([plus, spec.timeShort], ' ')
56  const forms: [AskFit['form'], string, string][] = [
57    [1, spec.question, full],
58    [2, spec.question, short],
59    [3, spec.short, short],
60    [4, spec.short, plus],
61    [5, spec.short, ''],
62  ]
63  for (const [form, question, meta] of forms) {
64    if (askLength(question, spec.options, meta) <= columns) return { form, question, meta }
65  }
66  return { form: 6, question: spec.short, meta: '' }
67}
68
69/** Plain text of a fitted ask line, meta flush right at `columns`, as the reference captures read. */
70export const askText = (spec: AskSpec, fit: AskFit, columns: number): string => {
71  const head = [`${spec.sigil} ${fit.question}`, ...spec.options.map((o, i) => `${i + 1}: ${o}`)].join('  ')
72  if (fit.meta === '') return head
73  return head + ' '.repeat(Math.max(2, columns - head.length - fit.meta.length)) + fit.meta
74}
75
76/** The ask line's spec for one question; `plus` counts the other open ones. */
77export const askSpec = (q: Question, plus: number, now: number): AskSpec => {
78  const base = { question: q.question, short: q.short, options: q.options, plus }
79  if (q.kind === 'drift') return { ...base, sigil: '?', time: `after turn ${q.turn ?? 0}`, timeShort: `t${q.turn ?? 0}` }
80  if (q.blocking) return { ...base, sigil: '!', time: mins(now - q.at), timeShort: mins(now - q.at) }
81  if (q.kind === 'default') return { ...base, sigil: '?', time: `${mins(now - q.at)} ago`, timeShort: mins(now - q.at) }
82  const left = mins(q.at + DEFAULT_MS - now)
83  return { ...base, sigil: '?', time: `default in ${left}`, timeShort: left }
84}
85
86// --- the activity line ---
87
88export type Count = { k: number; n: number; step: string | undefined }
89
90/** Steps from the agent's task list when it has one, else the done-when count. */
91export const stepCount = (steps: readonly Step[], doneWhen: readonly DoneItem[]): Count | undefined => {
92  if (steps.length > 0) {
93    const done = steps.filter(s => s.status === 'completed').length
94    const current = steps.find(s => s.status === 'in_progress')
95    const next = current ?? steps.find(s => s.status === 'pending')
96    return { k: Math.min(steps.length, done + (current === undefined ? 0 : 1)), n: steps.length, step: next?.subject }
97  }
98  if (doneWhen.length > 0) {
99    return { k: doneWhen.filter(d => d.met).length, n: doneWhen.length, step: doneWhen.find(d => !d.met)?.text }
100  }
101  return undefined
102}
103
104export const isDone = (steps: readonly Step[], doneWhen: readonly DoneItem[]): boolean =>
105  steps.length > 0 ? steps.every(s => s.status === 'completed') : doneWhen.length > 0 && doneWhen.every(d => d.met)
106
107export type Activity =
108  | { kind: 'progress'; count: string; step: string; state: string }
109  | { kind: 'done'; count: string; doneWhen: string; time: string }
110
111export type ActivityInput = {
112  steps: readonly Step[]
113  doneWhen: readonly DoneItem[]
114  jobs: readonly Job[]
115  crons: readonly Cron[]
116  startedAt: number
117  endedAt: number
118  now: number
119}
120
121/** Between turns only: where the work stands and what the session waits on. */
122export const activity = (a: ActivityInput, columns: number): Activity | undefined => {
123  const count = stepCount(a.steps, a.doneWhen)
124  if (count !== undefined && isDone(a.steps, a.doneWhen) && a.jobs.length === 0) {
125    const met = a.doneWhen.filter(d => d.met).length
126    return {
127      kind: 'done',
128      count: `${count.n}/${count.n}`,
129      doneWhen: a.doneWhen.length === 0 ? '' : `${met}/${a.doneWhen.length} done-when met`,
130      time: a.startedAt > 0 ? mins(a.now - a.startedAt) : '',
131    }
132  }
133  let state = ''
134  const job = a.jobs[0]
135  if (job !== undefined) state = `waiting on ${job.label} ${duration(a.now - job.since)}`
136  else if (a.crons.length > 0) {
137    const at = Math.min(...a.crons.map(c => nextFire(c.schedule, a.now) ?? Infinity))
138    state = Number.isFinite(at) ? `wakes in ${mins(at - a.now)}` : 'wakes later'
139  } else if (a.endedAt > 0) state = `ended ${mins(a.now - a.endedAt)} ago`
140  if (count === undefined && job === undefined && a.crons.length === 0) return undefined
141  const head = count === undefined ? '' : `${count.k}/${count.n}`
142  // The step gives way first: the count and the state are what a glance needs.
143  const room = columns - head.length - 1 - (state === '' ? 0 : 2 + state.length)
144  const step = count?.step === undefined || room < 4 ? '' : count.step.slice(0, room)
145  return { kind: 'progress', count: head, step, state }
146}
147
148export const activityText = (a: Activity): string =>
149  a.kind === 'done'
150    ? join([`${a.count} done`, a.doneWhen, a.time], '  ')
151    : join([join([a.count, a.step], ' '), a.state], '  ')
152
153// --- cron: when a session cron fires next ---
154
155const field = (spec: string, min: number, max: number): Set<number> | undefined => {
156  const out = new Set<number>()
157  for (const part of spec.split(',')) {
158    const m = /^(\*|\d+(?:-\d+)?)(?:\/(\d+))?$/.exec(part)
159    if (m === null) return undefined
160    const step = m[2] === undefined ? 1 : Number(m[2])
161    let lo = min
162    let hi = max
163    if (m[1] !== '*') {
164      const [a, b] = (m[1] as string).split('-').map(Number)
165      lo = a as number
166      hi = b ?? (m[2] === undefined ? (a as number) : max)
167    }
168    if (step < 1 || lo < min || hi > max) return undefined
169    for (let v = lo; v <= hi; v += step) out.add(v)
170  }
171  return out
172}
173
174/** The next minute after `now` a five-field cron expression matches, in local time; undefined if none in 8 days. */
175export const nextFire = (schedule: string, now: number): number | undefined => {
176  const parts = schedule.trim().split(/\s+/)
177  if (parts.length !== 5) return undefined
178  const [mi, ho, dom, mon, dow] = parts as [string, string, string, string, string]
179  const sets = [field(mi, 0, 59), field(ho, 0, 23), field(dom, 1, 31), field(mon, 1, 12), field(dow.replace(/7/g, '0'), 0, 6)]
180  if (sets.some(s => s === undefined)) return undefined
181  const [M, H, D, Mo, W] = sets as Set<number>[]
182  const t = new Date(now)
183  t.setSeconds(0, 0)
184  for (let i = 0; i < 8 * 24 * 60; i++) {
185    t.setMinutes(t.getMinutes() + 1)
186    const domOk = (D as Set<number>).has(t.getDate())
187    const dowOk = (W as Set<number>).has(t.getDay())
188    // Cron's rule: when both day fields are restricted, either may match.
189    const dayOk = dom === '*' || dow === '*' ? domOk && dowOk : domOk || dowOk
190    if ((M as Set<number>).has(t.getMinutes()) && (H as Set<number>).has(t.getHours()) && (Mo as Set<number>).has(t.getMonth() + 1) && dayOk) {
191      return t.getTime()
192    }
193  }
194  return undefined
195}
196
hooks/model.ts 367 lines
1// What the agent writes (brief_ask, brief_note), what the person answers, and what each sends back.
2// Pure functions only: the hooks in register.tsx hold the state and the clock.
3import type { Changes, Check, DoneItem, Question, SnapLine, Step } from '../types'
4import { DEFAULT_MS, mins } from './band'
5
6export const MAX_QUESTION = 60
7export const MAX_SHORT = 24
8export const MAX_OPTION = 12
9export const MAX_OPTIONS = 4
10export const MAX_ROW = 120
11export const MAX_GOAL = 100
12export const MAX_CHECK = 60
13
14export const ASK_DESCRIPTION =
15  "Queue a multiple-choice question without stopping. Put your default first; it applies if they don't answer in time."
16
17// Eval 2026-10-17: without the brief_note sentence the agent never set a goal (0/3), and without "only they can do"
18// a missing credential never blocked (0/3). docs/brief-v2-eval.md.
19export const RULE =
20  "Brief: for work with more than one step, brief_note a one-line goal and 2-8 done-when checks first, and brief_note met: [...] as each is met. Ask with brief_ask and keep working on option 1, your default. Block only for steps that can't be undone or that others will see. Anything you hand the person to do (a key, an account, a manual step) is a blocking brief_ask too. Goal under 100 characters, checks and questions under 60, options under 12. Call brief_read before you say you're done."
21
22const clean = (s: string): string => s.replace(/\s+/g, ' ').trim()
23
24/** Typographic punctuation folded to ASCII, so a dash or a curly quote is not a refused call and a retry. */
25export const foldAscii = (s: string): string =>
26  s
27    .replace(/[\u2012-\u2015\u2212]/g, '-')
28    .replace(/[\u2018\u2019\u201a\u2032]/g, "'")
29    .replace(/[\u201c\u201d\u201e\u2033]/g, '"')
30    .replace(/\u2026/g, '...')
31    .replace(/\u2192/g, '->')
32    .replace(/[\u00a0\u2000-\u200b\u202f]/g, ' ')
33
34/** A list field, also when a client sent it JSON-encoded. */
35const listOf = (v: unknown): unknown => {
36  if (typeof v !== 'string') return v
37  try {
38    return JSON.parse(v)
39  } catch {
40    return v
41  }
42}
43
44export type AskInput = { question: string; short: string; options: string[]; blocking: boolean }
45
46/** brief_ask's input, checked; each error names the limit so the agent can retry. */
47export const validateAsk = (input: unknown): { ok: true; value: AskInput } | { ok: false; error: string } => {
48  const o = (input ?? {}) as { question?: unknown; short?: unknown; options?: unknown; blocking?: unknown }
49  if (typeof o.question !== 'string' || clean(o.question) === '') return { ok: false, error: 'question is required' }
50  const question = clean(foldAscii(o.question))
51  if (question.length > MAX_QUESTION) return { ok: false, error: `question is ${question.length} characters; keep it to ${MAX_QUESTION}` }
52  if (typeof o.short !== 'string' || clean(o.short) === '') return { ok: false, error: `short is required: the question in at most ${MAX_SHORT} characters` }
53  const short = clean(foldAscii(o.short))
54  if (short.length > MAX_SHORT) return { ok: false, error: `short is ${short.length} characters; keep it to ${MAX_SHORT}` }
55  const raw = listOf(o.options)
56  if (!Array.isArray(raw) || raw.length < 2 || raw.length > MAX_OPTIONS) {
57    return { ok: false, error: `options must be a list of 2 to ${MAX_OPTIONS} choices, your default first` }
58  }
59  const options: string[] = []
60  for (const x of raw) {
61    if (typeof x !== 'string' || clean(x) === '') return { ok: false, error: 'each option is a non-empty string' }
62    const opt = clean(foldAscii(x))
63    // Eval: on a bare limit error the agent swapped its preferred choice for a shorter one. Say to shorten the label.
64    if (opt.length > MAX_OPTION) {
65      return { ok: false, error: `option "${opt}" is ${opt.length} characters; keep each to ${MAX_OPTION}. Keep your choice and shorten its label (put the full name in the question)` }
66    }
67    if (options.includes(opt)) return { ok: false, error: `option "${opt}" is listed twice` }
68    options.push(opt)
69  }
70  const all = [question, short, ...options]
71  if (!all.every(s => /^[\x20-\x7e]*$/.test(s))) return { ok: false, error: 'use plain ASCII characters in the question, short and options' }
72  return { ok: true, value: { question, short, options, blocking: o.blocking === true } }
73}
74
75export type NoteInput = { goal?: string; doneWhen?: DoneItem[]; met?: string[]; assumption?: string }
76
77/** brief_note's input. doneWhen items are strings (`[x] ` marks one met) or `{ text, met }`; `met` ticks checks by name. */
78export const validateNote = (input: unknown): { ok: true; value: NoteInput } | { ok: false; error: string } => {
79  const o = (input ?? {}) as { goal?: unknown; doneWhen?: unknown; met?: unknown; assumption?: unknown }
80  const out: NoteInput = {}
81  if (o.goal !== undefined) {
82    if (typeof o.goal !== 'string' || clean(o.goal) === '') return { ok: false, error: 'goal is one line' }
83    const goal = clean(o.goal)
84    if (goal.length > MAX_GOAL) return { ok: false, error: `goal is ${goal.length} characters; keep it to ${MAX_GOAL}` }
85    out.goal = goal
86  }
87  if (o.doneWhen !== undefined) {
88    const raw = listOf(o.doneWhen)
89    if (!Array.isArray(raw) || raw.length > 8) return { ok: false, error: 'doneWhen is a list of at most 8 checks' }
90    const items: DoneItem[] = []
91    for (const x of raw) {
92      let item: DoneItem
93      if (typeof x === 'string') {
94        const m = /^\s*\[( |x|X)\]\s*(.*)$/.exec(x)
95        item = { text: clean(m === null ? x : (m[2] as string)), met: m !== null && m[1] !== ' ' }
96      } else if (x !== null && typeof x === 'object' && typeof (x as { text?: unknown }).text === 'string') {
97        item = { text: clean((x as { text: string }).text), met: (x as { met?: unknown }).met === true }
98      } else return { ok: false, error: 'each doneWhen item is a string or { text, met }' }
99      // Eval 2026-10-18: a check cut at 40 hid its end from the person and failed met by its full text. Refuse instead.
100      if (item.text.length > MAX_CHECK) return { ok: false, error: `check "${item.text}" is ${item.text.length} characters; keep each to ${MAX_CHECK}` }
101      if (item.text !== '') items.push(item)
102    }
103    out.doneWhen = items
104  }
105  if (o.met !== undefined) {
106    const raw = listOf(o.met)
107    const list = typeof raw === 'string' ? [raw] : raw
108    if (!Array.isArray(list) || !list.every(x => typeof x === 'string')) return { ok: false, error: 'met is a list of done-when checks, by their text' }
109    out.met = list.map(x => clean(x)).filter(x => x !== '')
110  }
111  if (o.assumption !== undefined) {
112    if (typeof o.assumption !== 'string' || clean(o.assumption) === '') return { ok: false, error: 'assumption is one line' }
113    const assumption = clean(o.assumption)
114    if (assumption.length > MAX_ROW) return { ok: false, error: `assumption is ${assumption.length} characters; keep it to ${MAX_ROW}` }
115    out.assumption = assumption
116  }
117  if (out.goal === undefined && out.doneWhen === undefined && out.met === undefined && out.assumption === undefined) {
118    return { ok: false, error: 'give at least one of goal, doneWhen, met, assumption' }
119  }
120  return { ok: true, value: out }
121}
122
123const words = (s: string): string[] => s.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(w => w !== '')
124
125/**
126 * Ticks the checks `met` names, by whole words: the same words, or every word of the name in the check.
127 * A name with no words, or one that fits more than one unticked check, ticks nothing and comes back unmatched.
128 */
129export const applyMet = (items: readonly DoneItem[], met: readonly string[]): { items: DoneItem[]; unmatched: string[] } => {
130  const unmatched: string[] = []
131  const out = items.map(d => ({ ...d }))
132  for (const m of met) {
133    const want = words(m)
134    if (want.length === 0) {
135      unmatched.push(m)
136      continue
137    }
138    const same = out.filter(d => words(d.text).join(' ') === want.join(' '))
139    const covering = out.filter(d => {
140      const have = words(d.text)
141      return have.length > 0 && want.every(w => have.includes(w))
142    })
143    const pick = same.length === 1 ? same : covering.filter(d => !d.met).length === 1 ? covering.filter(d => !d.met) : covering.length === 1 ? covering : []
144    if (pick.length !== 1) unmatched.push(m)
145    else (pick[0] as DoneItem).met = true
146  }
147  return { items: out, unmatched }
148}
149
150/**
151 * A call refused because it needs an approval nobody could give (seen under `claude -p`). Core's own wordings, each
152 * anchored at the start: a failed command's output ("Exit code 1 ... requires approval from a reviewer") is not one.
153 * A person who declines at the prompt reads "The user doesn't want to proceed".
154 */
155export const NEEDS_APPROVAL = /^(This command (requires|uses shell operators that require) approval|This Bash command contains multiple operations\. The following parts? requires? approval|Multiple directory changes in one command require approval|[\w.-]+ in '[^']*' needs approval\.|Claude requested permissions to )/
156
157/**
158 * What the agent reads after such a refusal. Eval 2026-10-19 (s5): an `rm` refused this way was handed to the person
159 * in prose in every with-brief run, so the brief showed nothing waiting on them. Most refusals are commands the agent
160 * rewrites and runs another way, so the band does not show refusals itself: the agent decides at the moment it sees one.
161 */
162export const APPROVAL_HINT =
163  "brief: nobody could approve this call. Do it another way if there is one; if the person has to run or approve it, brief_ask it with blocking: true, so the band shows it waits on them."
164
165export const openQuestions = (qs: readonly Question[]): Question[] => qs.filter(q => q.status === 'open')
166
167/**
168 * The armed ask: the one already armed while it is open, so hotkeys never renumber under the person;
169 * else a blocking ask, else the oldest.
170 */
171export const pickArmed = (qs: readonly Question[], armed: string | null): string | null => {
172  const open = openQuestions(qs)
173  if (armed !== null && open.some(q => q.id === armed)) return armed
174  const next = open.find(q => q.blocking) ?? open[0]
175  return next?.id ?? null
176}
177
178/** Non-blocking agent asks whose default has applied by `now`. */
179export const expired = (qs: readonly Question[], now: number): Question[] =>
180  openQuestions(qs).filter(q => q.kind === 'agent' && !q.blocking && now - q.at >= DEFAULT_MS)
181
182/** At most MAX_ROW characters; a cut ends in "...", so it shows. */
183export const cutRow = (s: string): string => (s.length <= MAX_ROW ? s : `${s.slice(0, MAX_ROW - 3)}...`)
184
185/** What the agent reads when the person answers; undefined when nothing needs saying. */
186export const answerRow = (q: Question, option: string): string | undefined => {
187  if (q.kind === 'agent') {
188    const first = q.options[0] as string
189    const follow = q.blocking ? `Resume with ${option}.` : option === first ? `Keep going with ${option}.` : `Switch from ${first} to ${option}.`
190    return cutRow(`[brief] ${q.id} -> ${option} (answered by the person). ${follow}`)
191  }
192  if (q.kind === 'drift') {
193    const what = q.question.replace(/ isn't in done-when$/, '')
194    return option === 'keep'
195      ? cutRow(`[brief] ${q.id} -> keep (answered by the person). "${what}" is now in done-when.`)
196      : cutRow(`[brief] ${q.id} -> drop (answered by the person). Stop work on "${what}"; it isn't in done-when.`)
197  }
198  // A default that applied: keeping it needs no word; dropping it does.
199  if (option === 'keep') return undefined
200  // The default ask's own id, so a row sent by another channel closes this ask; the original is named in the text.
201  return cutRow(`[brief] ${q.id} -> drop (answered by the person). Undo the default "${q.answer ?? ''}" of ${q.ref ?? 'the ask'}; ask again if it matters.`)
202}
203
204// Eval 2026-10-17: with "(you)" the agent read the row as its own and would not post on it.
205const ANSWER_ROW = /^\[brief\] (D\d+) -> (.+?) \(answered by the person\)\./
206
207/** The answers a `[brief]` row carries, one per line: how a row sent by any channel is matched to its ask. */
208export const parseAnswerRows = (text: string): { id: string; option: string }[] =>
209  text
210    .split('\n')
211    .map(l => ANSWER_ROW.exec(l.trim()))
212    .filter((m): m is RegExpExecArray => m !== null)
213    .map(m => ({ id: m[1] as string, option: m[2] as string }))
214
215/** Several events in one step become one row, one line each. */
216export const mergeRows = (rows: readonly string[]): string => rows.join('\n')
217
218/** At most `n` characters, cut at a word boundary where one is near. */
219export const cutWords = (s: string, n: number): string => {
220  if (s.length <= n) return s
221  const at = s.lastIndexOf(' ', n)
222  return at >= n / 2 ? s.slice(0, at) : s.slice(0, n)
223}
224
225export const driftQuestion = (id: string, what: string, turn: number, now: number): Question => {
226  const w = what.slice(0, MAX_QUESTION - 20)
227  return { id, kind: 'drift', question: `${w} isn't in done-when`, short: `${cutWords(w, MAX_SHORT - 1)}?`, options: ['keep', 'drop'], blocking: false, at: now, status: 'open', turn }
228}
229
230export const defaultQuestion = (id: string, from: Question, now: number): Question => {
231  const first = from.options[0] as string
232  return {
233    id,
234    kind: 'default',
235    question: `${from.short}: went with ${first}`.slice(0, MAX_QUESTION),
236    short: `Went with ${first}`.slice(0, MAX_SHORT),
237    options: ['keep', 'drop'],
238    blocking: false,
239    at: now,
240    status: 'open',
241    answer: first,
242    ref: from.id,
243  }
244}
245
246// --- the direction check ---
247
248export const checkPrompt = (goal: string, doneWhen: readonly DoneItem[]): string =>
249  [
250    'A direction check for the person running this session; do not continue the task.',
251    `Goal: ${goal}`,
252    `Done when: ${doneWhen.map(d => d.text).join('; ') || '(none)'}`,
253    'Did your last turn do work that serves none of the done-when checks? Reply with JSON only:',
254    '{"onTrack": true|false, "unplanned": ["<at most 30 characters each>"]}',
255    'List only real unplanned work (a new feature, an unrequested change), not setup, tests or fixes for a check.',
256  ].join('\n')
257
258export const parseCheck = (reply: string, turn: number): Check | undefined => {
259  const m = /\{[\s\S]*\}/.exec(reply)
260  if (m === null) return undefined
261  try {
262    const o = JSON.parse(m[0]) as { onTrack?: unknown; unplanned?: unknown }
263    const unplanned = Array.isArray(o.unplanned)
264      ? o.unplanned.filter((x): x is string => typeof x === 'string' && clean(x) !== '').map(x => clean(x).replace(/[^\x20-\x7e]/g, '').slice(0, 30)).slice(0, 3)
265      : []
266    return { turn, onTrack: o.onTrack !== false && unplanned.length === 0, unplanned }
267  } catch {
268    return undefined
269  }
270}
271
272// --- the /brief snapshot and brief_read ---
273
274export type BriefView = {
275  goal: string | null
276  doneWhen: readonly DoneItem[]
277  questions: readonly Question[]
278  steps: readonly Step[]
279  check: Check | null
280  changes: Changes
281  ctxPercent: number | undefined
282  assumptions: readonly string[]
283  now: number
284}
285
286const checkText = (d: DoneItem): string => `[${d.met ? 'x' : ' '}] ${d.text}`
287const doneWhenHead = (items: readonly DoneItem[]): string => `done when ${items.filter(d => d.met).length}/${items.length} met:`
288
289/**
290 * Where the session stands, in the words a returning person asks about. Eval 2026-10-18: without it the reader guessed
291 * the status (0.63). "finished" is the agent's own claim: every check it set is ticked and nothing waits on the person.
292 */
293export const statusText = (v: Pick<BriefView, 'doneWhen' | 'questions'>): string => {
294  const open = openQuestions(v.questions)
295  const blocking = open.filter(q => q.blocking)
296  if (blocking.length > 0) return `blocked on you (${blocking.map(q => q.id).join(', ')})`
297  // Only the agent's own asks default; a drift or a default's keep/drop waits for the person.
298  const waiting = open.filter(q => q.kind !== 'agent').map(q => q.id)
299  const going = open.filter(q => q.kind === 'agent').map(q => q.id)
300  const rest = going.length > 0 ? `; ${going.join(', ')} open, default applies` : ''
301  const allMet = v.doneWhen.length > 0 && v.doneWhen.every(d => d.met)
302  if (allMet && waiting.length === 0) return `finished${rest}`
303  if (allMet) return `waiting on you (${waiting.join(', ')})${rest}`
304  return `in progress${waiting.length > 0 ? `; ${waiting.join(', ')} waits on you` : ''}${rest}`
305}
306
307const questionText = (q: Question, now: number): string => {
308  const time = q.kind === 'drift' ? `after turn ${q.turn ?? 0}` : q.blocking ? mins(now - q.at) : q.kind === 'default' ? `${mins(now - q.at)} ago` : `default in ${mins(q.at + DEFAULT_MS - now)}`
309  return `${q.blocking ? '!' : '?'} ${q.question}  ${q.options.join(' / ')}  ${time}`
310}
311
312const changesText = (c: Changes, now: number): string | undefined => {
313  const parts = [...c.done]
314  if (c.asks > 0) parts.push(`${c.asks} ask${c.asks === 1 ? '' : 's'}`)
315  if (c.answers > 0) parts.push(`${c.answers} answer${c.answers === 1 ? '' : 's'}`)
316  if (c.edits > 0) parts.push(`${c.edits} file edit${c.edits === 1 ? '' : 's'}`)
317  if (parts.length === 0) return undefined
318  return `since ${mins(now - c.since)}  ${parts.join(', ')}`
319}
320
321const healthText = (v: BriefView): string | undefined => {
322  const parts: string[] = []
323  if (v.check !== null) {
324    parts.push(v.check.onTrack ? `on track after turn ${v.check.turn}` : `drift after turn ${v.check.turn}`)
325    if (v.check.unplanned.length > 0) parts.push(`unplanned: ${v.check.unplanned.join(', ')}`)
326  }
327  if (v.ctxPercent !== undefined) parts.push(`ctx ${Math.round(v.ctxPercent)}%`)
328  return parts.length === 0 ? undefined : parts.join('  ')
329}
330
331/** The /brief snapshot: goal, done-when, every open ask, what changed, health; no frame, empty lines left out. */
332export const snapshot = (v: BriefView): SnapLine[] => {
333  const lines: SnapLine[] = []
334  lines.push({ text: v.goal ?? 'No goal set (brief_note).', tone: v.goal === null ? 'dim' : 'goal' })
335  lines.push({ text: statusText(v), tone: 'dim' })
336  if (v.doneWhen.length > 0) {
337    lines.push({ text: doneWhenHead(v.doneWhen), tone: 'dim' })
338    for (const d of v.doneWhen) lines.push({ text: `  ${checkText(d)}`, tone: 'dim' })
339  }
340  for (const q of openQuestions(v.questions)) lines.push({ text: questionText(q, v.now), tone: q.blocking ? 'warning' : 'plain' })
341  const changed = changesText(v.changes, v.now)
342  if (changed !== undefined) lines.push({ text: changed, tone: 'dim' })
343  const health = healthText(v)
344  if (health !== undefined) lines.push({ text: health, tone: 'dim' })
345  return lines
346}
347
348/** brief_read: plain lines, one per check, for the agent before it says it is done. Every field is bounded where it is written. */
349export const readText = (v: BriefView): string => {
350  const lines: string[] = []
351  lines.push(`goal: ${v.goal ?? '(none; set it with brief_note)'}`)
352  lines.push(`status: ${statusText(v)}`)
353  if (v.doneWhen.length > 0) {
354    lines.push(doneWhenHead(v.doneWhen))
355    for (const d of v.doneWhen) lines.push(`  ${checkText(d)}`)
356  }
357  const open = openQuestions(v.questions)
358  for (const q of open.slice(0, 3)) lines.push(`open ${q.id}${q.blocking ? ' (blocking)' : ''}: ${q.question} [${q.options.join(' / ')}]`)
359  if (open.length > 3) lines.push(`+${open.length - 3} more open asks`)
360  const answered = v.questions.filter(q => q.status === 'answered' || q.status === 'defaulted').slice(-2)
361  for (const q of answered) lines.push(`${q.id}: ${q.status === 'defaulted' ? 'default applied' : 'answered'} ${q.answer ?? ''}`)
362  if (v.assumptions.length > 0) lines.push(`assumed: ${v.assumptions.slice(-2).join('; ')}`)
363  const health = healthText(v)
364  if (health !== undefined) lines.push(health)
365  return lines.join('\n')
366}
367
types/index.d.ts 87 lines
1// --- the band: what the agent asks, what the hooks observe ---
2
3/** Who raised a question: the agent through brief_ask, or the mod itself. */
4export type QuestionKind = 'agent' | 'drift' | 'default'
5
6export type Question = {
7  /** `D<n>`, what the agent's rows name */
8  id: string
9  kind: QuestionKind
10  question: string
11  short: string
12  /** options[0] is the default, or the safe choice when blocking */
13  options: string[]
14  blocking: boolean
15  at: number
16  status: 'open' | 'answered' | 'defaulted' | 'closed'
17  /** the option the person picked (or the default that applied) */
18  answer?: string
19  /** drift: the main-loop turn the check ran after */
20  turn?: number
21  /** default: the agent question whose default applied */
22  ref?: string
23}
24
25/** An answer held for the undo window before it goes to the agent. */
26export type Pending = { id: string; option: string; at: number }
27
28export type StepStatus = 'pending' | 'in_progress' | 'completed'
29
30/** One step of the agent's own task list, from its task tool's calls. */
31export type Step = { id: string; subject: string; status: StepStatus }
32
33export type DoneItem = { text: string; met: boolean }
34
35/** In-flight background work, from classic.Stop's background_tasks. */
36export type Job = { id: string; label: string; since: number }
37
38/** A wakeup the session has scheduled, from classic.Stop's session_crons. */
39export type Cron = { id: string; schedule: string; recurring: boolean; seenAt: number }
40
41/** The last direction check's verdict. */
42export type Check = { turn: number; onTrack: boolean; unplanned: string[] }
43
44/** What changed since the person last looked, for the /brief snapshot. */
45export type Changes = { since: number; done: string[]; asks: number; answers: number; edits: number }
46
47export type SnapTone = 'goal' | 'dim' | 'warning' | 'plain'
48
49export type SnapLine = { text: string; tone: SnapTone }
50
51declare module 'claude-code' {
52  interface PluginState {
53    brief: {
54      goal: string | null
55      doneWhen: DoneItem[]
56      assumptions: string[]
57      questions: Question[]
58      /** the ask whose hotkeys are live; it stays armed until it closes */
59      armed: string | null
60      pending: Pending | null
61      nextId: number
62      steps: Step[]
63      /** whether the agent has a task tool this session */
64      hasTaskTool: boolean
65      jobs: Job[]
66      crons: Cron[]
67      /** whether a main-loop turn is running */
68      isWorking: boolean
69      startedAt: number
70      endedAt: number
71      turn: number
72      check: Check | null
73      changes: Changes
74      /** rows waiting to reach the agent, merged into one */
75      outbox: string[]
76      /** a row appended mid-turn that no model request has read yet */
77      unread: string | null
78      /** drift the person kept: never asked about again */
79      kept: string[]
80      /** the session id the state belongs to; a /clear or a resume moves the process to another */
81      sid: string | null
82      /** the /brief snapshot as it was when the command ran */
83      snapshot: SnapLine[]
84    }
85  }
86}
87