SLOPSHOPPER

todo-list

Keeps a running list of open items from the conversation and shows it above the prompt.

panebandcommandtoastpromptmodel
★ 1v0.9.1MITupdated 2026-10-15cldotdev/claude-todo-list
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · todo-list
│ ┃ todos ✕ › fix the failing auth test and add an audit log call │ ┃ Todos │ ┃ No open items. ⏺ Read(src/auth.ts) │ ┃ t: band ⎿ 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 │ │ › /todos │ ⎿ todo-list: No open items. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · todos
Todos No open items. t: band
README

Claude Todo List

CI

English | 繁體中文

A Claude Code mod that keeps a running list of the open items in a conversation and shows it in a band above the prompt.

Long sessions leave decisions, promised follow-ups, and unanswered questions far back in the conversation, where they are easy to drop. The mod collects them as the conversation goes, so they stay in sight until they are settled.

Demo

How It Works

  • After each main-loop turn that ends with an answer, the mod sends the turn to Sonnet (the sonnet alias, so the model follows the installed Claude Code version) and asks which current items the turn resolved and which new ones it opened. Subagent turns do not count.
  • An open item is work someone deferred, a follow-up or check the agent promised, or a question or decision that is not settled yet. The step being carried out right now, anything finished within the same turn, and tasks already listed in an OpenSpec tasks.md stay off the list.
  • Each item has a one-line title and a short detail, written in the language the agent answers in.
  • The list is kept per session and comes back when the session is resumed. A saved list left unchanged for longer than cleanupPeriodDays, the setting for how long Claude Code keeps transcripts (30 days by default), is dropped. When the saved lists of all sessions pass 80% of the 4 MiB the mod's store can hold, the lists left unchanged the longest are dropped until they are back at 80%, never the current session's. If a list cannot be saved, a toast says so once per session. /clear empties the list and the trash.
  • Every item that leaves the list goes to a trash with its title, its detail, who removed it (you or the model), and when. Each source keeps its newest 99 entries. Items you removed are never added back; items the model removed are not added back unless the conversation reopens them.
  • An item that a later turn made moot has no turn of its own to remove it, so a review also runs over the recent turns: after 8 answered turns, or after 3 when the list holds 6 or more items. It only removes items that are no longer open; it never adds any. Removed items can be brought back with /todos restore.

Each answered turn costs one extra Sonnet call, and a review adds one more, at most one every 3 turns. /todos refresh forks the main conversation, so it runs on the main model with the whole context. It reviews each item on the list against that context: it removes the ones that are no longer open, adds missing ones, and may rewrite a kept item's detail, while every kept item keeps its title. Right after a resume there is nothing to fork yet, so it rebuilds the list from the transcript instead, on the main model without the prompt cache, which costs more. The transcript holds the newest 200,000 characters of the conversation, with each tool result cut to 2,000.

Requirements

Claude Code with mod support (>= 2.1.299).

Installation

Install it from this repository's marketplace:

claude plugin marketplace add cldotdev/claude-todo-list
claude plugin install todo-list@claude-todo-list

Usage

The /todos Command

CommandEffect
/todosLists the open items with their details.
/todos paneOpens the list in a pane, see The Pane. From an empty prompt it hands the keys to the pane, also when the pane is already open. /todos pane <text> still sends pane <text> as a prompt.
/todos refreshReviews each item against the whole conversation: removes items that are no longer open, adds missing ones, and refreshes details.
/todos clearDeletes every item. The items go to the trash as your deletions.
/todos resetEmpties the list and the trash, which also lifts every never-add-back block.
/todos trashLists the removed items, newest first, with their details and who removed each.
/todos restore <numbers>Puts items from the trash back on the list, numbered as /todos trash shows them and written like delete numbers. A number past the end of the trash cancels the whole restore.
/todos purge <numbers>Removes entries from the trash for good, numbered as /todos trash shows them. Purging an item you deleted lets the model add it back.
/todos delete <numbers>Deletes items by number, such as 2, 1-3, or 1,4 6. A number past the end of the list cancels the whole delete.
/todos <prompt>Sends the prompt with every item quoted and numbered above it, so the prompt can say "do 1 and 2, skip 3".

The Band

The band above the prompt shows the numbered list while it has items and the pane is closed. It shows its items as a window over the list, each with its number in the whole list, and a dim <n> more line under them counts the items after the window. The window holds as many items as fit in the rows Claude Code gives the band, up to 10, so a long draft in the prompt box shrinks the window instead of scrolling the band. When the band holds the focus, its help line is longer and may take another row, which can drop one item from a squeezed window. Leaving the band puts the window back at the top.

KeyAction
Ctrl+X TabFocus the band.
j/k, Tab/Shift+TabMove to the next or previous item.
sSelect or unselect the focused item.
aSelect every item, or clear the selection when every item is already selected.
n/pMove the window down or up by up to the number of items it shows; the focus keeps its row in the window. They do nothing when the whole list fits in the window, when the window cannot move further, or in the detail view.
vPaste the selected items, or the focused item when none is selected, into the prompt box. Each is quoted with its number in the band.
o/EnterShow the focused item's detail, or go back to the list.
tSwitch to the pane, which hides the band.
bAsk /btw about the focused item. While Claude is working, the answer waits for the current turn to end.
dDelete the focused item; a second d confirms and Esc cancels.
EscReturn to the prompt. The band goes back to the list if it was showing an item's detail.

The Pane

The pane lists the items in a pane of its own, which Claude Code docks beside the transcript from 110 columns in fullscreen, floor to ceiling, so a long prompt does not squeeze it. Every title is drawn whole, wrapped over as many rows as it needs, where the band cuts an unfocused title to one row. Its window holds as many items as fit in rows, with no cap of 10, and a dim <n> more line counts the items after it. With an empty list it shows No open items.

  • Opening: t on the band or /todos pane opens it. Besides that it opens on its own only at session start or on a resume when the default view is pane, never when the band is squeezed. While the pane is open the band is not drawn, so the list shows in one place. /todos pane with an empty prompt box and nothing else holding the keys gives the pane the keys, also when it is already open. After t, the band still held the keys when the pane asked for them, so press Ctrl+X Tab once to reach the pane.
  • Default view: the default_view setting, band (the default) or pane, shows in /config as todo-list.default_view and is saved in your settings. It applies when a session starts or is resumed, also with an empty list, and the pane it opens takes no keys, so what you type still goes to the prompt box; a change in /config takes effect at the next session start, and t switches at once. A hot reload of the mod and /clear do not apply it again. The pane opens only where Claude Code has room for it: a pane you did not ask for needs a terminal 144 columns wide (110 once you have opened it by hand), and on a narrower one the band stays.
  • Closing: t on the pane, Ctrl+X X, or the pane's close mark closes it and brings the band back. It also clears the pane's focus, selection, and expanded detail. Esc hands the keys back to the prompt box and keeps the pane open. /clear empties the pane's state but leaves it open.
  • Keys: the band's own, j/k, Tab/Shift+Tab, s, a, n/p, v, o/Enter, b, and d, with two differences: o/Enter expands the focused item's detail under its row, one item at a time, with the rest of the list still shown; moving the focus moves the expansion, and a second o collapses it; the pane has t to go back to the band instead of the band's t for the pane.
  • State: the pane keeps its own focus, expanded detail, selection, armed delete, and window, apart from the band's. Typing in the prompt box, sending a prompt, and Esc do not reset them, and the band's leave does not touch them. A successful v clears the pane's selection. While the pane lacks the keys, it draws no focus dot but keeps its focus, and its help line names Ctrl+X Tab as the way back. When an item leaves the list by anything other than the pane's own delete, the pane's focus moves to the item now at the same position.

Development

PathContents
hooks/register.tsxEvent hooks, the /todos command, the band, and the pane.
hooks/list.tsModel prompts, reply parsing, and the window arithmetic of the band and the pane.
hooks/store.tsStore keys and the arithmetic that keeps the store under its size cap.
types/index.d.tsThe mod's state contract.
tests/Tests run by claude plugin test.
claude plugin validate .
claude plugin test .

To try local changes, start Claude Code with the clone loaded for that session:

claude --plugin-dir /path/to/claude-todo-list

The clone replaces an installed todo-list@claude-todo-list for that session, so there is no need to disable or uninstall it first.

License

MIT

