Bookmarks and vim-style marks inside Claude Code conversations: mark a line, jump back, keep a reading position, browse your prompts, and let Claude cite…

Vim-style marks, a reading position, a numbered prompt history and durable bookmarks inside a Claude Code conversation. Mark a line with a letter and jump back to it from anywhere; keep your place while you scroll; browse every prompt you have typed; and let Claude cite earlier places in the conversation as links you can click to jump there.
<img src="images/prompts-pane-marked-line-and-bookmark-link.png" alt="The prompts pane open on the right, numbered from the first prompt; a marked line in the conversation with its c tag; a bookmark link in a reply; the band above the prompt in prompt mode"> <sub>In use: the prompts pane on the right, a marked line with its tag, a bookmark link Claude wrote in a reply, and the band above the input box.</sub>
Pre-alpha. In daily use in Win11 (Windows Terminal, Claude Code 2.1.288 to 2.1.296, fullscreen renderer). macOS and Linux are expected to work but have not been tried. The key layout will still change. The state of the plugin, with every known issue and what is coming, is in docs/status.md.
Reviewers: everything the plugin sets, runs, reads, writes and sends is listed under What it runs, reads, writes and sends below.
m and a letter a-z. The line lights up where it sits. With nothing freshly selected, the letter marks the message at the top of your screen.', and the letter scrolls back to that mark from anywhere and lights the line again; the jump pane lists the marks you have.Space Space after the leader keeps your place: once to go there, again to return to where you were, even after new replies arrived below.p after the leader lists every prompt of the conversation, numbered from your first, including the ones from before the plugin was loaded. Type a number or browse with j/k, then Enter. Pin the ones you keep returning to.file: link to a readable export of the message, with the message's id, transcript line and byte range in the link. Promote any mark into one; the link lands on your clipboard.bookmark tool: a verbatim fragment of a message and a label in, a markdown link out. In its reply the link is drawn with an anchor marker: a click jumps there and highlights the words; a ctrl-click opens the bookmark's file in your markdown editor. Your bookmarks and Claude's are separate lists; Claude never writes on yours unless you ask.The leader is Ctrl+], Claude Code's own abovePrompt:focus action bound to one key; the one-line binding is in the setup section of the full README. Every key, grouped by where the keyboard is: docs/keys.md. Each feature in detail: docs/usage.md. New to vim-style keys: the tutorial. When something does not work: troubleshooting.
Install from one place only. Installed from the Anthropic plugin directory and from a marketplace at the same time, the plugin would load twice and draw two bands.
From the directory, use its install flow. From this repository, which is also a marketplace, on Claude Code 2.1.288 or later:
/plugin install bookmarks --marketplace DazzleML/claude-bookmarks
Then bind the leader (one line in ~/.claude/keybindings.json), switch to the fullscreen renderer with /tui fullscreen, restart Claude Code, and check with /bm-env. To work on the plugin, load this folder directly: claude --plugin-dir /path/to/claude-bookmarks/plugin.
The plugin is a Claude Code mod: TypeScript that runs inside Claude Code's own process through its plugin API. It installs nothing and needs no package manager. The same facts in plain language, with how to remove everything: PRIVACY.md.
Sets. One environment variable, CONVO_BOOKMARKS_DEBUG, in the plugin's own process when you type /bm-debug on or off (the debug echo) or /bm-debug enable or disable (the debug channels), for that conversation; it dies with the process. No configuration file, settings file, start-up file or instructions file is written or edited.
Runs. The conversation's transcript file is often larger than the 4 MiB the plugin API will read at once, so the plugin reads it with a program already on your machine, for two jobs:
The programs are sh running grep, and sh running tail -c +<offset> <file> | head -c 4000000, where sh exists (macOS, Linux, Git Bash on Windows). On Windows they are three PowerShell scripts shipped in this folder, hooks/scripts/user-rows.ps1 (21 lines), hooks/scripts/grep-offsets.ps1 (17 lines) and hooks/scripts/read-chunk.ps1 (43 lines), run as powershell -NoProfile -NonInteractive -ExecutionPolicy Bypass -File <script>; each call falls back to the other form when the first is missing.
In every case the file path, the search text and the offset are passed as separate arguments, never spliced into a command string, so the text you select or Claude asks for cannot become a command. The only file any of them reads is the conversation's transcript. The program's output is read back by the plugin and goes nowhere else; each run is capped at 60 seconds. Nothing else is executed.
Reads. The conversation's transcript, which Claude Code keeps on disk under its config folder (~/.claude/projects/<project>/<session id>.jsonl, or CLAUDE_CONFIG_DIR): it is read, never written. The environment variables CLAUDE_CONFIG_DIR, CLAUDE_USER_DIR, HOME or USERPROFILE (to find those folders), CONVO_BOOKMARKS_DEBUG (the debug echo), and DCC_PATCH_H, DCC_PATCHES, DCC_PATCHER (shown by /bm-env when the companion patched build of Claude Code is in use; absent otherwise). Your mouse selection, through Claude Code's own plugin API call $.ui.selection() (no other plugin is involved), to know which line to mark. The prompt box, when you submit or edit it, to catch the plugin's own /bm- commands and to keep your draft intact while a pane is open; anything else you type passes through untouched, and a draft you have not sent is not stored (a prompt you send is kept for the prompts list; see Writes). Its own settings, which you choose in /config and Claude Code stores and hands to the plugin; the plugin reads them and never writes them.
Writes.
~/claude/bookmarks/ (or CLAUDE_USER_DIR):sessions/, holding its bookmarks, marks, reading position and pinned prompts, with a .bak copy; and one markdown file per bookmarked message, which you can read and edit.sessions/index.json, sessions/INDEX.md), and a README.md saying what each folder holds.backups/, the original files, taken before a format migration changes them.prompttext/, the text of your prompts, kept for the prompts list's /words filter and capped by the "Prompt text kept for the filter" setting. Under replytext/, the text of Claude's replies, up to 4 MB. Under transcript/, an index of where each message sits in the transcript, so a read resumes instead of starting over.~/.claude/plugins/store/bookmarks_inline-<id>.json), per conversation: the prompt lists, the jumplist, the reading position's way back, and when each conversation was last opened. Marks are kept there instead only when there is no data folder at all. A debug log per conversation, ~/claude/bookmarks/debug/<session id>.log, kept to its last 400 lines, holding key names, pane and jump events and never the text you type. The clipboard, when you promote a mark (the bookmark's link) or when a jump is refused (a phrase of the message to search for). Every path is computed from your home folder and the conversation's id; none is a file another tool runs or obeys. Nothing is written into the session file, and nothing under ~/.claude other than the plugin store.Hooks. It hooks Claude Code's events to keep its lists current and to draw, and passes each event on unchanged: session.start, session.end, session.append, turn.start, turn.complete, prompt.submit and prompt.edit (it reads them; your prompt goes on as you wrote it); config.set for its own bookmarks.* settings and for theme, where it lets Claude Code apply the change first, then reads the new value and redraws, and never changes or refuses a setting; ui.render, to draw its highlights and link markers on your screen only; command.run for its own /bm-* commands and tool.call for its own bookmark tool. On its own band and pane only: ui.focus keeps the band's keyboard ring on the band's fields, and ui.close turns the first Esc on the prompts list, while a filter is active, into clearing the filter. It answers no permission check, changes no permission mode or Remote Control setting, and registers no agent.
Sends. Nothing. The plugin makes no network connections and contacts no service. The one thing the model sees is its own bookmark tool and the links it returns.
GPL-3.0; see LICENSE. Source, issues and the roadmap: github.com/DazzleML/claude-bookmarks.
hooks/register.tsx 1693 lines1// claude-bookmarks: the plugin's engine adapter.
2//
3// Everything that talks to Claude Code lives here: the render hooks, the panes, the
4// band (the one-line command strip after the leader key), the `/bm-*` commands, the
5// `bookmark` tool, the store and the debug log. The rules themselves are pure modules
6// in core/, each with its tests in the repository's tests/core (`node --test tests/core/*.test.ts`), and
7// docs/engine-quirks.md records what the engine does and does not let a plugin do.
8//
9// Diagnostics report with $.ui.log (a dim transcript row Claude never reads) or a
10// toast, never as command `text`, because that text becomes a row Claude reads.
11
12import { atom, read, update } from 'claude-code'
13import type { EngineInterface, Register } from 'claude-code'
14
15import type { PaneMode, Row } from '../types'
16import {
17 markLinks, markdownLinks,
18 type MarkerStyle,
19} from './core/bookmarks/anchor'
20import { headOf, resolveRows, rowsFromGrep, targetPattern, type Resolution } from './core/bookmarks/transcript-lines'
21import { excerpt, type Channel } from './core/log/debug'
22import { CHORD_ACTIONS, VERIFIED_CLIENTS, bandFocusRoute, barFor, helpFor, listHint, listKeysFor, route, type Operation, type Pane } from './core/band/keys'
23import type { Cause } from './core/band/after-action'
24import { LEADER_FIELD, isKeyRow, leaderChord, rowDenial, type Problem } from './core/band/keymap'
25import { FOLD_FIELDS, foldLabel, rowHidden } from './core/settings-fold'
26import { installedFromCache, type Settings } from './core/settings'
27import { SettingsState } from './core/settings-state'
28import type { Role, Style } from './core/palette'
29import { classifyAppend, type FootnoteRef } from './core/prompts/prompt-rows'
30import { short } from './core/kit/message-id'
31import { configDirOf, dataRootOf } from './core/kit/paths'
32import { ECHO_POLICY_KEY, readingStateKey } from './core/store-keys'
33import { diagLine, editLine, focusLine, keyLabel, parseOnOff } from './core/log/diagnostics'
34import { NO_SIGNALS, capabilityOf, choose, chooseAll, pathsLine, type Signals } from './engine/select'
35import { firstColorSplit, tagMarksMarkdown, tagMarksPlain } from './core/marks/highlight'
36import { ScreenModel } from './core/kit/screen-model'
37import { MARK_LETTERS, MarkCache, READING_LETTER, marksShowing, type Mark, type Marks } from './core/marks/marks'
38import { BOOKMARK_GROUPS, footnoteAt, nextGroup, pickNumbered, promptEntry } from './core/band/band-entry'
39import { listInputTarget } from './core/band/routes'
40import { debugCommand } from './handlers/debug-command'
41import { anchoredReply, markedPrompt, markedReply, type MarkStyles } from './views/marked-message'
42import { bandView } from './views/band'
43import { bookmarksPaneView } from './views/bookmarks-pane'
44import { marksPaneView } from './views/marks-pane'
45import { promptsPaneView } from './views/prompts-pane'
46import { configCommand, envCommand, idsCommand, jumpCommand, marksCommand, selCommand, timelineCommand } from './handlers/diagnostics-commands'
47import type { BandPorts, BookmarksPorts, CommandLinePorts, DiagnosticsPorts, EchoPorts, LogFilesPorts, LoggerPorts, MarksPorts, NavigationPorts, PromptsPorts, ResolveOutcome, TranscriptPorts, ViewPorts } from './engine/ports'
48import { closeAll as bandCloseAll, endBandMode as bandEnd, settle as bandSettle, paneOf } from './handlers/band'
49import * as band_ from './handlers/band'
50import * as commandLine from './handlers/command-line'
51import * as marks_ from './handlers/marks'
52import * as bookmarks_ from './handlers/bookmarks'
53import * as prompts_ from './handlers/prompts'
54import * as transcript_ from './handlers/transcript'
55import * as log_ from './handlers/log'
56import { MarkState } from './core/marks/mark-state'
57import { Navigation } from './handlers/navigation'
58import { ViewTracker } from './handlers/view-tracker'
59import { PanePosition } from './core/kit/pane-position'
60import { BandState } from './core/band/band-state'
61import { PromptsPaneState } from './core/prompts/prompts-pane-state'
62import { DrawnMessages } from './core/kit/drawn-messages'
63import { BOOKMARK_TOOL } from './core/bookmarks/bookmark-tool'
64import { COMMANDS } from './core/band/commands'
65import { promptList, transcriptGuess, type PromptRef } from './core/prompts/prompt-store'
66
67
68// The plugin's settings as they stand, and the palette: core/settings-state.ts
69// SettingsState, kept current by `register`'s load and the config.set hooks below;
70// resolved once per change.
71const settings = new SettingsState()
72function currentSettings(): Settings {
73 return settings.current()
74}
75// The key tables the person's keymap rows make (#36; core/band/keymap.ts), which every
76// reader of core/band/keys.ts takes: the band, its help, the panes' keys and the hints.
77function currentTables() {
78 return settings.keymap().tables
79}
80// What in the keymap could not be used, one line (the default stands for each).
81const keymapProblemsLine = (problems: readonly Problem[]) =>
82 `[bm] keymap: ${problems.map(p => `${p.command}${p.key !== undefined ? ` "${p.key}"` : ''}: ${p.reason}`).join('; ')}; the defaults stand for those`
83
84// The plugin's one pane id (prompts, bookmarks, mark and jump panes all open under it).
85const PANE = 'bm-pane'
86
87// The borrowed chord actions and the Claude Code builds they were verified on are
88// core/band/keys.ts CHORD_ACTIONS and VERIFIED_CLIENTS (the one list the start-up
89// tripwire and /bm-env both read); the mark letters and the reading position's key are
90// core/marks/marks.ts MARK_LETTERS and READING_LETTER (U60, 2026-10-22).
91
92const rows = atom({ plugin: 'bookmarks', key: 'rows' } as const, [])
93const paneMode = atom({ plugin: 'bookmarks', key: 'paneMode' } as const, 'list')
94const shown = atom({ plugin: 'bookmarks', key: 'shown' } as const, null)
95const bandMode = atom({ plugin: 'bookmarks', key: 'bandMode' } as const, 'idle')
96const pinsRev = atom({ plugin: 'bookmarks', key: 'pinsRev' } as const, 0)
97// The band's command line (design 2026-10-07__02-58-22): bumped after each command so
98// the field is drawn under a new key and starts empty; and the prompt number's digits.
99const cmdRev = atom({ plugin: 'bookmarks', key: 'cmdRev' } as const, 0)
100const bandNum = atom({ plugin: 'bookmarks', key: 'bandNum' } as const, '')
101// The band field's generation (handlers/band.ts renewField): its key is band-num-field-<n>.
102const bandFieldRev = atom({ plugin: 'bookmarks', key: 'bandFieldRev' } as const, 0)
103// The bookmarks pane shows one group at a time, cycled from the band (djdarcy, 2026-10-09:
104// start on "their" bookmarks, a key cycles to Claude's, and a third group such as team
105// members' can join later). An ordered list, so a group is one entry, not a code path.
106// The keys are vim's sideways pair; `o`/`i` already mean back/forward at the band's top
107// level. Both become settings (#7).
108const bandGroup = atom({ plugin: 'bookmarks', key: 'bandGroup' } as const, 0)
109// Bumped when the prompt nearest the view changes while the prompts pane is open, so
110// the pane redraws its yellow row as the person scrolls (djdarcy, 2026-10-11).
111const viewRev = atom({ plugin: 'bookmarks', key: 'viewRev' } as const, 0)
112// Bumped when one of the plugin's /config fields changes, so the panes and the band,
113// which read settings while drawing, draw again.
114const settingsRev = atom({ plugin: 'bookmarks', key: 'settingsRev' } as const, 0)
115
116
117// What is on screen, and when the plugin itself last caused a redraw: core/kit/screen-model.ts.
118const screen = new ScreenModel()
119function expectRedraw(why: string) {
120 screen.expectRedraw(why, Date.now())
121}
122
123// The marks cluster (the highlight, setting a mark, the reading position, jumping to a
124// mark) is handlers/marks.ts; its own state is core/marks/mark-state.ts MarkState.
125const markState = new MarkState()
126
127// The session's marks, kept in memory so render hooks can read them without a store
128// call per row. Loaded at session.start and refreshed on every mark write.
129// (core/marks/marks.ts MarkCache: `replace` and `showTransient` are its only writers.)
130const markCache = new MarkCache()
131function marksPorts($: EngineInterface): MarksPorts {
132 return {
133 state: markState,
134 markCache,
135 shown: () => read($, shown),
136 setShown: v => update($, shown, () => v),
137 after: (ms, fn) => $.clock.after(ms, fn),
138 every: (ms, fn) => $.clock.every(ms, fn),
139 expectRedraw,
140 note,
141 log: logTextVia($),
142 toast: toastVia($),
143 cut,
144 selection: () => $.ui.selection(),
145 allRows: () => allRows($),
146 drawnText: uuid => drawn.texts.get(uuid),
147 topOnScreen: () => topOnScreen($),
148 viewAnchor: () => viewAnchor($),
149 freshOnScreen,
150 screenEntries: () => screen.entries(),
151 paneAnchor: () => panePosition.anchor,
152 noteRestore: (top, paneAction) => panePosition.noteRestore(top, paneAction),
153 restoreView: () => restoreView($),
154 jumpTo: (uuid, via, label, words, probe, block) => jumpTo($, uuid, via, label, words, probe, block),
155 now: () => $.clock.now(),
156 loadMarks: () => loadMarks($),
157 setMark: (letter, mark) => bookmarks_.setMarkOp(bookmarksPorts($), letter, mark),
158 clearMarks: letters => bookmarks_.clearMarksOp(bookmarksPorts($), letters),
159 forgetMark: letter => bookmarks_.forgetOp(bookmarksPorts($), letter),
160 readingStateStored: async () => $.store.get(readingStateKey(await $.session.id())),
161 storeReadingState: async state => $.store.set(readingStateKey(await $.session.id()), state),
162 letters: MARK_LETTERS,
163 readingLetter: READING_LETTER,
164 }
165}
166
167// Every colour, background, dim and bold the plugin draws comes from the palette by role
168// (#27, core/palette.ts; resolved and kept by SettingsState.palette).
169const style = (role: Role): Style => settings.palette()[role]
170// A Button's label can't be coloured at rest (docs/engine-quirks.md): only its dimness.
171const buttonStyle = (role: Role): { dimColor?: boolean } => (style(role).dimColor ? { dimColor: true } : {})
172
173// Where the marked line sits in a message, and the bold «a» form: core/marks/highlight.ts. How
174// it is drawn: views/marked-message.tsx, with these two palette roles.
175const markStyles = (): MarkStyles => ({ band: style('markBand'), mark: style('mark') })
176
177// The shown mark, if it is on this row (core/marks/marks.ts marksShowing), from the cache.
178function marksOnRow(requestId: string, showing: string | undefined): [string, Mark][] {
179 return marksShowing(markCache.all, requestId, showing)
180}
181
182// Ids seen at UserMessage render time since this module loaded. A module variable on
183// purpose: a render hook may not write $.state, and a reload should forget these, so
184// "never drawn since load" (a jump target Claude Code may refuse) means what it says.
185// core/kit/drawn-messages.ts DrawnMessages, which also keeps the panes' first-four set.
186const drawn = new DrawnMessages()
187
188// A message's on-screen report (core/kit/screen-model.ts noteMessage: which ids count, what is news).
189function noteOnScreen(requestId: string, onScreen: { first: number; last: number; of: number } | null | undefined) {
190 screen.noteMessage(requestId, onScreen, Date.now())
191}
192// The `screen` debug channel (#35): handlers/log.ts LogFiles.screenReport, when the channel is on.
193function rawScreen($: EngineInterface, component: string, requestId: string, onScreen: { first: number; last: number; of: number } | null | undefined) {
194 logger.channels.read(echoPorts($))
195 if (!logger.channels.has('screen')) return
196 logger.files.screenReport(logFilesPorts($), component, requestId, onScreen)
197}
198
199// One render report from a non-message row: the screen channel's log, the news time
200// (a non-message row's report dates the latest burst: core/kit/screen-model.ts noteOther),
201// and the pane's view check.
202function noteOtherRow($: EngineInterface, tag: string, requestId: string, onScreen: { first: number; last: number; of: number } | null | undefined) {
203 rawScreen($, tag, requestId, onScreen)
204 screen.noteOther(requestId, onScreen, Date.now())
205 noteViewMoved($)
206}
207
208function freshOnScreen(): string[] {
209 return screen.fresh()
210}
211
212// The logger (handlers/log.ts Logger): the one instance. It owns the timeline
213// (`logger.timeline`), the file log (`logger.files`) and the debug channels
214// (`logger.channels`); readers here reach each part through it.
215const logger = new log_.Logger()
216// The timeline's one writer.
217function note(what: string) {
218 logger.timeline.note(what)
219}
220// The file log, the screen channel's file and their rings: handlers/log.ts LogFiles, the
221// logger's, over logFilesPorts($).
222function logFilesPorts($: EngineInterface): LogFilesPorts {
223 return {
224 sessionId: () => $.session.id(),
225 dataRoot: () => dataRoot($),
226 fsExists: path => $.fs.exists(path),
227 fsRead: path => $.fs.read(path),
228 fsWrite: (path, text) => $.fs.write(path, text),
229 after: (ms, fn) => $.clock.after(ms, fn),
230 }
231}
232
233// The debug echo (the machine-wide policy and this conversation's choice) is
234// handlers/log.ts, over echoPorts($); its callers call it directly with these ports.
235function echoPorts($: EngineInterface): EchoPorts {
236 return {
237 echoPolicyStored: () => $.store.get(ECHO_POLICY_KEY),
238 storeEchoPolicy: policy => $.store.set(ECHO_POLICY_KEY, policy),
239 settings: currentSettings,
240 debugEnv: () => $.env.get('CONVO_BOOKMARKS_DEBUG'),
241 setDebugEnv: value => $.env.set('CONVO_BOOKMARKS_DEBUG', value),
242 }
243}
244
245// log() is handlers/log.ts Logger.log, over these ports: the echo's, the file log's, the
246// engine's $.ui.log, and whether this build was loaded from a folder.
247function logPorts($: EngineInterface): LoggerPorts {
248 return {
249 ...echoPorts($),
250 ...logFilesPorts($),
251 uiLog: line => $.ui.log(line),
252 folderBuild: !installedFromCache($.plugin.root),
253 }
254}
255// The port closures every *Ports($) builder spells the same way (refactor-advisor 2026-10-22
256// row 8): one helper each, in this file, since the validator follows `$` only into functions
257// declared here (docs/engine-quirks.md, "Engine calls stay in the hooks module's own file").
258function toastVia($: EngineInterface) {
259 return (text: string, timeoutMs?: number) => (timeoutMs ? $.ui.toast(text, { timeoutMs }) : $.ui.toast(text))
260}
261function logTextVia($: EngineInterface) {
262 return (line: string, text?: boolean) => log($, line, text ? { text: true } : undefined)
263}
264function copyVia($: EngineInterface) {
265 return (text: string) => $.ui.copy({ text })
266}
267function scrollVia($: EngineInterface) {
268 return (uuid: string, block: 'start' | 'center' | 'end' | 'nearest') => $.ui.scroll({ to: { requestId: uuid }, block })
269}
270function bumpView($: EngineInterface) {
271 return update($, viewRev, v => v + 1)
272}
273
274function log($: EngineInterface, line: string, opts?: { always?: boolean; text?: boolean }) {
275 logger.log(logPorts($), line, opts)
276}
277
278// A quoted excerpt in a log line: short, or whole when `debugTextLength` is `full`.
279const cut = (text: string, n: number) => excerpt(text, n, currentSettings().debugTextLength)
280
281// The person's home folder: USERPROFILE (Windows), else HOME. Read here, where the
282// validator follows `$.env.get`; what is built from it is core/kit/paths.ts.
283async function homeDir($: EngineInterface): Promise<string | undefined> {
284 return (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
285}
286// Claude Code's config folder (core/kit/paths.ts configDirOf).
287async function configDir($: EngineInterface): Promise<string | undefined> {
288 return configDirOf(await $.env.get('CLAUDE_CONFIG_DIR'), await homeDir($))
289}
290// The data root: where this plugin keeps what is the person's (bookmarks, exports, the
291// debug log); core/kit/paths.ts dataRootOf.
292async function dataRoot($: EngineInterface): Promise<string | undefined> {
293 const fromEnv = await $.env.get('CLAUDE_USER_DIR')
294 return dataRootOf(fromEnv, fromEnv ? undefined : await homeDir($))
295}
296
297// --- Conversations (Q261014-01) ---------------------------------------------------------
298// The process outlives a conversation: /clear starts a new one under a new session id, and
299// a resume puts another in its place, its own transcript drawn instead (the source's
300// REPL.tsx: the messages are replaced, not extended). No session.start fires for either.
301// So the plugin notes the id it is working for, and wherever it next looks (a stored row,
302// a submitted prompt, the band or a pane drawn, a band command, a session's end) a changed
303// id means a new conversation: what was held for the one before is reset, and what is
304// kept per conversation (its marks, jumplist, register, log) is read for the new one.
305// Compaction keeps the id, so it resets nothing.
306let conversationId: string | undefined
307async function sameConversation($: EngineInterface): Promise<void> {
308 const id = await $.session.id()
309 if (conversationId === undefined || id === conversationId) {
310 conversationId = id
311 return
312 }
313 const before = conversationId
314 conversationId = id
315 await resetConversationMemory()
316 await bookmarks_.startRegister(bookmarksPorts($))
317 await marks_.startMarks(marksPorts($))
318 pruneThenBackfill($)
319 startLoader($)
320 log($, `[bm] a new conversation: ${short(before)} -> ${short(id)}; what the one before left in memory is reset`)
321}
322// The store's prune, then this conversation's back-fill (done once per conversation, by its
323// flag): at session.start, and when the process moves to another conversation (0.4.79;
324// acceptance check 2026-10-14__16-55-20, #15: a resumed conversation was never back-filled
325// until the next process start). Not awaited, by either.
326function pruneThenBackfill($: EngineInterface) {
327 void prompts_.pruneStoreNow(promptsPorts($))
328 .catch(err => log($, `[bm] store prune failed: ${String(err)}`))
329 .then(() => prompts_.backfillPrompts(promptsPorts($)))
330 .catch(err => log($, `[bm] backfill failed: ${String(err)}`))
331}
332// From a render hook, which may not write state (the reset clears the highlight): notice
333// a changed id there and do the reset on a clock tick.
334function sameConversationSoon($: EngineInterface) {
335 void $.session.id().then(id => {
336 if (conversationId !== undefined && id !== conversationId) $.clock.after(0, () => void sameConversation($).catch(() => {}))
337 }).catch(() => {})
338}
339// What a conversation leaves in memory: one list of its owners, each forgetting its own
340// part (newConversation): the log files' place and rings (0.4.74), the prompts pane's
341// filter, folds and pending centre, the band's state, the pane position and the view
342// tracker (0.4.73). Left out on purpose, so adding an owner is a decision made here:
343// the register and the marks reset through their own start parts (startRegister,
344// startMarks); the settings are the person's, not a conversation's; the drawn ids
345// (DrawnMessages) are "drawn since load", and whether a resumed conversation's messages
346// are drawn before or after this reset is not known; paneGeometry is the pane's.
347async function resetConversationMemory() {
348 for (const owner of [logger.files, promptsPane, band, panePosition, viewTracker]) await owner.newConversation()
349 // U60 commit B: three more parts a conversation leaves behind. The replies whose links
350 // were logged (handlers/bookmarks.ts), what was on screen (the reports belong to the
351 // transcript drawn before), and the title the start event carried (session.start sets
352 // the new one after this reset).
353 bookmarks_.newConversation()
354 transcript_.newConversation()
355 screen.newConversation()
356 sessionTitle = undefined
357}
358
359// Mark and Marks: core/marks/marks.ts.
360
361// This plugin's own version, from its manifest (the one Claude Code installs by).
362async function pluginVersion($: EngineInterface): Promise<string> {
363 try {
364 const manifest = JSON.parse(await $.fs.read(`${$.plugin.root}/.claude-plugin/plugin.json`))
365 return typeof manifest.version === 'string' ? manifest.version : '?'
366 } catch {
367 return '?'
368 }
369}
370
371async function allRows($: EngineInterface): Promise<Row[]> {
372 return (await read($, rows)) as Row[]
373}
374
375// The prompt store (the session's prompts and footnotes, the prompts' text for the filter)
376// is handlers/prompts.ts, over promptsPorts($).
377function promptsPorts($: EngineInterface): PromptsPorts {
378 return {
379 sessionId: () => $.session.id(),
380 storeGet: key => $.store.get(key),
381 storeSet: (key, value) => $.store.set(key, value),
382 storeKeys: () => $.store.keys(),
383 storeDelete: key => $.store.delete(key),
384 dataRoot: () => dataRoot($),
385 fsExists: path => $.fs.exists(path),
386 fsRead: path => $.fs.read(path),
387 fsWrite: (path, text) => $.fs.write(path, text),
388 after: (ms, fn) => $.clock.after(ms, fn),
389 settings: currentSettings,
390 now: () => $.clock.now(),
391 log: line => log($, line),
392 transcriptPath: () => transcriptPath($),
393 userRows: path => userRows($, path),
394 }
395}
396async function keptPrompts($: EngineInterface): Promise<PromptRef[]> {
397 return prompts_.keptPrompts(promptsPorts($))
398}
399async function keptFootnotes($: EngineInterface): Promise<FootnoteRef[]> {
400 return prompts_.keptFootnotes(promptsPorts($))
401}
402
403// --- Back-fill: the prompts sent before the mod was loaded ------------------------
404// The transcript holds them but is too big for $.fs.read (4 MiB; 18 MB here). The
405// platform's own tool filters it to the user rows (no install: Windows PowerShell 5.1
406// on Windows, sh + grep elsewhere) and the mod parses the JSON lines. Settled by the
407// measurement in tests/one-offs/thinking/prompt-history/ (2026-10-04: 152/152 prompts,
408// identical text; ~1 MB of output; 328 ms PowerShell, 81 ms sh + grep). Runs once per
409// conversation; after that the live capture keeps the list current.
410// Which rows are prompts, and the words of a queued one: core/prompts/prompt-rows.ts (tested),
411// shared by the transcript back-fill below and the live capture in session.append.
412
413// The PowerShell fallbacks are scripts shipped with the plugin (hooks/scripts/*.ps1),
414// run with -File and named parameters. Until v0.3.0 they were inline scripts passed as
415// base64 UTF-16LE text, to keep their double quotes intact; a measurement on 2026-10-09
416// showed -File parameters keep `"type":"user"` verbatim from a non-shell spawn, and
417// base64-encoded PowerShell is what a security scan flags. Each $.process.run below
418// receives its argv as a literal array at the call, program name and flags spelled
419// out, so a static reader can see what runs; only the file path, the search text and
420// the plugin's own folder are variables.
421
422// The session's transcript: <config dir>/projects/<project>/<session id>.jsonl. The
423// project folder is the cwd with every non-alphanumeric character turned into `-`;
424// if that guess misses, every project folder is looked in.
425async function transcriptPath($: EngineInterface): Promise<string | undefined> {
426 const config = await configDir($)
427 if (!config) return undefined
428 const sid = await $.session.id()
429 const file = `${sid}.jsonl`
430 const guess = transcriptGuess(config, await $.session.cwd(), sid)
431 if (await $.fs.exists(guess)) return guess
432 for (const entry of await $.fs.list(`${config}/projects`)) {
433 const candidate = `${config}/projects/${entry.name}/${file}`
434 if (entry.kind === 'dir' && (await $.fs.exists(candidate))) return candidate
435 }
436 return undefined
437}
438
439// --- For reviewers: the three places this plugin runs a program --------------------
440// userRows() and grepTranscript() below, and readChunk in transcriptPorts() after them,
441// are the plugin's only $.process.run calls. Each reads the conversation's transcript and
442// nothing else. Why a program at all: the transcript is often larger than the 4 MiB that
443// $.fs.read accepts (it rejects above that), so the file is searched, or read in 4 MB
444// pieces by byte offset, by a tool already on the machine. What runs: `sh -c 'grep ...'`
445// or `sh -c 'tail -c +"$1" "$2" | head -c 4000000'` where sh exists, else `powershell
446// -NoProfile -NonInteractive -ExecutionPolicy Bypass -File <one of the three .ps1 files
447// shipped in hooks/scripts/>`. The transcript path, the search text and the offset are
448// always separate argv elements ("$1"/"$2" to sh, named -Path/-Pattern/-Offset
449// parameters to PowerShell), never spliced into the command string, so selected or
450// model-chosen text cannot become a command. Output is read back here and parsed as JSON lines;
451// it is not sent anywhere, and the plugin opens no network connection. Each run is
452// capped at 60 seconds and at 4 MiB of output by the engine. See README "What it
453// runs, reads, writes and sends" and PRIVACY.md.
454
455// The user rows of the transcript, one JSON line each, from the platform's own tool.
456async function userRows($: EngineInterface, path: string) {
457 const windows = /^[A-Za-z]:[\\/]/.test(path)
458 if (windows) {
459 // Windows PowerShell 5.1 first on a Windows path. The row markers ("type":"user",
460 // "type":"tool_result") are spelled out at each call so the command reads as fixed
461 // text; the sh form below uses the same two.
462 try {
463 const started = Date.now()
464 const r = await $.process.run(
465 ['powershell', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', `${$.plugin.root}/hooks/scripts/user-rows.ps1`,
466 '-Path', path, '-UserRow', '"type":"user"', '-QueuedRow', '"type":"queued_command"', '-ToolResultRow', '"type":"tool_result"', '-MetaRow', '"isMeta":true'],
467 { timeoutMs: 60_000 },
468 )
469 if (r.exitCode === 0 || r.stdout) return { via: 'powershell' as const, ms: Date.now() - started, ...r }
470 } catch {
471 // PowerShell is not there: try sh.
472 }
473 }
474 try {
475 const started = Date.now()
476 const r = await $.process.run(
477 ['sh', '-c', 'grep -F -e \'"type":"user"\' -e \'"type":"queued_command"\' "$1" | grep -vF -e \'"type":"tool_result"\' -e \'"isMeta":true\'', 'sh', path],
478 { timeoutMs: 60_000 },
479 )
480 if (r.exitCode === 0 || r.stdout) return { via: 'sh' as const, ms: Date.now() - started, ...r }
481 } catch {
482 // sh is not there either.
483 }
484 return undefined
485}
486
487// `grep -bn` over the transcript: every line containing `pattern`, as `line:byteoffset:
488// text`. sh + grep first on every platform (29 ms on a 10 MB file here; Git Bash has
489// grep on Windows); PowerShell second, computing the byte offsets itself since
490// Select-String has none. The output cap (4 MiB) cuts the newest matches first; a cut
491// line fails to parse and is skipped.
492async function grepTranscript($: EngineInterface, path: string, pattern: string) {
493 try {
494 const started = Date.now()
495 const r = await $.process.run(
496 ['sh', '-c', 'grep -bnF -- "$1" "$2"', 'sh', pattern, path],
497 { timeoutMs: 60_000 },
498 )
499 // grep exits 1 for "no match" with empty output: that is an answer, not a failure.
500 if (r.exitCode === 0 || r.exitCode === 1 || r.stdout) return { via: 'sh' as const, ms: Date.now() - started, ...r }
501 } catch {
502 // sh is not there: try PowerShell.
503 }
504 try {
505 const started = Date.now()
506 const r = await $.process.run(
507 ['powershell', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', `${$.plugin.root}/hooks/scripts/grep-offsets.ps1`,
508 '-Path', path, '-Pattern', pattern],
509 { timeoutMs: 60_000 },
510 )
511 if (r.exitCode === 0 || r.exitCode === 1 || r.stdout) return { via: 'powershell' as const, ms: Date.now() - started, ...r }
512 } catch {
513 // PowerShell is not there either.
514 }
515 return undefined
516}
517
518// The message a request names, with its line and byte range: by uuid (full or 8+
519// prefix), or by a fragment of its text (earliest real message that contains it; several
520// are returned as candidates). The anchors DWP's resolver (2026-10-09). Its outcome type,
521// ResolveOutcome, is in engine/ports.ts since 0.4.64: handlers/bookmarks.ts names it too.
522// The loader's pass (handlers/transcript.ts, slice F): one background read of the whole
523// transcript in chunks, through the third program this plugin runs. `tail -c +N | head -c`
524// returns CHUNK_BYTES of the file from a byte offset; the path and the offset are argv
525// elements ("$1"/"$2"), never spliced into the command. On a Windows path,
526// hooks/scripts/read-chunk.ps1 is tried first (0.6.19: the engine does not find Git Bash's
527// sh there); without either the loader stays off and the two readers above stand (the
528// capability row `transcript.chunks`).
529function transcriptPorts($: EngineInterface): TranscriptPorts {
530 return {
531 sessionId: () => $.session.id(),
532 transcriptPath: () => transcriptPath($),
533 fileSize: async path => {
534 const s: unknown = await $.fs.stat(path, { resolve: true }).catch(() => undefined)
535 const size = (s as { size?: unknown } | undefined)?.size
536 return typeof size === 'number' ? size : undefined
537 },
538 readChunk: async (path, offset) => {
539 // PowerShell first on a Windows path (the engine does not find Git Bash's sh here:
540 // "Command 'sh' not found", 2026-10-22), as userRows does; sh second, everywhere.
541 if (/^[A-Za-z]:[\\/]/.test(path)) {
542 try {
543 const r = await $.process.run(
544 ['powershell', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', `${$.plugin.root}/hooks/scripts/read-chunk.ps1`,
545 '-Path', path, '-Offset', String(offset), '-Count', '4000000'],
546 { timeoutMs: 60_000 },
547 )
548 if (r.exitCode === 0 || r.stdout) return { stdout: r.stdout, via: 'powershell' as const }
549 log($, `[bm] loader: powershell returned ${r.exitCode} with no output at byte ${offset}${r.stderr ? `: ${r.stderr.slice(0, 200)}` : ''}`)
550 } catch (err) {
551 log($, `[bm] loader: the PowerShell chunk read threw: ${String(err).slice(0, 300)}`)
552 }
553 }
554 try {
555 const r = await $.process.run(
556 ['sh', '-c', 'tail -c +"$1" "$2" | head -c 4000000', 'sh', String(offset + 1), path],
557 { timeoutMs: 60_000 },
558 )
559 if (r.exitCode === 0 || r.stdout) return { stdout: r.stdout, via: 'sh' as const }
560 log($, `[bm] loader: sh returned ${r.exitCode} with no output at byte ${offset}${r.stderr ? `: ${r.stderr.slice(0, 200)}` : ''}`)
561 } catch (err) {
562 // sh is not there, or the engine refused the run: say which, for the next diagnosis.
563 log($, `[bm] loader: the chunk read threw: ${String(err).slice(0, 300)}`)
564 }
565 return undefined
566 },
567 dataRoot: () => dataRoot($),
568 fsExists: path => $.fs.exists(path),
569 fsRead: path => $.fs.read(path),
570 fsWrite: (path, text) => $.fs.write(path, text),
571 promptTexts: () => prompts_.promptTexts(promptsPorts($)),
572 after: (ms, fn) => $.clock.after(ms, fn),
573 log: line => log($, line),
574 publish: (backfill, truncated) => prompts_.applyBackfill(promptsPorts($), backfill, truncated),
575 }
576}
577function startLoader($: EngineInterface) {
578 void transcript_.startPass(transcriptPorts($)).catch(err => log($, `[bm] loader failed to start: ${String(err)}`))
579}
580
581async function resolveTarget($: EngineInterface, want: { uuid?: string; fragment?: string }): Promise<ResolveOutcome> {
582 // The loader's rows first (in memory, every message the pass has read); the grep below
583 // while the pass is incomplete, or when no program could read the file.
584 const loaded = transcript_.resolveLoaded(want)
585 if (loaded?.kind === 'one') return { kind: 'one', row: loaded.row, via: 'loader', ms: 0 }
586 if (loaded?.kind === 'many') return { kind: 'many', rows: loaded.rows, earliest: loaded.earliest, via: 'loader', ms: 0 }
587 if (loaded?.kind === 'none') return { kind: 'none', via: 'loader', ms: 0, reason: 'no message holds it' }
588 const path = await transcriptPath($)
589 if (!path) return { kind: 'none', reason: 'transcript not found' }
590 const pattern = targetPattern(want)
591 if (!pattern) return { kind: 'none', reason: 'nothing to look for' }
592 const g = await grepTranscript($, path, pattern)
593 if (!g) return { kind: 'none', reason: 'neither sh + grep nor PowerShell ran' }
594 const rows = rowsFromGrep(g.stdout)
595 const r: Resolution = resolveRows(rows, want)
596 if (r.kind === 'none') return { kind: 'none', via: g.via, ms: g.ms, reason: g.isStdoutTruncated ? 'no match (output was cut at 4 MiB)' : 'no match' }
597 return { ...r, via: g.via, ms: g.ms }
598}
599
600// The store's prune and the back-fill are handlers/prompts.ts (pruneStoreNow,
601// backfillPrompts), over promptsPorts($); userRows above is their program run.
602
603// The stored prompts that are prompts, then the rows captured live this session that the
604// store lacks (core/prompts/prompt-store.ts promptList). Rows kept before the list knew them for
605// notices drop out, so the numbers match the transcript's; a `<task-notification>` row
606// the rebuild dropped once came back as the newest prompt and sent the yellow row to the
607// bottom (djdarcy, 2026-10-11: scrolling up from #325 moved it to #342).
608async function prompts($: EngineInterface): Promise<PromptRef[]> {
609 return promptList(await keptPrompts($), await allRows($))
610}
611
612// Since 0.5.5 the marks are records in the register, pointed at by its slots (the data
613// design, 2026-10-16); the v2 -> v3 migration moves them out of the store (`marks:<sid>`,
614// core/store-keys.ts) at the conversation's start, and the store is the fallback when there
615// is no data root. handlers/bookmarks.ts derives the `Marks` the panes draw.
616async function loadMarks($: EngineInterface): Promise<Marks> {
617 return bookmarks_.marksOf(bookmarksPorts($))
618}
619
620// The conversation's title for the register header (unit 6): the /rename name the start
621// event carried (`session_title`, the only place the engine says it), else the head of the
622// first prompt. No engine call reads the title after the start, so it is kept here.
623let sessionTitle: string | undefined
624async function conversationTitle($: EngineInterface): Promise<string | undefined> {
625 if (sessionTitle) return sessionTitle
626 return (await prompts($))[0]?.head || undefined
627}
628
629// Bookmark anchors and the register (its file, minting, exports, prose anchors, the
630// anchor press, the model's tool): handlers/bookmarks.ts, over bookmarksPorts($).
631function bookmarksPorts($: EngineInterface): BookmarksPorts {
632 return {
633 log: logTextVia($),
634 logAlways: line => log($, line, { always: true }),
635 toast: toastVia($),
636 cut,
637 expectRedraw,
638 dataRoot: () => dataRoot($),
639 pluginFile: async relative => {
640 const path = `${$.plugin.root}/${relative}`
641 return (await $.fs.exists(path)) ? await $.fs.read(path) : undefined
642 },
643 sessionId: () => $.session.id(),
644 cwd: () => $.session.cwd(),
645 title: () => conversationTitle($),
646 pluginName: $.plugin.name,
647 pluginVersion: () => pluginVersion($),
648 configDir: () => configDir($),
649 now: () => $.clock.now(),
650 after: (ms, fn) => $.clock.after(ms, fn),
651 fsExists: path => $.fs.exists(path),
652 fsRead: path => $.fs.read(path),
653 fsWrite: (path, text) => $.fs.write(path, text),
654 fsList: path => $.fs.list(path),
655 storeGet: key => $.store.get(key),
656 storeSet: (key, value) => $.store.set(key, value),
657 storeDelete: key => $.store.delete(key),
658 storeKeys: () => $.store.keys(),
659 resolveTarget: want => resolveTarget($, want),
660 transcriptPath: () => transcriptPath($),
661 allRows: () => allRows($),
662 jumpTo: (uuid, via, label, words) => jumpTo($, uuid, via, label, words),
663 loadMarks: () => loadMarks($),
664 copy: copyVia($),
665 highlightWords: (letter, uuid, words) => marks_.showWords(marksPorts($), letter, uuid, words),
666 }
667}
668
669// How link kinds are told apart in a reply (djdarcy, 2026-10-09: "how can we denote that
670// a link has secondary metadata ... so I don't have to ctrl-click every link"). Settings
671// in a later version (#7); constants until then.
672const LINK_MARKERS: MarkerStyle = 'glyph'
673const LINK_LEGEND = true
674
675// Every jump, the jumplist and the view's return: handlers/navigation.ts, over these ports.
676const navigation = new Navigation()
677function navPorts($: EngineInterface): NavigationPorts {
678 return {
679 sessionId: () => $.session.id(),
680 storeGet: key => $.store.get(key),
681 storeSet: (key, value) => $.store.set(key, value),
682 scroll: scrollVia($),
683 copy: copyVia($),
684 toast: toastVia($),
685 log: logTextVia($),
686 note,
687 drawnHead: uuid => drawn.texts.get(uuid),
688 markHead: uuid => markCache.headOf(uuid),
689 pathFor: gap => choose(capabilityOf(gap), capabilitySignals ?? NO_SIGNALS).path,
690 leavingFrom: async () => panePosition.view ?? (await viewAnchor($)),
691 paneJumped: () => panePosition.jumped(),
692 takeRestore: () => panePosition.takeRestore(),
693 freshOnScreen,
694 }
695}
696async function jumplistMove($: EngineInterface, step: -1 | 1) {
697 await navigation.jumplistMove(navPorts($), step)
698}
699async function jumpTo($: EngineInterface, uuid: string, via: string, label: string, words?: string, probe = false, block: 'start' | 'end' = 'start'): Promise<string | undefined> {
700 return navigation.jumpTo(navPorts($), uuid, via, label, words, probe, block)
701}
702
703// Where the view was before a pane opened, and where it goes back to: core/kit/pane-position.ts
704// (the three fields and their writers, each a named method).
705const panePosition = new PanePosition()
706async function restoreView($: EngineInterface) {
707 await navigation.restoreView(navPorts($))
708}
709
710async function setMark($: EngineInterface, letter: string) {
711 await marks_.setMark(marksPorts($), letter)
712}
713
714// The view tracker (handlers/view-tracker.ts) owns which messages are on screen in
715// conversation order, the prompt nearest the view, the view anchor and the pane's
716// follow; it reads the screen model. Its ports are spelled once here.
717const viewTracker = new ViewTracker(screen)
718function viewPorts($: EngineInterface): ViewPorts {
719 return {
720 prompts: () => prompts($),
721 rows: () => allRows($),
722 log: line => log($, line),
723 closeShare: () => currentSettings().closeShare,
724 after: (ms, fn) => $.clock.after(ms, fn),
725 listPaneOpen: async () => (await read($, paneMode)) === 'list' && (await $.ui.panes()).some(p => p.id === PANE),
726 heldChannel: () => logger.channels.has('held'),
727 bumpView: () => bumpView($),
728 followHere: () => currentSettings().followHere,
729 bandNumEmpty: async () => (await read($, bandNum)) === '',
730 scrollPaneTo: key => $.ui.scroll({ in: PANE, to: { key }, block: 'nearest' }),
731 }
732}
733async function topOnScreen($: EngineInterface): Promise<string | undefined> {
734 return viewTracker.topOnScreen(viewPorts($))
735}
736
737async function promptHere($: EngineInterface): Promise<string | undefined> {
738 return viewTracker.promptHere(viewPorts($))
739}
740// The prompts pane's own state -- the filter, the unfolded footnotes, the prompt to centre
741// on -- is core/prompts/prompts-pane-state.ts PromptsPaneState, written only through its
742// named methods.
743const promptsPane = new PromptsPaneState()
744function noteViewMoved($: EngineInterface) {
745 viewTracker.noteViewMoved(viewPorts($))
746}
747async function viewAnchor($: EngineInterface): Promise<{ uuid: string; block: 'start' | 'end' } | undefined> {
748 return viewTracker.viewAnchor(viewPorts($))
749}
750
751async function goToReading($: EngineInterface, reading: Mark, via: string) {
752 await marks_.goToReading(marksPorts($), reading, via)
753}
754async function readingToggle($: EngineInterface) {
755 await marks_.readingToggle(marksPorts($))
756}
757async function jumpToMark($: EngineInterface, letter: string, probe = false): Promise<string | undefined> {
758 return marks_.jumpToMark(marksPorts($), letter, probe)
759}
760
761// --- The band's command line -----------------------------------------------------------
762// The band's command line (the field the leader lands on, and `perform`) is
763// handlers/command-line.ts. The borrowed action each chord button carries is
764// core/band/keys.ts CHORD_ACTIONS.
765
766// Draw the field anew, empty.
767async function clearCommandLine($: EngineInterface) {
768 await update($, cmdRev, v => v + 1)
769}
770
771// The band's own state -- its wait and watch timers, the focus ring, its requestId, the
772// Esc reminder -- is core/band/band-state.ts BandState, written only through its named methods.
773const band = new BandState()
774async function runCommandLine($: EngineInterface, typed: string, via: 'input' | 'submit') {
775 await sameConversation($)
776 await commandLine.runCommandLine(commandLinePorts($), typed, via)
777}
778async function perform($: EngineInterface, operation: Operation, via: 'field' | string) {
779 await commandLine.perform(commandLinePorts($), operation, via)
780}
781
782async function closeAll($: EngineInterface, via: string) {
783 await bandCloseAll(bandPorts($), via)
784}
785
786// DIAGNOSTIC (2026-10-07): who holds the keyboard around a key, to explain a pane that is
787// kept or refused. Lengths only, never the draft's text. Keystrokes are logged only
788// while /bm-diag-keys is on.
789const diag = { lastEditAt: 0, busy: false, logKeys: false }
790async function diagState($: EngineInterface, when: string) {
791 log($, diagLine(when, (await $.prompt.read()).text.length, diag.lastEditAt, Date.now(), diag.busy, await $.ui.panes()))
792}
793
794async function openFor($: EngineInterface, mode: PaneMode, action: string) {
795 await band_.openFor(bandPorts($), mode, action)
796}
797
798
799// Jumps to prompt #n, from the prompts pane's field or the band's.
800// --- Pinned prompts ------------------------------------------------------------------
801// Favourite prompts to come back to (djdarcy, 2026-10-05), per conversation, kept in
802// the order they were pinned. Drawn as `245★)` and listed again at the top of the
803// prompts pane. Toggled by `*21` (or `*` for the newest) in the `#` field, or /bm-pin.
804// Since 0.5.4 the pins live in the register file (the data design, 2026-10-16: pins are
805// authored, so they are the person's and not Claude Code's housekeeping); the v1 -> v2
806// migration moves them out of the store (`pins:<sid>`, core/store-keys.ts) at the
807// conversation's start. handlers/bookmarks.ts owns the read and the toggle.
808async function loadPins($: EngineInterface): Promise<string[]> {
809 return bookmarks_.pinnedPrompts(bookmarksPorts($))
810}
811
812// Toggles the pin on prompt #n (the newest when `typed` names none). Returns false when
813// there is no such prompt. `known`: the list the caller already read (move audit F6).
814async function togglePin($: EngineInterface, typed: string, known?: PromptRef[]): Promise<boolean> {
815 const all = known ?? (await prompts($))
816 const picked = pickNumbered(typed, all, 'prompt', true)
817 if ('error' in picked) {
818 $.ui.toast(picked.error)
819 return false
820 }
821 const { n, target } = picked
822 const pins = await loadPins($)
823 const pinned = pins.includes(target.uuid)
824 const r = await bookmarks_.togglePinned(bookmarksPorts($), target.uuid, !pinned)
825 if ('error' in r) {
826 $.ui.toast(r.error, { timeoutMs: 8000 })
827 return false
828 }
829 await update($, pinsRev, v => v + 1)
830 $.ui.toast(`${pinned ? 'unpinned' : 'pinned'} #${n}: ${target.head.slice(0, 40)}`)
831 log($, `[bm] ${pinned ? 'unpinned' : 'pinned'} prompt #${n} ${short(target.uuid)}`)
832 return true
833}
834
835// The prompts list's `/words` filter as a field sets it while the person types (the pane's
836// own `#` field, and the band's field since input routing): true when it changed.
837function setPromptFilter($: EngineInterface, query: string): boolean {
838 if (!promptsPane.setFilter(query)) return false
839 log($, `[bm] prompts filter: "${cut(query, 40)}"`, { text: true })
840 void bumpView($)
841 return true
842}
843
844// Where the band takes a list number (core/band/routes.ts): the band holds the keyboard,
845// so the pane's own field is never the answer here; a build that could hand the pane the
846// keyboard (focus.paneFromBand patched) would be read here and still type in the band
847// until that hand-off exists.
848function bandListInput(): 'band-field' | 'band-buttons' {
849 const handoff = choose(capabilityOf('focus.paneFromBand'), capabilitySignals ?? NO_SIGNALS).path
850 const r = listInputTarget({ paneHasKeyboard: false }, currentSettings().listInput, handoff)
851 return r.target === 'band-buttons' ? 'band-buttons' : 'band-field'
852}
853
854// What the entry means (pin, filter, unfold, footnote, jump): core/band/band-entry.ts promptEntry.
855async function jumpToPromptNumber($: EngineInterface, typed: string, via: string) {
856 const all = await prompts($)
857 const entry = promptEntry(typed, all.length)
858 if (entry.kind === 'pin') {
859 await togglePin($, entry.typed, all)
860 return
861 }
862 if (entry.kind === 'filter') {
863 promptsPane.setFilter(entry.words)
864 await bumpView($)
865 return
866 }
867 if (entry.kind === 'unfold') {
868 // Hidden footnotes: `N.k` still jumps (djdarcy, 2026-10-12: "Rows hidden, keys work"),
869 // but `N.` has nothing to show, so it says why.
870 if (currentSettings().footnotes === 'hidden') return void $.ui.toast('Footnotes are hidden: "Footnotes in the prompts list" in /config shows them')
871 promptsPane.toggleFold(entry.n)
872 await bumpView($)
873 return
874 }
875 if (entry.kind === 'footnote') {
876 const f = footnoteAt(all.map(p => p.uuid), await keptFootnotes($), entry.n, entry.k)
877 if (!f) {
878 $.ui.toast(`no footnote ${entry.n}.${entry.k}`)
879 return
880 }
881 await jumpTo($, f.uuid, via, `footnote ${entry.n}.${entry.k}`)
882 await settle($, 'list', 'jump')
883 return
884 }
885 if (entry.kind === 'invalid') {
886 $.ui.toast(`no prompt #${entry.typed} (1-${all.length})`)
887 return
888 }
889 const target = all[entry.n - 1]!
890 await jumpTo($, target.uuid, via, `prompt #${entry.n}`, target.head)
891 await settle($, 'list', 'jump')
892}
893
894// Bookmarks in the pane and the band: the list, a bookmark's arrival and its highlight
895// are handlers/bookmarks.ts.
896async function bookmarkList($: EngineInterface) {
897 return bookmarks_.bookmarkList(bookmarksPorts($))
898}
899async function arriveAtBookmark($: EngineInterface, record: { uuid: string; words?: string; label: string }, via: string): Promise<string | undefined> {
900 return bookmarks_.arriveAtBookmark(bookmarksPorts($), record, via)
901}
902
903// Cycle the bookmarks pane's group from the band: yours -> Claude's -> all -> yours.
904async function bandGroupStep($: EngineInterface, step: -1 | 1) {
905 await update($, bandGroup, g => nextGroup(g, step, BOOKMARK_GROUPS.length))
906 band_.keepBandWaiting(bandPorts($))
907}
908
909async function jumpToBookmarkNumber($: EngineInterface, typed: string, via: string) {
910 const picked = pickNumbered(typed, await bookmarkList($), 'bookmark')
911 if ('error' in picked) return void $.ui.toast(picked.error)
912 await arriveAtBookmark($, picked.target, via)
913 await settle($, 'bookmarks', 'jump')
914}
915
916// `d` after a number in the bookmarks list (the band's row or the pane's field): that bookmark leaves the list.
917async function removeBookmarkNumber($: EngineInterface, typed: string) {
918 const picked = pickNumbered(typed, await bookmarkList($), 'bookmark')
919 if ('error' in picked) return void $.ui.toast(picked.error)
920 await bookmarks_.removeBookmark(bookmarksPorts($), picked.target)
921}
922
923async function promoteLetter($: EngineInterface, letter: string) {
924 await bookmarks_.promoteLetter(bookmarksPorts($), letter)
925}
926
927
928// Set by the pane's render hook (which may not write state): the placement and width
929// the surface actually gave it, logged when it closes.
930let paneGeometry: string | undefined
931
932// The band cluster's close path is handlers/band.ts, over these ports.
933function bandPorts($: EngineInterface): BandPorts {
934 return {
935 band,
936 settings: currentSettings,
937 bandNum: () => read($, bandNum),
938 setBandNum: v => update($, bandNum, () => v),
939 bandMode: () => read($, bandMode),
940 setBandMode: v => update($, bandMode, () => v),
941 paneId: PANE,
942 panes: () => $.ui.panes(),
943 closePaneUi: () => $.ui.close({ id: PANE }),
944 expectRedraw,
945 note,
946 log: logTextVia($),
947 paneGeometry: () => paneGeometry,
948 paneAnchored: () => !!panePosition.anchor,
949 restoreView: () => restoreView($),
950 paneMode: () => read($, paneMode),
951 prompts: () => prompts($),
952 bookmarkList: () => bookmarkList($),
953 jumpToPromptNumber: (typed, via) => jumpToPromptNumber($, typed, via),
954 setPromptFilter: query => setPromptFilter($, query),
955 tables: currentTables,
956 listInput: bandListInput,
957 bandFieldKey: async () => band_.bandFieldKeyOf(await read($, bandFieldRev)),
958 renewBandField: async () => {
959 await update($, bandFieldRev, v => v + 1)
960 return band_.bandFieldKeyOf(await read($, bandFieldRev))
961 },
962 jumpToBookmarkNumber: (typed, via) => jumpToBookmarkNumber($, typed, via),
963 removeBookmarkNumber: typed => removeBookmarkNumber($, typed),
964 scrollPaneCentre: key => $.ui.scroll({ in: PANE, to: { key }, block: 'center' }),
965 toast: toastVia($),
966 togglePin: typed => togglePin($, typed),
967 groupStep: dir => bandGroupStep($, dir),
968 claimBookmark: uuid => bookmarks_.claimBookmark(bookmarksPorts($), uuid),
969 now: () => $.clock.now(),
970 after: (ms, fn) => $.clock.after(ms, fn),
971 focus: (requestId, key) => $.ui.focus({ requestId, key }),
972 loadMarks: () => loadMarks($),
973 letters: MARK_LETTERS,
974 readingLetter: READING_LETTER,
975 every: (ms, fn) => $.clock.every(ms, fn),
976 diagState: when => diagState($, when),
977 setPaneMode: mode => update($, paneMode, () => mode as PaneMode),
978 topOnScreen: () => topOnScreen($),
979 viewAnchor: () => viewAnchor($),
980 promptHere: () => promptHere($),
981 paneOpened: (anchor, view) => panePosition.opened(anchor, view),
982 paneView: () => panePosition.view,
983 openPane: async title =>
984 (await $.ui.open({ id: PANE, title, focus: true, closeOnEscape: true, columns: 16, rows: 4 })) as
985 { isPlaced?: boolean; reason?: string } | undefined,
986 openPaneFocused: title => $.ui.open({ id: PANE, title, focus: true, closeOnEscape: true }),
987 setBandGroup: index => update($, bandGroup, () => index),
988 scroll: scrollVia($),
989 setPendingCentre: uuid => promptsPane.centreOnNextDraw(uuid),
990 selection: () => $.ui.selection(),
991 setSelectionAtChord: sel => markState.setAtChord(sel),
992 draftText: async () => (await $.prompt.read()).text,
993 cut,
994 }
995}
996function commandLinePorts($: EngineInterface): CommandLinePorts {
997 return {
998 ...bandPorts($),
999 clearCommandLine: () => clearCommandLine($),
1000 setBandGroup: group => update($, bandGroup, () => group),
1001 jumpToMark: letter => jumpToMark($, letter),
1002 readingToggle: () => readingToggle($),
1003 promoteLetter: letter => promoteLetter($, letter),
1004 clearLetter: letter => marks_.clearLetter(marksPorts($), letter),
1005 forgetLetter: letter => marks_.forgetLetter(marksPorts($), letter),
1006 jumplistMove: dir => jumplistMove($, dir),
1007 tables: () => currentTables(),
1008 }
1009}
1010async function settle($: EngineInterface, pane: Pane, cause: Cause, needsMore = false) {
1011 return bandSettle(bandPorts($), pane, cause, needsMore)
1012}
1013
1014// An action and what it leaves behind, named once, so a render hook gathers what it draws
1015// and hands the press here rather than deciding the sequence itself (advisor row R18).
1016// A mark set from the band or the marks pane: then the after-action rule, then the view
1017// back to where the highlight found it.
1018async function markThenSettle($: EngineInterface, pane: Pane, letter: string) {
1019 await setMark($, letter)
1020 await settle($, pane, 'mark-set')
1021 await restoreView($)
1022}
1023// A jump to a mark: the marks pane also puts the view back (`restoreAfter`); the band's
1024// jump does not. The difference is the one the two had before this was named.
1025async function jumpToMarkThenSettle($: EngineInterface, pane: Pane, letter: string, restoreAfter: boolean) {
1026 await jumpToMark($, letter)
1027 await settle($, pane, 'jump')
1028 if (restoreAfter) await restoreView($)
1029}
1030// A press on a row of the prompts list (a prompt or a footnote).
1031async function pressPromptRow($: EngineInterface, uuid: string, label: string, words?: string) {
1032 await jumpTo($, uuid, 'prompts pane', label, words)
1033 await settle($, 'list', 'row-press')
1034}
1035// A press on a row of the bookmarks list.
1036async function pressBookmarkRow($: EngineInterface, record: { uuid: string; words?: string; label: string }) {
1037 await arriveAtBookmark($, record, 'bookmarks pane')
1038 await settle($, 'bookmarks', 'row-press')
1039}
1040async function endBandMode($: EngineInterface) {
1041 await bandEnd(bandPorts($))
1042}
1043
1044// The engine, as the diagnostic commands may hold it (hooks/engine/ports.ts): one closure
1045// per primitive, each spelled `$.noun.event(...)` here, where the validator follows `$`.
1046function diagnosticsPorts($: EngineInterface): DiagnosticsPorts {
1047 return {
1048 log: (line, always, text) => log($, line, always || text ? { ...(always ? { always: true } : {}), ...(text ? { text: true } : {}) } : undefined),
1049 prompts: () => prompts($),
1050 rows: () => allRows($),
1051 marks: () => loadMarks($),
1052 jumpTo: (uuid, via, label) => jumpTo($, uuid, via, label),
1053 rendered: () => drawn.texts,
1054 timeline: () => logger.timeline.items,
1055 note,
1056 selection: () => $.ui.selection(),
1057 cut,
1058 settings: () => settings.resolved(),
1059 folderBuild: !installedFromCache($.plugin.root),
1060 pluginName: $.plugin.name,
1061 configKeys: async () => (await $.config.list().catch(() => [])).map(row => row.key),
1062 claudeVersion: async () => (await $.session.version()).version,
1063 pluginVersion: () => pluginVersion($),
1064 sessionId: () => $.session.id(),
1065 dccPatcher: () => $.env.get('DCC_PATCHER'),
1066 dccPatchH: () => $.env.get('DCC_PATCH_H'),
1067 dccPatches: () => $.env.get('DCC_PATCHES'),
1068 echoState: () => log_.echoStateLine(echoPorts($)),
1069 capabilityPaths: () => pathsLine(chooseAll(capabilitySignals ?? NO_SIGNALS)),
1070 loaderStatus: () => transcript_.loaderStatus(),
1071 }
1072}
1073
1074// The capability signals (engine/select.ts, U59): the build and dcc-patcher's markers, read
1075// once at session.start; the chooser is pure over them. The variable names are literal
1076// here because the validator wants $.env.get's name at its call site.
1077let capabilitySignals: Signals | undefined
1078
1079export const register: Register = (on, options) => {
1080 settings.loaded(options)
1081
1082 // A change in /config to one of this plugin's fields: keep the values current and
1083 // redraw what reads them (settingsRev), whether or not Claude Code also reloads us.
1084 on('config.set', { key: /^bookmarks\./ }, async ($, e, next) => {
1085 const field = e.key.slice('bookmarks.'.length)
1086 // A keymap row (#36): refused before it is written when it would add a clash, a key the
1087 // band never receives, or no usable key, with the reason; the Leader row always, with
1088 // where the leader is bound (core/band/keymap.ts rowDenial).
1089 const denial = rowDenial(field, e.value, currentSettings() as unknown as Record<string, unknown>)
1090 if (denial) {
1091 log($, `[bm] keymap: ${field} not set: ${denial}`)
1092 return { deny: denial }
1093 }
1094 const result = await next(e)
1095 if (!result.deny) {
1096 settings.changed(field, result.value)
1097 // A smaller text budget frees memory and store now, not at the next prompt.
1098 if (e.key === 'bookmarks.promptTextBudget') await prompts_.savePromptTexts(promptsPorts($))
1099 // The fold: the key rows show or hide in the open menu. A change reloads the plugin on
1100 // 2.1.308, and the reload asks every row again (the fold look, 2026-10-24); the
1101 // invalidate keeps the fold working on a build that does not reload.
1102 if (FOLD_FIELDS.has(field)) {
1103 log($, `[bm] fold: ${field} set to ${JSON.stringify(result.value)}; asking /config to redraw its rows`)
1104 await $.ui.invalidate('config.describe')
1105 }
1106 if (isKeyRow(field)) {
1107 const problems = settings.keymap().problems
1108 if (problems.length) log($, keymapProblemsLine(problems))
1109 }
1110 await update($, settingsRev, v => v + 1)
1111 }
1112 return result
1113 })
1114 // Every row of the plugin behind the Bookmarks fold, the key rows behind their own fold
1115 // inside it (core/settings-fold.ts rowHidden; the fold look of 2026-10-24), and the Leader
1116 // row's help text naming the chord the person bound in keybindings.json.
1117 on('config.describe', { key: /^bookmarks\./ }, async ($, e, next) => {
1118 const r = await next(e)
1119 const field = e.key.slice('bookmarks.'.length)
1120 const values = currentSettings() as unknown as Record<string, unknown>
1121 const isHidden = rowHidden(field, values)
1122 // A fold row leads with its state's marker (▸ closed, ▾ open).
1123 const label = foldLabel(field, r.label, values)
1124 if (field !== LEADER_FIELD) return { ...r, isHidden, label }
1125 const dir = await configDir($)
1126 const path = dir ? `${dir}/keybindings.json` : undefined
1127 const text = path && (await $.fs.exists(path)) ? await $.fs.read(path).catch(() => undefined) : undefined
1128 const chord = leaderChord(typeof text === 'string' ? text : undefined)
1129 const description = chord
1130 ? `Bound to ${chord} (abovePrompt:focus in ~/.claude/keybindings.json); change it there, not here`
1131 : 'Not bound yet: bind a chord to abovePrompt:focus in ~/.claude/keybindings.json (docs/keys.md has the recipe)'
1132 return { ...r, isHidden, label, description }
1133 })
1134 // The theme decides the mark band's light or dark value (#27).
1135 on('config.set', { key: 'theme' }, async ($, e, next) => {
1136 const result = await next(e)
1137 if (!result.deny) {
1138 settings.themeIs(String(result.value))
1139 await update($, settingsRev, v => v + 1)
1140 }
1141 return result
1142 })
1143
1144 on('session.start', async ($, e, next) => {
1145 // A session start is a conversation boundary (a new conversation, /clear, /resume)
1146 // in a process whose module state outlives it; what belonged to the conversation
1147 // that ended goes back to its defaults (test-plan 2026-10-12__15-25-30, row M).
1148 // Since 0.4.67 each cluster resets its own below (startRegister, startMarks), and the
1149 // register in memory is held per conversation (0.4.65); the panes' and the band's are here.
1150 // Corrected 0.4.75 (Q261014-01): session.start runs once per process and once per fresh
1151 // load of the plugin (a reload, an enable), "never /clear", and no session.start fires
1152 // after a resume (the engine's types, 2.1.296). So a new conversation is noticed by its
1153 // id instead (sameConversation, below); these resets stay for a reload, and the
1154 // conversation the process starts in is noted.
1155 conversationId = await $.session.id()
1156 // The start event's type carries no title today (only the SessionStart hook input does); read it if a build adds it.
1157 const started = e as unknown as { session_title?: unknown }
1158 await resetConversationMemory()
1159 sessionTitle = typeof started.session_title === 'string' ? started.session_title : undefined
1160 void $.config.list().then(rows => {
1161 const theme = rows.find(r => r.key === 'theme')?.value
1162 if (typeof theme === 'string') settings.themeIs(theme)
1163 }).catch(() => {})
1164 // The command table is core/band/commands.ts.
1165 for (const [name, description] of COMMANDS) {
1166 await $.command.register({ name, description, immediate: true })
1167 }
1168
1169 // The model's tool: what it takes and how it answers is core/bookmarks/bookmark-tool.ts.
1170 try {
1171 const t = await $.tool.register(BOOKMARK_TOOL)
1172 log($, `[bm] tool registered: ${t.tool}`)
1173 } catch (err) {
1174 log($, `[bm] tool.register failed: ${String(err)}`, { always: true })
1175 }
1176 // Each cluster's own part of a conversation's start: handlers/bookmarks.ts (the
1177 // register), handlers/marks.ts (the marks and the selection poll).
1178 await bookmarks_.startRegister(bookmarksPorts($))
1179 await marks_.startMarks(marksPorts($))
1180 // Not awaited: session start should not wait on a third of a second of PowerShell.
1181 pruneThenBackfill($)
1182 startLoader($)
1183
1184 // The tracking mechanism for the borrowed actions: say so whenever the build is
1185 // not one the chords were verified on.
1186 const v = await $.session.version()
1187 capabilitySignals = {
1188 version: v.version,
1189 ...(v.base ? { base: v.base } : {}),
1190 dccPatcher: await $.env.get('DCC_PATCHER'),
1191 dccPatchH: await $.env.get('DCC_PATCH_H'),
1192 dccPatches: await $.env.get('DCC_PATCHES'),
1193 }
1194 log($, `[bm] ${pathsLine(chooseAll(capabilitySignals))}`)
1195 // A keymap value that cannot be used (set by hand in settings.json, or by an older
1196 // version): named once here; the default stands for that command.
1197 const keymapProblems = settings.keymap().problems
1198 if (keymapProblems.length) log($, keymapProblemsLine(keymapProblems))
1199 if (!VERIFIED_CLIENTS.includes(v.base ?? v.version)) {
1200 $.ui.toast(hooks/core/bookmarks/anchor.ts 317 lines1// Bookmark anchors: the durable address of a place in a conversation.
2//
3// Pure: no engine, no I/O, so it runs under `node --test` and a real debugger. The mod
4// imports it; csb or a script can too. Design: the anchors DWP of 2026-10-09
5// (`2026-10-09__06-55-30__dev-workflow-process__claude-anchors-persistent-marks-and-click-to-jump.md`).
6//
7// Identity is (sessionId, uuid). The URL names the bookmark's own export file under the
8// data root and carries the position in a QUERY string: Windows opens a `file:` URL with a
9// query on ctrl-click and refuses one with a `#` fragment, raw or encoded (measured
10// 2026-10-09). The line, bytes and words are hints that make the place quick to find and
11// easy to verify by hand; the uuid is the truth.
12//
13// file:///<dataRoot>/bookmarks/sessions/<sessionId>/<uuid8>.md?u=<uuid>&l=<line>&b=<start>-<end>&q=<words>&v=1
14
15export const ANCHOR_VERSION = 1
16
17export type AnchorBy = 'claude' | 'user' | 'prose'
18/** How a record came to be: the tool, a promotion, a hand-written link, or a letter set by the person (`mark`, 0.5.5). */
19export type AnchorSource = 'tool' | 'promote' | 'prose' | 'mark'
20/**
21 * Whose list a record is on: the person's or Claude's today, and an open set tomorrow
22 * (an agent by name, another person by handle: the "N-subscribers" of the 2026-10-16
23 * design). The two known names stay narrow so the code that knows only them still type-checks.
24 */
25export type AnchorOwner = 'user' | 'claude' | `agent:${string}` | `person:${string}`
26/**
27 * How stable and visible a record is: the continuum's rungs, cold to warm (#19, #21;
28 * core/bookmarks/tiers.ts): `transient`, a place Claude mints with metadata for one reply;
29 * `mark`, a place a letter points at (reached through the file's slots, never listed as a
30 * bookmark; 0.5.5); `perma`, a stable link Claude cites without a bookmark's `⚓`;
31 * `bookmark`, a named place in the bookmarks pane. Stored by name, never by rank. Absent on
32 * records from before 0.4.20: they are bookmarks.
33 */
34export type AnchorTier = 'transient' | 'mark' | 'perma' | 'bookmark'
35export const tierOf = (r: { tier?: AnchorTier }): AnchorTier => r.tier ?? 'bookmark'
36
37export type AnchorRecord = {
38 /** The record's number in its conversation (format v2): never reused; the short reference `bm:<sid8>.<n>`. Absent in a v1 file. */
39 n?: number
40 sessionId: string
41 uuid: string
42 /** `drawn` when the uuid is the engine's stand-in for a message (fifth group zeros), to be replaced by the real one when found. */
43 idKind?: 'drawn'
44 /** Whose list this is on. Absent on records from before 2026-10-09: read it as `by`. */
45 owner?: AnchorOwner
46 /** Set on a copy made from the other list (`share`). */
47 sharedFrom?: AnchorOwner
48 /** 1-based line of the message in the transcript, as `grep -n` counts it. */
49 line?: number
50 /** Byte offset of that line's first byte, and of the byte after its last (newline excluded). */
51 bytes?: [number, number]
52 /** The words to highlight on arrival; a verbatim piece of the message. */
53 words?: string
54 head: string
55 label: string
56 why?: string
57 temporary?: boolean
58 tier?: AnchorTier
59 createdAt: number
60 updatedAt?: number
61 by: AnchorBy
62 source: AnchorSource
63 /** The transcript path as last seen. A hint: the file moves between project folders on /cd. */
64 transcript?: string
65 role?: 'user' | 'assistant'
66 timestamp?: string
67 /** Tags, nested with `/` (`design/records`); the Markdown note's writable set includes them (unit 9). */
68 tags?: string[]
69 /** Named axes with a named position each (`{ attention: 'read' }`); the read-state layer's shape (unit 8), never a rank. */
70 axes?: Record<string, string>
71 /** Relations to other records: `{ kind, to }`, `to` a canonical reference (`bm:<sid8>.<n>`) across conversations. */
72 rel?: { kind: string; to: string }[]
73 /** Open namespaces for what an owner wants to keep on a record: `x.claude`, `x.user`, `x['agent:<name>']`, `x['plugin:<name>']`. */
74 x?: Record<string, Record<string, unknown>>
75 /** The Markdown note's bookkeeping (unit 9): `base`, the write-back fields as last written to the note; `path` when the note is not at the default. */
76 md?: { path?: string; base?: { label?: string; why?: string; tags?: string[] } }
77}
78
79export type ParsedAnchor = {
80 href: string
81 /** From the path (`.../sessions/<sessionId>/<uuid8>.md`); absent when the path is not ours. */
82 sessionId?: string
83 /** The full uuid when the link carried one, else the 8-character prefix. */
84 uuid: string
85 uuid8: string
86 line?: number
87 bytes?: [number, number]
88 words?: string
89 version?: number
90 /** True for links written before the query form (position after `#`). */
91 legacyFragment: boolean
92}
93
94export const uuid8 = (uuid: string): string => uuid.slice(0, 8).toLowerCase()
95
96/** The list a record is on; older records without `owner` belong to whoever minted them. */
97export const ownerOf = (r: Pick<AnchorRecord, 'owner' | 'by'>): AnchorOwner => r.owner ?? (r.by === 'user' ? 'user' : 'claude')
98
99const UUID_PREFIX = /^[0-9a-f]{8}(-[0-9a-f-]{1,27})?$/i
100
101/** Forward slashes, no trailing slash. */
102export function normalizeRoot(dataRoot: string): string {
103 return dataRoot.replace(/\\/g, '/').replace(/\/+$/, '')
104}
105
106/** The export file's path under the data root (forward slashes, not URL-encoded). */
107export function anchorPath(dataRoot: string, sessionId: string, uuid: string): string {
108 return `${normalizeRoot(dataRoot)}/bookmarks/sessions/${sessionId}/${uuid8(uuid)}.md`
109}
110
111/** A `file:` URL for a path: `C:/x y` -> `file:///C:/x%20y`; `/home/x` -> `file:///home/x`. */
112export function fileUrl(path: string): string {
113 const p = path.replace(/\\/g, '/')
114 const abs = p.startsWith('/') ? p : `/${p}`
115 // `encodeURI` leaves `( ) ? #` raw (so does `encodeURIComponent` for the parens): a `)`
116 // ends the markdown link early (a data root under `Program Files (x86)`), and `?` or `#`
117 // would split the path from the query (tester sweep, 2026-10-09). They are plain path
118 // characters here, so they are percent-encoded by hand.
119 return `file://${encodeURI(abs).replace(/[()?#]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`)}`
120}
121
122/** The anchor URL of a record. */
123export function anchorHref(record: Pick<AnchorRecord, 'sessionId' | 'uuid' | 'line' | 'bytes' | 'words'>, dataRoot: string): string {
124 const params = [`u=${record.uuid}`]
125 if (record.line !== undefined) params.push(`l=${record.line}`)
126 if (record.bytes) params.push(`b=${record.bytes[0]}-${record.bytes[1]}`)
127 if (record.words) params.push(`q=${encodeURIComponent(record.words)}`)
128 params.push(`v=${ANCHOR_VERSION}`)
129 return `${fileUrl(anchorPath(dataRoot, record.sessionId, record.uuid))}?${params.join('&')}`
130}
131
132/** The markdown link a reply writes for a record. */
133export function anchorMarkdown(record: AnchorRecord, dataRoot: string, label = record.label): string {
134 return `[${label.replace(/[[\]]/g, ' ')}](${anchorHref(record, dataRoot)})`
135}
136
137const PATH_RE = /\/bookmarks\/sessions\/([0-9a-f-]{36})\/([0-9a-f]{8})\.md$/i
138
139/**
140 * Reads an anchor URL. Undefined for anything that is not one: not `file:`, no `u`, a `u`
141 * that is not a uuid or a uuid prefix, or a `u` that disagrees with the filename.
142 */
143export function parseAnchor(href: string): ParsedAnchor | undefined {
144 if (!/^file:/i.test(href)) return undefined
145 const q = href.indexOf('?')
146 const hash = href.indexOf('#')
147 const cut = q >= 0 ? q : hash
148 if (cut < 0) return undefined
149 const pathPart = safeDecode(href.slice(0, cut))
150 // Parameters after `?`, and after a `#` too (the morning's legacy form, or both).
151 const tail = href.slice(cut + 1).replace(/#/g, '&')
152 let uuid: string | undefined
153 let line: number | undefined
154 let bytes: [number, number] | undefined
155 let words: string | undefined
156 let version: number | undefined
157 for (const part of tail.split('&')) {
158 if (!part) continue
159 const eq = part.indexOf('=')
160 const k = eq < 0 ? part : part.slice(0, eq)
161 const v = eq < 0 ? '' : part.slice(eq + 1)
162 switch (k) {
163 case 'u':
164 if (UUID_PREFIX.test(v)) uuid = v.toLowerCase()
165 break
166 case 'l':
167 if (/^\d+$/.test(v)) line = Number(v)
168 break
169 case 'b': {
170 const m = /^(\d+)-(\d+)$/.exec(v)
171 if (m) bytes = [Number(m[1]), Number(m[2])]
172 break
173 }
174 case 'q': {
175 const w = safeDecode(v.replace(/\+/g, ' ')).trim()
176 if (w) words = w
177 break
178 }
179 case 'v':
180 if (/^\d+$/.test(v)) version = Number(v)
181 break
182 }
183 }
184 if (!uuid) return undefined
185 const m = PATH_RE.exec(pathPart)
186 const sessionId = m?.[1]?.toLowerCase()
187 const fileUuid8 = m?.[2]?.toLowerCase()
188 if (fileUuid8 && fileUuid8 !== uuid8(uuid)) return undefined
189 return { href, sessionId, uuid, uuid8: uuid8(uuid), line, bytes, words, version, legacyFragment: q < 0 }
190}
191
192function safeDecode(s: string): string {
193 try {
194 return decodeURIComponent(s)
195 } catch {
196 return s
197 }
198}
199
200export type LinkKind = 'anchor' | 'file' | 'web' | 'other'
201
202export type MarkdownLink = {
203 kind: LinkKind
204 label: string
205 href: string
206 /** Index of `[` and of the character after `)` in the text. */
207 start: number
208 end: number
209 anchor?: ParsedAnchor
210}
211
212const LINK_RE = /\[([^\]\n]*)\]\(([^)\s]+)\)/g
213
214/**
215 * The markdown links in a text, by kind, skipping fenced and inline code. A link whose
216 * href is an anchor URL carries its parse.
217 */
218export function markdownLinks(text: string): MarkdownLink[] {
219 const out: MarkdownLink[] = []
220 let offset = 0
221 let inFence = false
222 for (const lineText of text.split('\n')) {
223 const lineStart = offset
224 offset += lineText.length + 1
225 if (/^\s*(```|~~~)/.test(lineText)) {
226 inFence = !inFence
227 continue
228 }
229 if (inFence) continue
230 for (const m of lineText.matchAll(LINK_RE)) {
231 if (insideInlineCode(lineText, m.index!)) continue
232 const label = m[1]!
233 const href = m[2]!
234 const anchor = parseAnchor(href)
235 const kind: LinkKind = anchor ? 'anchor' : /^file:/i.test(href) ? 'file' : /^https?:/i.test(href) ? 'web' : 'other'
236 out.push({ kind, label, href, start: lineStart + m.index!, end: lineStart + m.index! + m[0].length, ...(anchor ? { anchor } : {}) })
237 }
238 }
239 return out
240}
241
242function insideInlineCode(lineText: string, at: number): boolean {
243 let ticks = 0
244 for (let i = 0; i < at; i++) if (lineText[i] === '`') ticks++
245 return ticks % 2 === 1
246}
247
248export const anchorLinks = (text: string): MarkdownLink[] => markdownLinks(text).filter(l => l.kind === 'anchor')
249
250export type MarkerStyle = 'glyph' | 'text' | 'off'
251
252export const MARKERS: Record<Exclude<MarkerStyle, 'off'>, Partial<Record<LinkKind, string>>> = {
253 glyph: { anchor: '⚓ ', file: '▤ ' },
254 text: { anchor: '[bm] ', file: '[file] ' },
255}
256
257/** The label with its kind marker in front, unless the style is off or the kind unmarked. */
258export function markLabel(label: string, kind: LinkKind, style: MarkerStyle): string {
259 if (style === 'off') return label
260 const marker = MARKERS[style][kind]
261 if (!marker || label.startsWith(marker)) return label
262 return marker + label
263}
264
265/**
266 * Rewrites a text's links so each label carries its kind marker. Only the drawn text
267 * changes; hrefs are untouched (so `pressableLinks` still matches them). An anchor that
268 * `isPerma` says is a perma record keeps its plain label: the `⚓` marks bookmarks only.
269 */
270export function markLinks(text: string, style: MarkerStyle, isPerma: (href: string) => boolean = () => false): string {
271 if (style === 'off') return text
272 let out = ''
273 let last = 0
274 for (const l of markdownLinks(text)) {
275 if (l.kind === 'anchor' && isPerma(l.href)) continue
276 const marked = markLabel(l.label, l.kind, style)
277 if (marked === l.label) continue
278 out += text.slice(last, l.start) + `[${marked}](${l.href})`
279 last = l.end
280 }
281 return out + text.slice(last)
282}
283
284export type FilePosition = { path: string; line?: number; endLine?: number; column?: number }
285
286/**
287 * `path:801`, `path:801-822`, `path:801:5` (vim and VS Code spellings). A Windows drive
288 * letter (`C:\x`) is not a line.
289 */
290export function parsePosition(ref: string): FilePosition | undefined {
291 const s = ref.trim()
292 if (!s) return undefined
293 const m = /^(.+?):(\d+)(?:-(\d+)|:(\d+))?$/.exec(s)
294 if (!m) return { path: s }
295 const path = m[1]!
296 if (/^[A-Za-z]$/.test(path)) return { path: s } // `C:801` is not a position
297 const pos: FilePosition = { path, line: Number(m[2]) }
298 if (m[3]) pos.endLine = Number(m[3])
299 if (m[4]) pos.column = Number(m[4])
300 return pos
301}
302
303/** UTF-8 byte length without Node's Buffer (the mod runtime has neither Node nor DOM). */
304export function utf8ByteLength(s: string): number {
305 let n = 0
306 for (let i = 0; i < s.length; i++) {
307 const c = s.charCodeAt(i)
308 if (c < 0x80) n += 1
309 else if (c < 0x800) n += 2
310 else if (c >= 0xd800 && c <= 0xdbff) {
311 n += 4
312 i++ // the low surrogate
313 } else n += 3
314 }
315 return n
316}
317hooks/core/bookmarks/transcript-lines.ts 190 lines1// Transcript lines: turning `grep -bn` output over a session's JSONL into message rows
2// with their line number and byte range, and picking the row a fragment or uuid names.
3//
4// Pure: the shell pass that produces the grep output lives in the mod (it needs
5// `$.process.run`); everything here runs under `node --test`.
6//
7// Each transcript line is one JSON object. Only `user` and `assistant` rows that carry
8// message text count as places; `last-prompt`, `system`, meta and sidechain rows, and
9// tool results, are bookkeeping. A fragment usually matches many lines (a later message
10// quoting it, the `last-prompt` rows); the earliest real row is where it was said.
11
12import { utf8ByteLength } from './anchor.ts'
13import { forwardSlashes } from '../kit/paths.ts'
14
15export type TranscriptRow = {
16 /** 1-based line in the file, as `grep -n` counts. */
17 line: number
18 /** Byte offset of the line's first byte, and of the byte after its last (the newline). */
19 byteStart: number
20 byteEnd: number
21 uuid: string
22 role: 'user' | 'assistant'
23 text: string
24 timestamp?: string
25}
26
27export type GrepLine = { line: number; byteStart: number; json: string }
28
29/** One `grep -bn` output line: `<line>:<byteoffset>:<text>`. */
30export function parseGrepLine(s: string): GrepLine | undefined {
31 // A trailing CR is the process runner's line ending on Windows, not the file's
32 // (the transcript has none): it must not count toward the line's bytes.
33 const m = /^(\d+):(\d+):(.*?)\r?$/s.exec(s)
34 if (!m) return undefined
35 return { line: Number(m[1]), byteStart: Number(m[2]), json: m[3]! }
36}
37
38/** The text a person or the model wrote in a row; undefined for everything else. */
39export function messageTextOf(o: any): { role: 'user' | 'assistant'; text: string } | undefined {
40 if (!o || o.isMeta || o.isSidechain) return undefined
41 // A message typed while Claude was working is not a `user` row: it is an `attachment`
42 // row of type `queued_command`, drawn as a user message, with the text in `prompt`
43 // (seen 2026-10-09; the `user` rows around it hold only that turn's tool results).
44 if (o.type === 'attachment') {
45 const a = o.attachment
46 if (a?.type === 'queued_command' && typeof a.prompt === 'string' && a.prompt.trim()) return { role: 'user', text: a.prompt }
47 return undefined
48 }
49 if (o.type !== 'user' && o.type !== 'assistant') return undefined
50 const content = o.message?.content
51 if (typeof content === 'string') return content ? { role: o.type, text: content } : undefined
52 if (!Array.isArray(content)) return undefined
53 // A message typed while Claude was working is stored beside that turn's tool result,
54 // in one user row: the text blocks are the message, the tool_result blocks are not.
55 const texts = content.filter((b: any) => b?.type === 'text').map((b: any) => String(b.text ?? ''))
56 const text = texts.join('\n').trim()
57 return text ? { role: o.type, text } : undefined
58}
59
60/** A grep line as a message row, or undefined when it is not a message. */
61export function rowFromGrepLine(g: GrepLine): TranscriptRow | undefined {
62 let o: any
63 try {
64 o = JSON.parse(g.json)
65 } catch {
66 return undefined // a line cut off at the output cap
67 }
68 const m = messageTextOf(o)
69 if (!m || typeof o.uuid !== 'string') return undefined
70 return {
71 line: g.line,
72 byteStart: g.byteStart,
73 byteEnd: g.byteStart + utf8ByteLength(g.json),
74 uuid: o.uuid,
75 role: m.role,
76 text: m.text,
77 ...(typeof o.timestamp === 'string' ? { timestamp: o.timestamp } : {}),
78 }
79}
80
81/** Every message row in a grep output, in file order. */
82export function rowsFromGrep(output: string): TranscriptRow[] {
83 const rows: TranscriptRow[] = []
84 for (const s of output.split('\n')) {
85 if (!s.trim()) continue
86 const g = parseGrepLine(s)
87 const r = g && rowFromGrepLine(g)
88 if (r) rows.push(r)
89 }
90 return rows.sort((a, b) => a.line - b.line)
91}
92
93export type Resolution =
94 | { kind: 'one'; row: TranscriptRow }
95 | { kind: 'many'; rows: TranscriptRow[]; earliest: TranscriptRow }
96 | { kind: 'none' }
97
98/**
99 * The row a request names, from the rows a grep returned.
100 * - by `uuid`: the row with that uuid (a prefix of 8+ characters is accepted);
101 * - by `fragment`: rows whose text contains it, earliest first. One match is the answer;
102 * several are returned together with the earliest, so the caller can ask rather than
103 * guess (#19: never jump somewhere wrong).
104 */
105export function resolveRows(rows: TranscriptRow[], want: { uuid?: string; fragment?: string }): Resolution {
106 let hits = rows
107 if (want.uuid) {
108 const u = want.uuid.toLowerCase()
109 hits = hits.filter(r => r.uuid.toLowerCase() === u || (u.length >= 8 && r.uuid.toLowerCase().startsWith(u)))
110 }
111 if (want.fragment) {
112 const f = want.fragment
113 hits = hits.filter(r => r.text.includes(f))
114 }
115 if (hits.length === 0) return { kind: 'none' }
116 if (hits.length === 1) return { kind: 'one', row: hits[0]! }
117 return { kind: 'many', rows: hits, earliest: hits[0]! }
118}
119
120/** The grep pattern for a fragment: as JSON escapes it inside the line. */
121export function jsonEscaped(fragment: string): string {
122 return JSON.stringify(fragment).slice(1, -1)
123}
124
125/** The grep pattern for a uuid. */
126export function uuidPattern(uuid: string): string {
127 return `"uuid":"${uuid}`
128}
129
130/** What the transcript grep looks for when a request names a message: its uuid (full or prefix), else a fragment of its text as the JSON line holds it, else nothing. (register.tsx's resolveTarget chose it inline until U60.) */
131export function targetPattern(want: { uuid?: string; fragment?: string }): string | undefined {
132 return want.uuid ? uuidPattern(want.uuid) : want.fragment ? jsonEscaped(want.fragment) : undefined
133}
134
135/** A message's text as one line: runs of whitespace (newlines included) become one space. A pane row draws this and lets the terminal cut it at the pane's edge (U64). */
136export const lineOf = (text: string): string => text.replace(/\s+/g, ' ').trim()
137
138/** A short head of a message: that line, 60 characters. The fallback a row draws when no fuller text is kept. */
139export const headOf = (text: string): string => lineOf(text).slice(0, 60)
140
141/** A line fitted to `width` columns: whole when it fits, else cut with an ellipsis as its last character. A pane row is cut this way to the pane's own width (`bodyColumns`, which the engine hands the pane at draw time), so a widened pane shows more and a narrow one never wraps (U64; live, a long Button label wraps and a Text's `truncate-end` inside a Button is not honoured, 2026-10-22). */
142export const fitLine = (text: string, width: number): string => fitLines(text, width, 1)
143
144/** A line fitted to `lines` rows of `width` columns (the rowLines setting, U70). The result carries hard lines (`\n`), each at most `width` characters, so the terminal's word wrap can never add a row; continuation lines are indented by `indent` columns to sit under the text (a plain prompts row's number column, the `a: ` the engine draws before a hotkey row). A line breaks at a space when the word straddling its edge would fit on a line of its own (djdarcy, 2026-10-22: "Feel fre / e" is hard to read), and cuts the word when it would not (a long token such as a path or a slug: "if it's not so large that it's effectively never going to properly fit on any line"). The last line is cut hard with an ellipsis as its last character, so `fitLines(t, w, 1)` is the one-line cut of 0.6.10. */
145export const fitLines = (text: string, width: number, lines: number, indent = 0): string => {
146 if (width <= 0 || lines <= 0) return ''
147 const out: string[] = []
148 let rest = text
149 for (let i = 0; i < lines && rest.length > 0; i++) {
150 let line: string
151 if (rest.length <= width) {
152 line = rest
153 rest = ''
154 } else if (i === lines - 1) {
155 line = `${rest.slice(0, width - 1)}…`
156 rest = ''
157 } else if (rest[width] === ' ') {
158 // The edge falls between words: the line is whole words, the space goes.
159 line = rest.slice(0, width)
160 rest = rest.slice(width + 1).trimStart()
161 } else {
162 const space = rest.lastIndexOf(' ', width - 1)
163 const wordEnd = rest.indexOf(' ', width)
164 const wordLength = (wordEnd === -1 ? rest.length : wordEnd) - (space + 1)
165 if (space > 0 && wordLength <= width) {
166 line = rest.slice(0, space).trimEnd()
167 rest = rest.slice(space + 1).trimStart()
168 } else {
169 line = rest.slice(0, width)
170 rest = rest.slice(width)
171 }
172 }
173 out.push(i === 0 ? line : `${' '.repeat(indent)}${line}`)
174 }
175 return out.join('\n')
176}
177
178/** What a bookmark takes from the transcript row it points at: where the row is, its head, the transcript's path (forward slashes) and who wrote it. Each mint from a row (a prose link, a promoted mark, the model's tool) starts from this. */
179export function rowPlace(row: TranscriptRow, transcript: string | undefined) {
180 return {
181 uuid: row.uuid,
182 line: row.line,
183 bytes: [row.byteStart, row.byteEnd] as [number, number],
184 head: headOf(row.text),
185 transcript: transcript === undefined ? undefined : forwardSlashes(transcript),
186 role: row.role,
187 ...(row.timestamp ? { timestamp: row.timestamp } : {}),
188 }
189}
190hooks/core/log/debug.ts 88 lines1// Debug channels (#35): heavier diagnostics a person turns on by name, off by default.
2//
3// The debug log is always written. A channel adds a diagnostic that is too heavy or too
4// narrow to run for everyone: the person enables it for one conversation
5// (`/bm-debug enable screen,held`), and it is gone when the session ends. The choice
6// lives in the one variable PRIVACY.md names, `CONVO_BOOKMARKS_DEBUG`, beside the echo's
7// on/off (2026-10-09__14-17-44 DWP): `1,screen` is the echo on and the screen channel,
8// `screen` the channel alone. djdarcy, 2026-10-12: PRIVACY.md is not edited; the code
9// fits inside it. `CONVO_BOOKMARKS_DEBUG=screen claude` works from a shell too.
10
11export const CHANNELS = {
12 screen: 'every on-screen report Claude Code sends, to <session>.screen.log (heavy: rewritten every half second while the screen redraws)',
13 held: 'a log line naming the rule that kept the prompts pane\'s yellow row where it was',
14 text: 'log lines quote the conversation (the selected words, a message\'s first line, a bookmark\'s label) in this conversation, whatever the debugText setting says',
15} as const
16
17/** Whether log lines quote the conversation now: the `text` channel, or the setting (already read for this build by `debugTextMode`) and whether debugging is on. */
18export function quotesText(mode: 'off' | 'with-debug' | 'always', textChannel: boolean, debugging: boolean): boolean {
19 return textChannel || mode === 'always' || (mode === 'with-debug' && debugging)
20}
21
22/** A quoted excerpt: `reference` keeps the first `n` characters, `full` the whole text. */
23export function excerpt(text: string, n: number, length: 'reference' | 'full'): string {
24 return length === 'full' ? text : text.slice(0, n)
25}
26
27export type Channel = keyof typeof CHANNELS
28
29export const isChannel = (name: string): name is Channel => Object.prototype.hasOwnProperty.call(CHANNELS, name)
30
31/** Channel names from a comma- or space-separated list; names it does not know are returned apart, not dropped silently. */
32export function parseChannels(list: string | undefined): { known: Channel[]; unknown: string[] } {
33 const known: Channel[] = []
34 const unknown: string[] = []
35 for (const raw of (list ?? '').split(/[\s,]+/)) {
36 const name = raw.trim().toLowerCase()
37 if (!name) continue
38 if (isChannel(name)) {
39 if (!known.includes(name)) known.push(name)
40 } else if (!unknown.includes(name)) unknown.push(name)
41 }
42 return { known, unknown }
43}
44
45// The log lines the screen channel copies into its own file, so the yellow row's moves
46// line up with the reports that caused them. Matched without the `[bm] ` prefix and cut
47// to 110 characters.
48const MIRRORED = /^\[bm\] ((nearest prompt moved|redraw ignored|pane follow|held by).*)$/
49
50/** The part of a log line the screen log mirrors, or undefined for a line it does not. */
51export function screenMirror(line: string): string | undefined {
52 const m = MIRRORED.exec(line)
53 return m ? m[1]!.slice(0, 110) : undefined
54}
55
56/** Known channels in table order, comma-separated; '' when none. */
57export function formatChannels(on: Iterable<Channel>): string {
58 const set = new Set(on)
59 return (Object.keys(CHANNELS) as Channel[]).filter(c => set.has(c)).join(',')
60}
61
62const ECHO_ON = new Set(['1', 'on', 'true'])
63const ECHO_OFF = new Set(['0', 'off', 'false'])
64
65/**
66 * `CONVO_BOOKMARKS_DEBUG` read whole: the echo choice (undefined when the value makes
67 * none) and the channels. A value from before channels (`1`, `0`, `off`) reads as it did.
68 */
69export function parseDebugEnv(value: string | undefined): { echo: boolean | undefined; channels: Channel[]; unknown: string[] } {
70 let echo: boolean | undefined
71 const rest: string[] = []
72 for (const raw of (value ?? '').split(/[\s,]+/)) {
73 const t = raw.trim().toLowerCase()
74 if (!t) continue
75 if (ECHO_ON.has(t)) echo = true
76 else if (ECHO_OFF.has(t)) echo = false
77 else rest.push(t)
78 }
79 const { known, unknown } = parseChannels(rest.join(','))
80 return { echo, channels: known, unknown }
81}
82
83/** The value to store: the echo choice first (when made), then the channels; undefined when nothing is left. */
84export function formatDebugEnv(echo: boolean | undefined, channels: Iterable<Channel>): string | undefined {
85 const parts = [...(echo === undefined ? [] : [echo ? '1' : '0']), formatChannels(channels)].filter(Boolean)
86 return parts.length ? parts.join(',') : undefined
87}
88hooks/core/band/keys.ts 433 lines1// The plugin's own key router: one table from a key and a context to an operation.
2//
3// Every surface the plugin draws (the band's command field, a pane's input, a future
4// pane) and every way in (the leader, a slash command) asks this module what a key means
5// and gets an operation back; no surface holds keys of its own (djdarcy, 2026-10-11: "we
6// simply want to have our OWN router that allows us to even add our OWN UI ... so we can
7// truly route inputs however we need from our <leader><key> system"; issue #29). The
8// hints the band shows are generated from the same table, so a key cannot be listed
9// twice or left unexplained, which is what the band's placeholder `' j m p ␣` beside its
10// buttons had become.
11//
12// Pure: no engine imports. The adapter in register.tsx performs the operation.
13import { isMarkLetter } from '../marks/marks.ts'
14
15export type Pane = 'none' | 'list' | 'mark' | 'jump' | 'bookmarks'
16
17export type Operation =
18 | { op: 'open'; pane: 'list' | 'mark' | 'jump' | 'bookmarks' }
19 | { op: 'jump-mark'; letter: string }
20 | { op: 'reading' }
21 | { op: 'promote'; letter: string }
22 // The delete gesture's two verbs on a letter (the keys design, unit 5): clear it (its history kept), or forget its record.
23 | { op: 'delete'; letter: string }
24 | { op: 'forget'; letter: string }
25 | { op: 'jumplist'; dir: -1 | 1 }
26 | { op: 'digit'; digit: string }
27 | { op: 'step'; dir: -1 | 1 }
28 | { op: 'go' }
29 | { op: 'pin' }
30 | { op: 'claim' }
31 // `d` in the bookmarks list: the numbered bookmark leaves the list (a tombstone keeps its place); a bookmark's only verb.
32 | { op: 'remove' }
33 | { op: 'group'; dir: -1 | 1 }
34 | { op: 'close' }
35 | { op: 'help' }
36 | { op: 'wait' }
37 | { op: 'hint'; reason: string }
38 // Typed in a list pane's own field only (`field` keys below): the filter's prefix (#28).
39 | { op: 'filter' }
40
41// `needsMore`: the operation waits for another key (a letter after `P`, a number in a
42// list), so whatever runs after it must leave the keyboard where it is (the after-action
43// policy reads this first).
44export type Routed = { operation: Operation; needsMore: boolean }
45
46// One command of the band's command line (no pane open): its keys, what follows them,
47// how the hint and the help name it, and how the band's bar shows it. Order is the order
48// of the hint, the help and the bar.
49//
50// The bar shows a few labelled commands and `?`; `?` shows the rest (djdarcy,
51// 2026-10-12: "We should probably just have a "?" and if the user types that we can then
52// show them a help message ... for the shortcuts that aren't already on the bar").
53// `chord`: the command has a borrowed engine action a keybinding can press (the four
54// "optional fast keys"), carried only while the chords setting is on (djdarcy, 01:30:
55// kept, optional, "an easy enable/disable so their removal can be tested").
56export type Chord = 'mark' | 'jump' | 'prompts' | 'read'
57
58// Engine keybinding actions the chords borrow (docs/engine-quirks.md, "A plugin can't
59// define its own keyboard shortcut"). None should have a handler mounted while the built-in diff mod
60// is enabled; the version check in session.start is how we notice when a new build
61// might have changed that.
62// A third borrowed action (2026-10-04, user: "ctrl-x p" for the recent-prompts pane,
63// then 1-9): `ctrl+x p` in keybindings.json. The engine's own docs use it as their
64// example of a Button `action`; another diff-viewer toggle, idle in a conversation.
65// A fourth (2026-10-04, user: "Ctrl+x space" for the reading position). Scrolls the
66// diff panel's file list, so idle in a conversation like the other three. `ctrl+x x`,
67// djdarcy's first idea, is Claude Code's own chord for closing a pane.
68// The borrowed engine action each chord command's button carries while chords are on.
69// (Moved from register.tsx under /move-code, U60, 2026-10-22; the four comments as they were.)
70export const CHORD_ACTIONS: Record<Chord, string> = {
71 mark: 'app:toggleDiffNoiseFilter',
72 jump: 'app:toggleDiffPreSession',
73 prompts: 'app:cycleDiffBase',
74 read: 'app:diffFileListDown',
75}
76
77// Claude Code builds the borrowed-action chords were verified on. The start-up tripwire
78// (register.tsx) toasts on any other build, because a new build could give a borrowed
79// action a handler of its own; /bm-env names them. Add a build here after re-verifying.
80// (The one definition since 0.4.91: 0.4.45 had copied it, leaving two to keep in step.)
81export const VERIFIED_CLIENTS = ['2.1.288', '2.1.289', '2.1.290']
82
83export type LineCommand = {
84 id: string
85 keys: readonly string[]
86 then?: 'letter' | 'mark-letter' | 'number'
87 label: string
88 // The bar's button text: one word.
89 button: string
90 shown: boolean
91 chord?: Chord
92 // One line for the help: what the command does.
93 help: string
94 route: (next: string | undefined) => Routed
95}
96
97const done = (operation: Operation): Routed => ({ operation, needsMore: false })
98const waiting = (operation: Operation): Routed => ({ operation, needsMore: true })
99
100export const LINE_COMMANDS: readonly LineCommand[] = [
101 {
102 id: 'mark',
103 keys: ['m'],
104 then: 'letter',
105 label: 'mark',
106 button: 'mark',
107 shown: true,
108 chord: 'mark',
109 help: 'set a mark a-z on the line at the top of your view (or your selection)',
110 route: () => waiting({ op: 'open', pane: 'mark' }),
111 },
112 {
113 // `j` stays beside vim's `'` (djdarcy, 2026-10-12: "it should be clear that mark is
114 // m, j is jump, etc since it's already literally saying it on the bar").
115 id: 'jump',
116 keys: ["'", 'j'],
117 then: 'letter',
118 label: 'jump',
119 button: 'jump',
120 shown: true,
121 chord: 'jump',
122 help: 'jump to a mark; alone, the list of marks',
123 // Alone it opens the jump pane, whose buttons take the letter (v0.1.7's shape); a
124 // letter typed fast enough to arrive with it jumps directly.
125 route: next =>
126 next === undefined
127 ? waiting({ op: 'open', pane: 'jump' })
128 : isMarkLetter(next)
129 ? done({ op: 'jump-mark', letter: next })
130 : done({ op: 'hint', reason: lineHint() }),
131 },
132 {
133 id: 'prompts',
134 keys: ['p'],
135 then: 'number',
136 label: 'prompt',
137 button: 'prompts',
138 shown: true,
139 chord: 'prompts',
140 help: 'your prompts, numbered; a number jumps to one',
141 route: () => waiting({ op: 'open', pane: 'list' }),
142 },
143 {
144 id: 'read',
145 keys: [' ', 'r'],
146 label: 'reading',
147 button: 'read',
148 shown: true,
149 chord: 'read',
150 help: 'go to your reading position, or back to where you were',
151 route: () => done({ op: 'reading' }),
152 },
153 {
154 id: 'bookmarks',
155 keys: ['b'],
156 label: 'bookmarks',
157 button: 'bookmarks',
158 shown: false,
159 help: "the bookmarks list, yours and Claude's",
160 route: () => waiting({ op: 'open', pane: 'bookmarks' }),
161 },
162 {
163 id: 'promote',
164 keys: ['P'],
165 then: 'mark-letter',
166 label: 'promote',
167 button: 'promote',
168 shown: false,
169 help: 'turn mark a-z into a bookmark that lasts',
170 route: next =>
171 next === undefined
172 ? waiting({ op: 'wait' })
173 : isMarkLetter(next, true)
174 ? done({ op: 'promote', letter: next })
175 : done({ op: 'hint', reason: 'P then a mark letter (a-z) promotes that mark into a bookmark' }),
176 },
177 // The delete gesture (the keys design, unit 5; djdarcy 2026-10-20: d/D, no confirmation):
178 // `d` + letter clears the letter, its history kept; `D` + letter forgets its current record
179 // too. `D` is uppercase, so it is typed after the leader and has no bar key -- fitting for
180 // the destructive one. Which letter is which is the keymap's to change, like any key.
181 {
182 id: 'delete',
183 keys: ['d'],
184 then: 'mark-letter',
185 label: 'clear mark',
186 button: 'clear',
187 shown: false,
188 help: 'clear mark a-z: the letter points at nothing, its history is kept',
189 route: next =>
190 next === undefined
191 ? waiting({ op: 'wait' })
192 : isMarkLetter(next, true)
193 ? done({ op: 'delete', letter: next })
194 : done({ op: 'hint', reason: 'd then a mark letter (a-z) clears that mark; its history is kept' }),
195 },
196 {
197 id: 'forget',
198 keys: ['D'],
199 then: 'mark-letter',
200 label: 'forget mark',
201 button: 'forget',
202 shown: false,
203 help: 'forget mark a-z: its record goes too (outright when nothing else refers to it)',
204 route: next =>
205 next === undefined
206 ? waiting({ op: 'wait' })
207 : isMarkLetter(next, true)
208 ? done({ op: 'forget', letter: next })
209 : done({ op: 'hint', reason: 'D then a mark letter (a-z) forgets that mark and its record' }),
210 },
211 { id: 'back', keys: ['o'], label: 'back', button: 'back', shown: false, help: 'back to where the last jump left from', route: () => done({ op: 'jumplist', dir: -1 }) },
212 { id: 'forward', keys: ['i'], label: 'forward', button: 'forward', shown: false, help: 'forward again', route: () => done({ op: 'jumplist', dir: 1 }) },
213 // `q` quits a view, as in Neovim's and Emacs's non-editing buffers: needed once a list
214 // can stay open after a jump (djdarcy, 2026-10-12, Q261012-09: "<leader> q, and q in a
215 // list").
216 { id: 'close', keys: ['q'], label: 'close', button: 'close', shown: false, help: "close the plugin's pane and end what the band is doing", route: () => done({ op: 'close' }) },
217 { id: 'help', keys: ['?'], label: 'help', button: '?', shown: true, help: 'this help', route: () => done({ op: 'help' }) },
218]
219
220// What a key shows as in a hint: Space has no glyph of its own.
221const keyName = (k: string) => (k === ' ' ? 'Space' : k)
222
223// The command line's hint, generated from the table: every key once, with what follows.
224// Every reader below takes the tables it reads (`DEFAULT_TABLES` unless a keymap, #36,
225// supplied others through core/band/keymap.ts), so the band, the panes and the help agree
226// on whatever keys the person chose.
227export function lineHint(tables: Tables = DEFAULT_TABLES): string {
228 const parts = tables.line.map(c => {
229 const keys = c.keys.map(keyName).join(' or ')
230 const then = c.then === 'letter' || c.then === 'mark-letter' ? ' + letter' : c.then === 'number' ? ' + number' : ''
231 return `${keys}${then} (${c.label})`
232 })
233 return `bm: ${parts.join(' ')}`
234}
235
236// A list pane's keys (the prompts and bookmarks lists), in the order of their hint.
237// `button`: how the band's number row draws it (the band-mode row is generated from this
238// table too, so it cannot offer a key the hint does not name). `field`: a key typed only
239// in the pane's own `#` field, as the prefix of what follows -- the filter's `/` (#28,
240// djdarcy 2026-10-12: "Pane field only") and the pin's `*` -- never on the band's number
241// row and never in the hint (the field's placeholder says them); it is in the table so a
242// keymap (#36) reaches it like any other key (the keys design, 2026-10-20, unit 1).
243export type ListKey = { key: string; label: string; button: string; panes: readonly Pane[]; field?: true; route: () => Routed }
244export const LIST_KEYS: readonly ListKey[] = [
245 { key: 'j', label: 'next', button: 'j↓', panes: ['list', 'bookmarks'], route: () => waiting({ op: 'step', dir: 1 }) },
246 { key: 'k', label: 'previous', button: 'k↑', panes: ['list', 'bookmarks'], route: () => waiting({ op: 'step', dir: -1 }) },
247 { key: 's', label: 'pin', button: 's★ pin', panes: ['list'], route: () => waiting({ op: 'pin' }) },
248 { key: 'h', label: 'previous group', button: 'h◂', panes: ['bookmarks'], route: () => waiting({ op: 'group', dir: -1 }) },
249 { key: 'l', label: 'next group', button: '▸l', panes: ['bookmarks'], route: () => waiting({ op: 'group', dir: 1 }) },
250 { key: 'c', label: 'claim', button: 'c claim', panes: ['bookmarks'], route: () => waiting({ op: 'claim' }) },
251 // The numbered bookmark leaves the list (the keys design, unit 5): typed after its number in the band's row or the pane's field.
252 { key: 'd', label: 'remove', button: 'd remove', panes: ['bookmarks'], route: () => waiting({ op: 'remove' }) },
253 { key: 'q', label: 'close', button: 'q close', panes: ['list', 'bookmarks'], route: () => done({ op: 'close' }) },
254 { key: '/', label: 'filter', button: '/ filter', panes: ['list'], field: true, route: () => waiting({ op: 'filter' }) },
255 { key: '*', label: 'pin prefix', button: '* pin', panes: ['list'], field: true, route: () => waiting({ op: 'pin' }) },
256]
257// The two tables every reader works from. The defaults are the tables above; a keymap
258// (core/band/keymap.ts) derives another pair from them, and a caller that has one passes
259// it to each reader.
260export type Tables = { line: readonly LineCommand[]; list: readonly ListKey[] }
261export const DEFAULT_TABLES: Tables = { line: LINE_COMMANDS, list: LIST_KEYS }
262
263// The bar's hotkey for a command: the first of its keys the engine takes as a Button
264// hotkey -- one digit or one lowercase letter ("anything else is refused", and Shift+w is
265// "w": plugin/.claude-plugin/types/claude-code/index.d.ts, Button.hotkey). `'`, Space,
266// `?` and an uppercase key are typed in the field; their buttons are click-only.
267export function barHotkey(keys: readonly string[]): string | undefined {
268 return keys.find(k => /^[a-z0-9]$/.test(k))
269}
270
271// A pane's list keys, as the band draws them: the field-only keys are not among them.
272export function listKeysFor(pane: Pane, tables: Tables = DEFAULT_TABLES): readonly ListKey[] {
273 return tables.list.filter(l => l.panes.includes(pane) && !l.field)
274}
275// A pane's field-only keys: the prefixes its `#` field reads.
276export function fieldKeysFor(pane: Pane, tables: Tables = DEFAULT_TABLES): readonly ListKey[] {
277 return tables.list.filter(l => l.panes.includes(pane) && l.field === true)
278}
279// What follows a field key in the pane's `#` field, when `typed` starts with the key that
280// routes to `op` (`/words` -> `words`; `*21` -> `21`), else undefined.
281export function fieldRest(typed: string, pane: Pane, op: 'filter' | 'pin', tables: Tables = DEFAULT_TABLES): string | undefined {
282 const k = fieldKeysFor(pane, tables).find(l => l.route().operation.op === op)
283 return k && typed.startsWith(k.key) ? typed.slice(k.key.length) : undefined
284}
285
286// Route what was typed in a context. `typed` is the whole command line for the band with
287// no pane (a command and maybe its argument), or a single key in a list pane.
288export function route(typed: string, ctx: { pane: Pane }, tables: Tables = DEFAULT_TABLES): Routed {
289 if (typed === '') return waiting({ op: 'wait' })
290 if (typed === '\u001b' || typed === 'Escape') return done({ op: 'close' })
291 if (ctx.pane === 'list' || ctx.pane === 'bookmarks') {
292 if (/^[0-9]$/.test(typed)) return waiting({ op: 'digit', digit: typed })
293 if (typed === '\r' || typed === 'Enter') return done({ op: 'go' })
294 const k = tables.list.find(l => l.key === typed && l.panes.includes(ctx.pane))
295 if (k) return k.route()
296 return waiting({ op: 'hint', reason: listHint(ctx.pane, tables) })
297 }
298 const first = typed[0]!
299 const cmd = tables.line.find(c => c.keys.includes(first))
300 if (!cmd) return done({ op: 'hint', reason: lineHint(tables) })
301 return cmd.route(typed.length > 1 ? typed[1] : undefined)
302}
303
304// A list pane's hint, generated from LIST_KEYS for that pane.
305// What a number typed into a list means (#33): `3` the prompt, `3.` unfold #3's
306// footnotes, `3.1` its first footnote; `0.1` a footnote before the first prompt.
307export type ListNumber = { n: number; k?: number; unfold?: true }
308export function parseListNumber(typed: string): ListNumber | undefined {
309 const m = /^(\d+)(?:\.(\d*))?$/.exec(typed.trim())
310 if (!m) return undefined
311 const n = Number(m[1])
312 if (m[2] === undefined) return { n }
313 if (m[2] === '') return { n, unfold: true }
314 return { n, k: Number(m[2]) }
315}
316
317export function listHint(pane: Pane, tables: Tables = DEFAULT_TABLES): string {
318 const keys = listKeysFor(pane, tables).map(l => `${l.key} ${l.label}`)
319 return ['number + Enter jump', ...keys, 'Esc close'].join(' · ')
320}
321
322// Every key the command line routes, for tests and for a surface that draws one button
323// per command.
324export function lineKeys(tables: Tables = DEFAULT_TABLES): string[] {
325 return tables.line.flatMap(c => [...c.keys])
326}
327
328// The band's bar: one button per shown command, in table order. Its key is the command's
329// key a press stands for (`route(key)`); `hotkey` only where the engine takes one (a
330// letter or digit: not `'`, Space or `?`, which are typed in the field); `chord` only
331// while chords are on. The field beside the buttons has no placeholder: the buttons say
332// what the keys are, and `?` says the rest (it replaced `' m ␣ p b P o i`, which named
333// keys without saying what they did).
334export type BandButton = { id: string; key: string; label: string; hotkey?: string; chord?: Chord }
335/** The help the band draws: the full lines when they fit the band's window (one line per command plus one), else the short form. The band must fit its window: taller, it scrolls, and the keyboard probe (showHelp) focuses `close`, which scrolls it back to the top (log 2026-10-12 18:02-18:09). (The band render hook's rule, moved here under U60.) */
336export function helpFor(now: { leader: string; chords: boolean; panes: boolean }, maxRows: number, tables: Tables = DEFAULT_TABLES): string[] {
337 const full = helpLines(now, tables)
338 return full.length + 1 <= maxRows ? full : helpShort(now, tables)
339}
340
341/** The bar's buttons as the band draws them: none with the field-only band; else each command's button with its hotkey and, while chords are on, the borrowed engine action its chord presses. */
342export function barFor(settings: { band: 'full' | 'field'; chords: 'on' | 'off' }, actions: Record<Chord, string>, tables: Tables = DEFAULT_TABLES): { id: string; label: string; key: string; hotkey?: string; action?: string }[] {
343 return settings.band === 'full'
344 ? bandButtons({ chords: settings.chords === 'on' }, tables).map(b => ({ id: b.id, label: b.label, key: b.key, ...(b.hotkey ? { hotkey: b.hotkey } : {}), ...(b.chord ? { action: actions[b.chord] } : {}) }))
345 : []
346}
347
348/** Where a focus move in the band lands, and what it means (the AbovePrompt ui.focus hook's two rules, moved here under U60; the hook reads the state and acts). */
349export type BandFocus = { element: string | undefined; step?: -1 | 1; kept?: true; /** The step came off the band's field: the hook renews the field and keeps the ring there. */ field?: true }
350export function bandFocusRoute(f: {
351 byPerson: boolean
352 ring: string | undefined
353 mode: string
354 element: string | undefined
355 cmdRev: number
356 /** The step buttons' keys beside the band's field (`band-num-<key>`), from the person's keymap; k and j by default. */
357 stepKeys?: { prev: string; next: string }
358}): BandFocus {
359 // While the band is idle, the person's focus moves stay on the command field. After
360 // a command the band keeps the keyboard (a plugin can't hand it back; Esc does), so
361 // a second Ctrl+] moved the ring onto the `mark` button, Space pressed it, and Enter
362 // marked `a` (djdarcy, 2026-10-07; log 08:10:23). Clicks and chords still press the
363 // buttons; only the ring is kept on the field.
364 // The arrows in the band's prompt mode: they move the ring (they can't be hotkeys),
365 // so a move off `go` onto its neighbour is read as a step through the pane's list,
366 // k (previous: Up, Left, Shift+Tab) or j (next: Down, Right, Tab), and the ring
367 // stays on `go` for Enter (djdarcy, 2026-10-07: "we'd of course also want to add
368 // <up> <down> if possible").
369 if (f.byPerson && f.ring === 'band-num-go' && f.mode === 'list' && (f.element === 'band-num-k' || f.element === 'band-num-j')) {
370 return { element: 'band-num-go', step: f.element === 'band-num-k' ? -1 : 1 }
371 }
372 // The same on the band's own field (input routing, 2026-10-25, unit 3b): the step buttons
373 // sit either side of it, so a move off the field (Tab, Shift+Tab, or Up/Down with the
374 // AbovePromptInput binding in docs/keys.md) lands on one, steps the list, and the ring
375 // stays on the field for the next key. Both lists step here.
376 const steps = f.stepKeys ?? { prev: 'band-num-k', next: 'band-num-j' }
377 // The field is drawn as `band-num-field-<n>` (handlers/band.ts renewField); the hook draws
378 // a fresh one after the step, so `element` here is where the ring was.
379 if (f.byPerson && f.ring?.startsWith('band-num-field') && (f.mode === 'list' || f.mode === 'bookmarks') && (f.element === steps.prev || f.element === steps.next)) {
380 return { element: f.ring, step: f.element === steps.prev ? -1 : 1, field: true }
381 }
382 if (f.byPerson && f.element?.startsWith('chord-') && f.mode === 'idle') {
383 return { element: `band-cmd-${f.cmdRev}`, kept: true }
384 }
385 return { element: f.element }
386}
387
388export function bandButtons(opts: { chords: boolean }, tables: Tables = DEFAULT_TABLES): BandButton[] {
389 return tables.line.filter(c => c.shown).map(c => {
390 const hotkey = barHotkey(c.keys)
391 return {
392 id: c.id,
393 key: c.keys[0]!,
394 label: c.button,
395 ...(hotkey ? { hotkey } : {}),
396 ...(opts.chords && c.chord ? { chord: c.chord } : {}),
397 }
398 })
399}
400
401// The help `?` shows: every command with its keys and what it does, the list keys, and
402// the switches as they are now. One string per line.
403export function helpLines(now: { leader: string; chords: boolean; panes: boolean }, tables: Tables = DEFAULT_TABLES): string[] {
404 const keysOf = (c: LineCommand) => {
405 const then = c.then === 'letter' || c.then === 'mark-letter' ? ' + letter' : c.then === 'number' ? ' + number' : ''
406 return `${c.keys.map(keyName).join(' or ')}${then}`
407 }
408 const width = Math.max(...tables.line.map(c => keysOf(c).length))
409 const filterKey = fieldKeysFor('list', tables).find(k => k.route().operation.op === 'filter')?.key ?? '/'
410 return [
411 `${now.leader}, then:`,
412 ...tables.line.map(c => ` ${keysOf(c).padEnd(width)} ${c.help}`),
413 'In the prompts list:',
414 ` ${listHint('list', tables)}; type ${filterKey}words in its # field to filter, N.k for a footnote`,
415 'In the bookmarks list:',
416 ` ${listHint('bookmarks', tables)}`,
417 `Chords (mark, jump, prompts, read on their own keybindings): ${now.chords ? 'on' : 'off'}. Lists in a pane: ${now.panes ? 'on' : 'off'}. Both in /config.`,
418 ]
419}
420
421// The same help in four lines, for a band too short for one line per command: each line
422// wraps to the band's width instead of adding rows the band would have to scroll.
423export function helpShort(now: { leader: string; chords: boolean; panes: boolean }, tables: Tables = DEFAULT_TABLES): string[] {
424 const full = helpLines(now, tables)
425 const filterKey = fieldKeysFor('list', tables).find(k => k.route().operation.op === 'filter')?.key ?? '/'
426 return [
427 `${now.leader}, then: ${lineHint(tables).replace(/^bm: /, '').split(' ').join(' · ')}`,
428 `Prompts list: ${listHint('list', tables)}; ${filterKey}words in its # field filters, N.k is a footnote`,
429 `Bookmarks list: ${listHint('bookmarks', tables)}`,
430 full.at(-1)!,
431 ]
432}
433hooks/core/band/after-action.ts 91 lines1// What happens after an action: does the pane close, does the band's mode end, and
2// where should the keyboard go. One pure decision in place of the choices made at each
3// call site (eleven places closed a pane on their own terms; issue #29, the refactor
4// advisor's row 5).
5//
6// The order of precedence is djdarcy's (2026-10-11): "each tool should dictate the
7// behavior with a 'lean' towards user preference". So: first the operation's own need
8// (one still waiting for a letter or a number keeps the band and the keyboard where they
9// are); then the person's settings; then the defaults below, which reproduce the
10// plugin's behaviour before this module except where djdarcy asked otherwise:
11// - typing in the input box, or clicking it, ends the band's mode but leaves a list
12// open (0.4.0 did this for the click; the typing case is the same request);
13// - after a completed action the keyboard returns to the input box (#24, widened from
14// `o`/`i` to every action). The engine cannot yet hand the keyboard back (see
15// docs/engine-quirks.md, "A plugin can't hand the keyboard back to the input box"), so
16// `focus: 'input'` is what is wanted; the adapter does what the engine allows, which
17// today is nothing (the person presses Esc).
18
19import type { Pane } from './keys.ts'
20
21export type Cause =
22 | 'jump' // a jump made from the band or a list (a mark, a prompt, a bookmark)
23 | 'row-press' // a list row clicked
24 | 'mark-set' // a mark placed from the mark pane
25 | 'pin' // a prompt pinned or unpinned in the list
26 | 'band-command' // any other completed band command (reading position, jumplist, promote)
27 | 'prompt-edit' // the person typed in the input box
28 | 'focus-left' // the keyboard left the band and the pane (a click in the input box)
29 | 'esc' // Esc
30 | 'timer' // the plugin closed the pane itself (the band lost the keyboard, a timeout)
31
32// `view`: after a pane closes, whether the conversation goes back to where it was before
33// the pane opened (#29, 2026-10-11). `return` now; `leave` when the action moved the view
34// on purpose (a jump) or nothing closed; `defer` when the close was the plugin's own and
35// Claude Code would refuse the scroll ("not person-initiated"), so the return waits for
36// the person's next key or scroll.
37export type Outcome = {
38 pane: 'close' | 'stay'
39 band: 'end' | 'keep'
40 focus: 'input' | 'band' | 'pane'
41 view: 'return' | 'leave' | 'defer'
42}
43
44export type AfterActionSettings = {
45 paneAfterJump: 'close' | 'stay'
46 paneWhileTyping: 'close' | 'stay'
47 afterActionFocus: 'input' | 'band'
48}
49
50/** The two list-shaped panes (prompts and bookmarks), which share the band's number entry (digits, j/k, Enter). */
51export const isList = (pane: Pane | 'idle') => pane === 'list' || pane === 'bookmarks'
52
53export function afterAction(input: { pane: Pane; cause: Cause; needsMore?: boolean; settings: AfterActionSettings }): Outcome {
54 const { pane, cause, needsMore, settings } = input
55 // 1. The operation still needs a key: nothing moves.
56 if (needsMore && cause !== 'esc' && cause !== 'prompt-edit' && cause !== 'focus-left' && cause !== 'timer') {
57 return { pane: 'stay', band: 'keep', focus: pane === 'none' ? 'band' : 'pane', view: 'leave' }
58 }
59 const back = settings.afterActionFocus
60 // 2. What the pane, band and keyboard do, then whether the view goes back: only when the
61 // pane closed and the action did not itself move the view.
62 const base = ((): Omit<Outcome, 'view'> & { moved: boolean } => {
63 switch (cause) {
64 case 'esc':
65 case 'timer':
66 return { pane: 'close', band: 'end', focus: 'input', moved: false }
67 case 'prompt-edit':
68 case 'focus-left':
69 // The person is already in the input box. A list may stay open beside it; the mark
70 // and jump panes are waiting for a letter the person has stopped typing.
71 return { pane: isList(pane) && settings.paneWhileTyping === 'stay' ? 'stay' : 'close', band: 'end', focus: 'input', moved: false }
72 case 'pin':
73 // Pinning is part of browsing the list: stay in it.
74 return { pane: 'stay', band: 'keep', focus: pane === 'none' ? 'band' : 'pane', moved: false }
75 case 'jump':
76 case 'row-press': {
77 const stay = isList(pane) && settings.paneAfterJump === 'stay'
78 return { pane: stay ? 'stay' : 'close', band: 'end', focus: back, moved: true }
79 }
80 case 'band-command':
81 // The reading position and back/forward move the view on purpose.
82 return { pane: 'close', band: 'end', focus: back, moved: true }
83 case 'mark-set':
84 // Setting a mark highlights in place; the view should come back to where it was.
85 return { pane: 'close', band: 'end', focus: back, moved: false }
86 }
87 })()
88 const view: Outcome['view'] = base.pane === 'stay' || base.moved ? 'leave' : cause === 'timer' ? 'defer' : 'return'
89 return { pane: base.pane, band: base.band, focus: base.focus, view }
90}
91hooks/core/band/keymap.ts 224 lines1// The keymap: the person's own keys over the key table (#36, "as versatile as .vimrc";
2// the keys design, 2026-10-20, unit 2). Pure: no engine imports, no state. A keymap is
3// read from wherever it is kept (unit 3 decides: /config rows, or a file) as one value
4// per command, parsed here, and applied to the default tables to make the pair every
5// reader of core/band/keys.ts takes. Nothing it cannot use is silently dropped: each
6// problem is named, and the default stands for that command, so a bad keymap can never
7// leave a command unreachable.
8//
9// A command's value: its keys separated by spaces, in the order the hint and the help
10// name them; `Space` spells the space; `hidden` as the last word takes the command's
11// button off the bar; an empty value is the default. Examples: `m`, `' j`, `Space r`,
12// `P hidden`, `q hidden`. The list keys are one value, `list`, in the table's own order:
13// `j k s h l c q` (the field-only keys, `/` and `*`, are not renamed here).
14import { DEFAULT_TABLES, lineHint, type LineCommand, type ListKey, type Tables } from './keys.ts'
15
16export { barHotkey } from './keys.ts'
17
18/** One value per command id, plus `list` for the list keys. */
19export type Keymap = { readonly [commandId: string]: string | undefined }
20
21/** Why a value, or part of it, was not applied; the default stands for that command. */
22export type Problem = { command: string; key?: string; reason: string }
23
24export const LIST_ROW = 'list'
25export const HIDDEN_WORD = 'hidden'
26/** Words that spell a key the field cannot show as itself. */
27export const KEY_WORDS: Readonly<Record<string, string>> = { Space: ' ', space: ' ' }
28/** Names of keys the band never receives on a stock build (docs/engine-quirks.md). */
29const UNUSABLE_NAMES = new Set(['Up', 'Down', 'Left', 'Right', 'Tab', 'Enter', 'Esc', 'Escape', 'Backspace'])
30
31/** The rows as read, trimmed; empty values dropped. */
32export function parseKeymap(rows: Readonly<Record<string, string | undefined>>): { keymap: Keymap; problems: Problem[] } {
33 const keymap: Record<string, string> = {}
34 for (const [command, value] of Object.entries(rows)) {
35 const v = (value ?? '').trim()
36 if (v) keymap[command] = v
37 }
38 return { keymap, problems: [] }
39}
40
41/** One word of a value as a key, or the reason it is not one. */
42function keyOf(word: string): { key: string } | { reason: string } {
43 const key = KEY_WORDS[word] ?? word
44 if (UNUSABLE_NAMES.has(word)) return { reason: `${word} never reaches the band on a stock build` }
45 if ([...key].length !== 1) return { reason: `"${word}" is not one key` }
46 return { key }
47}
48
49/**
50 * The tables a keymap makes from the defaults. A command the keymap names gets its keys
51 * and its `shown`; a command it does not name keeps the default. Clashes are judged per
52 * context (the command line; each list pane): a key two commands claim goes to the first
53 * in table order and the second keeps its default, with the problem named. A key may be a
54 * line key and a list key at once (`j` is jump on the line and next in a list).
55 */
56export function applyKeymap(keymap: Keymap, base: Tables = DEFAULT_TABLES): { tables: Tables; problems: Problem[] } {
57 const problems: Problem[] = []
58 const known = new Set<string>([...base.line.map(c => c.id), LIST_ROW])
59 for (const command of Object.keys(keymap)) {
60 if (!known.has(command)) problems.push({ command, reason: 'not a command of this version' })
61 }
62
63 // The command line. A command's own `route` may answer a hint naming the line's keys
64 // (jump does, for a bad letter); it is rewritten to name the keymap's keys, so the hint
65 // never shows a key the person changed away. `result` is assigned below, before any
66 // route can run.
67 let result: Tables = base
68 const taken = new Map<string, string>()
69 const line: LineCommand[] = base.line.map(c => {
70 const value = keymap[c.id]
71 let keys: string[] = [...c.keys]
72 let shown = c.shown
73 if (value !== undefined) {
74 const words = value.split(/\s+/).filter(Boolean)
75 shown = true
76 if (words.at(-1) === HIDDEN_WORD) {
77 shown = false
78 words.pop()
79 }
80 const chosen: string[] = []
81 for (const w of words) {
82 const k = keyOf(w)
83 if ('reason' in k) problems.push({ command: c.id, key: w, reason: k.reason })
84 else if (!chosen.includes(k.key)) chosen.push(k.key)
85 }
86 if (chosen.length > 0) keys = chosen
87 else if (words.length > 0) problems.push({ command: c.id, reason: 'no usable key; the default is kept' })
88 }
89 const kept = keys.filter(k => {
90 const by = taken.get(k)
91 if (by !== undefined && by !== c.id) {
92 problems.push({ command: c.id, key: k, reason: `already ${by}` })
93 return false
94 }
95 return true
96 })
97 const finalKeys = kept.length > 0 ? kept : [...c.keys].filter(k => !taken.has(k) || taken.get(k) === c.id)
98 if (kept.length === 0 && finalKeys.length === 0) problems.push({ command: c.id, reason: 'every key is taken; the command has no key' })
99 for (const k of finalKeys) taken.set(k, c.id)
100 const route: LineCommand['route'] = next => {
101 const r = c.route(next)
102 return r.operation.op === 'hint' && r.operation.reason === lineHint(base) ? { ...r, operation: { op: 'hint', reason: lineHint(result) } } : r
103 }
104 return { ...c, keys: finalKeys, shown, route }
105 })
106
107 // The list keys, renamed by position in table order; the field-only keys stay.
108 const listValue = keymap[LIST_ROW]
109 const renamable = base.list.filter(l => !l.field)
110 const names: (string | undefined)[] = []
111 if (listValue !== undefined) {
112 const words = listValue.split(/\s+/).filter(Boolean)
113 if (words.length > renamable.length) problems.push({ command: LIST_ROW, reason: `${words.length} keys for ${renamable.length} list commands; the extra are ignored` })
114 words.slice(0, renamable.length).forEach((w, i) => {
115 const k = keyOf(w)
116 if ('reason' in k) problems.push({ command: LIST_ROW, key: w, reason: k.reason })
117 else if (/^[0-9]$/.test(k.key)) problems.push({ command: LIST_ROW, key: w, reason: 'a digit is a number in a list' })
118 else names[i] = k.key
119 })
120 }
121 let i = 0
122 const listTaken = new Map<string, string>() // `${pane}:${key}` -> label; the field prefixes count as taken
123 for (const f of base.list.filter(l => l.field)) for (const p of f.panes) listTaken.set(`${p}:${f.key}`, `the ${f.label} prefix`)
124 const list: ListKey[] = base.list.map(l => {
125 if (l.field) return l
126 const wanted = names[i++]
127 const key = wanted ?? l.key
128 const clash = l.panes.find(p => listTaken.has(`${p}:${key}`))
129 const finalKey = clash ? l.key : key
130 if (clash) problems.push({ command: LIST_ROW, key, reason: `already ${listTaken.get(`${clash}:${key}`)} in the ${clash} list; ${l.label} keeps ${l.key}` })
131 for (const p of l.panes) listTaken.set(`${p}:${finalKey}`, l.label)
132 return finalKey === l.key ? l : { ...l, key: finalKey, button: l.button.replace(l.key, finalKey) }
133 })
134
135 result = { line, list }
136 return { tables: result, problems }
137}
138
139// The keymap's /config rows (the keys design, 2026-10-20, unit 3). djdarcy's fold look of
140// 2026-10-24 chose rows behind a fold: one row per band command and one for the list keys,
141// shown only while the fold row says so, and a Leader row that says where the leader is
142// bound. Each field name is a /config key (core/settings.ts FIELDS has the same names; a
143// core test holds the two together). A row's value is the command's value above; an empty
144// row is the table's own keys.
145export const KEY_FIELDS: Readonly<Record<string, string>> = {
146 mark: 'keyMark',
147 jump: 'keyJump',
148 prompts: 'keyPrompts',
149 read: 'keyRead',
150 bookmarks: 'keyBookmarks',
151 promote: 'keyPromote',
152 delete: 'keyDelete',
153 forget: 'keyForget',
154 back: 'keyBack',
155 forward: 'keyForward',
156 close: 'keyClose',
157 help: 'keyHelp',
158}
159export const LIST_FIELD = 'keyList'
160export const LEADER_FIELD = 'keyLeader'
161export const KEYS_SHOWN_FIELD = 'keysShown'
162const ROW_COMMAND = new Map<string, string>([...Object.entries(KEY_FIELDS).map(([id, field]) => [field, id] as [string, string]), [LIST_FIELD, LIST_ROW]])
163
164/** A row the fold hides: every key row and the Leader row, never the fold itself. */
165export const isKeyRow = (field: string): boolean => ROW_COMMAND.has(field) || field === LEADER_FIELD
166
167/** The keymap the rows hold: a command row by its command's id, the list row as `list`; empty rows left out. */
168export function keymapOf(values: Readonly<Record<string, unknown>>): Keymap {
169 const keymap: Record<string, string> = {}
170 for (const [field, command] of ROW_COMMAND) {
171 const v = values[field]
172 if (typeof v === 'string' && v.trim()) keymap[command] = v.trim()
173 }
174 return keymap
175}
176
177/** Why the leader is not a row the plugin sets: it is Claude Code's own keybinding. */
178export const LEADER_RECIPE =
179 'The leader is a Claude Code keybinding, not a plugin setting: in ~/.claude/keybindings.json bind your chord to "abovePrompt:focus" in the Chat context, then start a new session (docs/keys.md has the recipe).'
180
181const keyLabel = (k: string) => (k === ' ' ? 'Space' : k)
182function problemText(p: Problem, row: string): string {
183 if (p.key !== undefined && p.reason.startsWith('already ')) {
184 const owner = p.command === row ? p.reason.slice('already '.length) : p.command
185 return `${keyLabel(p.key)} is already ${owner}'s key`
186 }
187 return `${p.command}${p.key !== undefined ? ` ${keyLabel(p.key)}` : ''}: ${p.reason}`
188}
189
190/**
191 * Why a change to a key row is refused, or undefined when it may be made. A change is refused
192 * only for the problems it adds (a clash, an unusable key, no usable key); one the keymap
193 * already had is not this change's to answer for. The Leader row is always refused, with the
194 * recipe.
195 */
196export function rowDenial(field: string, value: unknown, values: Readonly<Record<string, unknown>>): string | undefined {
197 if (field === LEADER_FIELD) return LEADER_RECIPE
198 const command = ROW_COMMAND.get(field)
199 if (command === undefined) return undefined
200 const before = applyKeymap(keymapOf(values)).problems.map(p => problemText(p, command))
201 const after = applyKeymap(keymapOf({ ...values, [field]: value })).problems.map(p => problemText(p, command))
202 const added = after.filter(p => !before.includes(p))
203 return added.length > 0 ? `Not set: ${added.join('; ')}. The keys stay as they were.` : undefined
204}
205
206/** The chord bound to `abovePrompt:focus` in keybindings.json's text, or undefined. */
207export function leaderChord(json: string | undefined): string | undefined {
208 if (!json) return undefined
209 let parsed: unknown
210 try {
211 parsed = JSON.parse(json)
212 } catch {
213 return undefined
214 }
215 const blocks = (parsed as { bindings?: unknown })?.bindings
216 if (!Array.isArray(blocks)) return undefined
217 for (const b of blocks) {
218 const map = (b as { bindings?: unknown })?.bindings
219 if (!map || typeof map !== 'object') continue
220 for (const [chord, action] of Object.entries(map as Record<string, unknown>)) if (action === 'abovePrompt:focus') return chord
221 }
222 return undefined
223}
224hooks/core/settings-fold.ts 39 lines1// Which of the plugin's /config rows the menu leaves out, and how a fold row is labelled
2// (djdarcy, 2026-10-24: "I think for now every option should be hidden by default as I really
3// don't think users are going to want to mess with anything"; the main fold "should
4// absolutely be called 'Bookmarks'"; a fold for the debug options, each leading "Debug:"; and
5// "some sort of leading indicator to show something is a fold group"). Pure: the
6// config.describe hook in register.tsx asks it for every `bookmarks.*` row.
7//
8// Three folds. The Bookmarks fold (`settingsShown`) hides every other row of the plugin;
9// open, it shows the settings and two folds of its own, the keys (`keysShown`) and the
10// debugging rows (`debugShown`), whose rows stay hidden until each is opened too. A hidden
11// row still holds and applies its value, and `/config bookmarks.<field>=<value>` still sets it.
12import { KEYS_SHOWN_FIELD, isKeyRow } from './band/keymap.ts'
13import { FOLD_CLOSED, FOLD_OPEN } from './settings.ts'
14
15export const SETTINGS_SHOWN_FIELD = 'settingsShown'
16export const DEBUG_SHOWN_FIELD = 'debugShown'
17/** The rows behind the debug fold. */
18export const DEBUG_ROWS: ReadonlySet<string> = new Set(['debugDefault', 'debugText', 'debugTextLength'])
19/** The fold rows, each a true/false setting: /config flips those in place with Enter. */
20export const FOLD_FIELDS: ReadonlySet<string> = new Set([SETTINGS_SHOWN_FIELD, KEYS_SHOWN_FIELD, DEBUG_SHOWN_FIELD])
21
22const open = (values: Readonly<Record<string, unknown>>, fold: string) => values[fold] === true
23
24/** Whether the /config menu leaves this plugin row out, given the settings as they stand. */
25export function rowHidden(field: string, values: Readonly<Record<string, unknown>>): boolean {
26 if (field === SETTINGS_SHOWN_FIELD) return false
27 if (!open(values, SETTINGS_SHOWN_FIELD)) return true
28 if (isKeyRow(field)) return !open(values, KEYS_SHOWN_FIELD)
29 if (DEBUG_ROWS.has(field)) return !open(values, DEBUG_SHOWN_FIELD)
30 return false
31}
32
33/** A fold row's label with its marker for the fold's state (`▾` open, `▸` closed); any other row's label as it is. */
34export function foldLabel(field: string, label: string, values: Readonly<Record<string, unknown>>): string {
35 if (!FOLD_FIELDS.has(field)) return label
36 const bare = label.replace(new RegExp(`^[${FOLD_CLOSED}${FOLD_OPEN}]\\s*`), '')
37 return `${open(values, field) ? FOLD_OPEN : FOLD_CLOSED} ${bare}`
38}
39hooks/core/settings.ts 357 lines1// The plugin's settings: what can be set, the defaults, and how the layers combine.
2//
3// Pure (imports nothing from the engine), so the rule is testable and the adapters that
4// read Claude Code's /config (userConfig) and the plugin store stay thin. Three layers,
5// later wins: the defaults here, the machine's values (the person's /config choices,
6// stored by Claude Code in settings.json), then a conversation's own values (only the
7// debug echo uses this slot today). Claude Code fills every field's declared default into
8// the machine layer (a picker field must declare one), so a machine value equal to the
9// default reports its source as `default`. A value that does not fit
10// its field is rejected and the layer below stands, so a bad setting can never break a
11// draw (#7: "an invalid value falls back to the default").
12//
13// Keys are identifiers because Claude Code requires it of userConfig keys: they become
14// CLAUDE_PLUGIN_OPTION_<KEY> environment variables in hooks (Claude Code's manifest
15// schema, read 2026-10-11). So `afterAction.focus` is `afterActionFocus`.
16//
17// The fields, from the asks of 2026-10-11 (ordering DWP, slice 1; the approved plan):
18// where the prompts list opens, whether it follows the view, how close two exchanges
19// must be for the earlier to win, whether a list stays open after a jump or while the
20// person types, where the keyboard goes after an action, and the debug echo's default.
21
22export type EnumField = { kind: 'enum'; values: readonly string[]; default: string; title: string; description: string }
23export type BooleanField = { kind: 'boolean'; default: boolean; title: string; description: string }
24export type NumberField = { kind: 'number'; min: number; max: number; default: number; title: string; description: string }
25export type TextField = { kind: 'text'; default: string; title: string; description: string }
26export type Field = EnumField | BooleanField | NumberField | TextField
27
28// U70 (djdarcy, 2026-10-22): "letting users choose how many lines per entry is best. I suspect
29// a good default is "2 lines"". The default is his guess, dogfooded; the cap is the loop's.
30// A fold row's leading marker (djdarcy, 2026-10-24: "some sort of leading indicator to show
31// something is a fold group"): closed in the manifest's title, and the config.describe hook
32// draws it open while the fold is shown (core/settings-fold.ts foldLabel). Not `>`, which
33// reads as a second copy of the menu's own `❯` cursor.
34export const FOLD_CLOSED = '▸'
35export const FOLD_OPEN = '▾'
36
37export const ROW_LINES_DEFAULT = 2
38export const ROW_LINES_MAX = 5
39
40export const FIELDS = {
41 // The fold over every other row (core/settings-fold.ts), first so it heads the plugin's
42 // block in /config. djdarcy, 2026-10-24: "every option should be hidden by default".
43 // The folds are true/false rows because /config flips those in place with Enter; a
44 // plugin's choice row always opens a picker (2.1.310 sets pickToCommit on every one), so
45 // the ‹ › cycler the menu's own rows use is not open to a plugin.
46 settingsShown: {
47 kind: 'boolean',
48 default: false,
49 title: `${FOLD_CLOSED} Bookmarks`,
50 description:
51 "true: the plugin's settings appear below (the prompts list, the band, the lists' rows, debugging, colours, and the keys behind their own row); false: folded away, and everything you set still applies",
52 },
53 listOpensAt: {
54 kind: 'enum',
55 values: ['nearest', 'newest'],
56 default: 'nearest',
57 title: 'Prompts list opens at',
58 description: 'nearest: centred on the prompt nearest your view; newest: at the newest prompt',
59 },
60 followHere: {
61 kind: 'enum',
62 values: ['when-idle', 'always', 'never'],
63 default: 'when-idle',
64 title: 'Prompts list follows the view',
65 description: 'when-idle: slides to keep the yellow row showing unless you are typing a number; always; never',
66 },
67 closeShare: {
68 kind: 'number',
69 min: 0,
70 max: 1,
71 default: 0.6,
72 title: 'Closeness for the earlier prompt',
73 description: 'An earlier exchange is "nearest" while it holds at least this share of the screen lines the biggest one holds (0 to 1)',
74 },
75 paneAfterJump: {
76 kind: 'enum',
77 values: ['close', 'stay'],
78 default: 'close',
79 // Retitled 2026-10-12: djdarcy looked for this as "keep the Panel open for prompts
80 // after I click an item" and did not find it under "A list after a jump".
81 title: 'Prompts or bookmarks list after you pick a row',
82 description: 'close: clicking a row (or Enter on a number) jumps there and closes the list; stay: the list stays open for the next pick',
83 },
84 paneWhileTyping: {
85 kind: 'enum',
86 values: ['close', 'stay'],
87 default: 'stay',
88 title: 'A list while you type',
89 description: 'stay: typing in the input box leaves an open list where it is; close: typing closes it',
90 },
91 afterActionFocus: {
92 kind: 'enum',
93 values: ['input', 'band'],
94 default: 'input',
95 title: 'Keyboard after an action',
96 description: 'input: back to the input box once Claude Code allows a plugin to do it; band: stay in the band',
97 },
98 // #27: a role's colour, background, dim or bold, as JSON; core/palette.ts validates it.
99 palette: {
100 kind: 'text',
101 default: '',
102 title: 'Colour overrides',
103 description: 'JSON, e.g. {"here": {"color": "cyan"}, "markBand": {"backgroundColor": "#203040"}}. Roles: here, pinned, footnote, legend, heading, mark, markBand, used, unused, unreached, emphasis, search. A colour is a theme key (warning, subtle, ...), a terminal colour name or #rrggbb; anything else is ignored',
104 },
105 // #33: the person's slash commands, `!` shell commands and interruptions, as N.k rows
106 // under their prompt in the prompts list. The fold is the first ladder on the
107 // continuum (core/kit/continuum.ts): hidden (-1) < folded (0) < shown (+1).
108 footnotes: {
109 kind: 'enum',
110 values: ['folded', 'shown', 'hidden'],
111 default: 'folded',
112 title: 'Footnotes in the prompts list',
113 description: "folded: a prompt with footnotes (your slash commands, ! shell commands, interruptions) shows an ellipsis, and . unfolds them; shown: always listed under their prompt; hidden: never listed",
114 },
115 // #28, djdarcy 2026-10-12: "The whole prompt up to a budget is fine, but for private
116 // builds and with the dcc-patcher we should be able to go further. So we want to make
117 // sure we can allow unlimited for machines that have less limitations."
118 promptTextBudget: {
119 kind: 'number',
120 min: 0,
121 max: 1_000_000_000,
122 default: 2_000_000,
123 title: 'Prompt text kept for the filter (bytes)',
124 description: 'How much of your prompts the filter searches, across the conversation; 0 = unlimited (for machines with room to spare). The default keeps whole prompts in most conversations',
125 },
126 // The input layers (#29) as switches. `band`: full shows the field, the labelled
127 // commands and `?`; field shows the field alone. A band with nothing in it cannot take
128 // the leader (an Input or a Button is what focuses), so "hidden" waits on Q261012-08.
129 band: {
130 kind: 'enum',
131 values: ['full', 'field'],
132 default: 'full',
133 title: 'The band',
134 description: 'full: the command field, the labelled commands and ? for the rest; field: the command field alone, one short row (the leader still lands there; ? shows the commands)',
135 },
136 // djdarcy, 2026-10-12 01:30: chords kept, optional, "an easy enable/disable so their
137 // removal can be tested".
138 chords: {
139 kind: 'enum',
140 values: ['on', 'off'],
141 default: 'on',
142 title: 'Chords on their own keybindings',
143 description: "on: mark, jump, prompts and read also answer the keybindings bound to their borrowed actions (docs: Optional fast keys); off: only the leader and the band's field",
144 },
145 panes: {
146 kind: 'enum',
147 values: ['on', 'off'],
148 default: 'on',
149 title: 'Lists in a pane',
150 description: "on: the prompts and bookmarks lists open in a pane beside the conversation; off: p and b take a number in the band and jump, with no pane",
151 },
152 // Where a list number is typed when the band holds the keyboard (the input-routing design,
153 // 2026-10-25; core/band/routes.ts). A new field, never a changed type (docs/engine-quirks.md,
154 // "A saved setting of the wrong type stops the plugin loading"): `auto` names the best
155 // pathway this build has, so a better one can become the default without a saved value
156 // changing meaning.
157 listInput: {
158 kind: 'enum',
159 values: ['auto', 'field', 'buttons'],
160 default: 'auto',
161 title: 'Typing a list number',
162 description: "auto: the best way this Claude Code build allows (today the band's own field); field: the band's own field, where Backspace, /words and * work; buttons: one key per digit, as before 0.6.27",
163 },
164 // U70: how much of each row the prompts and jump lists show. The pane's width is known, so
165 // lines are the one control that matters; the text is cut with an ellipsis at the end of
166 // the last line.
167 rowLines: {
168 kind: 'number',
169 min: 1,
170 max: ROW_LINES_MAX,
171 default: ROW_LINES_DEFAULT,
172 title: 'Lines per row in the lists',
173 description: 'How many lines each prompt in the prompts list, and each mark in the jump list, may take (1 to 5); the text is cut with an ellipsis at the end of the last line',
174 },
175 // The keymap (#36; the keys design, unit 3). djdarcy's fold look of 2026-10-24 chose rows
176 // behind a fold: `keysShown` hides the rows below it (a config.describe hook), so /config
177 // stays short until the person opens it. The names are core/band/keymap.ts KEY_FIELDS,
178 // LIST_FIELD and LEADER_FIELD (a core test holds them together). An empty row is the
179 // table's own keys; a value is keys separated by spaces, `Space` for the space key, and
180 // `hidden` last to take the button off the bar.
181 keysShown: {
182 kind: 'boolean',
183 default: false,
184 title: `${FOLD_CLOSED} Keys: show the key rows`,
185 description: 'true: the rows below set the band\'s keys, one per command, and the list keys; false: they are folded away (your keys stay as set)',
186 },
187 keyMark: keyRow('mark', 'm'),
188 keyJump: keyRow('jump', "' j"),
189 keyPrompts: keyRow('prompts', 'p'),
190 keyRead: keyRow('reading position', 'Space r'),
191 keyBookmarks: keyRow('bookmarks', 'b'),
192 keyPromote: keyRow('promote a mark', 'P'),
193 keyDelete: keyRow('clear a mark', 'd'),
194 keyForget: keyRow('forget a mark', 'D'),
195 keyBack: keyRow('back', 'o'),
196 keyForward: keyRow('forward', 'i'),
197 keyClose: keyRow('close', 'q'),
198 keyHelp: keyRow('help', '?'),
199 keyList: {
200 kind: 'text',
201 default: '',
202 title: 'Keys: in a list',
203 description: 'The list keys in order: next previous pin previous-group next-group claim remove close (default: j k s h l c d q); empty = the defaults',
204 },
205 keyLeader: {
206 kind: 'text',
207 default: '',
208 title: 'Keys: the leader',
209 description: 'The leader is a Claude Code keybinding (abovePrompt:focus in ~/.claude/keybindings.json), not set here',
210 },
211 // The debugging rows behind their own fold (djdarcy, 2026-10-24: a fold "for our debug
212 // options so they can be grouped together better", each leading with "Debug:"), last in
213 // the block so they read as one group.
214 debugShown: {
215 kind: 'boolean',
216 default: false,
217 title: `${FOLD_CLOSED} Debug: show the debug rows`,
218 description: 'true: the rows below set what the debug log echoes and quotes; false: they are folded away (what you set stays)',
219 },
220 debugDefault: {
221 kind: 'enum',
222 values: ['off', 'on'],
223 default: 'off',
224 title: 'Debug: echo by default',
225 description: "Whether the plugin's log lines are echoed into a conversation that has not chosen; /bm-debug decides per conversation",
226 },
227 // djdarcy, 2026-10-12: "In the dev build it should always be on, and in the main build
228 // it should always be off by default unless the person turns the feature on" and
229 // "some instances we might want the full output and other times just enough to identify
230 // the location". `auto` is that rule: debugTextMode() reads it per build.
231 debugText: {
232 kind: 'enum',
233 values: ['auto', 'off', 'with-debug', 'always'],
234 default: 'auto',
235 title: 'Debug: conversation text in the log',
236 description: "auto: off in an installed plugin, always in one loaded from a folder; off: log lines name places by id only; with-debug: they also quote the conversation while this conversation's debugging is on; always: they always quote it",
237 },
238 debugTextLength: {
239 kind: 'enum',
240 values: ['reference', 'full'],
241 default: 'reference',
242 title: 'Debug: how much text a line quotes',
243 description: 'reference: a short excerpt, enough to find the place; full: the whole text',
244 },
245} as const satisfies Record<string, Field>
246
247// One keymap row: a text field whose empty value is the command's default keys.
248function keyRow(what: string, defaults: string) {
249 return {
250 kind: 'text',
251 default: '',
252 title: `Keys: ${what}`,
253 description: `Keys for ${what}, separated by spaces (default: ${defaults}); Space spells the space key; end with hidden to take its button off the bar; empty = the default`,
254 } as const
255}
256
257export type FieldName = keyof typeof FIELDS
258type ValueOf<F> = F extends { kind: 'enum'; values: readonly (infer V)[] }
259 ? V
260 : F extends { kind: 'boolean' }
261 ? boolean
262 : F extends { kind: 'number' }
263 ? number
264 : F extends { kind: 'text' }
265 ? string
266 : never
267export type Settings = { [K in FieldName]: ValueOf<(typeof FIELDS)[K]> }
268export type Source = 'default' | 'machine' | 'conversation'
269export type Layer = Readonly<Record<string, unknown>>
270
271export const DEFAULTS: Settings = Object.fromEntries(
272 Object.entries(FIELDS).map(([k, f]) => [k, f.default]),
273) as Settings
274
275// Whether a value fits its field. Numbers given as strings (as a text field may hold
276// them) are accepted when they parse and fall within the range.
277export function fit(field: Field, raw: unknown): { ok: true; value: string | boolean | number } | { ok: false } {
278 switch (field.kind) {
279 case 'enum':
280 return typeof raw === 'string' && field.values.includes(raw) ? { ok: true, value: raw } : { ok: false }
281 case 'boolean':
282 if (typeof raw === 'boolean') return { ok: true, value: raw }
283 if (raw === 'true' || raw === 'false') return { ok: true, value: raw === 'true' }
284 return { ok: false }
285 case 'number': {
286 const n = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim() !== '' ? Number(raw) : NaN
287 return Number.isFinite(n) && n >= field.min && n <= field.max ? { ok: true, value: n } : { ok: false }
288 }
289 case 'text':
290 return typeof raw === 'string' ? { ok: true, value: raw } : { ok: false }
291 }
292}
293
294export type Resolved = {
295 values: Settings
296 sources: Record<FieldName, Source>
297 // Values that were given but did not fit, as `layer.key=value`, for /bm-config and the log.
298 rejected: string[]
299 // Keys a layer held that are not fields (a renamed or retired setting), as `layer.key`.
300 unknown: string[]
301}
302
303export function resolve(machine: Layer = {}, conversation: Layer = {}): Resolved {
304 const values = { ...DEFAULTS } as Record<string, unknown>
305 const sources = Object.fromEntries(Object.keys(FIELDS).map(k => [k, 'default'])) as Record<FieldName, Source>
306 const rejected: string[] = []
307 const unknown: string[] = []
308 for (const [layerName, layer] of [['machine', machine], ['conversation', conversation]] as const) {
309 for (const [key, raw] of Object.entries(layer)) {
310 if (raw === undefined) continue
311 if (!(key in FIELDS)) {
312 unknown.push(`${layerName}.${key}`)
313 continue
314 }
315 const name = key as FieldName
316 const fitted = fit(FIELDS[name], raw)
317 if (!fitted.ok) {
318 rejected.push(`${layerName}.${key}=${JSON.stringify(raw)}`)
319 continue
320 }
321 values[name] = fitted.value
322 // The machine layer carries every default Claude Code filled in: a value equal to
323 // the default is not a choice anyone made.
324 if (!(layerName === 'machine' && fitted.value === FIELDS[name].default)) sources[name] = layerName
325 }
326 }
327 return { values: values as Settings, sources, rejected, unknown }
328}
329
330// What `debugText` means in this build: `auto` is off in an installed plugin and
331// always in one loaded from a folder (a developer's build).
332export function debugTextMode(value: Settings['debugText'], loadedFromFolder: boolean): 'off' | 'with-debug' | 'always' {
333 return value === 'auto' ? (loadedFromFolder ? 'always' : 'off') : value
334}
335
336// Whether the plugin was loaded from Claude Code's plugin cache (a marketplace install)
337// rather than a folder (`--plugin-dir`, a working tree). Slashes either way.
338export function installedFromCache(pluginRoot: string): boolean {
339 return /[\\/]plugins[\\/]cache[\\/]/.test(pluginRoot)
340}
341
342// The `userConfig` block for plugin.json, generated from FIELDS so the manifest and the
343// code cannot drift (a test compares the two). Enum fields become strings with an
344// `options` list, which /config draws as a picker; every field declares its default (the
345// validator requires it of a picker).
346export function manifestUserConfig(): Record<string, Record<string, unknown>> {
347 return Object.fromEntries(
348 Object.entries(FIELDS).map(([k, f]) => {
349 const base = { title: f.title, description: f.description, default: f.default }
350 if (f.kind === 'enum') return [k, { type: 'string', ...base, options: [...f.values] }]
351 if (f.kind === 'number') return [k, { type: 'number', ...base, min: f.min, max: f.max }]
352 if (f.kind === 'text') return [k, { type: 'string', ...base }]
353 return [k, { type: 'boolean', ...base }]
354 }),
355 )
356}
357hooks/core/settings-state.ts 73 lines1// The plugin's settings as they stand, owned in one place (the one-owner principle,
2// notes/meta/2026-10-12__22-48-40): the person's /config values and the theme's name, with
3// the resolution and the palette kept until one of them changes. These were module
4// `let`s in register.tsx (machineOptions, themeName, paletteCache), and every read
5// re-resolved every field; here the writes are named and a read is a lookup.
6import { resolve, type Resolved, type Settings } from './settings.ts'
7import { resolvePalette, type Palette } from './palette.ts'
8import { applyKeymap, keymapOf, type Problem } from './band/keymap.ts'
9import type { Tables } from './band/keys.ts'
10
11export class SettingsState {
12 // The person's /config values (the `userConfig` in plugin.json), which Claude Code hands
13 // to `register` with every default filled in and a change to which arrives as
14 // `config.set`, over the defaults in core/settings.ts.
15 private machine: Record<string, unknown> = {}
16 // The theme's name (/config's `theme` row): the mark band's light or dark value.
17 private theme: string | undefined
18 private resolution: Resolved | undefined
19 private paletteCache: { key: string; palette: Palette } | undefined
20 // The key tables the person's keymap rows make (core/band/keymap.ts), and what in them
21 // could not be used (the default stands for that command). Made once per change.
22 private keymapCache: { tables: Tables; problems: Problem[] } | undefined
23
24 /** The /config values Claude Code handed `register` at load. */
25 loaded(options: Record<string, unknown>): void {
26 this.machine = { ...options }
27 this.resolution = undefined
28 this.keymapCache = undefined
29 }
30 /** One of this plugin's /config fields changed (`bookmarks.<field>`). */
31 changed(field: string, value: unknown): void {
32 this.machine = { ...this.machine, [field]: value }
33 this.resolution = undefined
34 this.keymapCache = undefined
35 }
36 /** The key tables every reader of core/band/keys.ts takes, from the keymap rows, and the problems that left a default standing. */
37 keymap(): { tables: Tables; problems: Problem[] } {
38 return (this.keymapCache ??= applyKeymap(keymapOf(this.current() as unknown as Record<string, unknown>)))
39 }
40 /** The theme's name, from /config's `theme` row. */
41 themeIs(name: string): void {
42 this.theme = name
43 }
44
45 /** The resolution: each value and where it came from (for /bm-config). */
46 resolved(): Resolved {
47 return (this.resolution ??= resolve(this.machine))
48 }
49 current(): Settings {
50 return this.resolved().values
51 }
52
53 // Every colour, background, dim and bold the plugin draws comes from the palette by role
54 // (#27, core/palette.ts): theme keys first, so a role reads on dark and light themes; the
55 // mark band's light or dark value from the theme's name (/config's `theme` row, kept
56 // current by a config.set hook); the person's overrides from the `palette` setting.
57 palette(): Palette {
58 const overrides = this.current().palette
59 const key = `${this.theme ?? ''}|${overrides}`
60 if (this.paletteCache?.key !== key) {
61 let parsed: Record<string, unknown> = {}
62 try {
63 const v: unknown = overrides.trim() ? JSON.parse(overrides) : {}
64 if (v && typeof v === 'object') parsed = v as Record<string, unknown>
65 } catch {
66 // Not JSON: the defaults stand, as for any override that does not fit.
67 }
68 this.paletteCache = { key, palette: resolvePalette({ theme: this.theme, overrides: parsed }).palette }
69 }
70 return this.paletteCache.palette
71 }
72}
73hooks/core/palette.ts 94 lines1// Every colour the plugin draws, by what it means rather than where it is drawn (#27).
2//
3// A role names a meaning (the prompt nearest the view, a pinned prompt, a footnote row,
4// a mark's highlighted words); its style is the engine's own style shape (the colour,
5// background, dim and bold a Text takes). Defaults use Claude Code's theme keys wherever
6// one fits: a theme key "follows the person's theme" (the engine's Color type), so the
7// same role reads on a dark and on a light terminal without the plugin knowing which.
8// The one colour with no theme key, the mark's background band, has a dark and a light
9// value chosen from the theme's name; a theme whose name says neither gets the dark one.
10//
11// Overrides (a setting, #7) are validated here: an unknown role or a colour that is not
12// a theme key, a hex value or a terminal colour name is dropped, and the default stands
13// (#7: "an invalid colour falls back to the palette default").
14
15export type Role = 'here' | 'pinned' | 'footnote' | 'legend' | 'heading' | 'mark' | 'markBand' | 'used' | 'unused' | 'unreached' | 'emphasis' | 'search'
16export type Style = { color?: string; backgroundColor?: string; dimColor?: boolean; bold?: boolean }
17export type Palette = Record<Role, Style>
18
19// Claude Code's theme keys (plugin/.claude-plugin/types/claude-code/index.d.ts, ThemeKey).
20export const THEME_KEYS = [
21 'text', 'inverseText', 'inactive', 'subtle', 'suggestion', 'remember', 'success', 'error', 'warning',
22 'merged', 'claude', 'permission', 'planMode', 'autoAccept', 'promptBorder', 'bashBorder', 'ide',
23 'diffAdded', 'diffRemoved', 'diffAddedDimmed', 'diffRemovedDimmed', 'diffAddedWord', 'diffRemovedWord',
24] as const
25
26const NAMED = new Set([
27 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white', 'gray', 'grey',
28 'blackBright', 'redBright', 'greenBright', 'yellowBright', 'blueBright', 'magentaBright', 'cyanBright', 'whiteBright',
29])
30
31// The mark band behind a highlighted line. Dark: a soft navy below the selection blue
32// (#264F78), the value the plugin has drawn since round 4. Light: its counterpart.
33export const MARK_BAND = { dark: '#1B3754', light: '#D6E4F5' } as const
34
35// The group headings' blue-gray (U71, a trial value; djdarcy's "hint of blue"), a dark and a
36// light value like the mark band, since no theme key is a blue-gray.
37export const HEADING = { dark: '#8FA3C0', light: '#5A6B85' } as const
38
39export const DEFAULTS: Palette = {
40 here: { color: 'warning', bold: true }, // the prompt nearest the view (yellow in the default themes)
41 pinned: { color: 'warning' }, // the pin star
42 footnote: { color: 'subtle', dimColor: true }, // non-prompt rows (#33): below whole prompts in priority; dim, since a Button row can't take the colour
43 legend: { dimColor: true },
44 // The group headings in the prompts list ("★ pinned", "all prompts"): the legend's dim
45 // gray with a hint of blue, so they read as headings without standing out (djdarcy,
46 // 2026-10-22: "slightly dark-gray as it's currently colored, but with a hint of blue ...
47 // I'm not convinced yet the gray-blue will work, just a test"). A hex pair chosen by the
48 // theme's brightness (resolvePalette), not a theme key: no key is a blue-gray. Override
49 // it in /config's colour overrides to try another.
50 heading: { color: HEADING.dark, dimColor: true },
51 mark: { color: 'warning', bold: true }, // a mark's highlighted words
52 markBand: { backgroundColor: MARK_BAND.dark },
53 used: { color: 'inactive' }, // a mark letter already taken, in the mark pane
54 unused: { dimColor: true }, // a mark letter still free
55 unreached: { dimColor: true }, // a prompt not drawn since load, possibly out of reach
56 emphasis: { bold: true }, // what the person is typing (a prompt number), the letter just marked
57 search: { color: 'suggestion', bold: true }, // search matches (#20): a cool colour, never the marks' yellow
58}
59
60export function brightness(themeName: string | undefined): 'light' | 'dark' {
61 return themeName && /light/i.test(themeName) ? 'light' : 'dark'
62}
63
64export function isColour(value: unknown): value is string {
65 return (
66 typeof value === 'string' &&
67 ((THEME_KEYS as readonly string[]).includes(value) || /^#[0-9a-f]{6}$/i.test(value) || NAMED.has(value))
68 )
69}
70
71export function resolvePalette(opts: { theme?: string; overrides?: Readonly<Record<string, unknown>> } = {}): {
72 palette: Palette
73 dropped: string[]
74} {
75 const palette = Object.fromEntries(Object.entries(DEFAULTS).map(([r, s]) => [r, { ...s }])) as Palette
76 palette.markBand.backgroundColor = MARK_BAND[brightness(opts.theme)]
77 palette.heading.color = HEADING[brightness(opts.theme)]
78 const dropped: string[] = []
79 for (const [role, raw] of Object.entries(opts.overrides ?? {})) {
80 if (!(role in DEFAULTS) || typeof raw !== 'object' || raw === null) {
81 dropped.push(role)
82 continue
83 }
84 const style = raw as Record<string, unknown>
85 const target = palette[role as Role]
86 for (const [k, v] of Object.entries(style)) {
87 if ((k === 'color' || k === 'backgroundColor') && isColour(v)) target[k] = v
88 else if ((k === 'dimColor' || k === 'bold') && typeof v === 'boolean') target[k] = v
89 else dropped.push(`${role}.${k}`)
90 }
91 }
92 return { palette, dropped }
93}
94hooks/core/prompts/prompt-rows.ts 241 lines1// Which transcript rows are the person's prompts, and their text.
2//
3// Claude Code's transcript keeps more under `"type":"user"` than typed prompts: tool
4// results, the `!` shell's input and output, local-command echoes, "[Request
5// interrupted by user]" rows, and the summary a compaction injects. And a message typed
6// while Claude was working is not a user row at all: it is queued and stored as an
7// `attachment` of type `queued_command` with the text in `attachment.prompt`
8// (djdarcy found one missing from the prompts list, 2026-10-11; 88 of them in one
9// transcript). This module decides, so that the transcript back-fill and the live
10// capture agree.
11
12import { headOf } from '../bookmarks/transcript-lines.ts'
13
14// Text the engine wraps around rows that are not the person's words. A prompt that
15// happens to begin with one of these is lost; none has been seen.
16// `<teammate-message …>`: a row another agent sent into the conversation (claude-devtools
17// excludes these from prompts, src/main/types/messages.ts:366-378; none seen here yet).
18// `<task-notification>`: the engine's notice that a background task finished, filed as a
19// user row (44 in the author's transcript, 2026-10-11; one reached the list as #318).
20// `[SYSTEM NOTIFICATION`, `Another Claude session sent a message`, `Stop hook feedback`:
21// a background task's notice, another session's message, a /goal check -- each queued
22// into a running turn the way the person's own mid-turn message is, and listed as a
23// prompt by the live capture (djdarcy, 2026-10-12: "The whole point of the "prompts"
24// panel is it is showing genuine user inputs, full stop").
25const NOT_A_PROMPT = /^\s*(<bash-(input|stdout|stderr)>|<command-name>|<command-message>|<local-command-(stdout|stderr)>|<teammate-message[\s>]|<task-notification>|\[Request interrupted by user|This session is being continued from a previous conversation|\[SYSTEM NOTIFICATION|Another Claude session sent a message|Stop hook feedback)/
26
27export function looksLikePrompt(text: string): boolean {
28 return text.trim() !== '' && !NOT_A_PROMPT.test(text)
29}
30
31// The person's words out of a queued message as the engine renders it for the model:
32// a `<system-reminder>` whose first line says a message arrived while Claude was
33// working, then the text, then a closing paragraph on how such messages surface. The
34// framing is the engine's and may change; when it is not recognised the whole text is
35// kept rather than nothing.
36export function unwrapQueued(rendered: string): string {
37 let s = rendered.replace(/<\/?system-reminder[^>]*>/g, '')
38 s = s.replace(/^\s*The user sent a new message while you were working:\s*/, '')
39 s = s.replace(/\n\s*This is how Claude Code surfaces messages[\s\S]*$/, '')
40 return s.trim() || rendered.trim()
41}
42
43// A row a schedule sent: a /loop firing is a plain user row carrying the command it runs,
44// stamped `turnOrigin: "scheduled"` and the task's id (one conversation kept 337 of them
45// as footnotes, 2026-10-15). It is the schedule's, never the person's.
46const scheduled = (o: any): boolean => o?.turnOrigin === 'scheduled' || o?.scheduledTaskId !== undefined
47
48// A transcript row's prompt text, or undefined when the row is not a prompt.
49export function promptTextOf(o: any): string | undefined {
50 if (o?.type === 'attachment') {
51 const a = o.attachment
52 if (a?.type === 'queued_command' && a.humanTurn && typeof a.prompt === 'string' && !o.isSidechain) {
53 return looksLikePrompt(a.prompt) ? a.prompt : undefined
54 }
55 return undefined
56 }
57 // A compaction summary is a user row flagged `isCompactSummary` (4 in this session's
58 // transcript, 2026-10-11); the flag is checked before the opening sentence, which is
59 // the engine's wording and may change.
60 if (o?.type !== 'user' || o.isMeta || o.isSidechain || o.isCompactSummary || scheduled(o)) return undefined
61 const content = o.message?.content
62 let text: string | undefined
63 if (typeof content === 'string') text = content
64 else if (Array.isArray(content)) {
65 if (content.some((b: any) => b?.type === 'tool_result')) return undefined
66 const texts = content.filter((b: any) => b?.type === 'text').map((b: any) => String(b.text ?? ''))
67 text = texts.length > 0 ? texts.join(' ') : undefined
68 }
69 return text !== undefined && looksLikePrompt(text) ? text : undefined
70}
71
72// Footnotes (#33): the person's own actions that are not prompts, numbered `N.k` under
73// the prompt before them. djdarcy, 2026-10-12: the prompts pane gives "USER invoked
74// markers (compactions aren't users, tasks aren't users, interruptions are users ...)".
75// So a slash command, a `!` shell command and an interruption are footnotes; their
76// output (`<local-command-stdout>`, `<bash-stdout>`) folds into the footnote before it;
77// meta rows, compaction summaries and task notifications are not footnotes.
78export type FootnoteKind = 'command' | 'shell' | 'interrupted'
79export type Footnote = { kind: FootnoteKind; label: string }
80
81// The longest footnote label kept. A command's label is its name and arguments, and a
82// /goal can carry its whole brief as arguments (3,155 characters seen, 2026-10-15); the
83// pane draws a label whole, so a long one wrapped over many rows and filled the store.
84export const FOOTNOTE_LABEL_MAX = 120
85
86const tagged = (text: string, tag: string) => new RegExp(`<${tag}>([\\s\\S]*?)</${tag}>`).exec(text)?.[1]?.trim()
87
88// A transcript row's footnote, or undefined when the row is not one.
89export function footnoteOf(o: any): Footnote | undefined {
90 return capped(footnoteWhole(o))
91}
92
93const capped = (fn: Footnote | undefined): Footnote | undefined =>
94 fn && fn.label.length > FOOTNOTE_LABEL_MAX ? { ...fn, label: `${fn.label.slice(0, FOOTNOTE_LABEL_MAX - 1)}…` } : fn
95
96// A slash command's footnote from the tags the engine writes it in, or undefined.
97function commandFootnote(t: string): Footnote | undefined {
98 if (!(t.startsWith('<command-name>') || t.startsWith('<command-message>'))) return undefined
99 const name = tagged(t, 'command-name') ?? tagged(t, 'command-message') ?? ''
100 const args = tagged(t, 'command-args') ?? ''
101 return { kind: 'command', label: `${name}${args ? ` ${args}` : ''}`.trim() }
102}
103
104// Setting a goal leaves no command row: the engine queues "Goal set: <condition>" into the
105// conversation from `auto-continuation` (8 in one transcript, 2026-10-11 to 2026-10-20). It is
106// the person's /goal, so it is a footnote with the condition as its label, never a prompt
107// (2026-10-23: three of them stood in the list as prompts #725-#727). The prefix is the
108// engine's wording and may change; when it does, a goal set is simply not footnoted.
109const GOAL_SET = /^\s*Goal set:\s*/
110export function goalSetFootnote(text: string): Footnote | undefined {
111 const m = GOAL_SET.exec(text)
112 return m ? capped({ kind: 'command', label: `/goal ${text.slice(m[0].length).replace(/\s+/g, ' ').trim()}`.trim() }) : undefined
113}
114
115function footnoteWhole(o: any): Footnote | undefined {
116 // Built-in commands the engine runs itself (/goal clear, /rename, /branch, /fork, /cd,
117 // /feedback) are written as `system` rows with subtype `local_command`, in the same tags a
118 // slash command uses; their output is a second such row (`<local-command-stdout>`), which
119 // folds into the command as the user-row form's does (7 in one transcript, 2026-10-23).
120 if (o?.type === 'system') {
121 if (o.subtype !== 'local_command' || o.isMeta || o.isSidechain) return undefined
122 return commandFootnote(String(o.content ?? '').trimStart())
123 }
124 if (o?.type === 'attachment') {
125 const a = o.attachment
126 if (o.isSidechain || a?.type !== 'queued_command' || a.humanTurn || a.origin?.kind !== 'auto-continuation' || typeof a.prompt !== 'string') return undefined
127 return goalSetFootnote(a.prompt)
128 }
129 if (o?.type !== 'user' || o.isMeta || o.isSidechain || o.isCompactSummary || scheduled(o)) return undefined
130 const content = o.message?.content
131 let text: string | undefined
132 if (typeof content === 'string') text = content
133 else if (Array.isArray(content)) {
134 if (content.some((b: any) => b?.type === 'tool_result')) return undefined
135 text = content.filter((b: any) => b?.type === 'text').map((b: any) => String(b.text ?? '')).join(' ')
136 }
137 if (!text) return undefined
138 const t = text.trimStart()
139 const cmd = commandFootnote(t)
140 if (cmd) return cmd
141 if (t.startsWith('<bash-input>')) return { kind: 'shell', label: `!${tagged(t, 'bash-input') ?? ''}` }
142 if (t.startsWith('[Request interrupted by user')) return { kind: 'interrupted', label: t.replace(/^\[|\]$/g, '').trim() }
143 return undefined
144}
145
146// Who-caused-the-row stamps (session.append's `origin.kind`) that are never the person.
147export const AUTOMATED_ORIGINS = new Set(['task-notification', 'scheduled-trigger', 'peer-send-message', 'coordinator', 'observer', 'observer-activity', 'auto-continuation', 'projects-relay', 'channel'])
148
149// The shape of a session.append event this module reads (structural, so no engine import):
150// the row's transcript uuid, its door, the agent that wrote it if not the person, who caused
151// it, and the message with its blocks.
152export type AppendEvent = {
153 uuid: string
154 door: string
155 agentId?: unknown
156 origin: { kind: string }
157 message: { type: string; name?: string; isMeta?: boolean; content: readonly { type: string; text?: string }[] }
158}
159
160/** What an appended row is to the plugin: a row to keep (a prompt or a response), the prompt's whole text to keep for the filter, a footnote, or nothing. The decisions session.append made in register.tsx until 0.6.12, moved here under /move-code with their comments; the hook keeps the stores, the redraw and the log. */
161export function classifyAppend(e: AppendEvent): { row?: { uuid: string; door: 'prompt' | 'response'; head: string; text: string }; promptText?: string; footnote?: Footnote } {
162 const out: { row?: { uuid: string; door: 'prompt' | 'response'; head: string; text: string }; promptText?: string; footnote?: Footnote } = {}
163 const isWanted = e.door === 'prompt' || e.door === 'response'
164 // A message typed while Claude was working arrives as an attachment named
165 // `queued_command`, its text wrapped in the engine's reminder prose (the transcript
166 // keeps the raw text in `attachment.prompt`, which this event does not carry). It is
167 // the person's prompt: unwrap it and keep it as one (djdarcy, 2026-10-11).
168 const queued = !e.agentId && e.message.type === 'attachment' && e.message.name === 'queued_command'
169 // Not the person's: the engine stamps who caused the row. A background task's notice,
170 // a scheduled firing, another session's message, a coordinator or observer: none is a
171 // prompt (djdarcy, 2026-10-12: the list shows "genuine user inputs, full stop"). A
172 // notice queued into a running turn is stamped `engine`, as the person's own queued
173 // message is; its text tells them apart (NOT_A_PROMPT above).
174 const automated = AUTOMATED_ORIGINS.has(e.origin.kind)
175 // A goal the person set arrives the same way, queued from `auto-continuation`: it is their
176 // /goal, a footnote and never a prompt (goalSetFootnote above). Any other continuation is
177 // still nothing.
178 if (queued && e.origin.kind === 'auto-continuation') {
179 const goal = goalSetFootnote(unwrapQueued(e.message.content.map(block => (block.type === 'text' ? block.text ?? '' : '')).join(' ')))
180 if (goal) out.footnote = goal
181 return out
182 }
183 if (!automated && (queued || (!e.agentId && isWanted && !e.message.isMeta))) {
184 const raw = e.message.content.map(block => (block.type === 'text' ? block.text ?? '' : '')).join(' ')
185 const text = queued ? unwrapQueued(raw) : raw
186 if (looksLikePrompt(text)) {
187 // `text` (first 4000 chars) lets a selection mark check it landed in the right row.
188 // A queued message arrives by the `attachment` door; it is a prompt (0.4.0 stored it
189 // under the engine's door, so the list, which counts `prompt` rows, dropped every one).
190 const door = (queued ? 'prompt' : e.door) as 'prompt' | 'response'
191 out.row = { uuid: e.uuid, door, head: headOf(text), text: text.slice(0, 4000) }
192 if (door === 'prompt') out.promptText = text
193 }
194 }
195 // A footnote (#33): the person's slash command, `!` shell command or interruption,
196 // kept with the prompt it follows, as the back-fill keeps it. A row the person did not
197 // cause is no footnote either: a /loop firing runs a slash command (2026-10-15: 535 of
198 // the 671 stored footnotes were firings).
199 if (!automated && !e.agentId && !queued && e.door !== 'response') {
200 const fn = footnoteOf({ type: 'user', isMeta: e.message.isMeta, message: { content: e.message.content } })
201 if (fn) out.footnote = fn
202 }
203 return out
204}
205
206// A footnote as kept: `after` is the uuid of the prompt before it (null before the first).
207export type FootnoteRef = Footnote & { uuid: string; after: string | null }
208
209// The `N.k` of kept footnotes, given the prompts in order (#1 first). A footnote whose
210// prompt is no longer in the list (aged out of the kept window) has no number.
211export function numberFootnotes(promptUuids: readonly string[], footnotes: readonly FootnoteRef[]): (Numbered | undefined)[] {
212 const index = new Map(promptUuids.map((u, i) => [u, i + 1]))
213 const seen = new Map<number, number>()
214 return footnotes.map(f => {
215 const n = f.after === null ? 0 : index.get(f.after)
216 if (n === undefined) return undefined
217 const k = (seen.get(n) ?? 0) + 1
218 seen.set(n, k)
219 return { n, k }
220 })
221}
222
223export type Numbered = { n: number; k: number }
224
225// The `N.k` of each row in a stream of prompts and footnotes, in transcript order: N is
226// the number of the prompt before it (0 before the first), k counts the footnotes under
227// that prompt from 1; a prompt is `N.0`. Footnotes never shift a prompt's number.
228export function numberRows(kinds: readonly ('prompt' | 'footnote')[]): Numbered[] {
229 let n = 0
230 let k = 0
231 return kinds.map(kind => {
232 if (kind === 'prompt') {
233 n += 1
234 k = 0
235 return { n, k: 0 }
236 }
237 k += 1
238 return { n, k }
239 })
240}
241