One global ledger of the todos, parked work, proposals and discussions you and Claude leave behind, across every project, in a ToDo's sidebar

A Claude Code mod that keeps one global ledger of the work you and Claude leave behind: todos, parked or deferred items, proposals and discussions, from every project and session. It lives in a ToDo's sidebar in the desktop app and the terminal.
/todo add.Tested on Windows; macOS and Linux are ported and unit-tested but not yet run on real machines. Requires Claude Code v2.1.287 or later (mods support).
Website and docs: https://samact.github.io/todo-ledger/ (a live copy of the sidebar you can click through, plus the full command and tool reference).
In Claude Code:
/plugin marketplace add SamAct/todo-ledger
/plugin install todo-ledger@todo-ledger
Then start a new session (or run /reload-plugins). A ☰ ToDo's button appears in the prompt footer.
☰ ToDo's N: opens the sidebar. N is this project's open items.This project ▾ switches to all projects; tabs Agent / Human / Done; items grouped by what they need (Needs decision, To do, Discussion, Parked). Click an item to open its card.s start, d done, x drop, n note, a approve.Commands:
| Command | Does | ||
|---|---|---|---|
/todos | Toggle the sidebar | ||
/todos list [all] | Print open items (this project, or all) | ||
/todos refresh | Reload items written by other sessions | ||
| `/todo add [-d\ | -p\ | -n] <text>` | Add a todo (-d deferred, -p proposal, -n discussion) |
/todo done <id> | Mark an item done | ||
/todo delete <id> | Delete a dropped item forever |
Claude gets four tools: park_item, list_items, get_item and update_item. It keeps the ledger current by itself, and agents can only drop items, never delete them.
One JSON file per item in ~/.claude/todo-ledger/items/ (%USERPROFILE%\.claude\todo-ledger\items\ on Windows). Every Claude Code session on the machine shares it; open panes pick up changes within about 10 seconds. Nothing leaves your machine except the end-of-turn scan, which sends the last reply to Claude Haiku through your own Claude Code session.
claude plugin validate . --strict
claude plugin test .
claude --plugin-dir .
MIT
hooks/register.ts 1108 lines1import { formatItem, formatList, parseTodoCommand, parseTodosArgs } from '../src/commands.ts'
2import { SCAN_SYSTEM, buildScanPrompt, parseScanReply, parseScanUpdates, shouldScan } from '../src/scan.ts'
3import type { ScanUpdate } from '../src/scan.ts'
4import { KINDS, cleanTitle, clip, dedupeKey, wrapLines, isOpen, lastSessionTitle, makeItem, parseItem, randomHex4, sessionLabel, similarTitle } from '../src/item.ts'
5import type { Item, Kind, Origin, Source, Status } from '../src/item.ts'
6import { batchPrompt, fallbackArgv, startOptions, startPrompt, terminalArgv, terminalTask } from '../src/start.ts'
7import type { StartChoice } from '../src/start.ts'
8import { TABS, age, bandLabel, displayOrder, firstView, groupItems, itemsForTab, tabOf } from '../src/view.ts'
9import type { Tab } from '../src/view.ts'
10import { THEMES, nextTheme, themeById, withAlpha } from '../src/theme.ts'
11import type { Theme } from '../src/theme.ts'
12
13// Every function below that takes $ must stay top-level in this file: the validator
14// rejects passing $ into functions imported from other files.
15
16let cache: Item[] = []
17const reportedBad = new Set<string>()
18let parkedThisTurn = false
19// True while the main loop is answering; a prompt sent then waits for the reply to end.
20let replying = false
21let lastUserText = ''
22let deletingId: string | null = null
23const STATUS_VALUES = ['open', 'in_progress', 'done', 'dropped']
24// What the card shows under an item's title, asked of every agent that adds one.
25const DETAIL_HINT = 'Optional but recommended: 2 to 4 short sentences in plain English, no jargon: what this task is ' +
26 'and why it is proposed or parked. Shown to the user in the item\'s card.'
27
28const PANE = 'todo-ledger'
29// The dock width asked for on open; a width the person dragged wins (the engine has no minimum).
30const PANE_COLUMNS = 72
31let paneOpen = false
32let tab: Tab = 'agent'
33let allProjects = false
34let expandedId: string | null = null
35let notingId: string | null = null
36let startingId: string | null = null
37let allNotesId: string | null = null
38// What is typed in the note field, mirrored so a wrapped preview can show it (the field
39// itself is one line). It belongs to draftFor and resets when another item is being noted.
40let noteDraft = ''
41let draftFor: string | null = null
42// One pending preview redraw at a time; it lands this long after the first key of a burst.
43let previewTimer = false
44const PREVIEW_MS = 300
45// Items picked with Queue, in the order they were picked. In memory only: a stale
46// queue must never send by surprise after a restart.
47const queue = new Set<string>()
48// The list draws its first LIST_LIMIT rows (in display order) until the person asks for all:
49// fewer elements per draw keeps presses responsive on a long ledger.
50const LIST_LIMIT = 40
51let showAllRows = false
52let cwd = ''
53// One accent colour for what needs attention (the open card, the decision mark,
54// started items); everything else is hierarchy by weight, dimming and spacing.
55// A theme key, so light and dark themes both fit.
56// These follow the chosen theme (src/theme.ts); applyTheme sets them all at once.
57let theme: Theme = THEMES[0]
58let ACCENT = theme.accent
59// Faint tints for a row's project, session and age.
60let META = { project: theme.project, session: theme.session, age: theme.age }
61// The same hues at low alpha, as pill backgrounds on the desktop. A coloured area
62// behind a plain Button keeps it pressable (a Button's own text takes no colour).
63let META_BG = { project: withAlpha(theme.project, 0.18), session: withAlpha(theme.session, 0.18), age: withAlpha(theme.age, 0.18) }
64// Behind the rows captured in the session being used, on the desktop (about 8% alpha).
65let THIS_SESSION_BG = withAlpha(theme.tint, 0.08)
66// A very light wash over the whole pane on the desktop; the default theme has none.
67let PANE_WASH: string | undefined
68function applyTheme(t: Theme) {
69 theme = t
70 ACCENT = t.accent
71 META = { project: t.project, session: t.session, age: t.age }
72 META_BG = { project: withAlpha(t.project, 0.18), session: withAlpha(t.session, 0.18), age: withAlpha(t.age, 0.18) }
73 THIS_SESSION_BG = withAlpha(t.tint, 0.08)
74 PANE_WASH = t.id === 'ledger' ? undefined : withAlpha(t.tint, 0.05)
75}
76const CLOSED_MEMORY_MS = 30 * 86_400_000
77let lastLoadAt = 0
78const REFRESH_MS = 5000
79const SYNC_MS = 10_000
80let folderSig = ''
81// TodoWrite entries (by dedupe key) already linked to a ledger item in this session.
82const linked = new Map<string, string>()
83
84// The machine the session runs on: Windows uses USERPROFILE, '\' and cmd; macOS and
85// Linux use HOME, '/' and POSIX tools. Read once, from the environment.
86let host: { win: boolean; sep: string; home: string } | null = null
87
88async function hostOf($: any): Promise<{ win: boolean; sep: string; home: string }> {
89 if (host) return host
90 const win = (await $.env.get('OS')) === 'Windows_NT'
91 const home = (win ? await $.env.get('USERPROFILE') : undefined) || (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
92 if (!home) throw new Error('Neither HOME nor USERPROFILE is set, so the ledger folder cannot be found')
93 host = { win, sep: win ? '\\' : '/', home }
94 return host
95}
96
97// Moves a file over another, replacing it (how a save lands in one step).
98async function moveFile($: any, from: string, to: string): Promise<{ exitCode: number; stderr: string }> {
99 const h = await hostOf($)
100 return $.process.run(h.win ? ['cmd', '/c', 'move', '/y', from, to] : ['mv', '-f', from, to])
101}
102
103async function removeFile($: any, path: string): Promise<{ exitCode: number; stderr: string }> {
104 const h = await hostOf($)
105 return $.process.run(h.win ? ['cmd', '/c', 'del', '/q', path] : ['rm', '-f', path])
106}
107
108async function ledgerDir($: any): Promise<string> {
109 const h = await hostOf($)
110 return [h.home, '.claude', 'todo-ledger'].join(h.sep)
111}
112
113async function sep($: any): Promise<string> {
114 return (await hostOf($)).sep
115}
116
117async function itemsDir($: any): Promise<string> {
118 return (await ledgerDir($)) + (await sep($)) + 'items'
119}
120
121async function loadAll($: any): Promise<Item[]> {
122 const dir = await itemsDir($)
123 lastLoadAt = await $.clock.now()
124 if (!(await $.fs.exists(dir))) { cache = []; return cache }
125 const entries = await $.fs.list(dir)
126 const items: Item[] = []
127 for (const entry of entries) {
128 if (!entry.name.endsWith('.json')) continue
129 // A read can reject (over 4 MiB, permission, removed since the list); treat it like bad JSON.
130 let text: string | null
131 try { text = await $.fs.read(dir + (await sep($)) + entry.name) } catch { text = null }
132 const item = text === null ? null : parseItem(text)
133 if (item) items.push(item)
134 else if (!reportedBad.has(entry.name)) {
135 reportedBad.add(entry.name)
136 $.ui.log('skipped unreadable item file ' + entry.name)
137 }
138 }
139 cache = items
140 folderSig = signatureOf(entries)
141 return items
142}
143
144// What the items folder looks like on disk: changes when any session adds,
145// edits (size or mtime) or removes an item file.
146function signatureOf(entries: { name: string; size?: number; mtimeMs?: number }[]): string {
147 return entries
148 .filter((x) => x.name.endsWith('.json'))
149 .map((x) => x.name + ':' + (x.size ?? 0) + ':' + (x.mtimeMs ?? 0))
150 .sort()
151 .join('|')
152}
153
154// Background check: one directory listing; reload and redraw only when another
155// session (CLI or desktop) changed the folder since our last load.
156async function syncIfChanged($: any): Promise<void> {
157 try {
158 const dir = await itemsDir($)
159 const entries = (await $.fs.exists(dir)) ? await $.fs.list(dir) : []
160 if (signatureOf(entries) === folderSig) return
161 await loadAll($)
162 $.ui.invalidate('ui.render')
163 } catch { /* a failed check waits for the next tick */ }
164}
165
166// The pane's Refresh button and `/todos refresh`.
167async function forceRefresh($: any): Promise<number> {
168 await loadAll($)
169 $.ui.invalidate('ui.render')
170 return cache.length
171}
172
173async function saveItem($: any, item: Item): Promise<void> {
174 // $.fs.write creates missing parent directories, so no separate mkdir step.
175 const dir = await itemsDir($)
176 const path = dir + (await sep($)) + item.id + '.json'
177 await $.fs.write(path + '.tmp', JSON.stringify(item, null, 2))
178 const r = await moveFile($, path + '.tmp', path)
179 if (r.exitCode !== 0) throw new Error('could not save ' + item.id + ': ' + r.stderr.trim())
180 cache = [...cache.filter((i) => i.id !== item.id), item]
181 $.ui.invalidate('ui.render')
182}
183
184// The session's name (its tab title). The mods API has no call for it, so it is
185// read from the transcript's `custom-title` lines; null for an unnamed session.
186let sessionName: string | null = null
187let transcriptPath: string | null = null
188
189async function lookupSessionName($: any): Promise<string | null> {
190 try {
191 if (!transcriptPath) {
192 const id = await $.session.id()
193 const h = await hostOf($)
194 const projects = [h.home, '.claude', 'projects'].join(h.sep)
195 const found = await $.process.run(h.win
196 ? ['cmd', '/c', 'dir', '/s', '/b', projects + h.sep + id + '.jsonl']
197 : ['find', projects, '-name', id + '.jsonl'])
198 const first = found.exitCode === 0 ? found.stdout.split(/\r?\n/).find((l: string) => l.trim()) : undefined
199 if (!first) return sessionName
200 transcriptPath = first.trim()
201 }
202 // findstr / grep print only lines that begin with a title record, so a large
203 // transcript is never read whole (`.` matches the quotes in the regex).
204 const r = await $.process.run((await hostOf($)).win
205 ? ['findstr', '/r', '/b', '/c:{.type.:.custom-title.', transcriptPath]
206 : ['grep', '^{.type.:.custom-title.', transcriptPath])
207 sessionName = lastSessionTitle(r.stdout) ?? sessionName
208 } catch { /* keep the last known name */ }
209 return sessionName
210}
211
212async function capture(
213 $: any,
214 f: { title: string; kind: Kind; origin: Origin; source: Source; body?: string },
215): Promise<{ item: Item; isNew: boolean }> {
216 const project = await $.session.cwd()
217 const items = await loadAll($)
218 const key = dedupeKey(f.title, project)
219 const now = await $.clock.now()
220 const at = new Date(now).toISOString()
221 // Same item when the title matches exactly, or is a rewording of an open item in this project.
222 const existing = items.find((i) => isOpen(i) && dedupeKey(i.title, i.project) === key) ??
223 items.find((i) => isOpen(i) && i.project.toLowerCase() === project.toLowerCase() && similarTitle(i.title, f.title))
224 if (existing) {
225 // The scan re-reading a known item says nothing new; a note per turn was only noise.
226 if (f.source === 'scan' || f.source === 'todowrite') return { item: existing, isNew: false }
227 const reworded = dedupeKey(existing.title, existing.project) !== key ? ' as "' + cleanTitle(f.title) + '"' : ''
228 const text = 'Captured again (' + f.source + ')' + reworded + (f.body ? ': ' + f.body : '')
229 if (existing.notes.at(-1)?.text === text) return { item: existing, isNew: false }
230 const updated = { ...existing, updatedAt: at, notes: [...existing.notes, { by: f.origin, text, at }] }
231 await saveItem($, updated)
232 return { item: updated, isNew: false }
233 }
234 // The scan must not bring back what was just finished or turned down when a
235 // later reply mentions it again; a person or an agent asking on purpose still can.
236 if (f.source === 'scan') {
237 const closed = items.find((i) => !isOpen(i) && i.project.toLowerCase() === project.toLowerCase() &&
238 now - Date.parse(i.updatedAt) < CLOSED_MEMORY_MS && (dedupeKey(i.title, i.project) === key || similarTitle(i.title, f.title)))
239 if (closed) return { item: closed, isNew: false }
240 }
241 const sessionId = await $.session.id()
242 const name = sessionName ?? (await lookupSessionName($))
243 const dir = await itemsDir($)
244 // Ids are second-resolution plus 4 hex chars and `move /y` overwrites, so check before the first write.
245 let item = makeItem({ ...f, title: cleanTitle(f.title), project, sessionId, sessionName: name ?? undefined, nowMs: now, hex4: randomHex4() })
246 for (let tries = 0; tries < 5 && (await $.fs.exists(dir + (await sep($)) + item.id + '.json')); tries++) {
247 item = makeItem({ ...f, title: cleanTitle(f.title), project, sessionId, sessionName: name ?? undefined, nowMs: now, hex4: randomHex4() })
248 }
249 await saveItem($, item)
250 return { item, isNew: true }
251}
252
253// Called while drawing: one folder listing at most every few seconds, and a full
254// reload only when the folder changed (reading every item file per draw was slow).
255async function refreshIfStale($: any): Promise<void> {
256 try {
257 const now = await $.clock.now()
258 if (now - lastLoadAt < REFRESH_MS) return
259 lastLoadAt = now
260 await syncIfChanged($)
261 } catch { /* keep the old cache; the next command or tool reports the error */ }
262}
263
264async function setStatus($: any, id: string, status: Status, note?: string): Promise<Item | null> {
265 const items = await loadAll($)
266 const found = items.filter((i) => i.id.startsWith(id))
267 if (found.length !== 1) return null
268 const at = new Date(await $.clock.now()).toISOString()
269 const notes = note ? [...found[0].notes, { by: 'agent' as Origin, text: note, at }] : found[0].notes
270 const updated = { ...found[0], status, updatedAt: at, notes }
271 await saveItem($, updated)
272 return updated
273}
274
275async function mirrorTodos($: any, todos: { content: string; status: string }[]): Promise<void> {
276 const project = await $.session.cwd()
277 const sessionId = await $.session.id()
278 for (const todo of todos) {
279 if (typeof todo?.content !== 'string' || !todo.content.trim()) continue
280 const items = await loadAll($)
281 const key = dedupeKey(todo.content, project)
282 const sameKey = (i: Item) => dedupeKey(i.title, i.project) === key
283 // Link to this session's earlier mirror, else to any open item with the same key and project
284 // (parked, scanned or manual), so repeated TodoWrite calls never add "Captured again" notes.
285 const linkedId = linked.get(key)
286 const mine =
287 (linkedId ? items.find((i) => i.id === linkedId) : undefined) ??
288 items.find((i) => i.source === 'todowrite' && i.sessionId === sessionId && sameKey(i)) ??
289 items.find((i) => isOpen(i) && sameKey(i))
290 const status: Status = todo.status === 'completed' ? 'done' : todo.status === 'in_progress' ? 'in_progress' : 'open'
291 if (mine) {
292 linked.set(key, mine.id)
293 if (mine.status !== status && isOpen(mine)) {
294 await saveItem($, { ...mine, status, updatedAt: new Date(await $.clock.now()).toISOString() })
295 }
296 continue
297 }
298 if (status === 'done') continue
299 const r = await capture($, { title: todo.content, kind: 'todo', origin: 'agent', source: 'todowrite' })
300 linked.set(key, r.item.id)
301 if (r.isNew && status !== 'open') await saveItem($, { ...r.item, status })
302 }
303 // TodoWrite sends the whole list each time: an entry it no longer carries was
304 // removed from the session's plan, so its mirror is dropped rather than left open forever.
305 const keep = new Set(todos.filter((t) => typeof t?.content === 'string').map((t) => dedupeKey(t.content, project)))
306 const at = new Date(await $.clock.now()).toISOString()
307 for (const i of await loadAll($)) {
308 if (i.source !== 'todowrite' || i.sessionId !== sessionId || !isOpen(i) || keep.has(dedupeKey(i.title, i.project))) continue
309 await saveItem($, { ...i, status: 'dropped', updatedAt: at, notes: [...i.notes, { by: 'agent' as Origin, text: 'removed from the session\'s task list', at }] })
310 }
311}
312
313// What the scan concluded about an open item, applied with a note saying why.
314async function applyUpdate($: any, item: Item, u: ScanUpdate): Promise<void> {
315 const at = new Date(await $.clock.now()).toISOString()
316 const note = (text: string) => [...item.notes, { by: 'agent' as Origin, text, at }]
317 if (u.action === 'approve') {
318 await saveItem($, { ...item, kind: item.kind === 'proposal' ? 'todo' : item.kind, updatedAt: at, notes: note('approved by the user (seen by the end-of-turn scan)') })
319 } else if (u.action === 'reject') {
320 await saveItem($, { ...item, status: 'dropped', updatedAt: at, notes: note('rejected by the user (seen by the end-of-turn scan)') })
321 } else if (u.action === 'done') {
322 await saveItem($, { ...item, status: 'done', updatedAt: at, notes: note('done (seen by the end-of-turn scan)') })
323 } else {
324 await saveItem($, { ...item, status: 'dropped', updatedAt: at, notes: note('duplicate of ' + u.of + ' (seen by the end-of-turn scan)') })
325 }
326}
327
328async function runScan($: any, answer: string, userText: string): Promise<void> {
329 try {
330 const project = (await $.session.cwd()).toLowerCase()
331 const open = (await loadAll($)).filter((i) => isOpen(i) && i.project.toLowerCase() === project)
332 const r = await $.model.complete({
333 model: 'haiku',
334 system: SCAN_SYSTEM,
335 prompt: buildScanPrompt(answer, open.map((i) => ({ id: i.id, title: i.title, kind: i.kind })), userText),
336 maxTokens: 1200,
337 timeoutMs: 20000,
338 })
339 if (!r.isAnswered) { $.ui.log('scan skipped: ' + r.reason); return }
340 const found = parseScanReply(r.text)
341 if (!found) { $.ui.log('scan skipped: reply was not JSON'); return }
342 // Updates first, against the items the prompt listed, so new captures cannot be touched.
343 for (const u of parseScanUpdates(r.text, open.map((i) => i.id))) {
344 const item = open.find((i) => i.id === u.id)
345 if (item) await applyUpdate($, item, u)
346 }
347 for (const f of found) await capture($, { title: f.title, kind: f.kind, origin: 'agent', source: 'scan', body: f.detail })
348 } catch (err: any) {
349 $.ui.log('scan skipped: ' + err.message)
350 }
351}
352
353async function togglePane($: any): Promise<void> {
354 if (paneOpen) {
355 paneOpen = false
356 await $.ui.close({ id: PANE })
357 return
358 }
359 try { await loadAll($) } catch (err: any) { $.ui.toast('Ledger not loaded: ' + err.message) }
360 // Open on something to look at: a tab with items, and every project when this one has none.
361 let here = cwd
362 try { here = await $.session.cwd() } catch { /* keep the session.start value */ }
363 const view = firstView(cache, here, tab, allProjects)
364 tab = view.tab
365 allProjects = view.allProjects
366 const r = await $.ui.open({ id: PANE, title: "ToDo's", focus: true, closeOnEscape: true, columns: PANE_COLUMNS })
367 // Only a placed pane counts as open; otherwise the next press must try to open it again.
368 paneOpen = r?.isPlaced === true
369 if (!paneOpen) $.ui.toast("Could not open the ToDo's pane: " + (r?.reason ?? 'unknown reason'))
370 $.ui.invalidate('ui.render')
371}
372
373async function safeToggle($: any): Promise<void> {
374 try { await togglePane($) } catch (err: any) { $.ui.toast("ToDo's pane failed: " + err.message) }
375}
376
377async function markStatus($: any, id: string, status: Status): Promise<void> {
378 try { await setStatus($, id, status) } catch (err: any) { $.ui.toast('ToDo not saved: ' + err.message) }
379}
380
381async function addNote($: any, id: string, text: string): Promise<void> {
382 const item = cache.find((i) => i.id === id)
383 if (!item || !text.trim()) return
384 const at = new Date(await $.clock.now()).toISOString()
385 try {
386 await saveItem($, { ...item, updatedAt: at, notes: [...item.notes, { by: 'human' as Origin, text: text.trim(), at }] })
387 } catch (err: any) {
388 $.ui.toast('Note not saved: ' + err.message)
389 }
390}
391
392async function copyText($: any, text: string, okMessage: string, failPrefix: string): Promise<void> {
393 const r = await $.ui.copy({ text })
394 $.ui.toast(r?.isCopied ? okMessage : failPrefix + ' (' + (r?.reason ?? 'unknown') + ')')
395}
396
397async function doStart($: any, item: Item, choice: StartChoice): Promise<void> {
398 const text = startPrompt(item, cwd || (await $.session.cwd()))
399 try {
400 if (choice === 'send') {
401 await saveItem($, { ...item, status: 'in_progress', updatedAt: new Date(await $.clock.now()).toISOString() })
402 // A plugin's prompt waits until Claude is idle, so say so at once instead of
403 // looking like nothing happened while a reply is still running.
404 $.ui.toast(replying ? 'Queued: starts when the current reply finishes' : 'Sending: ' + clip(item.title, 40))
405 let dropped: string | null = null
406 try {
407 const r = await $.prompt.submit({ text, asUser: true })
408 if (r && typeof r.drop === 'string') dropped = r.drop
409 } catch (err: any) { dropped = err.message }
410 if (dropped !== null) {
411 await saveItem($, { ...item, updatedAt: new Date(await $.clock.now()).toISOString() })
412 $.ui.toast('Prompt not sent: ' + dropped)
413 }
414 } else if (choice === 'draft') {
415 const r = await $.prompt.fill({ text })
416 if (!r.isFilled) await copyText($, text, 'Could not fill the prompt; copied instead', 'Could not fill or copy the prompt')
417 } else if (choice === 'copy') {
418 await copyText($, text, 'Prompt copied', 'Prompt not copied')
419 } else {
420 // The full prompt goes in a file; the command line carries a one-line pointer to it.
421 const s = await sep($)
422 const file = (await ledgerDir($)) + s + 'start' + s + item.id + '.md'
423 await $.fs.write(file, text)
424 const task = terminalTask(item.id, file)
425 let ok = false
426 // Opening a new terminal window is wired for Windows (wt, else cmd start); elsewhere the prompt is copied.
427 if (!(await hostOf($)).win) {
428 await copyText($, text, 'Prompt copied: start claude in a new terminal and paste it', 'Prompt not copied')
429 return
430 }
431 try { ok = (await $.process.run(terminalArgv(item.project, task))).exitCode === 0 } catch { ok = false }
432 if (!ok) {
433 try { ok = (await $.process.run(fallbackArgv(item.project, task))).exitCode === 0 } catch { ok = false }
434 }
435 if (!ok) await copyText($, text, 'Could not open a terminal; prompt copied instead', 'Could not open a terminal or copy the prompt')
436 }
437 } catch (err: any) {
438 $.ui.toast('Start failed: ' + err.message)
439 }
440}
441
442// Sends every queued item as one prompt; the agent decides how to run them.
443async function sendQueued($: any, items: Item[]): Promise<void> {
444 if (!items.length) return
445 const text = batchPrompt(items, cwd || (await $.session.cwd()))
446 try {
447 const stamp = new Date(await $.clock.now()).toISOString()
448 for (const item of items) await saveItem($, { ...item, status: 'in_progress', updatedAt: stamp })
449 $.ui.toast(replying ? 'Queued: starts when the current reply finishes' : 'Sending ' + items.length + ' items')
450 let dropped: string | null = null
451 try {
452 const r = await $.prompt.submit({ text, asUser: true })
453 if (r && typeof r.drop === 'string') dropped = r.drop
454 } catch (err: any) { dropped = err.message }
455 if (dropped !== null) {
456 const back = new Date(await $.clock.now()).toISOString()
457 for (const item of items) await saveItem($, { ...item, updatedAt: back })
458 $.ui.toast('Prompt not sent: ' + dropped)
459 return
460 }
461 queue.clear()
462 } catch (err: any) {
463 $.ui.toast('Send failed: ' + err.message)
464 }
465}
466
467// The Start step: one button per way to start, in place of the card's actions, so
468// a choice is a single press (a picker needed focus, arrows and Enter). The first
469// is the main one; Cancel is plain and dim so it never competes.
470function startChooser($: any, e: any, item: Item) {
471 const { Button } = $.ui.resolve(e)
472 const redraw = () => $.ui.invalidate('ui.render')
473 return [
474 ...startOptions(e.surface === 'desktop' ? 'desktop' : 'terminal').map((o, k) =>
475 Button({ key: 'start-' + o.value + '-' + item.id, label: o.label, hotkey: o.hotkey,
476 ...(k === 0 ? { variant: 'primary' as const, autoFocus: true as const } : { plain: true as const }),
477 onPress: async () => { startingId = null; await doStart($, item, o.value as StartChoice); redraw() } })),
478 Button({ key: 'start-cancel-' + item.id, label: 'Cancel', plain: true, dimColor: true, onPress: () => { startingId = null; redraw() } }),
479 ]
480}
481
482// Permanent deletion: only for items already dropped, only by the person (pane or
483// /todo delete). Agents' tools can drop but never delete.
484async function deleteItem($: any, idPrefix: string): Promise<{ ok: true; title: string } | { ok: false; message: string }> {
485 const items = await loadAll($)
486 const found = items.filter((i) => i.id.startsWith(idPrefix))
487 if (found.length !== 1) return { ok: false, message: 'No single item matches id ' + idPrefix }
488 const item = found[0]
489 if (item.status !== 'dropped') return { ok: false, message: 'Only dropped items can be deleted. Drop it first: ' + item.title }
490 if (!/^[A-Za-z0-9_-]+$/.test(item.id)) return { ok: false, message: 'Refused: unexpected characters in id ' + item.id }
491 const path = (await itemsDir($)) + (await sep($)) + item.id + '.json'
492 const r = await removeFile($, path)
493 if (r.exitCode !== 0 || (await $.fs.exists(path))) return { ok: false, message: 'Could not delete ' + item.title + ': ' + (r.stderr.trim() || 'file still there') }
494 cache = cache.filter((i) => i.id !== item.id)
495 $.ui.invalidate('ui.render')
496 return { ok: true, title: item.title }
497}
498
499async function runTodo($: any, args: string): Promise<{ text: string }> {
500 const cmd = parseTodoCommand(args)
501 if (cmd.action === 'error') return { text: cmd.message }
502 try {
503 if (cmd.action === 'done') {
504 const item = await setStatus($, cmd.idPrefix, 'done')
505 return { text: item ? 'Done: ' + item.title : 'No single item matches id ' + cmd.idPrefix }
506 }
507 if (cmd.action === 'delete') {
508 const r = await deleteItem($, cmd.idPrefix)
509 return { text: r.ok ? 'Deleted forever: ' + r.title : r.message }
510 }
511 const r = await capture($, { title: cmd.text, kind: cmd.kind, origin: 'human', source: 'manual' })
512 return { text: (r.isNew ? 'Added ' : 'Already listed, noted: ') + r.item.title }
513 } catch (err: any) {
514 $.ui.toast('ToDo not saved: ' + err.message)
515 return { text: 'Not saved: ' + err.message }
516 }
517}
518
519async function runTodos($: any, args: string): Promise<{ text?: string }> {
520 const cmd = parseTodosArgs(args)
521 if (cmd.action === 'list') {
522 try { return { text: formatList(await loadAll($), await $.session.cwd(), cmd.all) } }
523 catch (err: any) { return { text: 'Not loaded: ' + err.message } }
524 }
525 if (cmd.action === 'refresh') {
526 try {
527 await forceRefresh($)
528 return { text: 'Ledger refreshed: ' + cache.filter(isOpen).length + ' open.' }
529 } catch (err: any) { return { text: 'Not loaded: ' + err.message } }
530 }
531 await safeToggle($)
532 return {}
533}
534
535// Registers a command under its preferred name, or under the fallback name if that one is refused.
536async function registerCommand($: any, spec: any, fallback: string): Promise<void> {
537 try {
538 await $.command.register(spec)
539 } catch (err: any) {
540 $.ui.log('/' + spec.name + ' not registered (' + err.message + '); using /' + fallback)
541 try { await $.command.register({ ...spec, name: fallback }) }
542 catch (err2: any) { $.ui.log('/' + fallback + ' not registered either: ' + err2.message) }
543 }
544}
545
546async function registerTool($: any, spec: any): Promise<void> {
547 try { await $.tool.register(spec) } catch (err: any) { $.ui.log('tool ' + spec.name + ' not registered: ' + err.message) }
548}
549
550export function register(on) {
551 on('session.start', async ($, e, next) => {
552 try { cwd = await $.session.cwd() } catch { /* keep '' until a render reads it */ }
553 // The theme the person last chose, kept across sessions.
554 try { applyTheme(themeById(await $.store.get('theme'))) } catch { /* the default theme */ }
555 // Picks up items other sessions write; the timer stops when the module reloads.
556 $.clock.every(SYNC_MS, () => syncIfChanged($))
557 $.clock.after(0, () => lookupSessionName($))
558 await registerTool($, {
559 name: 'park_item',
560 description:
561 'Record an item in the user\'s global todo ledger. Call this, without asking first, whenever you ' +
562 'defer, park, postpone or put something out of scope, or propose work the user has not asked for. ' +
563 'If it may already be recorded, call list_items first and update that item instead of adding a second one. ' +
564 'kind: todo | deferred | proposal | discussion. Keep title to one line.',
565 inputSchema: {
566 type: 'object',
567 properties: {
568 title: { type: 'string' },
569 kind: { type: 'string', enum: ['todo', 'deferred', 'proposal', 'discussion'] },
570 body: { type: 'string', description: DETAIL_HINT },
571 },
572 required: ['title', 'kind'],
573 },
574 })
575 await registerTool($, {
576 name: 'list_items',
577 description:
578 'List open items in the user\'s todo ledger (their todos, parked work, proposals and discussions across ' +
579 'all projects and sessions). Use it whenever the user mentions todos, the ledger, parked or deferred work, ' +
580 'or asks what is pending. scope "project" (default) or "all". Each line gives the id to use with get_item and update_item.',
581 inputSchema: { type: 'object', properties: { scope: { type: 'string', enum: ['project', 'all'] } } },
582 })
583 await registerTool($, {
584 name: 'get_item',
585 description: 'Read one ledger item in full: title, details, project, session, status and its notes thread. id may be a unique prefix.',
586 inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] },
587 })
588 await registerTool($, {
589 name: 'update_item',
590 description:
591 'Update a ledger item: status (open, in_progress, done, dropped), title, kind, details, and/or add a note. ' +
592 'Keep the ledger current without being asked: as soon as the user approves a proposal set kind "todo"; when ' +
593 'they reject or drop it set status "dropped"; when an item\'s work is finished set status "done"; when two ' +
594 'items are the same, drop one with a note naming the other. ' +
595 'To remove an item, set status "dropped" (it moves to Done and can be reopened). id may be a unique prefix.',
596 inputSchema: {
597 type: 'object',
598 properties: {
599 id: { type: 'string' },
600 status: { type: 'string', enum: STATUS_VALUES },
601 title: { type: 'string' },
602 kind: { type: 'string', enum: ['todo', 'deferred', 'proposal', 'discussion'] },
603 body: { type: 'string', description: 'Replaces the item\'s details. ' + DETAIL_HINT },
604 note: { type: 'string', description: 'Appended to the notes thread' },
605 },
606 required: ['id'],
607 },
608 })
609 await registerCommand($, { name: 'todos', description: "Toggle the ToDo's pane", argumentHint: '[list [all] | refresh]', immediate: true }, 'ledger')
610 await registerCommand($, { name: 'todo', description: 'Add or close a ledger item', argumentHint: 'add [-d|-p|-n] <text> | done <id>' }, 'ledger-add')
611 // Warm the cache; a failure here must not block the session.
612 // The next loadAll (any command, tool or render) retries.
613 try { await loadAll($) } catch { cache = [] }
614 return next(e)
615 })
616
617 // After a press redraws the pane, the desktop loses the pane's focus ring, and the
618 // next click is spent taking it back (traced 2026-10-07: one press logged per two
619 // clicks). Putting the ring on the element the next press will want keeps every
620 // click live: the open card's Close, or the row title once the card closes.
621 on('ui.press', async ($, e, next) => {
622 const r = await next(e)
623 if (e.plugin !== 'todo-ledger' || e.requestId !== PANE) return r
624 const target = expandedId ? 'close-' + expandedId : e.element.replace(/^close-/, 'title-')
625 try { await $.ui.focus({ requestId: PANE, key: target }) } catch { /* a denied move leaves focus as it was */ }
626 return r
627 })
628
629 on('ui.close', async ($, e, next) => {
630 if (e.id === PANE) paneOpen = false
631 return next(e)
632 })
633
634 // The button lives in the prompt footer (the row with the permission-mode label),
635 // on the same line as the engine's own mode labels.
636 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
637 const theirs = await next(e)
638 await refreshIfStale($)
639 let here = cwd
640 try { here = await $.session.cwd() } catch { /* keep the session.start value */ }
641 const label = bandLabel(cache, here)
642 const { Box, Button } = $.ui.resolve(e)
643 const mine = Button({ key: 'ledger-toggle', label, plain: true, onPress: () => safeToggle($) })
644 return Box({ key: 'ledger-footer', flexDirection: 'row', columnGap: 2, alignItems: 'center',
645 children: theirs ? [mine, theirs] : [mine] })
646 })
647
648 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
649 if (e.requestId !== PANE) return next(e)
650 try {
651 const { Box, Text, Button, Input } = $.ui.resolve(e)
652 // Mobile's element table has no Input, so the note composer is skipped there.
653 const canInput = e.surface !== 'mobile'
654 const redraw = () => $.ui.invalidate('ui.render')
655 const now = await $.clock.now()
656 await refreshIfStale($)
657 // Read the cwd per render so the filter follows /cd and matches what capture stores.
658 let here = cwd
659 try { here = await $.session.cwd() } catch { /* keep the session.start value */ }
660 let thisSession = ''
661 try { thisSession = await $.session.id() } catch { /* no highlight without an id */ }
662 const rows = itemsForTab(cache, tab, allProjects ? null : here)
663 const ordered = displayOrder(rows, tab)
664 const head = ordered.slice(0, LIST_LIMIT)
665 const picked = ordered.find((x) => x.id === expandedId)
666 const shown = showAllRows ? ordered : picked && !head.includes(picked) ? [...head, picked] : head
667
668 const scoped = cache.filter((i) => allProjects || i.project.toLowerCase() === here.toLowerCase())
669 const count = (t: Tab) => scoped.filter((i) => tabOf(i) === t).length
670 const select = (id: string | null) => { expandedId = id; startingId = null; notingId = null; deletingId = null; redraw() }
671
672 // Closing an item from its card opens the next one, so a run of items is
673 // triaged with one press each instead of select, act, select again.
674 const closeItem = async (i: Item, status: Status, kindChange?: Kind) => {
675 const at = ordered.findIndex((x) => x.id === i.id)
676 const following = ordered.slice(at + 1).concat(ordered.slice(0, Math.max(0, at))).find((x) => x.id !== i.id)
677 try {
678 if (kindChange) {
679 const stamp = new Date(await $.clock.now()).toISOString()
680 await saveItem($, { ...i, kind: kindChange, updatedAt: stamp, notes: [...i.notes, { by: 'human' as Origin, text: 'approved', at: stamp }] })
681 } else await setStatus($, i.id, status)
682 } catch (err: any) { $.ui.toast('ToDo not saved: ' + err.message); return }
683 if (kindChange) { redraw(); return }
684 // Closed items are kept: say where they went.
685 $.ui.toast((status === 'dropped' ? 'Dropped, moved to Done: ' : 'Done: ') + clip(i.title, 40))
686 select(expandedId === i.id ? (following?.id ?? null) : expandedId)
687 }
688
689 // Row 1: where the list comes from, with a dim refresh at the far end. The open
690 // count is not repeated here: the tabs carry it.
691 const scopeRow = Box({
692 flexDirection: 'row',
693 justifyContent: 'space-between',
694 children: [
695 Button({ key: 'scope', plain: true, hotkey: 'p',
696 label: (allProjects ? 'All projects' : 'This project') + ' ▾',
697 onPress: () => { allProjects = !allProjects; showAllRows = false; select(null) } }),
698 Box({ flexDirection: 'row', columnGap: 2, children: [
699 // One button steps through the five themes and remembers the choice.
700 Button({ key: 'theme', plain: true, dimColor: true, label: '◐ ' + theme.label,
701 onPress: async () => {
702 applyTheme(nextTheme(theme.id))
703 try { await $.store.set('theme', theme.id) } catch { /* kept for this session only */ }
704 redraw()
705 } }),
706 Button({ key: 'refresh', plain: true, dimColor: true, label: '↻',
707 onPress: async () => {
708 try { await forceRefresh($) } catch (err: any) { $.ui.toast('Refresh failed: ' + err.message) }
709 } }),
710 ] }),
711 ],
712 })
713
714 // Queued items that are still open (a closed one drops out), in pick order.
715 const queued = [...queue].map((id) => cache.find((i) => i.id === id)).filter((i): i is Item => !!i && isOpen(i))
716 for (const id of [...queue]) if (!queued.some((i) => i.id === id)) queue.delete(id)
717 // Shown only with something queued, as one bar under the tabs: the count at the left,
718 // a dim Clear and the one primary Send all at the right. On the desktop the bar is
719 // washed in the accent so it reads as part of the list it acts on.
720 const tray = queued.length === 0 ? [] : [Box({
721 key: 'queue-tray',
722 flexDirection: 'row',
723 alignItems: 'center',
724 justifyContent: 'space-between',
725 marginBottom: 1,
726 ...(e.surface === 'desktop' ? { paddingX: 2, backgroundColor: withAlpha(theme.tint, 0.1) } : {}),
727 children: [
728 Text({ color: ACCENT, children: [queued.length + ' queued'] }),
729 Box({ flexDirection: 'row', alignItems: 'center', columnGap: 2, children: [
730 Button({ key: 'queue-clear', label: 'Clear', plain: true, dimColor: true, onPress: () => { queue.clear(); redraw() } }),
731 Button({ key: 'queue-send', label: 'Send all', variant: 'primary', onPress: async () => { await sendQueued($, queued); redraw() } }),
732 ] }),
733 ],
734 })]
735
736 // Row 2: who started it; the chosen tab at full strength, the others dim.
737 const tabRow = Box({
738 flexDirection: 'row',
739 columnGap: 3,
740 marginBottom: 1,
741 children: TABS.map((t) =>
742 Button({ key: 'tab-' + t.id, plain: true, hotkey: t.hotkey, dimColor: tab !== t.id,
743 label: t.label + ' ' + count(t.id),
744 onPress: () => { tab = t.id; showAllRows = false; select(null) } })),
745 })
746
747 // The card's actions in one fixed order, the first the primary. Proposals are
748 // decided (Approve / Reject) rather than worked, so they lead with that. While a
749 // note is being typed the Note button turns into Cancel and letter keys rest.
750 const actionsFor = (i: Item) => {
751 if (startingId === i.id) return startChooser($, e, i)
752 const noting = notingId === i.id
753 const hk = (k: string) => (notingId === null ? { hotkey: k } : {})
754 if (tab === 'done') {
755 const reopen = Button({ key: 'reopen-' + i.id, label: 'Reopen', variant: 'primary', ...hk('o'), onPress: () => markStatus($, i.id, 'open') })
756 if (i.status !== 'dropped') return [reopen]
757 // Two-step: the first press arms it; only Confirm deletes the file. Neither is
758 // primary: nothing should invite an irreversible press.
759 if (deletingId === i.id) {
760 return [
761 Button({ key: 'delete-confirm-' + i.id, label: 'Confirm delete', onPress: async () => {
762 deletingId = null
763 const r = await deleteItem($, i.id)
764 if (!r.ok) $.ui.toast(r.message)
765 else { expandedId = null; $.ui.toast('Deleted forever: ' + r.title) }
766 redraw()
767 } }),
768 Button({ key: 'delete-cancel-' + i.id, label: 'Cancel', plain: true, dimColor: true, onPress: () => { deletingId = null; redraw() } }),
769 ]
770 }
771 return [reopen, Button({ key: 'delete-' + i.id, label: 'Delete forever', dimColor: true, onPress: () => { deletingId = i.id; redraw() } })]
772 }
773 const start = Button({ key: 'start-' + i.id, label: 'Start', ...hk('s'),
774 ...(i.kind === 'proposal' ? {} : { variant: 'primary' as const }),
775 onPress: () => { startingId = i.id; notingId = null; redraw() } })
776 const picked = queue.has(i.id)
777 const queueBtn = Button({ key: 'queue-' + i.id, label: picked ? 'Queued ✓' : 'Queue', ...hk('q'),
778 onPress: () => { if (picked) queue.delete(i.id); else queue.add(i.id); redraw() } })
779 const note = !canInput ? []
780 : noting
781 ? [Button({ key: 'note-cancel-' + i.id, label: 'Cancel', plain: true, dimColor: true, onPress: () => { notingId = null; redraw() } })]
782 : [Button({ key: 'note-' + i.id, label: 'Note', ...hk('n'), onPress: () => { notingId = i.id; startingId = null; redraw() } })]
783 if (i.kind === 'proposal') {
784 return [
785 Button({ key: 'approve-' + i.id, label: 'Approve', variant: 'primary', ...hk('a'), onPress: () => closeItem(i, i.status, 'todo') }),
786 Button({ key: 'drop-' + i.id, label: 'Reject', ...hk('x'), onPress: () => closeItem(i, 'dropped') }),
787 start,
788 queueBtn,
789 ...note,
790 ]
791 }
792 return [
793 start,
794 queueBtn,
795 Button({ key: 'done-' + i.id, label: 'Done', ...hk('d'), onPress: () => closeItem(i, 'done') }),
796 Button({ key: 'drop-' + i.id, label: 'Drop', ...hk('x'), onPress: () => closeItem(i, 'dropped') }),
797 ...note,
798 ]
799 }
800
801 // Row width in title characters. The desktop draws a proportional font, about
802 // 1.4 characters per cell, so text wraps later there to use the pane's real width.
803 const cols = Math.max(12, (e.props.bodyColumns ?? 40) - 1)
804 const wide = e.surface === 'desktop' ? 1.2 : 1
805 // Row chrome: mark and gap (2), a spare column; on the desktop also the row's side
806 // padding (2), so a title never runs past its row or the open card.
807 const chrome = e.surface === 'desktop' ? 6 : 3
808 const titleCols = Math.max(16, Math.floor((cols - chrome) * wide))
809
810 const projectOf = (i: Item) => i.project.split(/[\\/]/).filter(Boolean).pop() ?? i.project
811 // Where and when, each part in its own faint tint (a mid-tone drawn dim, readable
812 // on light and dark). The project is named only when the list spans projects:
813 // inside one project it would be the same word on every row. Closed items show
814 // how long ago they closed, which is also the Done tab's order.
815 // On the desktop each part is a pill tinted at low alpha; given `open`, the
816 // pills are buttons, so the whole row opens the card. The terminal cannot draw
817 // alpha, so there the parts stay faintly tinted text.
818 const pills = e.surface === 'desktop'
819 const metaLine = (i: Item, open?: () => void) => {
820 const room = Math.max(12, titleCols - 8)
821 const part = (k: 'project' | 'session' | 'age', text: string) => {
822 if (!pills) return Text({ color: META[k], dimColor: true, wrap: 'truncate-end', children: [text] })
823 const inner = open
824 ? Button({ key: 'meta-' + k + '-' + i.id, plain: true, label: text, onPress: open })
825 : Text({ children: [text] })
826 return Box({ backgroundColor: META_BG[k], paddingX: 1, children: [inner] })
827 }
828 const dot = Text({ dimColor: true, children: ['·'] })
829 const when = part('age', age(now, tab === 'done' ? i.updatedAt : i.createdAt))
830 const session = part('session', clip(sessionLabel(i), allProjects ? Math.floor(room / 2) : room))
831 const parts = allProjects ? [part('project', clip(projectOf(i), Math.ceil(room / 2))), session, when] : [session, when]
832 // Pills sit apart on their own; text parts need the dot between them.
833 const children = pills ? parts : parts.flatMap((x, k) => (k ? [dot, x] : [x]))
834 return Box({ key: 'meta-' + i.id, flexDirection: 'row', columnGap: 1, children })
835 }
836 // A started item shows ▶ in place of its group mark.
837 const markOf = (i: Item, mark: string, color?: string) =>
838 i.status === 'in_progress' ? Text({ color: ACCENT, children: ['▶'] }) : Text({ color, dimColor: !color, children: [mark] })
839
840 // Scanning: a mark, the title on up to two lines (both open the card), the meta
841 // line. Rows are set apart by one blank line, none after a group's last; no
842 // borders, no rules.
843 const compactRow = (i: Item, mark: string, color: string | undefined, last: boolean) => {
844 const open = () => select(i.id)
845 const lines = wrapLines(i.title, titleCols, 2)
846 // After the meta line: a dot on the terminal for a row from this session (the
847 // desktop tints it instead), and "queued" for a picked one.
848 const extras = [
849 ...(!pills && thisSession && i.sessionId === thisSession ? [Text({ color: ACCENT, children: ['● this session'] })] : []),
850 ...(queue.has(i.id) ? [Text({ color: ACCENT, children: ['queued'] })] : []),
851 ]
852 return Box({
853 key: 'row-' + i.id,
854 flexDirection: 'row',
855 columnGap: 1,
856 alignItems: 'flex-start',
857 // Desktop rows are padded blocks (the padding is also the gap between them, so
858 // a tint has room around the text); the terminal separates rows by one blank line.
859 // Flat rows, no outline (only the open card is outlined). Desktop rows get a little
860 // side padding so the this-session tint has room; the gap between rows is the same
861 // blank line as on the terminal.
862 ...(pills ? { paddingX: 1, marginBottom: 1 } : last ? {} : { marginBottom: 1 }),
863 ...(pills && thisSession && i.sessionId === thisSession ? { backgroundColor: THIS_SESSION_BG } : {}),
864 children: [
865 markOf(i, mark, color),
866 Box({
867 flexDirection: 'column',
868 flexGrow: 1,
869 flexShrink: 1,
870 children: [
871 Button({ key: 'title-' + i.id, plain: true, label: lines[0] ?? '', onPress: open }),
872 ...(lines[1] ? [Button({ key: 'title2-' + i.id, plain: true, label: lines[1], onPress: open })] : []),
873 extras.length
874 ? Box({ flexDirection: 'row', columnGap: 1, children: [metaLine(i, open), ...extras] })
875 : metaLine(i, open),
876 ],
877 }),
878 ],
879 })
880 }
881
882 // One note: who and when on a dim line, the text under it; no blank between notes.
883 const noteView = (n: { by: string; text: string; at: string }, k: number, id: string) =>
884 Box({
885 key: 'note-' + k + '-' + id,
886 flexDirection: 'column',
887 children: [
888 Text({ dimColor: true, children: [(n.by === 'human' ? 'You' : 'Claude') + ' · ' + age(now, n.at)] }),
889 Text({ wrap: 'wrap', children: [n.text] }),
890 ],
891 })
892
893 // Acting: the picked item opens into a card outlined in the accent. Inside, by
894 // weight: the title bold, the same meta line as a row, details, the latest notes
895 // (older ones one press away), the composer when open, then the actions. The kind
896 // is not repeated: the card sits under its group heading.
897 const selectedCard = (i: Item, mark: string, color?: string) => {
898 const noting = notingId === i.id && canInput
899 if (draftFor !== (noting ? i.id : null) && (noting || draftFor === i.id)) { noteDraft = ''; draftFor = noting ? i.id : null }
900 const showAll = allNotesId === i.id
901 const hidden = showAll ? 0 : Math.max(0, i.notes.length - 3)
902 return Box({
903 key: 'row-' + i.id,
904 flexDirection: 'column',
905 borderStyle: 'round',
906 borderColor: ACCENT,
907 paddingX: pills ? 2 : 1,
908 ...(pills ? { paddingY: 1 } : {}),
909 marginBottom: 1,
910 children: [
911 Box({
912 flexDirection: 'row',
913 columnGap: 1,
914 alignItems: 'flex-start',
915 children: [
916 markOf(i, mark, color),
917 Box({
918 flexDirection: 'column',
919 flexGrow: 1,
920 flexShrink: 1,
921 children: [
922 Text({ bold: true, wrap: 'wrap', children: [i.title] }),
923 metaLine(i),
924 ],
925 }),
926 Button({ key: 'close-' + i.id, plain: true, dimColor: true, label: 'Close', onPress: () => select(null) }),
927 ],
928 }),
929 ...(i.body ? [Box({ marginTop: 1, children: [Text({ wrap: 'wrap', children: [i.body] })] })] : []),
930 ...(i.notes.length
931 ? [Box({
932 flexDirection: 'column',
933 marginTop: 1,
934 children: [
935 hidden
936 ? Button({ key: 'notes-more-' + i.id, plain: true, dimColor: true, label: 'Show ' + hidden + ' earlier',
937 onPress: () => { allNotesId = i.id; redraw() } })
938 : Text({ dimColor: true, children: ['Notes'] }),
939 ...i.notes.slice(hidden).map((n, k) => noteView(n, k + hidden, i.id)),
940 ],
941 })]
942 : []),
943 ...(noting
944 // A roomy field: full width (a column, so the Input stretches), taller than one
945 // line, and outlined in the accent so it reads as the place to type. The Input
946 // itself is one line, so Enter adds the note.
947 ? [Box({ marginTop: 1, flexDirection: 'column', width: '100%', children: [
948 Text({ dimColor: true, children: ['Add a note'] }),
949 Box({ width: '100%', minHeight: 5, borderStyle: 'round', borderColor: ACCENT, paddingX: 2, paddingY: 1, flexDirection: 'column', children: [
950 // No `value`: a drawn value replaces what the person typed, which moves the
951 // cursor when the preview redraws. The field keeps its own text instead.
952 Input({ key: 'note-input-' + i.id, placeholder: 'What should the agent know? Context, constraints, a decision.', submitLabel: 'add note', autoFocus: true,
953 // Redrawing on every key can move the cursor, so the preview catches up
954 // a moment after typing pauses, and only while it is (or is about to be) shown.
955 onInput: (v: string) => {
956 const was = noteDraft.length > 40
957 noteDraft = v; draftFor = i.id
958 if (!was && v.length <= 40) return
959 if (previewTimer) return
960 previewTimer = true
961 $.clock.after(PREVIEW_MS, () => { previewTimer = false; redraw() })
962 },
963 onSubmit: async (v: string) => { notingId = null; noteDraft = ''; draftFor = null; await addNote($, i.id, v); redraw() } }),
964 // The field scrolls sideways; this shows the whole note, wrapped, as it grows.
965 ...(noteDraft.length > 40 ? [Box({ marginTop: 1, children: [Text({ dimColor: true, wrap: 'wrap', children: [noteDraft] })] })] : []),
966 ] }),
967 ] })]
968 : []),
969 Box({ flexDirection: 'row', columnGap: 1, flexWrap: 'wrap', marginTop: 1, children: actionsFor(i) }),
970 ],
971 })
972 }
973
974 const itemView = (i: Item, mark: string, color: string | undefined, last: boolean) =>
975 expandedId === i.id ? selectedCard(i, mark, color) : compactRow(i, mark, color, last)
976
977 // Group headings are secondary: dim, no count (the rows under them are the count).
978 const body = rows.length === 0
979 ? [Text({ dimColor: true, wrap: 'wrap', children: [
980 tab === 'done'
981 ? 'Nothing closed yet.'
982 : 'Nothing open. Claude adds what it parks or proposes; add your own with /todo add <text>.',
983 ] })]
984 : tab === 'done'
985 ? shown.map((i, k) => itemView(i, i.status === 'dropped' ? '✕' : '✓', undefined, k === shown.length - 1))
986 : groupItems(shown).flatMap((g, gi) => [
987 Box({ ...(gi === 0 ? {} : { marginTop: 1 }), children: [Text({ dimColor: true, children: [g.label] })] }),
988 ...g.items.map((i, k) => itemView(i, g.mark, g.color === 'suggestion' ? ACCENT : g.color, k === g.items.length - 1)),
989 ])
990 const more = ordered.length - shown.length
991 if (more > 0) {
992 body.push(Box({ marginTop: 1, children: [Button({ key: 'show-all-rows', plain: true, dimColor: true,
993 label: 'Show ' + more + ' more', onPress: () => { showAllRows = true; redraw() } })] }))
994 }
995
996 return Box({
997 flexDirection: 'column',
998 ...(pills && PANE_WASH ? { backgroundColor: PANE_WASH } : {}),
999 children: [scopeRow, tabRow, ...tray, ...body],
1000 })
1001 } catch (err: any) {
1002 // A failed draw shows its reason instead of a blank pane.
1003 $.ui.log('pane draw failed: ' + (err?.stack ?? err?.message ?? String(err)))
1004 const { Text } = $.ui.resolve(e)
1005 return Text({ wrap: 'wrap', children: ["ToDo's could not draw: " + (err?.message ?? String(err))] })
1006 }
1007 })
1008
1009 on('turn.start', async ($, e, next) => {
1010 parkedThisTurn = false
1011 if (e.agentId === undefined) replying = true
1012 // The scan reads what the user said this turn to see which items they decided.
1013 if (e.agentId === undefined && typeof e.text === 'string') lastUserText = e.text
1014 // Picks up a /rename since the last turn, without holding the turn.
1015 $.clock.after(0, () => lookupSessionName($))
1016 // Other sessions may have written items; the next render reloads.
1017 lastLoadAt = 0
1018 return next(e)
1019 })
1020
1021 on('turn.complete', async ($, e, next) => {
1022 const result = await next(e)
1023 if (e.agentId === undefined) replying = false
1024 // Subagent turns and non-answer turns are not scanned.
1025 if (e.agentId === undefined && e.reason === 'answer' && shouldScan(e.answer, parkedThisTurn)) {
1026 const answer = e.answer
1027 const userText = lastUserText
1028 $.clock.after(0, () => runScan($, answer, userText))
1029 }
1030 return result
1031 })
1032
1033 on('tool.call', { tool: 'mcp__todo-ledger__park_item' }, async ($, e) => {
1034 if (!KINDS.includes(e.kind)) return { result: 'Not saved: kind must be one of ' + KINDS.join(', ') }
1035 if (typeof e.title !== 'string' || !e.title.trim()) return { result: 'Not saved: title is required' }
1036 try {
1037 const r = await capture($, { title: e.title, kind: e.kind, origin: 'agent', source: 'tool', body: e.body })
1038 parkedThisTurn = true
1039 return { result: (r.isNew ? 'Parked ' : 'Already in ledger, added note to ') + r.item.id + ': ' + r.item.title }
1040 } catch (err: any) {
1041 $.ui.toast('ToDo not saved: ' + err.message)
1042 return { result: 'Not saved: ' + err.message }
1043 }
1044 })
1045
1046 on('tool.call', { tool: 'mcp__todo-ledger__list_items' }, async ($, e) => {
1047 try { return { result: formatList(await loadAll($), await $.session.cwd(), e.scope === 'all') } }
1048 catch (err: any) { return { result: 'Not loaded: ' + err.message } }
1049 })
1050
1051 on('tool.call', { tool: 'mcp__todo-ledger__get_item' }, async ($, e) => {
1052 try {
1053 const match = (await loadAll($)).filter((i) => typeof e.id === 'string' && e.id && i.id.startsWith(e.id))
1054 return { result: match.length === 1 ? formatItem(match[0]) : 'No single item matches id ' + e.id }
1055 } catch (err: any) { return { result: 'Not loaded: ' + err.message } }
1056 })
1057
1058 on('tool.call', { tool: 'mcp__todo-ledger__update_item' }, async ($, e) => {
1059 try {
1060 const items = await loadAll($)
1061 const match = items.filter((i) => typeof e.id === 'string' && i.id.startsWith(e.id))
1062 if (match.length !== 1) return { result: 'No single item matches id ' + e.id }
1063 if (e.kind !== undefined && !KINDS.includes(e.kind)) return { result: 'Not saved: kind must be one of ' + KINDS.join(', ') }
1064 if (e.title !== undefined && (typeof e.title !== 'string' || !e.title.trim())) return { result: 'Not saved: title cannot be empty' }
1065 // A wrong status used to be ignored while the reply still said "updated".
1066 if (e.status !== undefined && !STATUS_VALUES.includes(e.status)) return { result: 'Not saved: status must be one of ' + STATUS_VALUES.join(', ') }
1067 const item = match[0]
1068 const at = new Date(await $.clock.now()).toISOString()
1069 const edits = {
1070 ...(e.title !== undefined ? { title: cleanTitle(e.title) } : {}),
1071 ...(e.kind !== undefined ? { kind: e.kind as Kind } : {}),
1072 ...(typeof e.body === 'string' ? { body: e.body } : {}),
1073 }
1074 const note = typeof e.note === 'string' && e.note.trim() ? e.note.trim() : ''
1075 // One write for every change, so another session never sees half an update.
1076 const final: Item = {
1077 ...item, ...edits, status: (e.status as Status | undefined) ?? item.status, updatedAt: at,
1078 notes: note ? [...item.notes, { by: 'agent' as Origin, text: note, at }] : item.notes,
1079 }
1080 await saveItem($, final)
1081 const changed = ['status ' + final.status, ...Object.keys(edits), ...(note ? ['note added'] : [])]
1082 return { result: 'Item ' + final.id + ' updated: ' + changed.join(', ') }
1083 } catch (err: any) {
1084 $.ui.toast('ToDo not saved: ' + err.message)
1085 return { result: 'Not saved: ' + err.message }
1086 }
1087 })
1088
1089 on('tool.call', { tool: 'TodoWrite' }, async ($, e, next) => {
1090 const result = await next(e)
1091 // Subagents' and workflow agents' working lists are theirs, not the person's ledger.
1092 if (e.agentId !== undefined) return result
1093 try {
1094 await mirrorTodos($, Array.isArray(e.todos) ? e.todos : [])
1095 } catch (err: any) {
1096 $.ui.log('TodoWrite mirror failed: ' + err.message)
1097 }
1098 return result
1099 })
1100
1101 on('command.run', { command: 'todo' }, async ($, e) => runTodo($, e.args))
1102 on('command.run', { command: 'todos' }, async ($, e) => runTodos($, e.args))
1103 // Fallback names, used only when /todo or /todos could not be registered.
1104 on('command.run', { command: 'ledger-add' }, async ($, e) => runTodo($, e.args))
1105 on('command.run', { command: 'ledger' }, async ($, e) => runTodos($, e.args))
1106}
1107
1108src/commands.ts 56 lines1import { isOpen, sessionLabel } from './item.ts'
2import type { Item, Kind } from './item.ts'
3
4export type TodoCommand =
5 | { action: 'add'; kind: Kind; text: string }
6 | { action: 'done'; idPrefix: string }
7 | { action: 'delete'; idPrefix: string }
8 | { action: 'error'; message: string }
9
10const FLAGS: Record<string, Kind> = { '-d': 'deferred', '-p': 'proposal', '-n': 'discussion' }
11const USAGE = 'Usage: /todo add [-d|-p|-n] <text> · /todo done <id> · /todo delete <id> (dropped items only)'
12
13export function parseTodoCommand(args: string): TodoCommand {
14 const parts = args.trim().split(/\s+/).filter(Boolean)
15 if (parts[0] === 'done' && parts[1]) return { action: 'done', idPrefix: parts[1] }
16 if (parts[0] === 'delete' && parts[1]) return { action: 'delete', idPrefix: parts[1] }
17 if (parts[0] !== 'add') return { action: 'error', message: USAGE }
18 let kind: Kind = 'todo'
19 let rest = parts.slice(1)
20 if (rest[0] && FLAGS[rest[0]]) { kind = FLAGS[rest[0]]; rest = rest.slice(1) }
21 if (rest.length === 0) return { action: 'error', message: USAGE }
22 return { action: 'add', kind, text: rest.join(' ') }
23}
24
25export function parseTodosArgs(args: string): { action: 'toggle' } | { action: 'refresh' } | { action: 'list'; all: boolean } {
26 const parts = args.trim().split(/\s+/).filter(Boolean)
27 if (parts[0] === 'list') return { action: 'list', all: parts[1] === 'all' }
28 if (parts[0] === 'refresh') return { action: 'refresh' }
29 return { action: 'toggle' }
30}
31
32export function formatList(items: Item[], project: string, all: boolean): string {
33 const shown = items
34 .filter(isOpen)
35 .filter((i) => all || i.project.toLowerCase() === project.toLowerCase())
36 .sort((a, b) => b.createdAt.localeCompare(a.createdAt))
37 if (shown.length === 0) return all ? 'No open ledger items.' : 'No open ledger items for this project.'
38 return shown
39 .map((i) => `- [${i.id}] (${i.kind}, ${i.origin}, ${i.status}) ${i.title} · session ${sessionLabel(i)}` + (all ? ` · ${i.project}` : ''))
40 .join('\n')
41}
42
43// One item in full, for the get_item tool: everything an agent needs to act on it.
44export function formatItem(i: Item): string {
45 const lines = [
46 `[${i.id}] ${i.title}`,
47 `kind: ${i.kind} · status: ${i.status} · started by: ${i.origin} (${i.source})`,
48 `project: ${i.project}`,
49 `session: ${sessionLabel(i)} (${i.sessionId})`,
50 `created: ${i.createdAt} · updated: ${i.updatedAt}`,
51 ]
52 if (i.body) lines.push('', i.body)
53 if (i.notes.length) lines.push('', 'Notes:', ...i.notes.map((n) => `- ${n.by === 'human' ? 'user' : 'agent'} (${n.at}): ${n.text}`))
54 return lines.join('\n')
55}
56src/scan.ts 64 lines1export type ScanKind = 'todo' | 'deferred' | 'proposal'
2const SCAN_KINDS: ScanKind[] = ['todo', 'deferred', 'proposal']
3
4export const SCAN_SYSTEM =
5 'You keep a todo ledger current from one turn of a conversation between a USER and an AI coding assistant (the REPLY).\n' +
6 '1. items: things the assistant explicitly deferred, parked, left for later, put out of scope, or proposed without being ' +
7 'asked. Not work completed in the reply. Not anything already in KNOWN, even reworded.\n' +
8 '2. updates: KNOWN items this turn changed. "approve": the USER agreed to a proposal. "reject": the USER declined it. ' +
9 '"done": the REPLY shows its work was completed. "duplicate": it is the same thing as another KNOWN item (give "of": that id). ' +
10 'Use only ids from KNOWN. Only when the USER message or the REPLY says so clearly; when unsure, leave it out.\n' +
11 'Give each item a "detail": 2 to 4 short sentences in plain English, no jargon, saying what the task is and why it ' +
12 'was deferred or proposed.\n' +
13 'Reply with JSON only: {"items":[{"title":"one line","kind":"todo|deferred|proposal","detail":"..."}],' +
14 '"updates":[{"id":"…","action":"approve|reject|done|duplicate","of":"…"}]}. Use empty arrays when there is nothing.'
15
16export function shouldScan(answer: unknown, parked: boolean): boolean {
17 return typeof answer === 'string' && answer.length >= 400 && !parked
18}
19
20export type KnownItem = { id: string; title: string; kind: string }
21
22export function buildScanPrompt(answer: string, known: (string | KnownItem)[], userText?: string): string {
23 const lines = known.length
24 ? known.map((k) => (typeof k === 'string' ? '- ' + k : `- [${k.id}] (${k.kind}) ${k.title}`)).join('\n')
25 : '(none)'
26 const user = userText && userText.trim() ? 'USER:\n' + userText.trim().slice(-2000) + '\n\n' : ''
27 return 'KNOWN:\n' + lines + '\n\n' + user + 'REPLY:\n' + answer.slice(-6000)
28}
29
30export type ScanUpdate = { id: string; action: 'approve' | 'reject' | 'done' } | { id: string; action: 'duplicate'; of: string }
31const ACTIONS = ['approve', 'reject', 'done', 'duplicate']
32
33// Updates the model proposed, kept only when they name ids the prompt listed.
34export function parseScanUpdates(text: string, knownIds: string[]): ScanUpdate[] {
35 const start = text.indexOf('{')
36 const end = text.lastIndexOf('}')
37 if (start < 0 || end <= start) return []
38 let v: any
39 try { v = JSON.parse(text.slice(start, end + 1)) } catch { return [] }
40 if (!v || !Array.isArray(v.updates)) return []
41 const known = new Set(knownIds)
42 const out: ScanUpdate[] = []
43 for (const u of v.updates) {
44 if (!u || !known.has(u.id) || !ACTIONS.includes(u.action)) continue
45 if (u.action === 'duplicate') {
46 if (typeof u.of === 'string' && known.has(u.of) && u.of !== u.id) out.push({ id: u.id, action: 'duplicate', of: u.of })
47 } else out.push({ id: u.id, action: u.action })
48 }
49 return out
50}
51
52export function parseScanReply(text: string): { title: string; kind: ScanKind; detail?: string }[] | null {
53 const start = text.indexOf('{')
54 const end = text.lastIndexOf('}')
55 if (start < 0 || end <= start) return null
56 let v: any
57 try { v = JSON.parse(text.slice(start, end + 1)) } catch { return null }
58 if (!v || !Array.isArray(v.items)) return null
59 return v.items
60 .filter((i: any) => i && typeof i.title === 'string' && i.title.trim() && SCAN_KINDS.includes(i.kind))
61 .map((i: any) => ({ title: i.title.trim(), kind: i.kind,
62 ...(typeof i.detail === 'string' && i.detail.trim() ? { detail: i.detail.trim().slice(0, 600) } : {}) }))
63}
64src/item.ts 163 lines1export type Kind = 'todo' | 'deferred' | 'proposal' | 'discussion'
2export type Origin = 'agent' | 'human'
3export type Status = 'open' | 'in_progress' | 'done' | 'dropped'
4export type Source = 'tool' | 'todowrite' | 'scan' | 'manual'
5
6export interface Note { by: Origin; text: string; at: string }
7
8export interface Item {
9 id: string
10 title: string
11 body: string
12 kind: Kind
13 origin: Origin
14 status: Status
15 project: string
16 sessionId: string
17 // The session's name as its tab shows it (/rename), when it had one at capture.
18 sessionName?: string
19 source: Source
20 createdAt: string
21 updatedAt: string
22 notes: Note[]
23}
24
25export interface NewItemFields {
26 title: string
27 kind: Kind
28 origin: Origin
29 source: Source
30 project: string
31 sessionId: string
32 sessionName?: string
33 body?: string
34 nowMs: number
35 hex4: string
36}
37
38export const KINDS: Kind[] = ['todo', 'deferred', 'proposal', 'discussion']
39const STATUSES: Status[] = ['open', 'in_progress', 'done', 'dropped']
40
41const pad = (n: number) => String(n).padStart(2, '0')
42
43export function newId(nowMs: number, hex4: string): string {
44 const d = new Date(nowMs)
45 const date = `${d.getUTCFullYear()}${pad(d.getUTCMonth() + 1)}${pad(d.getUTCDate())}`
46 const time = `${pad(d.getUTCHours())}${pad(d.getUTCMinutes())}${pad(d.getUTCSeconds())}`
47 return `${date}-${time}-${hex4}`
48}
49
50export function randomHex4(): string {
51 const b = new Uint8Array(2)
52 crypto.getRandomValues(b)
53 return Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('')
54}
55
56export function cleanTitle(s: string): string {
57 const one = s.replace(/\s+/g, ' ').trim()
58 return one.length > 200 ? one.slice(0, 197) + '...' : one
59}
60
61export function dedupeKey(title: string, project: string): string {
62 return cleanTitle(title).toLowerCase() + '|' + project.toLowerCase()
63}
64
65export function isOpen(item: Item): boolean {
66 return item.status === 'open' || item.status === 'in_progress'
67}
68
69export function makeItem(f: NewItemFields): Item {
70 const at = new Date(f.nowMs).toISOString()
71 return {
72 id: newId(f.nowMs, f.hex4),
73 title: cleanTitle(f.title),
74 body: f.body ?? '',
75 kind: f.kind,
76 origin: f.origin,
77 status: 'open',
78 project: f.project,
79 sessionId: f.sessionId,
80 ...(f.sessionName ? { sessionName: f.sessionName } : {}),
81 source: f.source,
82 createdAt: at,
83 updatedAt: at,
84 notes: [],
85 }
86}
87
88export function parseItem(text: string): Item | null {
89 let v: any
90 try { v = JSON.parse(text) } catch { return null }
91 if (!v || typeof v !== 'object') return null
92 const strings = ['id', 'title', 'project', 'sessionId', 'createdAt', 'updatedAt']
93 if (!strings.every((k) => typeof v[k] === 'string')) return null
94 if (!KINDS.includes(v.kind) || !STATUSES.includes(v.status)) return null
95 if (v.origin !== 'agent' && v.origin !== 'human') return null
96 return { ...v, body: typeof v.body === 'string' ? v.body : '', notes: Array.isArray(v.notes) ? v.notes : [] }
97}
98
99// Cut text to at most `max` characters, ending in an ellipsis when cut.
100export function clip(s: string, max: number): string {
101 return s.length <= max ? s : s.slice(0, Math.max(1, max - 1)) + '…'
102}
103
104// Wrap text at word boundaries into at most `lines` lines of `width`; the last
105// line ends in an ellipsis when text is left over.
106export function wrapLines(s: string, width: number, lines: number): string[] {
107 const w = Math.max(4, width)
108 const out: string[] = []
109 let rest = s.replace(/\s+/g, ' ').trim()
110 while (rest && out.length < lines) {
111 if (rest.length <= w) { out.push(rest); rest = ''; break }
112 if (out.length === lines - 1) { out.push(clip(rest, w)); rest = ''; break }
113 const cut = rest.lastIndexOf(' ', w)
114 const at = cut > w / 3 ? cut : w
115 out.push(rest.slice(0, at).trimEnd())
116 rest = rest.slice(at).trimStart()
117 }
118 return out
119}
120
121// How the pane names the session an item came from: its name, else the id's first block.
122export function sessionLabel(item: Item): string {
123 return item.sessionName?.trim() || item.sessionId.split('-')[0]
124}
125
126// The newest session name in transcript lines (`{"type":"custom-title","customTitle":...}`).
127export function lastSessionTitle(lines: string): string | null {
128 let found: string | null = null
129 for (const line of lines.split(/\r?\n/)) {
130 if (!line.includes('"custom-title"')) continue
131 try {
132 const v = JSON.parse(line)
133 if (v?.type === 'custom-title' && typeof v.customTitle === 'string' && v.customTitle.trim()) found = v.customTitle.trim()
134 } catch { /* a partial line; skip it */ }
135 }
136 return found
137}
138// Words that carry no meaning for "is this the same item": articles, joiners and
139// the verbs titles start with ("add", "implement", "build"...).
140const STOP = new Set(['the', 'an', 'and', 'or', 'to', 'of', 'in', 'on', 'for', 'from', 'with', 'by', 'at', 'as', 'is', 'are',
141 'be', 'it', 'its', 'this', 'that', 'into', 'per', 'via', 'then', 'add', 'implement', 'build', 'make', 'create', 'support',
142 'handle', 'extract', 'display', 'show', 'use'])
143
144function titleWords(s: string): Set<string> {
145 const words = s.toLowerCase().replace(/[^a-z0-9\s]/g, ' ').split(/\s+/)
146 .filter((w) => w.length >= 2 && !STOP.has(w))
147 .map((w) => (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') ? w.slice(0, -1) : w))
148 return new Set(words)
149}
150
151// Two titles name the same item when at least 70% of the shorter one's meaningful
152// words appear in the other. Titles under 3 meaningful words never match this way
153// ("Fix login" / "Fix logout"); exact duplicates are caught by dedupeKey instead.
154export function similarTitle(a: string, b: string): boolean {
155 const A = titleWords(a)
156 const B = titleWords(b)
157 const small = Math.min(A.size, B.size)
158 if (small < 3) return false
159 let shared = 0
160 for (const w of A) if (B.has(w)) shared++
161 return shared / small >= 0.7
162}
163src/start.ts 80 lines1import type { Item } from './item.ts'
2
3export type StartChoice = 'send' | 'draft' | 'terminal' | 'copy'
4
5export interface StartOption { value: StartChoice; label: string; hotkey: string }
6
7// The ways to start an item, drawn as one button each (one press, no picker).
8// The first is the main one. Terminals can open a new window; the desktop copies instead.
9export function startOptions(surface: 'terminal' | 'desktop'): StartOption[] {
10 const common: StartOption[] = [
11 { value: 'send', label: 'Send', hotkey: 's' },
12 { value: 'draft', label: 'Draft', hotkey: 'd' },
13 ]
14 return surface === 'terminal'
15 ? [...common, { value: 'terminal', label: 'Terminal', hotkey: 't' }]
16 : [...common, { value: 'copy', label: 'Copy', hotkey: 'c' }]
17}
18
19// One prompt for several queued items. It hands the agent every detail and leaves the
20// method (order, one by one or in parallel with subagents) to the agent.
21export function batchPrompt(items: Item[], cwd: string): string {
22 const lines = [
23 `Work on these ${items.length} ledger items. Read them all first, then decide the best way to do them:`,
24 'the order, and whether to work them one after another or in parallel with subagents (parallel only',
25 'when they touch different files). Say your plan in a few lines, then carry it out. Ask me only when',
26 'something is truly ambiguous or needs my decision; otherwise proceed.',
27 ]
28 items.forEach((item, k) => {
29 lines.push('', `Item ${k + 1} of ${items.length} (id ${item.id}, ${item.kind}, project ${item.project}):`, item.title)
30 if (item.body) lines.push(item.body)
31 if (item.notes.length) lines.push('Notes:', ...item.notes.map((n) => `- ${n.by}: ${n.text}`))
32 if (item.project.toLowerCase() !== cwd.toLowerCase()) {
33 lines.push(`Note: this item came from a different project (${item.project}); this session is in ${cwd}.`)
34 }
35 })
36 lines.push('', 'When you finish an item, call update_item with its id and status done. If you cannot finish one,',
37 'call update_item with its id and a note saying what is left.')
38 return lines.join('\n')
39}
40
41export function startPrompt(item: Item, cwd: string): string {
42 const lines = [
43 `Work on this ledger item (id ${item.id}, ${item.kind}, from project ${item.project}):`,
44 item.title,
45 ]
46 if (item.body) lines.push(item.body)
47 if (item.notes.length) lines.push('Notes:', ...item.notes.map((n) => `- ${n.by}: ${n.text}`))
48 if (item.project.toLowerCase() !== cwd.toLowerCase()) {
49 lines.push(`Note: this item came from a different project (${item.project}); this session is in ${cwd}.`)
50 }
51 lines.push(`When finished, call update_item with id ${item.id} and status done.`)
52 return lines.join('\n')
53}
54
55// The full prompt never goes on a command line: Windows Terminal splits its own command line on ';'
56// (even inside one argument) and a newline ends a cmd command line. The new session gets a short
57// one-line task that points at a file holding the full prompt.
58export function terminalTask(id: string, file: string): string {
59 return `Work on todo-ledger item ${id}. Read the file ${file} and follow the instructions in it.`
60}
61
62function oneLine(s: string): string {
63 return s.replace(/[\r\n]+/g, ' ')
64}
65
66// wt documents '\;' as the escape for a literal ';' in its arguments.
67function wtEscape(s: string): string {
68 return oneLine(s).replace(/;/g, '\\;')
69}
70
71export function terminalArgv(project: string, task: string): string[] {
72 return ['wt', '-d', wtEscape(project), 'claude', wtEscape(task)]
73}
74
75// Fallback without Windows Terminal: `start` opens a new console in the project directory, where
76// `cmd /k` runs claude. No '&&' element: the outer `cmd /c` would run what follows it itself.
77export function fallbackArgv(project: string, task: string): string[] {
78 return ['cmd', '/c', 'start', '', '/d', oneLine(project), 'cmd', '/k', 'claude', oneLine(task)]
79}
80src/view.ts 74 lines1import { isOpen } from './item.ts'
2import type { Item, Kind } from './item.ts'
3
4export type Tab = 'agent' | 'human' | 'done'
5
6export const TABS: { id: Tab; label: string; hotkey: string }[] = [
7 { id: 'agent', label: 'Agent', hotkey: '1' },
8 { id: 'human', label: 'Human', hotkey: '2' },
9 { id: 'done', label: 'Done', hotkey: '3' },
10]
11
12// Tabs split by who started the item; the kind shows as a tag on the row instead.
13export function tabOf(item: Item): Tab {
14 if (!isOpen(item)) return 'done'
15 return item.origin === 'agent' ? 'agent' : 'human'
16}
17
18// Groups inside an open tab, ordered by what the item needs from the person:
19// a decision first, then work, then talk, then what was put off.
20export const GROUPS: { kind: Kind; label: string; mark: string; color?: string }[] = [
21 { kind: 'proposal', label: 'Needs decision', mark: '◆', color: 'suggestion' },
22 { kind: 'todo', label: 'To do', mark: '•' },
23 { kind: 'discussion', label: 'Discussion', mark: '◇' },
24 { kind: 'deferred', label: 'Parked', mark: '◇' },
25]
26
27export function groupItems(items: Item[]): { kind: Kind; label: string; mark: string; color?: string; items: Item[] }[] {
28 return GROUPS.map((g) => ({ ...g, items: items.filter((i) => i.kind === g.kind) })).filter((g) => g.items.length > 0)
29}
30
31export function itemsForTab(items: Item[], tab: Tab, project: string | null): Item[] {
32 const p = project?.toLowerCase() ?? null
33 const sortKey = (i: Item) => (tab === 'done' ? i.updatedAt : i.createdAt)
34 return items
35 .filter((i) => tabOf(i) === tab)
36 .filter((i) => p === null || i.project.toLowerCase() === p)
37 .sort((a, b) => sortKey(b).localeCompare(sortKey(a)))
38 .slice(0, tab === 'done' ? 50 : 100)
39}
40
41const inProject = (i: Item, project: string | null) => project === null || i.project.toLowerCase() === project.toLowerCase()
42
43// The footer button. It counts what the pane first shows (this project's open
44// items) and is always drawn, so the pane (Done tab included) stays reachable.
45// Compact: it shares the footer row with the mode labels.
46export function bandLabel(items: Item[], project: string | null = null): string {
47 const open = items.filter((i) => isOpen(i) && inProject(i, project))
48 return "☰ ToDo's" + (open.length ? ' ' + open.length : '')
49}
50
51// Where the pane opens: this project unless it has nothing open while others do,
52// and the open tab with items (Agent first) rather than an empty one.
53export function firstView(items: Item[], project: string, tab: Tab, allProjects: boolean): { tab: Tab; allProjects: boolean } {
54 const open = items.filter(isOpen)
55 const all = allProjects || (!open.some((i) => inProject(i, project)) && open.length > 0)
56 const scoped = open.filter((i) => all || inProject(i, project))
57 const has = (t: Tab) => scoped.some((i) => tabOf(i) === t)
58 if (tab !== 'done' && has(tab)) return { tab, allProjects: all }
59 return { tab: has('agent') ? 'agent' : has('human') ? 'human' : tab, allProjects: all }
60}
61
62// The list in the order the pane draws it: groups in GROUPS order inside an open tab.
63export function displayOrder(rows: Item[], tab: Tab): Item[] {
64 return tab === 'done' ? rows : groupItems(rows).flatMap((g) => g.items)
65}
66
67export function age(nowMs: number, iso: string): string {
68 const s = Math.max(0, (nowMs - Date.parse(iso)) / 1000)
69 if (s < 60) return 'now'
70 if (s < 3600) return Math.floor(s / 60) + 'm'
71 if (s < 86400) return Math.floor(s / 3600) + 'h'
72 return Math.floor(s / 86400) + 'd'
73}
74src/theme.ts 46 lines1// Colour themes for the pane. One button steps through them in order.
2//
3// Hues are mid-tones so they read on light and dark backgrounds. `accent` marks what
4// needs attention (the open card, decisions, started items); `tint` is the hue the
5// desktop draws behind things at low alpha; project, session and age colour the meta
6// line. The terminal cannot draw alpha, so there only the text colours apply.
7export interface Theme {
8 id: string
9 label: string
10 // A colour name from the person's own Claude theme, or a hex.
11 accent: string
12 // Hex, for the alpha tints (this-session rows, the pane wash).
13 tint: string
14 project: string
15 session: string
16 age: string
17}
18
19export const THEMES: readonly Theme[] = [
20 // Follows the person's own Claude theme for its accent.
21 { id: 'ledger', label: 'Ledger', accent: 'suggestion', tint: '#8b9cf7', project: '#5b8fd9', session: '#a57fd6', age: '#4fa88a' },
22 // Cool teal and sky over a deep-sea wash.
23 { id: 'aurora', label: 'Aurora', accent: '#14b8a6', tint: '#14b8a6', project: '#0ea5e9', session: '#8b5cf6', age: '#65a30d' },
24 // Warm orange and rose, like embers.
25 { id: 'ember', label: 'Ember', accent: '#f97316', tint: '#f97316', project: '#ec4899', session: '#f59e0b', age: '#ef4444' },
26 // Fresh green with teal and lime.
27 { id: 'forest', label: 'Forest', accent: '#22c55e', tint: '#22c55e', project: '#14b8a6', session: '#84cc16', age: '#eab308' },
28 // Neutral slate: one quiet hue, for a calm list.
29 { id: 'graphite', label: 'Graphite', accent: '#94a3b8', tint: '#94a3b8', project: '#94a3b8', session: '#cbd5e1', age: '#64748b' },
30]
31
32export function themeById(id: unknown): Theme {
33 return THEMES.find((t) => t.id === id) ?? THEMES[0]
34}
35
36export function nextTheme(id: string): Theme {
37 const at = THEMES.findIndex((t) => t.id === id)
38 return THEMES[(at + 1) % THEMES.length]
39}
40
41// `#rrggbb` plus a two-digit alpha: the desktop's translucent colours.
42export function withAlpha(hex: string, alpha: number): string {
43 const a = Math.max(0, Math.min(255, Math.round(alpha * 255)))
44 return hex + a.toString(16).padStart(2, '0')
45}
46