Source 4 files
hooks/register.tsx 1569 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { PendingTurn, ReviewTurn, TodoItem, TodoListState, TrashEntry, ViewKind } from '../types'
5import {
6  MAX_TRASH,
7  REVIEW_MIN_ITEMS,
8  REVIEW_MIN_TURNS,
9  REVIEW_SYSTEM,
10  REVIEW_TURNS,
11  SYSTEM,
12  WINDOW_SIZE,
13  type RemovedTitles,
14  applyChanges,
15  applyRefresh,
16  applyReview,
17  cellWidth,
18  charWidth,
19  cleanItems,
20  isItem,
21  incrementalPrompt,
22  normalizeParens,
23  parseNumbers,
24  prefixLines,
25  refreshPrompt,
26  renderTranscript,
27  removedTitles,
28  pageRows,
29  reviewPrompt,
30  rowWindow,
31  wrapRows,
32} from './list'
33import {
34  STORE_CAP,
35  type SavedKey,
36  keysToDrop,
37  legacyId,
38  parseKey,
39  savedKeyFor,
40} from './store'
41
42const MODEL = 'sonnet'
43const DAY_MS = 24 * 60 * 60 * 1000
44// Claude Code's own default for cleanupPeriodDays.
45const DEFAULT_CLEANUP_DAYS = 30
46const COMPLETE_TIMEOUT_MS = 60_000
47// The transcript fallback sends up to TRANSCRIPT_TEXT characters to the main model.
48const TRANSCRIPT_TIMEOUT_MS = 180_000
49// Rows take no hotkey: a digit hotkey also fires from an empty prompt, so a
50// message starting with "1." would quote the first item. A letter fires only
51// while the band holds the focus.
52const NEXT_KEY = 'j'
53const PREVIOUS_KEY = 'k'
54const DETAILS_KEY = 'o'
55const SELECT_KEY = 's'
56const SELECT_ALL_KEY = 'a'
57const PASTE_KEY = 'v'
58const NEXT_PAGE_KEY = 'n'
59const PREVIOUS_PAGE_KEY = 'p'
60const ASK_KEY = 'b'
61const DELETE_KEY = 'd'
62// Not hotkeys: Enter presses the focused row's Button, which shows its detail.
63const ENTER_KEY = 'Enter'
64const LEAVE_KEY = 'Esc'
65// Switches between the band and the pane.
66const TOGGLE_KEY = 't'
67const PANE_ID = 'todos'
68const PANE_TITLE = 'Todos'
69// The /config row of the plugin's `default_view` userConfig field.
70const DEFAULT_VIEW_KEY = 'todo-list.default_view'
71const NO_DETAIL = '(No detail. Run /todos refresh to add one.)'
72
73// The longest start of `text` that fits in `cells`, with an ellipsis.
74function fit(text: string, cells: number): string {
75  let used = 1
76  let out = ''
77  for (const ch of text) {
78    used += charWidth(ch)
79    if (used > cells) {
80      break
81    }
82    out += ch
83  }
84  return `${out}…`
85}
86
87// A trailing parenthetical, such as an item's caveat, drawn apart from the rest.
88const NOTE = /^(.*?)\s*(\([^()]*\))$/
89const ROW_PREFIX = 'item-'
90// How often the band checks whether the person has left it with Esc.
91const LEAVE_CHECK_MS = 100
92// The width of a row's focus marker and the space after it, so the title and
93// the help line start where the item numbers do.
94const GUTTER = '  '
95// A theme key, so a selected row follows the person's theme.
96const SELECTED_COLOR = 'suggestion'
97// Palette index 1 (red), so the terminal theme picks the shade. A plugin's
98// color may not hold a colon, which rules out `ansi:red`.
99const DELETE_COLOR = 'ansi256(1)'
100
101const items = atom({ plugin: 'todo-list', key: 'items' } as const, [])
102const trash = atom({ plugin: 'todo-list', key: 'trash' } as const, [] as TrashEntry[])
103// The counted turns since the last review. Like `pending`, it needs no store: a
104// resumed session starts a new window.
105const review = atom({ plugin: 'todo-list', key: 'review' } as const, [] as ReviewTurn[])
106// Titles: the item the band's focus ring stands on ('' while the ring is
107// outside the band), and the item whose detail the band shows.
108const focused = atom({ plugin: 'todo-list', key: 'focused' } as const, '')
109const detailed = atom({ plugin: 'todo-list', key: 'detailed' } as const, '')
110// The title of the item the first delete press armed; the next press deletes it.
111const deleting = atom({ plugin: 'todo-list', key: 'deleting' } as const, '')
112// Titles of the items picked for a paste. Session-only: never written to the store.
113const selected = atom({ plugin: 'todo-list', key: 'selected' } as const, [] as string[])
114// The index of the window's first item. Like the focus, it lasts only while the
115// band holds the focus.
116const windowStart = atom({ plugin: 'todo-list', key: 'windowStart' } as const, 0)
117// The pane's own copies of the five band atoms above, plus the position of the
118// item it last focused. They last until the pane closes.
119const paneFocused = atom({ plugin: 'todo-list', key: 'paneFocused' } as const, '')
120const paneFocusIndex = atom({ plugin: 'todo-list', key: 'paneFocusIndex' } as const, 0)
121const paneDetailed = atom({ plugin: 'todo-list', key: 'paneDetailed' } as const, '')
122const paneDeleting = atom({ plugin: 'todo-list', key: 'paneDeleting' } as const, '')
123const paneSelected = atom({ plugin: 'todo-list', key: 'paneSelected' } as const, [] as string[])
124const paneWindowStart = atom({ plugin: 'todo-list', key: 'paneWindowStart' } as const, 0)
125// Which view shows the list. Session-only: never written to the store. The band
126// draws nothing in pane mode.
127const mode = atom({ plugin: 'todo-list', key: 'mode' } as const, 'band' as ViewKind)
128// Whether this process has applied the default view yet. It lives in $.state so
129// a hot reload, which runs session.start again, does not reapply it.
130const viewApplied = atom({ plugin: 'todo-list', key: 'viewApplied' } as const, false)
131// The last main-loop answer, which the next user message often replies to.
132const lastAnswer = atom({ plugin: 'todo-list', key: 'lastAnswer' } as const, '')
133// Finished turns not yet applied. They live in $.state, not the module, because
134// a hot reload cancels the module's timers: a turn queued as the reload lands
135// waits here, and session.start, which runs again after the reload, picks it up.
136const pending = atom({ plugin: 'todo-list', key: 'pending' } as const, [] as PendingTurn[])
137// The store key this session's entry is saved under now, '' while it has none.
138const savedKey = atom({ plugin: 'todo-list', key: 'savedKey' } as const, '')
139// Whether the failed-save toast has been shown, so a hot reload does not repeat it.
140const failureShown = atom({ plugin: 'todo-list', key: 'failureShown' } as const, false)
141
142// An entry saved before items had a detail holds plain strings, and one saved
143// before the trash holds the titles the user removed as `done`.
144type Stored = {
145  items: (string | TodoItem)[]
146  trash?: TrashEntry[]
147  done?: string[]
148  updatedAt: number
149}
150
151const isTrashEntry = (value: unknown): value is TrashEntry =>
152  isItem(value) &&
153  ((value as TrashEntry).by === 'user' || (value as TrashEntry).by === 'model') &&
154  typeof (value as TrashEntry).at === 'number'
155
156const isStored = (value: unknown): value is Stored =>
157  typeof value === 'object' &&
158  value !== null &&
159  Array.isArray((value as Stored).items) &&
160  (value as Stored).items.every(one => typeof one === 'string' || isItem(one)) &&
161  ((value as Stored).trash === undefined ||
162    (Array.isArray((value as Stored).trash) && ((value as Stored).trash ?? []).every(isTrashEntry))) &&
163  (Array.isArray((value as Stored).trash) || Array.isArray((value as Stored).done)) &&
164  typeof (value as Stored).updatedAt === 'number'
165
166const migrate = (stored: (string | TodoItem)[]): TodoItem[] =>
167  stored.map(one => (typeof one === 'string' ? { title: one, detail: '' } : one))
168
169const loadTrash = (stored: Stored): TrashEntry[] =>
170  stored.trash ?? (stored.done ?? []).map(title => ({ title, detail: '', by: 'user', at: stored.updatedAt }))
171
172// Each source keeps its own newest MAX_TRASH entries.
173function capTrash(entries: readonly TrashEntry[]): TrashEntry[] {
174  const newest = (by: TrashEntry['by']) => entries.filter(one => one.by === by).slice(-MAX_TRASH)
175  const kept = new Set([...newest('user'), ...newest('model')])
176  return entries.filter(one => kept.has(one))
177}
178
179// A saved list lives as long as Claude Code keeps the session's transcript,
180// since a session it has deleted cannot be resumed. Null for an invalid
181// setting, under which Claude Code pauses its own cleanup.
182async function maxAgeMs($: EngineInterface): Promise<number | null> {
183  const { cleanupPeriodDays: days = DEFAULT_CLEANUP_DAYS } = await $.settings.read()
184  return typeof days === 'number' && days >= 1 ? days * DAY_MS : null
185}
186
187const userTexts = new Map<string, string>()
188// Runs list updates one at a time, so two turns never race.
189let queue: Promise<unknown> = Promise.resolve()
190// Bumped by /clear so a job that started before it drops its result.
191let generation = 0
192// Whether a leave check is scheduled, so focus moves start only one.
193let isWatchingLeave = false
194
195// The selection as the list holds it now: a deleted item drops out.
196const pickedFrom = (list: readonly TodoItem[], titles: readonly string[]) =>
197  list.filter(one => titles.includes(one.title))
198
199// A view's atom, reached through closures over `$`: the engine's state scan
200// reads only atoms named directly in a `read` or `update` call, and refuses `$`
201// passed as an argument.
202type Slot<T> = {
203  get: () => Promise<T>
204  set: (next: (current: T) => T) => Promise<unknown>
205}
206
207type Slots = {
208  focused: Slot<string>
209  detailed: Slot<string>
210  deleting: Slot<string>
211  selected: Slot<string[]>
212  windowStart: Slot<number>
213}
214
215// What the actions act on: the band or the pane, each with its own atoms.
216type View = Slots & {
217  kind: ViewKind
218  // The site the focus ring moves on.
219  requestId: string
220  // The pane only: where its focus last stood.
221  focusIndex?: Slot<number>
222}
223
224const bandSlots = ($: EngineInterface): Slots => ({
225  focused: { get: () => read($, focused), set: next => update($, focused, next) },
226  detailed: { get: () => read($, detailed), set: next => update($, detailed, next) },
227  deleting: { get: () => read($, deleting), set: next => update($, deleting, next) },
228  selected: { get: () => read($, selected), set: next => update($, selected, next) },
229  windowStart: { get: () => read($, windowStart), set: next => update($, windowStart, next) },
230})
231
232const bandView = ($: EngineInterface, requestId: string): View => ({ ...bandSlots($), kind: 'band', requestId })
233
234const paneView = ($: EngineInterface): View => ({
235  kind: 'pane',
236  requestId: PANE_ID,
237  focused: { get: () => read($, paneFocused), set: next => update($, paneFocused, next) },
238  detailed: { get: () => read($, paneDetailed), set: next => update($, paneDetailed, next) },
239  deleting: { get: () => read($, paneDeleting), set: next => update($, paneDeleting, next) },
240  selected: { get: () => read($, paneSelected), set: next => update($, paneSelected, next) },
241  windowStart: { get: () => read($, paneWindowStart), set: next => update($, paneWindowStart, next) },
242  focusIndex: { get: () => read($, paneFocusIndex), set: next => update($, paneFocusIndex, next) },
243})
244
245// What each view last drew, for its row-based window; key handlers cannot see
246// the render's props. `titles` and `details` hold each item's title rows and
247// the rows its detail would take expanded (empty for the band, whose items are
248// one row each), `rows` the rows left for items, `cap` the most items a window
249// holds. Until a view draws, a window of the band's size and the `<n> more` row.
250type Drawn = { titles: number[]; details: number[]; rows: number; cap: number }
251const undrawn = (cap: number): Drawn => ({ titles: [], details: [], rows: WINDOW_SIZE + 1, cap })
252const drawn: Record<ViewKind, Drawn> = { band: undrawn(WINDOW_SIZE), pane: undrawn(Infinity) }
253
254// The view's item heights with the detail expanded on the item titled
255// `expandedTitle` ('' for none). An item past the drawn list counts as one row.
256const heightsOf = (view: View, list: readonly TodoItem[], expandedTitle: string) => {
257  const { titles, details } = drawn[view.kind]
258  return list.map((one, i) => (titles[i] ?? 1) + (one.title === expandedTitle ? (details[i] ?? 0) : 0))
259}
260
261// Whether a turn is running, as the band last saw it. The pane gets no such prop.
262let isWorking = false
263// Whether the pane held the keys when it last drew.
264let isPaneHeld = false
265
266// The index of the item holding the focus, -1 for none. The pane also keeps the
267// position it last focused, so an item that left the list hands the focus to
268// the one now there.
269function resolveFocus(list: readonly TodoItem[], title: string, stored?: number): number {
270  const index = list.findIndex(one => one.title === title)
271  return index !== -1 || title === '' || stored === undefined ? index : Math.min(stored, list.length - 1)
272}
273
274async function focusOf(view: View, list: readonly TodoItem[]): Promise<number> {
275  const [title, stored] = await Promise.all([view.focused.get(), view.focusIndex?.get()])
276  return resolveFocus(list, title, stored)
277}
278
279async function setSelected(view: Pick<View, 'selected'>, next: string[]) {
280  const same = (list: string[]) => list.length === next.length && list.every((title, i) => title === next[i])
281  if (!same(await view.selected.get())) {
282    await view.selected.set(() => next)
283  }
284}
285
286async function disarm(view: Pick<View, 'deleting'>) {
287  if ((await view.deleting.get()) !== '') {
288    await view.deleting.set(() => '')
289  }
290}
291
292async function clearPane($: EngineInterface) {
293  isPaneHeld = false
294  await Promise.all([
295    update($, paneFocused, () => ''),
296    update($, paneFocusIndex, () => 0),
297    update($, paneDetailed, () => ''),
298    update($, paneDeleting, () => ''),
299    update($, paneSelected, () => []),
300    update($, paneWindowStart, () => 0),
301  ])
302}
303
304// What every close of the pane ends with, so the list is never left without a view.
305const backToBand = ($: EngineInterface) => Promise.all([clearPane($), update($, mode, () => 'band')])
306
307// A close raised from the pane's own Button does not reach this plugin's
308// ui.close hook, so the band comes back here as well.
309async function closePane($: EngineInterface) {
310  await $.ui.close({ id: PANE_ID })
311  await backToBand($)
312}
313
314// The dot, the selection, a pending delete, the detail view, and the window's
315// position last only while the band holds the focus.
316async function leave($: EngineInterface) {
317  const [current, shown, start] = await Promise.all([read($, focused), read($, detailed), read($, windowStart)])
318  if (start !== 0) {
319    await update($, windowStart, () => 0)
320  }
321  if (current !== '') {
322    await update($, focused, () => '')
323  }
324  if (shown !== '') {
325    await update($, detailed, () => '')
326  }
327  const view = bandSlots($)
328  await setSelected(view, [])
329  await disarm(view)
330}
331
332// The band raises no event when the person leaves it with Esc. While the dot
333// is shown, a timer asks the engine to put the ring back on the focused row;
334// the engine refuses once the band no longer holds the keys, and the refusal
335// counts as leaving.
336function watchLeave($: EngineInterface, requestId: string) {
337  if (isWatchingLeave) {
338    return
339  }
340  isWatchingLeave = true
341  const check = async () => {
342    const [list, current] = await Promise.all([read($, items), read($, focused)])
343    const index = list.findIndex(one => one.title === current)
344    if (index !== -1) {
345      const { deny } = await $.ui.focus({ requestId, key: `${ROW_PREFIX}${index}` })
346      if (deny === undefined) {
347        schedule()
348        return
349      }
350      await leave($)
351    }
352    isWatchingLeave = false
353  }
354  const schedule = () => {
355    $.clock.after(LEAVE_CHECK_MS, () => {
356      check().catch(() => {
357        isWatchingLeave = false
358      })
359    })
360  }
361  schedule()
362}
363
364function enqueue<T>(job: () => Promise<T>): Promise<T> {
365  const run = queue.then(job)
366  queue = run.catch(() => undefined)
367  return run
368}
369
370// Saves run one at a time, apart from `queue`: commit already runs inside queued
371// jobs, and the restore and purge commands save outside it.
372let saves: Promise<unknown> = Promise.resolve()
373
374function persist($: EngineInterface) {
375  const run = saves.then(() => save($))
376  saves = run.catch(() => undefined)
377  return run
378}
379
380// Deletes whole sessions, oldest first, to bring the store down to its target.
381async function freeRoom($: EngineInterface, currentId: string) {
382  const saved = (await $.store.keys()).flatMap(key => parseKey(key) ?? [])
383  for (const key of keysToDrop(saved, currentId)) {
384    await $.store.delete(key)
385  }
386}
387
388// A refusal for size is the only one worth a retry; a changed message turns it
389// into a reported failure.
390async function setWithRetry($: EngineInterface, currentId: string, key: string, value: unknown) {
391  try {
392    await $.store.set(key, value)
393  } catch (error) {
394    if (!String(error).includes(`over the ${STORE_CAP} limit`)) {
395      throw error
396    }
397    await freeRoom($, currentId)
398    await $.store.set(key, value)
399  }
400}
401
402// Writes the new key before deleting the old one, so a crash between them
403// leaves two keys for the session instead of none. Failures are reported here,
404// so callers carry on as if the save worked.
405async function save($: EngineInterface) {
406  try {
407    const [id, list, entries] = await Promise.all([$.session.id(), read($, items), read($, trash)])
408    const state: TodoListState = { items: list, trash: entries }
409    const isEmpty = state.items.length === 0 && state.trash.length === 0
410    const updatedAt = await $.clock.now()
411    const value = { ...state, updatedAt }
412    const key = isEmpty ? '' : savedKeyFor(id, updatedAt, JSON.stringify(value).length)
413    if (!isEmpty) {
414      await setWithRetry($, id, key, value)
415    }
416    // The swap reads the latest key; a read in another dispatch can be stale.
417    let previous = ''
418    await update($, savedKey, current => {
419      previous = current
420      return key
421    })
422    if (previous !== '' && previous !== key) {
423      await $.store.delete(previous)
424    }
425  } catch (error) {
426    $.ui.log(`Could not save the list: ${String(error)}`)
427    if (!(await read($, failureShown))) {
428      await update($, failureShown, () => true)
429      $.ui.toast('List changes are not being saved.')
430    }
431  }
432}
433
434async function commit($: EngineInterface, next: TodoItem[]) {
435  await update($, items, () => next)
436  await persist($)
437}
438
439// A new entry replaces an older one with the same title.
440async function record($: EngineInterface, removed: readonly TodoItem[], by: TrashEntry['by']) {
441  if (removed.length === 0) {
442    return
443  }
444  const at = await $.clock.now()
445  const titles = new Set(removed.map(one => one.title))
446  await update($, trash, list =>
447    capTrash([...list.filter(one => !titles.has(one.title)), ...removed.map(one => ({ ...one, by, at }))]),
448  )
449}
450
451async function tick($: EngineInterface, titles: readonly string[]) {
452  const ticked = new Set(titles)
453  const list = await read($, items)
454  await update($, items, current => current.filter(one => !ticked.has(one.title)))
455  await record($, pickedFrom(list, titles), 'user')
456  await persist($)
457}
458
459// `1. ` through `10. `, padded to the widest number so every title starts in
460// one column.
461const labelWidth = (last: number) => `${last}.`.length + 1
462const numberLabel = (number: number, width: number) => `${number}.`.padEnd(width)
463
464// Numbered titles, each with its detail lined up under it.
465function numberedLines<T extends TodoItem>(list: readonly T[], title: (one: T) => string = one => one.title): string[] {
466  const width = labelWidth(list.length)
467  return list.flatMap((one, i) => {
468    const line = `${numberLabel(i + 1, width)}${title(one)}`
469    return one.detail === '' ? [line] : [line, prefixLines(one.detail, ' '.repeat(width))]
470  })
471}
472
473// The detail lines up under the title.
474function quoteBlock(item: TodoItem, number: number, width: number): string {
475  const label = numberLabel(number, width)
476  const text =
477    item.detail === ''
478      ? `${label}${item.title}`
479      : `${label}${item.title}\n${prefixLines(item.detail, ' '.repeat(label.length))}`
480  return `${prefixLines(text, '> ')}\n`
481}
482
483// Numbered as the list shows them, so a prompt can say "do 1 and 2, skip 3",
484// with a bare quote line between items.
485function quoteItems(list: readonly TodoItem[], picked: readonly TodoItem[]): string {
486  const numbers = picked.map(one => list.indexOf(one) + 1)
487  const width = labelWidth(Math.max(...numbers))
488  return picked.map((one, i) => quoteBlock(one, numbers[i]!, width)).join('>\n')
489}
490
491async function insertQuote($: EngineInterface, quoted: string): Promise<boolean> {
492  const filled = await $.prompt.fill({ text: `${quoted}\n`, mode: 'insert' })
493  if (!filled.isFilled) {
494    $.ui.toast('Could not insert into the prompt box. Close the dialog and try again.')
495  }
496  return filled.isFilled
497}
498
499// Pastes the selected items, or the focused one when nothing is selected, each
500// numbered as in the list.
501async function paste($: EngineInterface, view: View) {
502  await disarm(view)
503  const [list, titles] = await Promise.all([read($, items), view.selected.get()])
504  const target = list[await focusOf(view, list)]
505  let picked = pickedFrom(list, titles)
506  if (picked.length === 0 && target !== undefined) {
507    picked = [target]
508  }
509  if (picked.length === 0) {
510    return
511  }
512  // A failed paste keeps the selection for the retry the toast asks for.
513  if (await insertQuote($, quoteItems(list, picked))) {
514    await setSelected(view, [])
515  }
516}
517
518async function toggleSelected($: EngineInterface, view: View) {
519  await disarm(view)
520  const [list, titles] = await Promise.all([read($, items), view.selected.get()])
521  const target = list[await focusOf(view, list)]?.title
522  if (target === undefined) {
523    return
524  }
525  const rest = pickedFrom(list, titles).map(one => one.title)
526  await setSelected(view, rest.includes(target) ? rest.filter(title => title !== target) : [...rest, target])
527}
528
529async function toggleAll($: EngineInterface, view: View) {
530  await disarm(view)
531  const [list, titles] = await Promise.all([read($, items), view.selected.get()])
532  if (list.length === 0) {
533    return
534  }
535  const isAll = pickedFrom(list, titles).length === list.length
536  await setSelected(view, isAll ? [] : list.map(one => one.title))
537}
538
539// Asks the built-in /btw about the focused item. It is not awaited: /btw
540// resolves only once it has run, which waits for the turn in progress to end.
541async function askAbout($: EngineInterface, view: View) {
542  await disarm(view)
543  const list = await read($, items)
544  const target = list[await focusOf(view, list)]?.title
545  if (target === undefined) {
546    return
547  }
548  const args = `Tell me more about this open item from our conversation: "${target}". What is it, why is it still open, and what would close it? Answer in the language of the conversation.`
549  $.command.run({ command: 'btw', args }).catch(() => {
550    $.ui.toast('Could not ask /btw about this item.')
551  })
552  if (isWorking) {
553    $.ui.toast('The /btw answer will appear once the current turn ends.')
554  }
555}
556
557async function setFocus(view: View, title: string, index: number) {
558  if ((await view.focused.get()) !== title) {
559    await view.focused.set(() => title)
560  }
561  if (view.focusIndex !== undefined && (await view.focusIndex.get()) !== index) {
562    await view.focusIndex.set(() => index)
563  }
564}
565
566// Puts the dot on the item at `index`. A delete armed on another item is
567// cancelled, the detail view walks from one item's detail to the next, and the
568// window scrolls just far enough to show the item.
569async function focusItem($: EngineInterface, view: View, index: number) {
570  const [list, shownTitle, armed, start] = await Promise.all([
571    read($, items),
572    view.detailed.get(),
573    view.deleting.get(),
574    view.windowStart.get(),
575  ])
576  const item = list[index]
577  if (item === undefined) {
578    return
579  }
580  const current = await focusOf(view, list)
581  await setFocus(view, item.title, index)
582  const { rows, cap } = drawn[view.kind]
583  // The pane's expansion moves with the focus, so the heights differ before and after.
584  const heightsBefore = heightsOf(view, list, shownTitle)
585  const heightsAfter = shownTitle === '' ? heightsBefore : heightsOf(view, list, item.title)
586  // Start from the window as drawn, which clamps a stale start.
587  const before = rowWindow(heightsBefore, start, current, rows, cap)
588  const scrolled = rowWindow(heightsAfter, before.start, index, rows, cap).start
589  if (scrolled !== start) {
590    await view.windowStart.set(() => scrolled)
591  }
592  if (armed !== '' && armed !== item.title) {
593    await view.deleting.set(() => '')
594  }
595  if (shownTitle !== '' && shownTitle !== item.title) {
596    await view.detailed.set(() => item.title)
597  }
598}
599
600// Moves the ring to the next or previous row, wrapping around as Tab does. The
601// move skips this plugin's own ui.focus hook, so the dot moves here; left
602// behind, the leave check would pull the ring back to the old row.
603async function moveFocus($: EngineInterface, view: View, step: 1 | -1) {
604  const list = await read($, items)
605  const index = await focusOf(view, list)
606  if (index === -1) {
607    return
608  }
609  const target = (index + step + list.length) % list.length
610  const { deny } = await $.ui.focus({ requestId: view.requestId, key: `${ROW_PREFIX}${target}` })
611  if (deny === undefined) {
612    await focusItem($, view, target)
613  }
614}
615
616// Moves the window a page down or up, and the focus with it so the focus keeps
617// its row. Like moveFocus, it moves the ring itself.
618async function movePage($: EngineInterface, view: View, step: 1 | -1) {
619  const [list, start, shownTitle] = await Promise.all([read($, items), view.windowStart.get(), view.detailed.get()])
620  const index = await focusOf(view, list)
621  // The band's detail replaces the list; the pane's sits inside it.
622  const canPage = index !== -1 && (view.kind === 'pane' || shownTitle === '')
623  const { rows, cap } = drawn[view.kind]
624  const page = canPage ? pageRows(heightsOf(view, list, shownTitle), start, index, step, rows, cap) : null
625  if (page === null) {
626    return
627  }
628  const { deny } = await $.ui.focus({ requestId: view.requestId, key: `${ROW_PREFIX}${page.index}` })
629  if (deny === undefined) {
630    // focusItem scrolls the least distance from the old focus, so the page's
631    // own start is set after it.
632    await focusItem($, view, page.index)
633    if ((await view.windowStart.get()) !== page.start) {
634      await view.windowStart.set(() => page.start)
635    }
636  }
637}
638
639// Switches the band between the list and the focused item's detail, or the
640// pane's detail under the focused item.
641async function toggleDetails($: EngineInterface, view: View) {
642  await disarm(view)
643  if ((await view.detailed.get()) !== '') {
644    await view.detailed.set(() => '')
645    return
646  }
647  const list = await read($, items)
648  const target = list[await focusOf(view, list)]?.title
649  if (target !== undefined) {
650    await view.detailed.set(() => target)
651  }
652}
653
654// The first press arms the focused item; the second deletes it and moves the
655// focus to the next item, or the previous one after the last. The ring tracks
656// its stop by position, so after the last row goes it may stand on a hotkey
657// Button; the leave check puts it back on the focused row.
658async function deleteFocused($: EngineInterface, view: View) {
659  const list = await read($, items)
660  const index = await focusOf(view, list)
661  const target = list[index]?.title
662  if (target === undefined) {
663    return
664  }
665  if ((await view.deleting.get()) !== target) {
666    await view.deleting.set(() => target)
667    return
668  }
669  await tick($, [target])
670  await disarm(view)
671  const nextIndex = list[index + 1] === undefined ? index - 1 : index
672  const title = (list[index + 1] ?? list[index - 1])?.title ?? ''
673  await setFocus(view, title, Math.max(0, nextIndex))
674  await view.detailed.set(shown => (shown === '' ? '' : title))
675}
676
677// Resolves to the new list, or null when the list was left as it was. `sent`
678// is the list the model was asked about: an item that reached the list after
679// that, by a restore, was never judged, so it stays.
680async function applyList(
681  $: EngineInterface,
682  parsed: TodoItem[] | null,
683  gen: number,
684  sent: readonly TodoItem[],
685): Promise<TodoItem[] | null> {
686  if (parsed === null || gen !== generation) {
687    return null
688  }
689  const [current, entries] = await Promise.all([read($, items), read($, trash)])
690  // Deletes made while the model was thinking win over its reply.
691  const blocked = new Set(removedTitles(entries).user)
692  const sentTitles = new Set(sent.map(one => one.title))
693  const unjudged = current.filter(one => !sentTitles.has(one.title))
694  const next = cleanItems([...parsed.filter(one => !blocked.has(one.title)), ...unjudged])
695  // Most turns change nothing; writing anyway would redraw the band and rewrite the store.
696  if (JSON.stringify(next) !== JSON.stringify(current)) {
697    const kept = new Set(next.map(one => one.title))
698    await record($, current.filter(one => !kept.has(one.title) && !blocked.has(one.title)), 'model')
699    await commit($, next)
700  }
701  return next
702}
703
704async function ask(
705  $: EngineInterface,
706  gen: number,
707  request: {
708    system: string
709    maxTokens: number
710    prompt: (sent: readonly TodoItem[], removed: RemovedTitles) => string
711    apply: (text: string, sent: readonly TodoItem[]) => TodoItem[] | null
712  },
713) {
714  try {
715    const [sent, entries] = await Promise.all([read($, items), read($, trash)])
716    const reply = await $.model.complete({
717      model: MODEL,
718      effort: 'medium',
719      system: request.system,
720      prompt: request.prompt(sent, removedTitles(entries)),
721      maxTokens: request.maxTokens,
722      timeoutMs: COMPLETE_TIMEOUT_MS,
723    })
724    if (reply.isAnswered) {
725      await applyList($, request.apply(reply.text, sent), gen, sent)
726    }
727  } catch {
728    // Keep the previous list.
729  }
730}
731
732const incremental = ($: EngineInterface, turn: PendingTurn, gen: number) =>
733  ask($, gen, {
734    system: SYSTEM,
735    maxTokens: 8192,
736    prompt: (sent, removed) => incrementalPrompt({ ...turn, items: sent, removed }),
737    apply: applyChanges,
738  })
739
740const reviewList = ($: EngineInterface, turns: readonly ReviewTurn[], gen: number) =>
741  ask($, gen, {
742    system: REVIEW_SYSTEM,
743    maxTokens: 2048,
744    prompt: (sent, removed) => reviewPrompt({ items: sent, removed, turns }),
745    apply: applyReview,
746  })
747
748// Counts a tried turn and runs a review when one is due. The window empties
749// when a review is due, whatever its outcome, so a review that keeps failing
750// does not retry on every turn.
751async function countForReview($: EngineInterface, turn: PendingTurn, gen: number) {
752  if (gen !== generation) {
753    return
754  }
755  const [counted, { length }] = await Promise.all([read($, review), read($, items)])
756  const turns = [...counted, { userText: turn.userText, answer: turn.answer }]
757  const isDue = turns.length >= REVIEW_TURNS || (turns.length >= REVIEW_MIN_TURNS && length >= REVIEW_MIN_ITEMS)
758  await update($, review, () => (isDue ? [] : turns))
759  if (isDue && length > 0) {
760    await reviewList($, turns, gen)
761  }
762}
763
764// Applies the queued turns oldest first. A turn leaves the queue once tried,
765// whatever the outcome, so a reply that never parses cannot retry forever.
766async function runPending($: EngineInterface, gen: number) {
767  for (;;) {
768    const [turn] = await read($, pending)
769    if (turn === undefined) {
770      return
771    }
772    await incremental($, turn, gen)
773    await update($, pending, turns => turns.slice(1))
774    await countForReview($, turn, gen)
775  }
776}
777
778const schedulePending = ($: EngineInterface) => {
779  const gen = generation
780  // A timer outlives the dispatch that sets it, so the answer shows without waiting.
781  $.clock.after(0, () => {
782    void enqueue(() => runPending($, gen))
783  })
784}
785
786// The keys work only while the view holds the focus.
787function helpLine(view: {
788  kind: View['kind']
789  isHeld: boolean
790  isArmed: boolean
791  isDetailed: boolean
792  selectedCount: number
793  hasPages: boolean
794}): string {
795  if (!view.isHeld) {
796    return 'Ctrl+X Tab to focus'
797  }
798  if (view.isArmed) {
799    return `${DELETE_KEY} confirm delete · ${LEAVE_KEY} cancel`
800  }
801  const isPane = view.kind === 'pane'
802  const pasting = view.selectedCount > 0 ? `${PASTE_KEY} paste ${view.selectedCount}` : `${PASTE_KEY} paste`
803  const toggle = isPane ? (view.isDetailed ? 'collapse' : 'expand') : view.isDetailed ? 'show list' : 'show details'
804  // The band's detail replaces the list, so there is nothing to page.
805  const paging = view.hasPages && (isPane || !view.isDetailed) ? ` · ${NEXT_PAGE_KEY}/${PREVIOUS_PAGE_KEY} page` : ''
806  const switching = ` · ${TOGGLE_KEY} ${isPane ? 'band' : 'pane'}`
807  return `${NEXT_KEY}/${PREVIOUS_KEY} move${paging} · ${SELECT_KEY} select · ${SELECT_ALL_KEY} select all · ${pasting}${switching} · ${DETAILS_KEY}/${ENTER_KEY} ${toggle} · ${ASK_KEY} ask /btw · ${DELETE_KEY} delete · ${LEAVE_KEY} leave`
808}
809
810const itemCount = (n: number) => `${n} ${n === 1 ? 'item' : 'items'}`
811
812const refreshFailed = (reason: string) => `Refresh failed (${reason}); the list is unchanged.`
813
814// Applies a refresh reply and reports the outcome, with `note` after a success.
815async function settleRefresh(
816  $: EngineInterface,
817  gen: number,
818  sent: readonly TodoItem[],
819  reply: { isAnswered: true; text: string } | { isAnswered: false; reason: string },
820  note = '',
821): Promise<string> {
822  if (!reply.isAnswered) {
823    return refreshFailed(reply.reason)
824  }
825  const next = await applyList($, applyRefresh(reply.text, sent), gen, sent)
826  return next === null ? refreshFailed('unparseable reply') : `Refreshed the list: ${itemCount(next.length)}.${note}`
827}
828
829// The main conversation has nothing to fork right after a resume.
830async function refreshFromTranscript(
831  $: EngineInterface,
832  gen: number,
833  sent: readonly TodoItem[],
834  removed: RemovedTitles,
835): Promise<string> {
836  const transcript = renderTranscript(await $.session.messages())
837  if (transcript === '') {
838    return 'Refresh failed: the main conversation has no messages yet, so there is nothing to refresh from. Send a message and try again.'
839  }
840  const [model] = await Promise.all([$.session.model(), update($, review, () => [])])
841  const reply = await $.model.complete({
842    model,
843    effort: 'medium',
844    prompt: refreshPrompt({ items: sent, removed, transcript }),
845    maxTokens: 8192,
846    timeoutMs: TRANSCRIPT_TIMEOUT_MS,
847  })
848  return settleRefresh($, gen, sent, reply, ' It was rebuilt from the transcript without the prompt cache.')
849}
850
851async function refresh($: EngineInterface, gen: number): Promise<string> {
852  try {
853    const [sent, entries] = await Promise.all([read($, items), read($, trash)])
854    const removed = removedTitles(entries)
855    const reply = await $.model.fork({ prompt: refreshPrompt({ items: sent, removed }) })
856    if (!reply.isAnswered && reply.reason === 'nothing-to-fork') {
857      return await refreshFromTranscript($, gen, sent, removed)
858    }
859    await update($, review, () => [])
860    return await settleRefresh($, gen, sent, reply)
861  } catch {
862    return 'Refresh failed; the list is unchanged.'
863  }
864}
865
866// Reads each legacy `session:<id>` entry once and saves it under the new key
867// format. It returns the new key, or null when the entry was deleted (invalid,
868// expired, or no newer than a new key) or its save failed.
869async function migrateLegacy(
870  $: EngineInterface,
871  key: string,
872  id: string,
873  currentId: string,
874  current: readonly SavedKey[],
875  now: number,
876  maxAge: number | null,
877): Promise<SavedKey | null> {
878  const stored = await $.store.get(key)
879  const isKept =
880    isStored(stored) &&
881    !(maxAge !== null && now - stored.updatedAt > maxAge) &&
882    !current.some(one => one.id === id && one.updatedAt >= stored.updatedAt)
883  if (!isKept) {
884    await $.store.delete(key)
885    return null
886  }
887  const size = JSON.stringify(stored).length
888  const migrated = { key: savedKeyFor(id, stored.updatedAt, size), id, updatedAt: stored.updatedAt, size }
889  try {
890    await setWithRetry($, currentId, migrated.key, stored)
891  } catch {
892    // The legacy key stays, and the next start tries again.
893    return null
894  }
895  await $.store.delete(key)
896  return migrated
897}
898
899// Brings the store down to what should be kept, reading key names only, apart
900// from each legacy entry. Returns the current session's surviving key.
901async function sweep($: EngineInterface, currentId: string): Promise<SavedKey | null> {
902  const now = await $.clock.now()
903  const maxAge = await maxAgeMs($)
904  const keys = await $.store.keys()
905  const saved = keys.flatMap(key => parseKey(key) ?? [])
906  for (const key of keys) {
907    const id = legacyId(key)
908    if (id !== null) {
909      const migrated = await migrateLegacy($, key, id, currentId, saved, now, maxAge)
910      if (migrated !== null) {
911        saved.push(migrated)
912      }
913    }
914  }
915
916  // The newest key of each session stays; the rest are older duplicates.
917  const newest = new Map<string, SavedKey>()
918  for (const one of saved) {
919    const best = newest.get(one.id)
920    if (best === undefined || one.updatedAt >= best.updatedAt) {
921      newest.set(one.id, one)
922    }
923  }
924  const kept: SavedKey[] = []
925  for (const one of saved) {
926    if (newest.get(one.id) !== one || (maxAge !== null && now - one.updatedAt > maxAge)) {
927      await $.store.delete(one.key)
928    } else {
929      kept.push(one)
930    }
931  }
932  for (const key of keysToDrop(kept, currentId)) {
933    await $.store.delete(key)
934  }
935  return kept.find(one => one.id === currentId) ?? null
936}
937
938type Elements = ReturnType<EngineInterface['ui']['resolve']>
939
940// Opening an open pane only retitles it, but its focus request is still
941// granted from an empty prompt, which hands the keys to the pane. The band
942// hides only once the pane is drawn, so the list always has a view. An open
943// nobody asked for takes no keys: they would turn the first letters typed into
944// the pane's hotkeys.
945async function openPane($: EngineInterface, takesKeys = true): Promise<boolean> {
946  const { isPlaced } = await $.ui.open({ id: PANE_ID, title: PANE_TITLE, ...(takesKeys && { focus: true as const }) })
947  if (isPlaced) {
948    await update($, mode, () => 'pane')
949  }
950  return isPlaced
951}
952
953// The `default_view` setting; band for a missing or unreadable row.
954async function defaultView($: EngineInterface): Promise<ViewKind> {
955  try {
956    const row = (await $.config.list()).find(one => one.key === DEFAULT_VIEW_KEY)
957    return row?.value === 'pane' ? 'pane' : 'band'
958  } catch {
959    return 'band'
960  }
961}
962
963// A view's window and its help line, drawn to fit. The help line wraps and names
964// the paging keys only when the list does not fit, so it is drawn once without
965// them and, if the list still does not fit, again with. `fit` gets the rows the
966// view's lines take apart from the items, and answers the window.
967function fitWindow<W extends { count: number }>(view: {
968  columns: number
969  length: number
970  // The rows the view's own lines take apart from the help line and the items.
971  fixedRows: number
972  helpFor: (hasPages: boolean) => string
973  fit: (others: number) => W
974}): { window: W; help: string } {
975  const attempt = (hasPages: boolean) => {
976    const help = view.helpFor(hasPages)
977    return { help, window: view.fit(view.fixedRows + wrapRows(`${GUTTER}${help}`, view.columns)) }
978  }
979  const whole = attempt(false)
980  return view.length > whole.window.count ? attempt(true) : whole
981}
982
983// The rows a title takes beyond its first once the focused item shows it whole.
984const extraTitleRows = (title: string | undefined, columns: number, numberWidth: number) =>
985  title === undefined ? 0 : wrapRows(normalizeParens(title), columns - GUTTER.length - numberWidth) - 1
986
987// One item's row, drawn by the band and the pane alike. The focus ring tracks
988// its stop by position, so a hidden row keeps its Button.
989function itemRow(
990  { Box, Button, Text }: Elements,
991  row: {
992    item: TodoItem
993    index: number
994    numberWidth: number
995    columns: number
996    isShown: boolean
997    // Whether the focus dot is drawn.
998    isFocused: boolean
999    // Whether the title is drawn whole instead of cut to one row.
1000    isWhole: boolean
1001    isPicked: boolean
1002    isArmed: boolean
1003    autoFocus?: true
1004    onPress: () => void
1005  },
1006) {
1007  const button = (
1008    <Button key={`${ROW_PREFIX}${row.index}`} label=" " plain autoFocus={row.autoFocus} onPress={row.onPress} />
1009  )
1010  if (!row.isShown) {
1011    return (
1012      <Box key={`row-${row.index}`} width={0} height={0} overflow="hidden">
1013        {button}
1014      </Box>
1015    )
1016  }
1017  // Items stored before parentheses were normalized still need normalizing here.
1018  const shown = normalizeParens(row.item.title)
1019  const [, main = shown] = NOTE.exec(shown) ?? []
1020  const room = row.columns - GUTTER.length - row.numberWidth
1021  const color = row.isPicked ? SELECTED_COLOR : undefined
1022  const isLong = !row.isWhole && cellWidth(shown) > room
1023  // The cut may end inside the note.
1024  const cut = isLong ? fit(shown, room) : shown
1025  const head = cut.slice(0, main.length)
1026  const tail = cut.slice(main.length)
1027  return (
1028    <Box key={`row-${row.index}`} flexDirection="row">
1029      {/* The focus ring always inverts a Button, so the row's Button takes
1030          no cells and the dot beside it marks the focus instead. */}
1031      <Box width={0} overflow="hidden">
1032        {button}
1033      </Box>
1034      <Text>{row.isFocused ? '• ' : '  '}</Text>
1035      <Text color={color}>{numberLabel(row.index + 1, row.numberWidth)}</Text>
1036      <Text color={color} wrap={isLong ? 'truncate-end' : 'wrap'}>
1037        {head}
1038        {tail !== '' && <Text dimColor>{tail}</Text>}
1039      </Text>
1040      {row.isArmed && (
1041        <Text weight="semibold" color={DELETE_COLOR}>
1042          {' '}
1043          delete?
1044        </Text>
1045      )}
1046    </Box>
1047  )
1048}
1049
1050// The hidden hotkey Buttons both views bind to their own view.
1051function keyButtons($: EngineInterface, { Button }: Elements, view: View) {
1052  return [
1053    <Button key="next" label="next" hotkey={NEXT_KEY} plain onPress={() => moveFocus($, view, 1)} />,
1054    <Button key="previous" label="previous" hotkey={PREVIOUS_KEY} plain onPress={() => moveFocus($, view, -1)} />,
1055    <Button key="details" label="details" hotkey={DETAILS_KEY} plain onPress={() => toggleDetails($, view)} />,
1056    <Button key="next-page" label="next page" hotkey={NEXT_PAGE_KEY} plain onPress={() => movePage($, view, 1)} />,
1057    <Button key="previous-page" label="previous page" hotkey={PREVIOUS_PAGE_KEY} plain onPress={() => movePage($, view, -1)} />,
1058    <Button key="paste" label="paste" hotkey={PASTE_KEY} plain onPress={() => paste($, view)} />,
1059    <Button key="select" label="select" hotkey={SELECT_KEY} plain onPress={() => toggleSelected($, view)} />,
1060    <Button key="select-all" label="select all" hotkey={SELECT_ALL_KEY} plain onPress={() => toggleAll($, view)} />,
1061    <Button key="ask" label="ask" hotkey={ASK_KEY} plain onPress={() => askAbout($, view)} />,
1062    <Button key="delete" label="delete" hotkey={DELETE_KEY} plain onPress={() => deleteFocused($, view)} />,
1063  ]
1064}
1065
1066export const register: Register = on => {
1067  on('session.start', async ($, e, next) => {
1068    await $.command.register({
1069      name: 'todos',
1070      description:
1071        'Show, refresh, clear or reset the open items list, open it in a pane, delete some, list, restore or purge removed items, or send them all with a prompt',
1072      argumentHint: '[refresh|clear|pane|reset|trash|restore <numbers>|purge <numbers>|delete <numbers>|<prompt>]',
1073    })
1074
1075    const id = await $.session.id()
1076    const mine = await sweep($, id)
1077
1078    await update($, focused, () => '')
1079    await update($, deleting, () => '')
1080    if ((await read($, pending)).length > 0) {
1081      schedulePending($)
1082    }
1083
1084    if (mine !== null) {
1085      await update($, savedKey, () => mine.key)
1086      const stored = await $.store.get(mine.key)
1087      if (isStored(stored)) {
1088        await update($, items, () => migrate(stored.items))
1089        await update($, trash, () => loadTrash(stored))
1090      }
1091    }
1092
1093    // Only the first start of the process applies the default view: a reload
1094    // runs this hook again, and /clear fires no start at all.
1095    if (!(await read($, viewApplied))) {
1096      await update($, viewApplied, () => true)
1097      if ((await defaultView($)) === 'pane') {
1098        await openPane($, false)
1099      }
1100    }
1101
1102    return next(e)
1103  })
1104
1105  on('session.end', async ($, e, next) => {
1106    if (e.reason === 'clear') {
1107      generation += 1
1108      userTexts.clear()
1109      await update($, lastAnswer, () => '')
1110      await update($, pending, () => [])
1111      await update($, items, () => [])
1112      await update($, trash, () => [])
1113      await update($, review, () => [])
1114      await update($, detailed, () => '')
1115      await update($, deleting, () => '')
1116      await update($, selected, () => [])
1117      await clearPane($)
1118      await update($, savedKey, () => '')
1119      for (const key of await $.store.keys()) {
1120        if ((parseKey(key)?.id ?? legacyId(key)) === e.sessionId) {
1121          await $.store.delete(key)
1122        }
1123      }
1124    }
1125
1126    return next(e)
1127  })
1128
1129  // Typing in the prompt box leaves the band without waiting for the leave check.
1130  on('prompt.edit', async ($, e, next) => {
1131    await leave($)
1132
1133    return next(e)
1134  })
1135
1136  on('prompt.submit', async ($, e, next) => {
1137    await leave($)
1138
1139    return next(e)
1140  })
1141
1142  on('turn.start', (_$, e, next) => {
1143    userTexts.set(e.turnId, e.text)
1144
1145    return next(e)
1146  })
1147
1148  on('turn.complete', async ($, e, next) => {
1149    const userText = userTexts.get(e.turnId) ?? ''
1150    userTexts.delete(e.turnId)
1151
1152    if (e.agentId === undefined && e.reason === 'answer') {
1153      const turn = { previousAnswer: await read($, lastAnswer), userText, answer: e.answer }
1154      await update($, lastAnswer, () => e.answer)
1155      await update($, pending, turns => [...turns, turn])
1156      schedulePending($)
1157    }
1158
1159    return next(e)
1160  })
1161
1162  on('command.run', { command: 'todos' }, async ($, e) => {
1163    const arg = e.args.trim()
1164
1165    if (arg === 'refresh') {
1166      const gen = generation
1167      return { text: await enqueue(() => refresh($, gen)) }
1168    }
1169    if (arg === 'pane') {
1170      return { text: (await openPane($)) ? 'The Todos pane is open.' : 'The Todos pane cannot be shown here.' }
1171    }
1172    if (arg === 'clear') {
1173      await enqueue(async () => tick($, (await read($, items)).map(one => one.title)))
1174      return { text: 'Cleared the list.' }
1175    }
1176    // Any argument led by one of these words is that subcommand, so a mistyped
1177    // one is refused instead of going out as a prompt.
1178    const sub = /^(reset|trash|restore|purge|delete)(?:\s+|$)(.*)$/s.exec(arg)
1179    if (sub?.[1] === 'reset') {
1180      if (sub[2] !== '') {
1181        return { text: 'Usage: /todos reset, with nothing after it. Nothing was changed.' }
1182      }
1183      await enqueue(async () => {
1184        await update($, trash, () => [])
1185        await update($, review, () => [])
1186        await commit($, [])
1187      })
1188      return { text: 'Emptied the list and the trash.' }
1189    }
1190    // Numbered newest first, so `restore 1` takes back the latest removal.
1191    const newestFirst = async () => [...(await read($, trash))].reverse()
1192    if (sub?.[1] === 'trash') {
1193      const removed = await newestFirst()
1194      if (sub[2] !== '') {
1195        return { text: 'Usage: /todos trash, with nothing after it.' }
1196      }
1197      if (removed.length === 0) {
1198        return { text: 'The trash is empty.' }
1199      }
1200      return { text: ['Trash', ...numberedLines(removed, one => `${one.title} [${one.by}]`)].join('\n') }
hooks/list.ts 467 lines
1import type { SessionMessage } from 'claude-code'
2
3import type { ReviewTurn, TodoItem, TrashEntry } from '../types'
4
5const MAX_ITEMS = 99
6export const MAX_TRASH = MAX_ITEMS
7const MAX_ITEM_LENGTH = 80
8export const MAX_DETAIL_LENGTH = 1000
9// A guard against pasted logs, far above any normal turn.
10const MAX_TEXT = 100_000
11// A review carries up to REVIEW_TURNS turns, so each is held to a smaller share.
12const REVIEW_TURN_TEXT = 20_000
13export const REVIEW_TURNS = 8
14export const REVIEW_MIN_TURNS = 3
15export const REVIEW_MIN_ITEMS = 6
16export const TRANSCRIPT_TOOL_RESULT_TEXT = 2_000
17export const TRANSCRIPT_TEXT = 200_000
18
19const DEFINITION = `An open item is something still pending in this conversation:
20- Work the user or the agent deferred (for example "later", "not now", "先不做", "之後再處理", "next step").
21- A follow-up the agent promised, or a check it said it had not run yet.
22- A decision or question raised in the discussion and not settled yet, whoever raised it: a choice among options waiting for the user, a question either side asked that has no answer or conclusion yet, or a point left to decide later.
23
24Do not list:
25- The step being carried out right now. A pending decision or open question is never this step.
26- Anything raised and finished within the same turn.
27- Tasks already listed in an OpenSpec tasks.md.
28
29Remove an item once the conversation shows it is done or the user drops it.`
30
31const ITEM_STYLE = `Write each item as an object with a "title" and a "detail", both in the language the agent answers in. Call the side that answers the user "the agent", never "the assistant"; in Chinese, keep it as the English word "agent", lowercase mid-sentence.
32- "title": one short line (at most ${MAX_ITEM_LENGTH} characters). Use half-width parentheses with a space before the opening one. End a title that carries a status, such as awaiting the user's reply or not yet tested, with that status in parentheses, written in the title's language, and nothing after it, as in "<what to do> (<status>)".
33- "detail": what to do, why it matters, and which part of the discussion it came from (at most ${MAX_DETAIL_LENGTH} characters, newlines included), so a reader who lost the conversation can act on it. Do not repeat the title. Put each distinct point on its own line, separated by a newline in the JSON string, as plain text with no Markdown bullets or headings.`
34
35const RESOLVE = `For every current item, decide whether this turn resolves it. Remove it when the turn answers it, decides it, completes it, or makes it moot, even when the turn does not name it. A user's reply to a question, or a choice among offered options, resolves that question. Keep an item only when it is still open after this turn.`
36
37const CHANGE_FORMAT = `Reply with a JSON object and nothing else: no code fence, no commentary. "remove" lists the numbers of the current items this turn resolves, and "add" lists the new open items as {"title", "detail"} objects, for example {"remove":[2],"add":[{"title":"<title>","detail":"<detail>"}]}. Reply with {"remove":[],"add":[]} when nothing changed.
38${ITEM_STYLE}`
39
40const REVIEW_RESOLVE = `For every current item, decide whether it is still open at the end of the turns below. Remove it when a later turn answered it, decided it, completed it, dropped it, or made it moot, even when no turn names it, and keep it only when the end of the turns still leaves it open.`
41
42const REVIEW_FORMAT = `Reply with a JSON object and nothing else: no code fence, no commentary. "remove" lists the numbers of the current items that are no longer open, for example {"remove":[2]}. Reply with {"remove":[]} when every item is still open. Do not add items.`
43
44const REFRESH_FORMAT = `Reply with a JSON object and nothing else: no code fence, no commentary. "remove" lists the numbers of the current items that are no longer open, "add" lists open items the list is missing as {"title", "detail"} objects, and "update" lists {"number", "detail"} objects for kept items whose detail is out of date or empty, for example {"remove":[2],"add":[{"title":"<title>","detail":"<detail>"}],"update":[{"number":1,"detail":"<detail>"}]}. An update changes only the detail; a kept item keeps its title. Reply with {"remove":[],"add":[],"update":[]} when nothing changed.
45${ITEM_STYLE}`
46
47export const SYSTEM = `You maintain a to-do list of open items for a coding conversation.\n\n${DEFINITION}\n\n${RESOLVE}\n\n${CHANGE_FORMAT}`
48
49export const REVIEW_SYSTEM = `You review a to-do list of open items for a coding conversation. You only remove items that are no longer open.\n\n${DEFINITION}\n\n${REVIEW_RESOLVE}\n\n${REVIEW_FORMAT}`
50
51// Keeps the tail, where an answer usually ends with the question it leaves open.
52const clip = (text: string, max = MAX_TEXT) =>
53  text.length > max
54    ? `${text.slice(0, max / 4)}\n[truncated]\n${text.slice(max / 4 - max)}`
55    : text
56
57export type RemovedTitles = { user: readonly string[]; model: readonly string[] }
58
59export const removedTitles = (entries: readonly TrashEntry[]): RemovedTitles => ({
60  user: entries.filter(one => one.by === 'user').map(one => one.title),
61  model: entries.filter(one => one.by === 'model').map(one => one.title),
62})
63
64const titlesOf = (titles: readonly string[]) => (titles.length === 0 ? '(none)' : JSON.stringify(titles))
65
66const removedBlocks = (removed: RemovedTitles) =>
67  [
68    `Items the user removed (never add them back):\n${titlesOf(removed.user)}`,
69    `Items removed earlier because they were no longer open (do not add them back unless the conversation reopens them):\n${titlesOf(removed.model)}`,
70  ].join('\n\n')
71
72// Prefixes every line of a multi-line text, such as an item's detail.
73export const prefixLines = (text: string, prefix: string) =>
74  text
75    .split('\n')
76    .map(line => `${prefix}${line}`)
77    .join('\n')
78
79const numbered = (items: readonly TodoItem[]) =>
80  items.length === 0
81    ? '(none)'
82    : items
83        .map((one, i) => `${i + 1}. ${one.title}${one.detail === '' ? '' : `\n${prefixLines(one.detail, '   ')}`}`)
84        .join('\n')
85
86export function incrementalPrompt(input: {
87  items: readonly TodoItem[]
88  removed: RemovedTitles
89  previousAnswer: string
90  userText: string
91  answer: string
92}): string {
93  return [
94    `Current list:\n${numbered(input.items)}`,
95    removedBlocks(input.removed),
96    `Agent final answer of the previous turn, which this turn's user message may reply to:\n${clip(input.previousAnswer) || '(none)'}`,
97    `User message of this turn:\n${clip(input.userText) || '(none)'}`,
98    `Agent final answer of this turn:\n${clip(input.answer) || '(none)'}`,
99    'Return the changes.',
100  ].join('\n\n')
101}
102
103export function reviewPrompt(input: {
104  items: readonly TodoItem[]
105  removed: RemovedTitles
106  turns: readonly ReviewTurn[]
107}): string {
108  const turns = input.turns.map(
109    (one, i) =>
110      `Turn ${i + 1} of ${input.turns.length}\nUser message:\n${clip(one.userText, REVIEW_TURN_TEXT) || '(none)'}\nAgent final answer:\n${clip(one.answer, REVIEW_TURN_TEXT) || '(none)'}`,
111  )
112  return [
113    `Current list:\n${numbered(input.items)}`,
114    removedBlocks(input.removed),
115    ...turns,
116    'Return the removals.',
117  ].join('\n\n')
118}
119
120const BLOCK_SEPARATOR = '\n\n'
121
122// A user message that only carries tool results renders to nothing, since the
123// results already sit under the calls that made them.
124const renderMessage = (message: SessionMessage) =>
125  [
126    message.text === '' ? '' : `[${message.role}]\n${message.text}`,
127    ...message.toolUses.map(
128      use => `[tool ${use.tool}]\n${clip(use.text ?? '', TRANSCRIPT_TOOL_RESULT_TEXT) || '(no result)'}`,
129    ),
130  ]
131    .filter(block => block !== '')
132    .join(BLOCK_SEPARATOR)
133
134// Renders the newest messages that fit TRANSCRIPT_TEXT, dropping whole oldest
135// messages first; a lone newest message past the limit is clipped instead.
136export function renderTranscript(messages: readonly SessionMessage[]): string {
137  const kept: string[] = []
138  let length = 0
139  for (let i = messages.length - 1; i >= 0; i -= 1) {
140    const block = renderMessage(messages[i] as SessionMessage)
141    if (block === '') {
142      continue
143    }
144    const next = length + block.length + (kept.length === 0 ? 0 : BLOCK_SEPARATOR.length)
145    if (next > TRANSCRIPT_TEXT && kept.length > 0) {
146      break
147    }
148    kept.push(clip(block, TRANSCRIPT_TEXT))
149    length = next
150  }
151  return kept.reverse().join(BLOCK_SEPARATOR)
152}
153
154// Without a transcript, the prompt refers to the conversation already in context.
155export function refreshPrompt({
156  items,
157  removed,
158  transcript,
159}: {
160  items: readonly TodoItem[]
161  removed: RemovedTitles
162  transcript?: string
163}): string {
164  const [head, source] =
165    transcript === undefined
166      ? [[], 'the whole conversation above']
167      : [[`Transcript of the conversation:\n\n${transcript}`], 'the transcript above']
168  return [
169    ...head,
170    `This request comes from the todo-list plugin, not from the user. Do not continue the conversation or call tools; answer only this request. Review the current to-do list against ${source}.`,
171    DEFINITION,
172    `Current list:\n${numbered(items)}`,
173    removedBlocks(removed),
174    'Judge each current item from where the conversation ended, and keep it only when the conversation shows it is still open. Also add open items the list is missing.',
175    REFRESH_FORMAT,
176  ].join('\n\n')
177}
178
179const FULL_WIDTH_PUNCTUATION = ',。、;:!?'
180
181// Turns full-width parentheses into half-width ones, spaced as Taiwan prose
182// spaces them: a space outside each, none next to full-width punctuation.
183const SPACED_OPEN = new RegExp(`([${FULL_WIDTH_PUNCTUATION}])\\s+\\(`, 'g')
184const UNSPACED_CLOSE = new RegExp(`\\)(?=[^\\s${FULL_WIDTH_PUNCTUATION})」』])`, 'g')
185
186export const normalizeParens = (text: string) =>
187  text
188    .replace(/\s*(\s*/g, ' (')
189    .replace(/\s*)/g, ')')
190    .replace(SPACED_OPEN, '$1(')
191    .replace(UNSPACED_CLOSE, ') ')
192    .trim()
193
194const tidy = (text: string) => normalizeParens(text.replace(/\s+/g, ' '))
195
196// Keeps the line breaks of a detail, tidying each line and dropping empty ones.
197const tidyDetail = (text: string) =>
198  text
199    .replace(/\r\n?/g, '\n')
200    .split('\n')
201    .map(tidy)
202    .filter(line => line !== '')
203    .join('\n')
204    .slice(0, MAX_DETAIL_LENGTH)
205    .trimEnd()
206
207// Normalizes, trims, deduplicates by title and caps a list of items.
208export function cleanItems(items: readonly TodoItem[]): TodoItem[] {
209  const seen = new Set<string>()
210  const kept: TodoItem[] = []
211  for (const one of items) {
212    const title = tidy(one.title).slice(0, MAX_ITEM_LENGTH)
213    if (title !== '' && !seen.has(title)) {
214      seen.add(title)
215      kept.push({ title, detail: tidyDetail(one.detail) })
216    }
217  }
218  return kept.slice(0, MAX_ITEMS)
219}
220
221function parseJson(text: string, open: string, close: string): unknown {
222  const start = text.indexOf(open)
223  const end = text.lastIndexOf(close)
224  if (start === -1 || end < start) {
225    return undefined
226  }
227  try {
228    return JSON.parse(text.slice(start, end + 1))
229  } catch {
230    return undefined
231  }
232}
233
234export const isItem = (value: unknown): value is TodoItem =>
235  typeof value === 'object' &&
236  value !== null &&
237  typeof (value as TodoItem).title === 'string' &&
238  typeof (value as TodoItem).detail === 'string'
239
240const isItems = (value: unknown): value is TodoItem[] => Array.isArray(value) && value.every(isItem)
241
242// Resolves item numbers such as "2", "1-3" or "1,4 6" against a list of
243// `count` items. Returns the numbers ascending and distinct, the smallest
244// number past the list when there is one, or null when the text is not such
245// a list.
246export function parseNumbers(
247  text: string,
248  count: number,
249): { numbers: number[] } | { missing: number } | null {
250  const tokens = text.split(/[\s,]+/).filter(token => token !== '')
251  if (tokens.length === 0) {
252    return null
253  }
254  const numbers = new Set<number>()
255  let missing = Infinity
256  for (const token of tokens) {
257    const match = /^(\d+)(?:-(\d+))?$/.exec(token)
258    if (match === null) {
259      return null
260    }
261    const from = Number(match[1])
262    const to = Number(match[2] ?? match[1])
263    if (from < 1 || to < from) {
264      return null
265    }
266    if (to > count) {
267      missing = Math.min(missing, Math.max(from, count + 1))
268    }
269    for (let n = from; n <= Math.min(to, count); n += 1) {
270      numbers.add(n)
271    }
272  }
273  return missing === Infinity ? { numbers: [...numbers].sort((a, b) => a - b) } : { missing }
274}
275
276const isNumberIn = (n: unknown, count: number): n is number => Number.isInteger(n) && (n as number) >= 1 && (n as number) <= count
277
278// The reply's "remove" applied to the `items` it was asked about: the numbers it
279// names and the items it leaves, with the reply's raw "add" and "update". Null
280// when "remove" is not a list of numbers within `items`.
281function parseRemove(text: string, items: readonly TodoItem[]) {
282  const parsed = parseJson(text, '{', '}') as Record<string, unknown> | undefined
283  const remove = parsed?.remove
284  if (parsed === undefined || !Array.isArray(remove) || !remove.every(n => isNumberIn(n, items.length))) {
285    return null
286  }
287  const gone = new Set(remove as number[])
288  return { gone, kept: items.filter((_, i) => !gone.has(i + 1)), add: parsed.add, update: parsed.update }
289}
290
291// Applies a {"remove": [...], "add": [...]} reply to the list it was asked
292// about; returns null when the reply has another shape or names no such item.
293export function applyChanges(text: string, items: readonly TodoItem[]): TodoItem[] | null {
294  const change = parseRemove(text, items)
295  const add = change?.add
296  if (change === null || !isItems(add)) {
297    return null
298  }
299  return cleanItems([...change.kept, ...add])
300}
301
302// Applies a {"remove": [...]} reply; any "add" in it is ignored.
303export function applyReview(text: string, items: readonly TodoItem[]): TodoItem[] | null {
304  const change = parseRemove(text, items)
305  return change === null ? null : change.kept
306}
307
308// Applies a {"remove": [...], "add": [...], "update": [{number, detail}]} reply.
309// An update takes the new detail and keeps the title. The reply fails when an
310// update names no such item, an item twice, or a removed item, or leaves the
311// detail empty.
312export function applyRefresh(text: string, items: readonly TodoItem[]): TodoItem[] | null {
313  const change = parseRemove(text, items)
314  const add = change?.add
315  const updates = change?.update ?? []
316  if (change === null || !isItems(add) || !Array.isArray(updates)) {
317    return null
318  }
319  const details = new Map<number, string>()
320  for (const one of updates as { number?: unknown; detail?: unknown }[]) {
321    const detail = typeof one?.detail === 'string' ? tidyDetail(one.detail) : ''
322    if (!isNumberIn(one?.number, items.length) || change.gone.has(one.number) || details.has(one.number) || detail === '') {
323      return null
324    }
325    details.set(one.number, detail)
326  }
327  const kept = items.flatMap((one, i) =>
328    change.gone.has(i + 1) ? [] : [{ title: one.title, detail: details.get(i + 1) ?? one.detail }],
329  )
330  return cleanItems([...kept, ...add])
331}
332
333// The most items the band shows at a time.
334export const WINDOW_SIZE = 10
335
336// Characters the terminal draws two cells wide: CJK, Hangul, and full-width forms.
337const WIDE_CLASS = '[\\u1100-\\u115F\\u2E80-\\uA4CF\\uAC00-\\uD7A3\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFF60\\uFFE0-\\uFFE6]'
338const WIDE = new RegExp(WIDE_CLASS)
339// Whitespace, one wide character, or a run of narrow non-space characters.
340const WRAP_TOKEN = new RegExp(`\\s+|${WIDE_CLASS}|(?:(?!${WIDE_CLASS})\\S)+`, 'gu')
341
342export const charWidth = (ch: string) => (WIDE.test(ch) ? 2 : 1)
343export const cellWidth = (text: string) => [...text].reduce((n, ch) => n + charWidth(ch), 0)
344
345// The rows `text` takes in `columns` cells under word wrap: a row starts at each
346// newline, a Latin word moves whole to the next row, and a wide character can
347// break anywhere.
348export function wrapRows(text: string, columns: number): number {
349  const width = Math.max(1, columns)
350  let rows = 0
351  for (const line of text.split('\n')) {
352    rows += 1
353    let used = 0
354    for (const [token] of line.matchAll(WRAP_TOKEN)) {
355      const cells = cellWidth(token)
356      if (/^\s/.test(token)) {
357        if (used + cells > width) {
358          rows += 1
359          used = 0
360        } else {
361          used += cells
362        }
363      } else if (used + cells <= width) {
364        used += cells
365      } else if (cells <= width) {
366        rows += 1
367        used = cells
368      } else {
369        // A word longer than a row breaks wherever it hits the edge.
370        for (const ch of token) {
371          const w = charWidth(ch)
372          if (used + w > width) {
373            rows += 1
374            used = 0
375          }
376          used += w
377        }
378      }
379    }
380  }
381  return rows
382}
383
384// How many items fit in `rows` rows from `start` on, with the `<n> more` row
385// when items come after them, and at most `cap`; at least 1 for a nonempty list.
386function rowsFit(heights: readonly number[], start: number, rows: number, cap: number): number {
387  let used = 0
388  let count = 0
389  for (let i = start; i < heights.length && count < cap; i += 1) {
390    used += heights[i]!
391    if (used + (i + 1 < heights.length ? 1 : 0) > rows) {
392      break
393    }
394    count += 1
395  }
396  return Math.max(1, count)
397}
398
399// The row-based window: `heights` holds each item's rows, `rows` the rows left
400// for items once the view's other lines are taken out, apart from the `<n> more`
401// row, which this reserves while items come after the window. From `start` it
402// moves the least distance that shows the whole item at `index` (-1 for none),
403// then, when the window reaches the last item, pulls up while earlier items
404// still fit. `cap` limits how many items the window holds, however many rows are free.
405export function rowWindow(
406  heights: readonly number[],
407  start: number,
408  index: number,
409  rows: number,
410  cap = Infinity,
411): { start: number; count: number } {
412  if (heights.length === 0) {
413    return { start: 0, count: 0 }
414  }
415  let next = Math.min(Math.max(start, 0), heights.length - 1)
416  if (index !== -1) {
417    next = Math.min(next, index)
418    while (index >= next + rowsFit(heights, next, rows, cap)) {
419      next += 1
420    }
421  }
422  let count = rowsFit(heights, next, rows, cap)
423  if (next + count >= heights.length) {
424    let used = heights.slice(next).reduce((sum, height) => sum + height, 0)
425    while (next > 0 && heights.length - next < cap && used + heights[next - 1]! <= rows) {
426      next -= 1
427      used += heights[next]!
428    }
429    count = rowsFit(heights, next, rows, cap)
430  }
431  return { start: next, count }
432}
433
434// A page move over row heights, from the window drawn around the item at
435// `index`: the next window starts at the first item after the current one and
436// the previous one ends just before the current start. The focus keeps its
437// offset in the window, clamped to the new window's items. Null when the window
438// cannot move. Windows hold at most `cap` items.
439export function pageRows(
440  heights: readonly number[],
441  start: number,
442  index: number,
443  step: 1 | -1,
444  rows: number,
445  cap = Infinity,
446): { start: number; index: number } | null {
447  const drawn = rowWindow(heights, start, index, rows, cap)
448  let next = drawn.start
449  if (step === 1) {
450    const after = drawn.start + drawn.count
451    next = after >= heights.length ? next : rowWindow(heights, after, -1, rows, cap).start
452  } else if (next > 0) {
453    next -= 1
454    let used = heights[next]!
455    // The window ends before the current start, so the `<n> more` row follows it.
456    while (next > 0 && drawn.start - next < cap && used + heights[next - 1]! + 1 <= rows) {
457      next -= 1
458      used += heights[next]!
459    }
460  }
461  if (next === drawn.start) {
462    return null
463  }
464  const { count } = rowWindow(heights, next, -1, rows, cap)
465  return { start: next, index: next + Math.min(index - drawn.start, count - 1) }
466}
467
hooks/store.ts 50 lines
1// Claude Code rejects a store whose JSON text passes this many characters.
2export const STORE_CAP = 4_194_304
3// The sweep and the retry free room down to this length, so a save rarely meets the cap.
4export const STORE_TARGET = Math.floor(STORE_CAP * 0.8)
5export const STORE_PREFIX = 'session:'
6
7// An entry's key carries its age and size, so they are known without reading values.
8export type SavedKey = { key: string; id: string; updatedAt: number; size: number }
9
10export const savedKeyFor = (id: string, updatedAt: number, size: number) =>
11  `${STORE_PREFIX}${id}:${updatedAt}:${size}`
12
13// The last two segments are the numbers, so an id is never split.
14export function parseKey(key: string): SavedKey | null {
15  const match = /^session:(.+):(\d+):(\d+)$/.exec(key)
16  return match === null ? null : { key, id: match[1] ?? '', updatedAt: Number(match[2]), size: Number(match[3]) }
17}
18
19// Any other session key is a legacy `session:<id>` one, which holds no metadata.
20export const legacyId = (key: string) => (key.startsWith(STORE_PREFIX) && parseKey(key) === null ? key.slice(STORE_PREFIX.length) : null)
21
22// The length of the whole store as JSON text, the measure the cap applies to:
23// braces, then `"key":value` pairs joined by commas.
24export const storeLength = (saved: readonly SavedKey[]) =>
25  saved.length === 0 ? 2 : 2 + saved.reduce((sum, one) => sum + JSON.stringify(one.key).length + 1 + one.size, saved.length - 1)
26
27// The keys of whole sessions to delete, oldest update first and never the
28// current session, to bring the store down to STORE_TARGET.
29export function keysToDrop(saved: readonly SavedKey[], currentId: string): string[] {
30  const sessions = new Map<string, { updatedAt: number; keys: SavedKey[] }>()
31  for (const one of saved) {
32    const session = sessions.get(one.id) ?? { updatedAt: 0, keys: [] }
33    session.updatedAt = Math.max(session.updatedAt, one.updatedAt)
34    session.keys.push(one)
35    sessions.set(one.id, session)
36  }
37  const oldest = [...sessions.entries()].filter(([id]) => id !== currentId).sort(([, a], [, b]) => a.updatedAt - b.updatedAt)
38  const dropped: string[] = []
39  let remaining = saved
40  for (const [, session] of oldest) {
41    if (storeLength(remaining) <= STORE_TARGET) {
42      break
43    }
44    const gone = new Set(session.keys)
45    remaining = remaining.filter(one => !gone.has(one))
46    dropped.push(...session.keys.map(one => one.key))
47  }
48  return dropped
49}
50
types/index.d.ts 46 lines
1export type TodoItem = { title: string; detail: string }
2
3// One finished turn waiting to update the list.
4export type PendingTurn = ReviewTurn & { previousAnswer: string }
5
6// An item that left the list, and who removed it.
7export type TrashEntry = TodoItem & { by: 'user' | 'model'; at: number }
8
9// One counted turn waiting for the next review.
10export type ReviewTurn = { userText: string; answer: string }
11
12// Which view shows the list.
13export type ViewKind = 'band' | 'pane'
14
15export type TodoListState = {
16  items: TodoItem[]
17  trash: TrashEntry[]
18}
19
20declare module 'claude-code' {
21  interface PluginState {
22    'todo-list': {
23      items: TodoItem[]
24      trash: TrashEntry[]
25      review: ReviewTurn[]
26      focused: string
27      detailed: string
28      windowStart: number
29      deleting: string
30      selected: string[]
31      paneFocused: string
32      paneFocusIndex: number
33      paneDetailed: string
34      paneDeleting: string
35      paneSelected: string[]
36      paneWindowStart: number
37      mode: ViewKind
38      viewApplied: boolean
39      lastAnswer: string
40      pending: PendingTurn[]
41      savedKey: string
42      failureShown: boolean
43    }
44  }
45}
46