Checkpoint notes and fresh context windows that continue from them, with searchable history of earlier windows

Keep working across fresh context windows. The agent saves checkpoint notes, starts a new window that contains only a pointer to those notes, and can still search what happened in earlier windows.
Ported from pi-notes-compaction, a Pi extension by howaboua in howaboua-pi-stuff.
/plugin install notes-compaction --marketplace ramtinJ95/claude-mods
notes: list, read, search, write and append on virtual paths. write_file replaces; append_to_file adds.new_context: accepted only directly after a successful notes write in the same turn, so a new window never starts from stale notes. It ends the turn once its tool batch has run, then opens a new context window with the agent name, window IDs and recent note paths, and tells the agent to continue.history: lists, searches and reads earlier windows of this session, or a subagent's transcript. Loaded on demand.get_context_remaining: remaining tokens in the current window. Loaded on demand.Tool calls with no arguments return help. The notes tool's description explains how to keep checkpoints, so a fresh session needs no extra instructions.
The main conversation is /root; a subagent is /root/<agentId>. Relative note paths belong to the calling agent. <agent>/notes/<path> reads another agent's notes in the same session, so a parent reads what its subagent saved and a subagent reads its parent's checkpoint. Writes stay in the caller's own notes. history takes the same names as agent_name. Only the main conversation starts new windows.
A new window replaces the conversation with one marker message; no summary is generated. The full transcript stays in the session, which history reads.
get_context_remaining measures against the same limit.new_context./compact asks the agent to save a checkpoint, then opens a new window only if that turn completed with a saved note. If the latest turn already saved notes and no instructions were given, it opens the new window at once. Instructions after /compact become checkpoint guidance. Like Claude Code's own /compact, the new window waits for your next prompt."idleCompaction": false in Claude Code's settings turns idle compaction off altogether.new_context, or the checkpoint turn, cancels the rollover and keeps the old context.From 2.1.299, on a machine with managed settings and for Team and Enterprise organizations, Claude Code's built-in security plugin skips installed plugins' compaction hooks. The mod then runs in a reduced mode and says so once with a notice and in /notes:
/compact the window waits instead, and the marker leads your next prompt. The rollover costs one summarization request./compact still asks for a checkpoint first, and instructions after it still become checkpoint guidance.CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS), it checkpoints and opens a new window as above. "idleCompaction": false turns it off too.According to Claude Code's setting descriptions, an administrator can restore the full behavior by enabling the mod in managed settings and seating it with "appendPlugins": ["notes-compaction@claude-mods"]; this is untested. Claude Code reads only the highest-priority managed source, so on a machine with an MDM profile these keys belong in that profile.
/notes opens a panel with continuity status and storage counts. Changes save immediately; with the panel focused (ctrl+x tab), the bracketed letters press its buttons.
n): off by default. On, each new window keeps Claude Code's summary ahead of the window message, and /compact is Claude Code's own.p, then y to confirm): removes stored notes and fork records of sessions whose Claude Code transcript no longer exists, and subagent notes no remaining session names. The active session stays. Uses the rm command.Notes belong to one session: resuming keeps them, /clear starts empty. A fork (--fork-session, /branch) starts with the notes as they stood at the fork point and continues the window chain; afterwards the fork and its parent write independently.
Everything is plaintext JSON under $XDG_DATA_HOME/claude-notes-compaction/, defaulting to ~/.local/share: sessions/<session id>/ holds the main conversation's notes and window state, agents/<agentId>/ a subagent's notes, and revisions/ one record per write, which forks rebuild from.
history reads the newest 4096 messages Claude Code keeps for the session and says so once a session is longer.
hooks/register.ts 990 lines1import type {
2 EngineInterface,
3 Register,
4 RenderElement,
5 SessionCompacted,
6 SessionMessage,
7 Timer,
8 ToolCallInput,
9 ToolCallResult,
10} from 'claude-code'
11import { MESSAGE_LIMIT, useHistory } from './history.ts'
12import {
13 agentIdOf,
14 agentName,
15 type Note,
16 noteFileName,
17 ROOT,
18 recentPaths,
19 resolvePath,
20 useNotes,
21 WRITE_ACTIONS,
22} from './notes.ts'
23import {
24 GUIDANCE,
25 newState,
26 nextWindow,
27 OPENING_PROMPTS,
28 type Opening,
29 reminderFor,
30 remindersDone,
31 type SessionState,
32 type WindowIdentity,
33 windowMarker,
34 windowText,
35} from './windows.ts'
36
37const NOTES_TOOL = 'mcp__notes-compaction__notes'
38
39type Namespace = 'notes' | 'history'
40interface ActionSpec {
41 fields: readonly string[]
42 required?: readonly string[]
43 /** The notes field that holds a virtual path. */
44 pathField?: string
45}
46/** Each tool's actions: the fields they take and which are required. Help, filtering and checks derive from it. */
47const ACTIONS: Record<Namespace, Record<string, ActionSpec>> = {
48 notes: {
49 list_files_by_prefix: { fields: ['prefix', 'file_order', 'file_order_by', 'max_results'], pathField: 'prefix' },
50 read_file: { fields: ['path', 'start_line', 'stop_line'], required: ['path'], pathField: 'path' },
51 search_contents: {
52 fields: ['query', 'path_prefix', 'max_files', 'max_matches_per_file', 'recent_file_first'],
53 required: ['query'],
54 pathField: 'path_prefix',
55 },
56 append_to_file: { fields: ['path', 'text'], required: ['path', 'text'], pathField: 'path' },
57 write_file: { fields: ['path', 'text'], required: ['path', 'text'], pathField: 'path' },
58 },
59 history: {
60 list_windows: { fields: ['agent_name', 'limit', 'recent_first'] },
61 list_items: {
62 fields: ['agent_name', 'window_id', 'role', 'tool_name', 'limit', 'max_chars_per_item', 'recent_first'],
63 },
64 read_item: {
65 fields: ['agent_name', 'window_id', 'item_id', 'offset_chars', 'limit_chars'],
66 required: ['window_id', 'item_id'],
67 },
68 search_contents: {
69 fields: ['agent_name', 'window_id', 'role', 'tool_name', 'query', 'limit', 'recent_first'],
70 required: ['query'],
71 },
72 },
73}
74const actionNames = (namespace: Namespace) => ['help', ...Object.keys(ACTIONS[namespace])]
75const STRING = { type: 'string' }
76const POSITIVE = { type: 'integer', minimum: 1 }
77const NOTES_SCHEMA = {
78 type: 'object',
79 properties: {
80 action: { type: 'string', enum: actionNames('notes') },
81 path: STRING,
82 text: STRING,
83 prefix: STRING,
84 query: STRING,
85 path_prefix: STRING,
86 start_line: POSITIVE,
87 stop_line: POSITIVE,
88 max_results: POSITIVE,
89 max_files: POSITIVE,
90 max_matches_per_file: POSITIVE,
91 file_order: { type: 'string', enum: ['ascending', 'descending'] },
92 file_order_by: { type: 'string', enum: ['name', 'created_at', 'updated_at'] },
93 recent_file_first: { type: 'boolean' },
94 },
95 additionalProperties: false,
96}
97const HISTORY_SCHEMA = {
98 type: 'object',
99 properties: {
100 action: { type: 'string', enum: actionNames('history') },
101 agent_name: STRING,
102 item_id: STRING,
103 window_id: STRING,
104 query: STRING,
105 limit: POSITIVE,
106 limit_chars: POSITIVE,
107 max_chars_per_item: POSITIVE,
108 offset_chars: { type: 'integer', minimum: 0 },
109 recent_first: { type: 'boolean' },
110 role: { type: 'string', enum: ['user', 'assistant', 'tool'] },
111 tool_name: STRING,
112 },
113 additionalProperties: false,
114}
115const EMPTY_SCHEMA = { type: 'object', properties: {}, additionalProperties: false }
116const TOOLS = [
117 {
118 name: 'notes',
119 // The description carries the checkpoint guidance: prompt events do not reach this mod (see AGENTS.md).
120 description: `Persistent notes. write_file replaces; append_to_file adds. Virtual paths: relative uses current agent; cross-agent uses <agent>/notes[/path], read-only. Call with no arguments for help.\n\n${GUIDANCE}`,
121 inputSchema: NOTES_SCHEMA,
122 isDeferred: false,
123 },
124 {
125 name: 'history',
126 description: "Search earlier conversation, don't browse it. Pass returned IDs unchanged. Call with no arguments for help.",
127 inputSchema: HISTORY_SCHEMA,
128 isDeferred: true,
129 },
130 {
131 name: 'new_context',
132 description: 'Start fresh from saved notes; recover earlier conversation through history',
133 inputSchema: EMPTY_SCHEMA,
134 isDeferred: false,
135 },
136 { name: 'get_context_remaining', description: 'Remaining context tokens', inputSchema: EMPTY_SCHEMA, isDeferred: true },
137]
138
139/** The tool's own arguments: tool.call's input also carries reserved keys beside them. */
140function args(e: object, schema: { properties: object }): Record<string, unknown> {
141 const keys = Object.keys(schema.properties)
142 return Object.fromEntries(Object.entries(e).filter(([key]) => keys.includes(key)))
143}
144
145/** Help-backed tools: no arguments, or action help, lists each action's fields; optional ones end in `?`. */
146function discovery(namespace: Namespace, params: Record<string, unknown>) {
147 const keys = Object.keys(params)
148 if (keys.length && params['action'] !== 'help') return
149 if (keys.some((key) => key !== 'action')) throw new Error('Help accepts only action: help')
150 return {
151 actions: Object.fromEntries([
152 ['help', ''],
153 ...Object.entries(ACTIONS[namespace]).map(([action, spec]) => [
154 action,
155 spec.fields.map((field) => (spec.required?.includes(field) ? field : `${field}?`)).join(' '),
156 ]),
157 ]),
158 }
159}
160
161/** The action's own fields, with its required ones present. */
162function relevant(namespace: Namespace, params: Record<string, unknown>) {
163 const spec = ACTIONS[namespace][String(params['action'])]
164 if (!spec) throw new Error('Unknown action')
165 const missing = (spec.required ?? []).filter((field) => typeof params[field] !== 'string' || !params[field])
166 if (missing.length)
167 throw new Error(
168 `${namespace} ${String(params['action'])} requires ${missing.join(' and ')}` +
169 (namespace === 'history' && params['action'] === 'read_item'
170 ? '. Copy window_id and item_id from the same search_contents or list_items result'
171 : ''),
172 )
173 const scoped = Object.fromEntries(
174 Object.entries(params).filter(([key]) => key === 'action' || spec.fields.includes(key)),
175 )
176 return { scoped, spec }
177}
178
179const message = (error: unknown) => (error instanceof Error ? error.message : String(error))
180const result = (payload: unknown) => ({ result: JSON.stringify(payload) })
181const failure = (error: unknown) => ({ deny: message(error) })
182
183/**
184 * Where Claude Code keeps plugins out of compaction (2.1.299+ on machines with managed settings and for Team and
185 * Enterprise organizations), a rollover is Claude Code's summary told to defer to the notes.
186 */
187const ROLLOVER_SUMMARY =
188 'The agent saved its working state in notes and continues from them in a new context window. Write at most a few lines: the user\'s latest request in their words, and only what happened after the last notes save that the notes lack. Do not restate saved notes.'
189const BLOCKED_NOTICE =
190 "Claude Code keeps plugins out of compaction here, so each new window starts from a short Claude Code summary and your notes. Compaction at the threshold stays Claude Code's own."
191
192const PENDING = 'A notes checkpoint or rollover is already pending.'
193const CHECKPOINT_FIRST = 'Saving a notes checkpoint first. The new window opens after it completes.'
194const ROLLOVER_FAILED = 'Context rollover failed. The existing context remains.'
195const NOTE_FIRST = 'Save your progress with notes, wait for the write to succeed, then call new_context next.'
196
197const CHECKPOINT_PROMPT =
198 '<context_window_reminder>\nContext checkpoint requested. Save the current state with notes, then finish your response. The new window opens after this turn. Do not call new_context. If saving fails, report the failure without rolling over.\n</context_window_reminder>'
199
200/** One successful root write: root's whole note set after it, its window, and the session's subagents. */
201interface Revision {
202 /** The writing session, so /notes can prune its records with it. */
203 session?: string
204 notes: Note[]
205 window?: WindowIdentity
206 agents?: string[]
207}
208/** $.fs.read takes at most 4 MiB, so a revision must stay below it to be restorable. */
209const REVISION_LIMIT = 4_000_000
210
211// Module state restarts on reload; the window identity itself is persisted per session.
212let storage: Promise<string> | undefined
213let sessionId: string | undefined
214let loaded: { dir: string; promise: Promise<{ dir: string; state: SessionState }> } | undefined
215/**
216 * The running main turn. Between turns, Claude Code compacts on its own only while idle. `lastCall` is its latest
217 * completed tool call and `savedNote` its latest successful notes write, so new_context can require that it directly
218 * follows a saved note.
219 */
220let turn: { id: string; notes: 'none' | 'saved' | 'failed'; lastCall?: string; savedNote?: string } | undefined
221/** The window whose latest completed turn saved fresh notes. */
222let freshWindowId: string | undefined
223/**
224 * At most one rollover at a time: requested by new_context, a checkpoint (/compact or idle compaction), or the
225 * /compact opening it. Each carries how its window opens: only /compact's waits for the user, as Claude Code's does.
226 */
227let pending:
228 | { kind: 'requested' }
229 | { kind: 'checkpoint'; windowId: string; opening: Opening }
230 | { kind: 'rolling'; opening: Opening; answered: boolean }
231 | undefined
232/** The context whose idle compaction already asked for a checkpoint; a later one there stays Claude Code's own. */
233let idleCheckpointWindowId: string | undefined
234/**
235 * Where our session.compact hook may be skipped, Claude Code's idle compaction goes unseen, so the idle rollover
236 * runs from this timer instead, armed when a main turn completes. Claude Code compacts a conversation of at least
237 * its minimum size at 90% of a one-hour prompt cache (54 minutes); the rollover's first request comes before that
238 * and restarts its clock.
239 */
240let idleTimer: Timer | undefined
241/** Our session.compact hook answered in this process; the stored `compaction` may predate an upgrade into the block. */
242let compactHookRan = false
243const IDLE_ROLLOVER_MS = 50 * 60 * 1000
244const IDLE_MIN_TOKENS = 200_000
245const IDLE_MIN_TOKENS_FLOOR = 100_000
246/**
247 * Where Claude Code compacts on its own (an auto-compact window such as 400k), refreshed each turn.
248 * Reminders and remaining context measure against it, so checkpoints come before that compaction.
249 */
250let compactThreshold: number | undefined
251/** Parallel calls in one batch would otherwise read the same note before either append lands. */
252let notesQueue: Promise<unknown> = Promise.resolve()
253/** The /notes setting: run Claude Code's summary before each new window, as Pi's normal compaction does. */
254let normalCompaction = false
255/**
256 * Whether our session.compact hook answers (`hooked`) or Claude Code skips it (`blocked`), as the last rollover or
257 * compaction found; unknown until then, and treated as possibly blocked. Kept in the store, so where the hook
258 * answers, rollover's /compact carries no summary instructions; after an upgrade into the block, the first
259 * rollover is therefore Claude Code's full summary.
260 */
261let compaction: 'hooked' | 'blocked' | undefined
262/** What the /notes pane shows; a change redraws it. */
263let panel: { status: string[]; confirmPrune: boolean; message?: string } = { status: [], confirmPrune: false }
264const PANE = 'notes-compaction'
265
266// The engine follows $ only into functions declared in this file, so all I/O lives here.
267
268/** Storage outside ~/.claude, which may be a synced dotfiles directory. */
269function storageRoot($: EngineInterface): Promise<string> {
270 storage ??= dataHome($)
271 return storage
272}
273
274async function dataHome($: EngineInterface): Promise<string> {
275 return `${(await $.env.get('XDG_DATA_HOME')) || `${await $.env.get('HOME')}/.local/share`}/claude-notes-compaction`
276}
277
278/** Where Claude Code keeps this profile's transcripts, one folder per project. */
279async function transcriptsDir($: EngineInterface): Promise<string> {
280 return `${(await $.env.get('CLAUDE_CONFIG_DIR')) || `${await $.env.get('HOME')}/.claude`}/projects`
281}
282
283async function revisionPath($: EngineInterface, toolUseId: string): Promise<string> {
284 return `${await storageRoot($)}/revisions/${toolUseId}.json`
285}
286
287const rootNotesDir = (sessionDir: string) => `${sessionDir}/notes`
288
289/**
290 * Root notes live with their session. A subagent's live under its agent ID, which is unique,
291 * so a fork that carries the Agent call reaches the same notes.
292 */
293async function notesDir($: EngineInterface, agent: string): Promise<string> {
294 const id = agentIdOf(agent)
295 return id === undefined ? rootNotesDir((await session($)).dir) : `${await storageRoot($)}/agents/${id}/notes`
296}
297
298/** The session's state, loaded once; concurrent first calls share the load, and a failed one is retried. */
299async function session($: EngineInterface) {
300 sessionId ??= await $.session.id()
301 const dir = `${await storageRoot($)}/sessions/${sessionId}`
302 if (loaded?.dir !== dir) {
303 const promise = loadSession($, dir)
304 loaded = { dir, promise }
305 promise.catch(() => {
306 if (loaded?.promise === promise) loaded = undefined
307 })
308 }
309 return loaded.promise
310}
311
312/**
313 * A session without state is new, or a fork (`--fork-session`, `/branch`) whose transcript was
314 * copied from its parent. Like Pi's receipts, each successful root write saves a revision under its
315 * tool use ID, so the last write the copied transcript shows restores the notes as they stood at
316 * the fork point. A window marker after that write wins for the window identity.
317 */
318async function loadSession($: EngineInterface, dir: string) {
319 const path = `${dir}/state.json`
320 if (await $.fs.exists(path)) return { dir, state: JSON.parse(await $.fs.read(path)) as SessionState }
321 const messages = await $.session.messages()
322 const markers = messages.map(windowMarker)
323 const state = newState()
324 state.projects = await transcriptsDir($)
325 // A fork inherits the subagents its copied transcript launched, with their notes.
326 const launched = messages.flatMap((m) => m.toolUses.flatMap((use) => (use.agentId ? [agentName(use.agentId)] : [])))
327 if (launched.length) state.agents = [...new Set(launched)]
328 let restored: Revision | undefined
329 let restoredFrom: string | undefined
330 let markerWindow: WindowIdentity | undefined
331 let sawWrite = false
332 for (let i = messages.length - 1; i >= 0 && !restored; i--) {
333 const marker = markers[i]
334 if (marker && !markerWindow)
335 markerWindow = {
336 firstWindowId: marker.first ?? marker.current,
337 currentWindowId: marker.current,
338 ...(marker.previous ? { previousWindowId: marker.previous } : {}),
339 windowNumber: markers.filter((m) => m && !m.repeated).length,
340 }
341 for (const use of [...messages[i]!.toolUses].reverse()) {
342 if (use.tool !== NOTES_TOOL || use.isError || !WRITE_ACTIONS.includes(use.input['action'])) continue
343 sawWrite = true
344 const file = await revisionPath($, use.tool_use_id)
345 if (!(await $.fs.exists(file))) continue
346 restored = JSON.parse(await $.fs.read(file)) as Revision
347 restoredFrom = use.tool_use_id
348 break
349 }
350 }
351 state.window = markerWindow ?? restored?.window ?? state.window
352 if (restored) {
353 await Promise.all(restored.notes.map((note) => writeNote($, rootNotesDir(dir), note)))
354 state.agents = [...new Set([...(state.agents ?? []), ...(restored.agents ?? [])])]
355 state.restoredFrom = restoredFrom
356 } else if (sawWrite || messages.length >= MESSAGE_LIMIT)
357 $.ui.toast("This session's earlier notes could not be restored. Notes start empty; earlier history remains.")
358 // Persist before use: history and notes may cite the first window's ID before anything else is saved.
359 await saveState($, dir, state)
360 return { dir, state }
361}
362
363async function saveState($: EngineInterface, dir: string, state: SessionState) {
364 await $.fs.write(`${dir}/state.json`, JSON.stringify(state))
365}
366
367async function writeNote($: EngineInterface, dir: string, note: Note) {
368 await $.fs.write(`${dir}/${await noteFileName(note.path)}`, JSON.stringify(note))
369}
370
371async function readNotes($: EngineInterface, dir: string): Promise<Map<string, Note>> {
372 if (!(await $.fs.exists(dir))) return new Map()
373 const files = (await $.fs.list(dir)).filter((entry) => entry.kind === 'file' && entry.name.endsWith('.json'))
374 const notes = await Promise.all(files.map(async (entry) => JSON.parse(await $.fs.read(`${dir}/${entry.name}`)) as Note))
375 return new Map(notes.map((note) => [note.path, note]))
376}
377
378/** One note, for a read: its own file instead of the whole set. */
379async function readNote($: EngineInterface, dir: string, path: string): Promise<Map<string, Note>> {
380 const file = `${dir}/${await noteFileName(path)}`
381 if (!(await $.fs.exists(file))) return new Map()
382 const note = JSON.parse(await $.fs.read(file)) as Note
383 return new Map([[note.path, note]])
384}
385
386/**
387 * Whether a note path may name this agent: root, the caller, subagents that wrote notes here, or
388 * a subagent the transcript in view launched.
389 */
390async function isSessionAgent($: EngineInterface, self: string, agent: string): Promise<boolean> {
391 if (agent === ROOT || agent === self || (await session($)).state.agents?.includes(agent)) return true
392 return (await $.session.messages()).some((m) => m.toolUses.some((use) => use.agentId && agentName(use.agentId) === agent))
393}
394
395/**
396 * The window's opening message, after `kept` (normal compaction's summary, or nothing for a
397 * notes-only window); the conversation continues once it stands, unless it waits for the user.
398 */
399async function openWindow($: EngineInterface, kept: readonly SessionMessage[], opening: Opening): Promise<SessionCompacted> {
400 const marker = await advanceWindow($)
401 if (opening !== 'wait') $.clock.after(100, () => $.prompt.submit({ text: OPENING_PROMPTS[opening] }))
402 return {
403 messages: [
404 ...kept,
405 { role: 'user', text: marker, toolUses: [] },
406 { role: 'assistant', text: 'New context window opened.', toolUses: [] },
407 ],
408 }
409}
410
411/** Moves the session into its next window, whose reminders start over, and returns that window's marker. */
412async function advanceWindow($: EngineInterface): Promise<string> {
413 const { dir, state } = await session($)
414 const ids = nextWindow(state.window)
415 const recent = recentPaths(await readNotes($, rootNotesDir(dir)), ROOT)
416 state.window = ids
417 state.reminded = []
418 delete state.unsentMarker
419 await saveState($, dir, state)
420 return windowText(ROOT, ids, recent)
421}
422
423/**
424 * Rollover runs between turns through /compact: the one route on which our session.compact hook answers.
425 * Where Claude Code skips that hook, its own summary runs instead, guided to defer to the notes.
426 */
427function roll($: EngineInterface, opening: Opening) {
428 const rolling = { kind: 'rolling' as const, opening, answered: false }
429 pending = rolling
430 $.clock.after(100, async () => {
431 try {
432 const guided = !normalCompaction && compaction !== 'hooked'
433 await $.command.run({ command: 'compact', ...(guided ? { args: ROLLOVER_SUMMARY } : {}) })
434 if (!rolling.answered) await continueAfterSummary($, opening)
435 } catch (error) {
436 $.ui.toast(`Context rollover failed: ${message(error)}. The existing context remains.`)
437 } finally {
438 pending = undefined
439 }
440 })
441}
442
443/**
444 * The window after Claude Code's own summary, when our hook could not answer: the marker that history reads
445 * window boundaries from arrives as the prompt that continues. Usage reads no context until the next request,
446 * so a context still measured means no compaction ran.
447 */
448async function continueAfterSummary($: EngineInterface, opening: Opening) {
449 if ((await $.session.usage()).context.tokens !== undefined)
450 throw new Error('Claude Code did not compact the conversation')
451 if (compaction !== 'blocked') {
452 $.ui.toast(BLOCKED_NOTICE)
453 await setCompaction($, 'blocked')
454 }
455 const marker = await advanceWindow($)
456 if (opening === 'wait') {
457 const { dir, state } = await session($)
458 state.unsentMarker = marker
459 await saveState($, dir, state)
460 } else $.clock.after(100, () => $.prompt.submit({ text: `${marker}\n${OPENING_PROMPTS[opening]}` }))
461}
462
463async function setCompaction($: EngineInterface, found: 'hooked' | 'blocked') {
464 compaction = found
465 await $.store.set('compaction', found)
466}
467
468/** In place of a compaction: a turn that saves notes, after which turn.complete rolls into a window opened as `opening`. */
469function checkpoint($: EngineInterface, windowId: string, guidance: string, opening: Opening) {
470 pending = { kind: 'checkpoint', windowId, opening }
471 $.clock.after(100, () => $.prompt.submit({ text: CHECKPOINT_PROMPT + guidance }))
472}
473
474function armIdleRollover($: EngineInterface) {
475 idleTimer?.cancel()
476 idleTimer = undefined
477 if (compactHookRan || normalCompaction) return
478 idleTimer = $.clock.after(IDLE_ROLLOVER_MS, () => {
479 idleTimer = undefined
480 idleRollover($).catch((error) => $.ui.toast(`Idle rollover failed: ${message(error)}. The existing context remains.`))
481 })
482}
483
484/** What the session.compact hook does with Claude Code's idle compaction, for a context it would compact. */
485async function idleRollover($: EngineInterface) {
486 const idle = () => !turn && !pending && !compactHookRan && !normalCompaction && compactThreshold !== undefined
487 if (!idle() || (await $.settings.read({})).idleCompaction === false) return
488 const { tokens } = await contextUsed($)
489 const configured = Number((await $.env.get('CLAUDE_CODE_IDLE_COMPACT_MIN_TOKENS')) || NaN)
490 const minTokens = Number.isFinite(configured) ? Math.max(IDLE_MIN_TOKENS_FLOOR, configured) : IDLE_MIN_TOKENS
491 if (tokens === undefined || tokens < minTokens) return
492 const windowId = (await session($)).state.window.currentWindowId
493 // A turn or /compact may have started while this read.
494 if (!idle()) return
495 if (freshWindowId === windowId) return roll($, 'resume')
496 if (idleCheckpointWindowId === windowId) return
497 idleCheckpointWindowId = windowId
498 checkpoint($, windowId, '', 'resume')
499}
500
501async function refreshThreshold($: EngineInterface) {
502 const breakdown = (await $.session.usage({ breakdown: 'summary' })).context.breakdown
503 compactThreshold = breakdown?.isAutoCompactEnabled ? breakdown.autoCompactThreshold : undefined
504}
505
506async function contextUsed($: EngineInterface): Promise<{ limit: number; tokens?: number }> {
507 const { context } = await $.session.usage()
508 return { limit: Math.min(context.window, compactThreshold ?? context.window), tokens: context.tokens }
509}
510
511/**
512 * Characters of tool results since the model's last request. Measured usage stops at that request,
513 * so a large batch (several file reads) would otherwise cross the limit unseen.
514 */
515let batchChars = 0
516/** A rough, early-leaning conversion for code and prose alike. */
517const CHARS_PER_TOKEN = 3
518/** The context dueReminder last measured, and the share of the limit it must fall by to count as a compaction. */
519let measured: number | undefined
520const UNSEEN_COMPACTION_DROP = 0.1
521
522/** The context reminder due once `unsentChars` more reach the model, marked sent. Each fires once per window. */
523async function dueReminder($: EngineInterface, unsentChars: number): Promise<string | undefined> {
524 const { dir, state } = await session($)
525 // Where the hook answers, compaction resets reminders there, so a reminded-out window needs no measuring.
526 if (compaction === 'hooked' && remindersDone(state)) return
527 const { limit, tokens } = await contextUsed($)
528 if (compaction !== 'hooked') {
529 // Where Claude Code keeps plugins out of compaction, its own compaction goes unseen here. Measured context only
530 // grows within a window, so a clear fall since the last check, or none measured (also on resume), means one ran.
531 const compacted = tokens === undefined || (measured !== undefined && measured - tokens > limit * UNSEEN_COMPACTION_DROP)
532 measured = tokens
533 if (compacted && state.reminded.length) {
534 state.reminded = []
535 await saveState($, dir, state)
536 }
537 }
538 if (remindersDone(state)) return
539 const estimate = tokens === undefined ? undefined : tokens + unsentChars / CHARS_PER_TOKEN
540 const reminder = reminderFor(state, estimate === undefined || limit <= 0 ? undefined : (100 * estimate) / limit)
541 if (reminder) await saveState($, dir, state)
542 return reminder
543}
544
545/** Mid-turn, reminders ride on tool results, the one channel to the model. */
546async function remind($: EngineInterface, agentId: string | undefined, called: ToolCallResult): Promise<ToolCallResult> {
547 if (agentId !== undefined || called.deny !== undefined) return called
548 batchChars += (called.text ?? (typeof called.result === 'string' ? called.result : JSON.stringify(called.result ?? ''))).length
549 try {
550 const reminder = await dueReminder($, batchChars)
551 return reminder ? { ...called, context: [...(called.context ?? []), reminder] } : called
552 } catch {
553 return called
554 }
555}
556
557function callNotes($: EngineInterface, e: ToolCallInput): Promise<ToolCallResult> {
558 const run = notesQueue.then(() => runNotes($, e))
559 notesQueue = run.catch(() => undefined)
560 return run
561}
562
563async function runNotes($: EngineInterface, e: ToolCallInput): Promise<ToolCallResult> {
564 const params = args(e, NOTES_SCHEMA)
565 const isWrite = WRITE_ACTIONS.includes(params['action'])
566 const main = e.agentId === undefined
567 try {
568 const help = discovery('notes', params)
569 if (help) return result(help)
570 const { scoped, spec } = relevant('notes', params)
571 const self = agentName(e.agentId)
572 const field = spec.pathField!
573 const target = resolvePath(scoped[field], self, spec.required?.includes(field) ?? false)
574 if (isWrite && target.agent !== self)
575 throw new Error(`Write only your own notes, with a relative path. ${target.agent}'s notes are read-only here.`)
576 if (!(await isSessionAgent($, self, target.agent)))
577 throw new Error(`${target.agent} is not an agent of this session. Use a relative path for your own notes.`)
578 const dir = await notesDir($, target.agent)
579 const notes = params['action'] === 'read_file' ? await readNote($, dir, target.path) : await readNotes($, dir)
580 const { payload, write } = useNotes(notes, { ...scoped, [field]: target.path }, await $.clock.now(), target.agent)
581 if (!write) return result(payload)
582 const { dir: sessionDir, state } = await session($)
583 // The revision is the receipt a fork rebuilds root notes from. Subagent notes need none: they
584 // live under the agent ID, which a fork shares. Its size is checked before anything changes.
585 notes.set(write.path, write)
586 const revision =
587 e.tool_use_id && main
588 ? JSON.stringify({
589 session: sessionId,
590 notes: [...notes.values()],
591 window: state.window,
592 agents: state.agents,
593 } satisfies Revision)
594 : undefined
595 if (revision && new TextEncoder().encode(revision).length > REVISION_LIMIT)
596 throw new Error('Notes exceed 4 MB in total. Shorten or replace existing notes, then save again.')
597 try {
598 await writeNote($, dir, write)
599 } catch {
600 throw new Error('Note could not be saved. Retry after local storage is available.')
601 }
602 if (revision)
603 try {
604 await $.fs.write(await revisionPath($, e.tool_use_id!), revision)
605 } catch {
606 throw new Error(
607 `${payload['path']} was saved, but forks of this session will not see it. Read it back and save it again with write_file.`,
608 )
609 }
610 if (!main && !state.agents?.includes(self)) {
611 state.agents = [...(state.agents ?? []), self]
612 await saveState($, sessionDir, state)
613 }
614 if (main && turn) {
615 if (turn.notes === 'none') turn.notes = 'saved'
616 turn.savedNote = e.tool_use_id
617 }
618 return result(payload)
619 } catch (error) {
620 if (isWrite && main && turn) turn.notes = 'failed'
621 return failure(error)
622 }
623}
624
625async function callHistory($: EngineInterface, e: ToolCallInput): Promise<ToolCallResult> {
626 const params = args(e, HISTORY_SCHEMA)
627 try {
628 const help = discovery('history', params)
629 if (help) return result(help)
630 const { scoped } = relevant('history', params)
631 const name = scoped['agent_name']
632 const id = agentIdOf(typeof name === 'string' && name ? name : agentName(e.agentId))
633 if (id === undefined) {
634 const { state } = await session($)
635 return result(useHistory(await $.session.messages(), scoped, state.window.currentWindowId))
636 }
637 // A subagent's transcript is its own single window.
638 const found = await $.session.messages({ agentId: id })
639 if ('deny' in found)
640 throw new Error(`${agentName(id)}'s history is not available here. Omit agent_name to search your own.`)
641 return result(useHistory(found, scoped, `agent:${id}`))
642 } catch (error) {
643 return failure(error)
644 }
645}
646
647function showPanel($: EngineInterface, change: Partial<typeof panel>) {
648 panel = { ...panel, ...change }
649 $.ui.invalidate('ui.render')
650}
651
652async function childNames($: EngineInterface, dir: string, kind: 'file' | 'dir'): Promise<string[]> {
653 if (!(await $.fs.exists(dir))) return []
654 return (await $.fs.list(dir)).filter((entry) => entry.kind === kind).map((entry) => entry.name)
655}
656
657async function refreshPanel($: EngineInterface) {
658 const base = await storageRoot($)
659 const { dir, state } = await session($)
660 const notes = (await childNames($, rootNotesDir(dir), 'file')).length
661 const sessions = (await childNames($, `${base}/sessions`, 'dir')).length
662 const records = (await childNames($, `${base}/revisions`, 'file')).length
663 const { limit } = await contextUsed($)
664 showPanel($, {
665 status: [
666 `Continuity active · window ${state.window.windowNumber + 1} · ${notes} notes in this session`,
667 ...(compaction === 'blocked' ? ['Claude Code keeps plugins out of compaction here: new windows start from a short summary'] : []),
668 `Reminders at 85% and 90% of ${limit} tokens (${compactThreshold ? 'the auto-compact threshold' : 'the model window'})`,
669 `${sessions} sessions · ${records} fork records`,
670 ],
671 })
672}
673
674async function toggleNormalCompaction($: EngineInterface) {
675 normalCompaction = !normalCompaction
676 await $.store.set('settings', { normalCompaction })
677 showPanel($, { message: undefined })
678}
679
680/** A session this recently active stays: one that saves no transcript may still be running. */
681const PRUNE_GRACE_MS = 24 * 60 * 60 * 1000
682
683/**
684 * Removes stored sessions of this profile whose Claude Code transcript is gone, with their fork
685 * records and the subagent notes no remaining session names. The active session, recently active
686 * ones, other profiles' sessions and records a remaining fork restored from stay.
687 */
688async function prune($: EngineInterface): Promise<string> {
689 const base = await storageRoot($)
690 const projects = await transcriptsDir($)
691 if (!(await $.fs.exists(projects))) return `No Claude Code transcripts found at ${projects}. Nothing was pruned.`
692 const live = new Set([sessionId])
693 for (const project of await childNames($, projects, 'dir'))
694 for (const file of await childNames($, `${projects}/${project}`, 'file'))
695 if (file.endsWith('.jsonl')) live.add(file.slice(0, -'.jsonl'.length))
696 const now = await $.clock.now()
697 const removed = new Set<string>()
698 const kept: SessionState[] = []
699 let retained = 0
700 for (const id of await childNames($, `${base}/sessions`, 'dir')) {
701 const dir = `${base}/sessions/${id}`
702 const entries = await $.fs.list(dir)
703 const stateFile = entries.find((entry) => entry.name === 'state.json')
704 const state = stateFile ? (JSON.parse(await $.fs.read(`${dir}/state.json`)) as SessionState) : undefined
705 const recent = entries.some((entry) => now - entry.mtimeMs < PRUNE_GRACE_MS)
706 if (live.has(id) || !state || state.projects !== projects || recent) {
707 if (state) kept.push(state)
708 if (!live.has(id)) retained++
709 } else removed.add(id)
710 }
711 const keptAgents = new Set(kept.flatMap((state) => state.agents ?? []))
712 const keptRecords = new Set(kept.flatMap((state) => (state.restoredFrom ? [`${state.restoredFrom}.json`] : [])))
713 const records: string[] = []
714 for (const file of await childNames($, `${base}/revisions`, 'file')) {
715 if (keptRecords.has(file)) continue
716 const owner = (JSON.parse(await $.fs.read(`${base}/revisions/${file}`)) as Revision).session
717 if (owner && removed.has(owner)) records.push(`${base}/revisions/${file}`)
718 }
719 const agents = (await childNames($, `${base}/agents`, 'dir')).filter((id) => !keptAgents.has(agentName(id)))
720 const paths = [
721 ...[...removed].map((id) => `${base}/sessions/${id}`),
722 ...records,
723 ...agents.map((id) => `${base}/agents/${id}`),
724 ]
725 const retainedNote = retained
726 ? ` Retained ${retained} sessions without a transcript that are recent, from another profile or of unknown origin.`
727 : ''
728 if (!paths.length) return `Nothing to prune.${retainedNote}`
729 for (let i = 0; i < paths.length; i += 200) {
730 let run: { exitCode: number; stderr: string }
731 try {
732 run = await $.process.run(['rm', '-rf', ...paths.slice(i, i + 200)])
733 } catch (error) {
734 return `Prune needs the rm command, which could not run: ${message(error)}. Nothing further was removed.`
735 }
736 if (run.exitCode !== 0) return `Prune stopped: ${run.stderr.trim() || `rm exited ${run.exitCode}`}.`
737 }
738 return `Pruned ${removed.size} sessions, ${records.length} fork records and ${agents.length} subagent note sets.${retainedNote}`
739}
740
741async function confirmPrune($: EngineInterface) {
742 showPanel($, { confirmPrune: false, message: 'Pruning…' })
743 let outcome: string
744 try {
745 outcome = await prune($)
746 } catch (error) {
747 outcome = `Prune failed: ${message(error)}`
748 }
749 showPanel($, { message: outcome })
750 await refreshPanel($)
751}
752
753export const register: Register = (on) => {
754 // First registered is outermost: this wraps every tool's result, the plugin's own included.
755 on('tool.call', async ($, e, next) => {
756 const called = await next(e)
757 if (e.agentId === undefined && turn && e.tool_use_id) turn.lastCall = e.tool_use_id
758 return remind($, e.agentId, called)
759 })
760
761 on('session.start', async ($, e, next) => {
762 const started = await next(e)
763 const [settings, found] = await Promise.all([$.store.get('settings'), $.store.get('compaction')])
764 normalCompaction = (settings as { normalCompaction?: boolean } | undefined)?.normalCompaction === true
765 compaction = found as typeof compaction
766 for (const tool of TOOLS) await $.tool.register(tool)
767 await $.command.register({ name: 'notes', description: 'Notes continuity status and settings' })
768 return started
769 })
770
771 // A turn without tool calls gets its reminder with the prompt. Our own prompts are skipped:
772 // "Continue." arrives while usage still measures the old window, and the checkpoint prompt already asks for notes.
773 on('prompt.submit', async ($, e, next) => {
774 if (e.origin.kind === 'plugin' && e.origin.name === 'notes-compaction') return next(e)
775 // A slash command's text cannot be rewritten, so the marker waits for a plain prompt.
776 let prompt = e
777 if (!e.command) {
778 const { dir, state } = await session($)
779 if (state.unsentMarker) {
780 prompt = { ...e, text: `${state.unsentMarker}\n${e.text}` }
781 delete state.unsentMarker
782 await saveState($, dir, state)
783 }
784 }
785 // This runs before turn.start refreshes the threshold, which a resumed session has yet to read.
786 const reminder = await refreshThreshold($)
787 .then(() => dueReminder($, e.text.length))
788 .catch(() => undefined)
789 return next(reminder ? { ...prompt, context: [...(prompt.context ?? []), reminder] } : prompt)
790 })
791
792 // After new_context, the turn ends at its next model request, once the whole tool batch ran,
793 // as Pi's new_context ends the run; the rollover then follows the turn's completion.
794 // A note that failed this turn keeps the turn going, so the model sees the error; the rollover is then cancelled.
795 on('turn.step', async function* ($, e, next) {
796 if (e.agentId === undefined) batchChars = 0
797 if (e.agentId !== undefined || pending?.kind !== 'requested' || turn?.notes === 'failed') return yield* next(e)
798 const answer = 'Starting a new context window.'
799 yield { kind: 'text', index: 0, text: answer }
800 yield { kind: 'stop', stopReason: 'end_turn', usage: null }
801 return { turnId: e.turnId, index: e.index, answer, toolUses: [], stopReason: 'end_turn', usage: null }
802 })
803
804 // /clear ends this session in the same process, under a new ID.
805 on('session.end', async ($, e, next) => {
806 idleTimer?.cancel()
807 sessionId = loaded = turn = freshWindowId = pending = idleCheckpointWindowId = measured = idleTimer = undefined
808 return next(e)
809 })
810
811 on('turn.start', async ($, e, next) => {
812 // A subagent's turn completes without clearing turn, so only the main turn is tracked.
813 if (e.agentId === undefined) {
814 turn = { id: e.turnId, notes: 'none' }
815 idleTimer?.cancel()
816 }
817 // /config and /model can move the threshold between turns; the previous figure stands meanwhile.
818 refreshThreshold($).catch(() => undefined)
819 return next(e)
820 })
821
822 on('turn.complete', async ($, e, next) => {
823 const completed = await next(e)
824 if (e.agentId !== undefined) return completed
825 const ended = turn?.id === e.turnId ? turn : undefined
826 turn = undefined
827 const windowId = (await session($)).state.window.currentWindowId
828 const fresh = e.reason === 'answer' && ended?.notes === 'saved'
829 freshWindowId = fresh ? windowId : undefined
830 const was = pending
831 if (was?.kind === 'checkpoint') {
832 pending = undefined
833 if (e.isAborted || was.windowId !== windowId) $.ui.toast('Checkpoint cancelled. The old context remains.')
834 else if (fresh) roll($, was.opening)
835 else
836 $.ui.toast(
837 'Rollover did not start. No fresh note was saved in the completed checkpoint. The old context remains.',
838 )
839 } else if (was?.kind === 'requested') {
840 pending = undefined
841 if (e.isAborted) $.ui.toast('Rollover cancelled by the interruption. The old context remains.')
842 else if (ended?.notes === 'failed')
843 $.ui.toast('Rollover did not start: a note failed to save this turn. The old context remains.')
844 else roll($, 'continue')
845 }
846 armIdleRollover($)
847 return completed
848 })
849
850 on('session.compact', async ($, e, next) => {
851 if (e.agentId !== undefined) return next(e)
852 compactHookRan = true
853 idleTimer?.cancel()
854 if (compaction !== 'hooked') await setCompaction($, 'hooked')
855 if (e.trigger === 'precompute') return next(e)
856 if (pending?.kind === 'rolling') {
857 const { opening } = pending
858 pending.answered = true
859 if (!normalCompaction) return openWindow($, [], opening)
860 const compacted = await next(e)
861 return compacted.messages ? openWindow($, compacted.messages, opening) : compacted
862 }
863 // With normal compaction on, idle compaction is Claude Code's own, as in Pi. Otherwise it is handled as /compact
864 // (the command.run hook): the prompt cache is still warm, so a checkpoint turn costs about what its summary would.
865 if (e.trigger === 'auto' && turn === undefined && !normalCompaction) {
866 if (pending) return { skip: PENDING }
867 const windowId = (await session($)).state.window.currentWindowId
868 if (freshWindowId === windowId) return openWindow($, [], 'resume')
869 if (idleCheckpointWindowId !== windowId) {
870 idleCheckpointWindowId = windowId
871 checkpoint($, windowId, '', 'resume')
872 return { skip: CHECKPOINT_FIRST }
873 }
874 }
875 // Other compaction stays Claude Code's own; reminders and the idle checkpoint restart in the compacted context.
876 // The window's marker leads it again, so the window keeps its identity and history files the summary under it.
877 const compacted = await next(e)
878 if (!compacted.messages) return compacted
879 idleCheckpointWindowId = undefined
880 const { dir, state } = await session($)
881 state.reminded = []
882 await saveState($, dir, state)
883 const marker = windowText(ROOT, state.window, recentPaths(await readNotes($, rootNotesDir(dir)), ROOT), true)
884 return { ...compacted, messages: [{ role: 'user', text: marker, toolUses: [] }, ...compacted.messages] }
885 }).catch(async ($, e, next) => {
886 // A called next replays what it settled to: a rejection there is Claude Code's own compaction failing.
887 if (next.called)
888 try {
889 await next(e)
890 } catch (error) {
891 return { skip: `Claude Code's compaction failed: ${message(error)}. The existing context remains.` }
892 }
893 return { skip: ROLLOVER_FAILED }
894 })
895
896 on('tool.call', { tool: 'mcp__notes-compaction__notes' }, ($, e) => callNotes($, e))
897
898 on('tool.call', { tool: 'mcp__notes-compaction__history' }, ($, e) => callHistory($, e))
899
900 on('tool.call', { tool: 'mcp__notes-compaction__new_context' }, async ($, e) => {
901 if (e.agentId !== undefined) return { deny: 'Only the main conversation can start a new context window.' }
902 if (pending)
903 return result({
904 started: false,
905 message: 'A checkpoint or rollover is already pending. Save notes and finish your response',
906 })
907 // A write earlier in the batch may still be saving.
908 await notesQueue
909 if (!turn?.savedNote || turn.lastCall !== turn.savedNote) return { deny: NOTE_FIRST }
910 pending = { kind: 'requested' }
911 return result({
912 started: true,
913 message: normalCompaction
914 ? 'Normal compaction will run before the new window opens'
915 : 'A new window will continue from your notes after this turn',
916 })
917 })
918
919 // /compact is decided here, before compaction, since Claude Code may keep plugins out of session.compact. With
920 // normal compaction on it is Claude Code's own, as in Pi. The rollover's own /compact, run by this plugin, skips this hook.
921 on('command.run', { command: 'compact' }, async ($, e, next) => {
922 if (normalCompaction) return next(e)
923 if (pending) return { text: PENDING }
924 const windowId = (await session($)).state.window.currentWindowId
925 const instructions = e.args.trim()
926 if (!instructions && freshWindowId === windowId) {
927 roll($, 'wait')
928 return { text: 'Opening a new window from your notes.' }
929 }
930 checkpoint($, windowId, instructions ? `\n\nCheckpoint guidance:\n${instructions}` : '', 'wait')
931 return { text: CHECKPOINT_FIRST }
932 }).catch(() => ({ text: ROLLOVER_FAILED }))
933
934 on('command.run', { command: 'notes' }, async ($, e) => {
935 if (e.args.trim()) return { text: 'Use /notes to open the notes panel.' }
936 showPanel($, { confirmPrune: false, message: undefined })
937 await refreshPanel($)
938 await $.ui.open({ id: PANE, title: 'Notes continuity' })
939 return { text: 'Notes panel opened.' }
940 })
941
942 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
943 const { Box, Text, Button } = $.ui.resolve(e)
944 const prune = panel.confirmPrune
945 ? h(
946 Box,
947 { flexDirection: 'row', gap: 1 },
948 h(
949 Button,
950 { key: 'confirm', hotkey: 'y', variant: 'primary', onPress: () => void confirmPrune($) },
951 'Confirm prune',
952 ),
953 h(Button, { key: 'cancel', hotkey: 'c', onPress: () => showPanel($, { confirmPrune: false }) }, 'Cancel'),
954 )
955 : h(
956 Button,
957 { key: 'prune', hotkey: 'p', onPress: () => showPanel($, { confirmPrune: true, message: undefined }) },
958 'Prune missing sessions',
959 )
960 return h(
961 Box,
962 { flexDirection: 'column' },
963 ...panel.status.map((line) => h(Text, null, line)),
964 h(
965 Button,
966 { key: 'normal', hotkey: 'n', onPress: () => void toggleNormalCompaction($) },
967 `Normal compaction before new windows: ${normalCompaction ? 'on' : 'off'}`,
968 ),
969 prune,
970 panel.confirmPrune &&
971 h(Text, { dimColor: true }, 'Removes stored notes of sessions whose Claude Code transcript no longer exists.'),
972 panel.message && h(Text, { dimColor: true }, panel.message),
973 h(Button, { key: 'close', hotkey: 'x', role: 'dismiss', onPress: () => void $.ui.close({ id: PANE }) }, 'Close'),
974 ) as RenderElement
975 })
976
977 on('tool.call', { tool: 'mcp__notes-compaction__get_context_remaining' }, async ($, e) => {
978 if (e.agentId !== undefined) return { deny: 'Context usage is reported for the main conversation only.' }
979 const { state } = await session($)
980 const { limit, tokens } = await contextUsed($)
981 const remainingTokens = typeof tokens === 'number' && limit > 0 ? Math.max(0, limit - tokens) : null
982 return result({
983 contextWindow: limit,
984 windowId: state.window.currentWindowId,
985 remainingTokens,
986 remainingPercent: remainingTokens === null ? null : Math.round((remainingTokens / limit) * 1000) / 10,
987 })
988 })
989}
990hooks/history.ts 151 lines1import type { SessionMessage } from 'claude-code'
2import { integer } from './notes.ts'
3import { promptAfterMarker, windowMarker } from './windows.ts'
4
5interface HistoryItem {
6 window_id: string
7 item_id: string
8 role: 'user' | 'assistant' | 'tool'
9 tool_name?: string
10 content: string
11}
12
13/** Characters one read or listing answers with. */
14const RESULT_LIMIT = 8000
15
16/** FNV-1a: a short, synchronous content key. */
17function hash(text: string): string {
18 let h = 0x811c9dc5
19 for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 0x01000193)
20 return (h >>> 0).toString(16).padStart(8, '0')
21}
22
23/** $.session.messages() answers the newest 4096 messages; past that, positions shift and old rows drop. */
24export const MESSAGE_LIMIT = 4096
25
26/**
27 * The session's own transcript is the archive: compaction replaces what the model reads,
28 * not what $.session.messages() returns. Item IDs survive the sliding message limit:
29 * tool use IDs where a row has one, otherwise a content key.
30 */
31export function useHistory(
32 messages: readonly SessionMessage[],
33 params: Record<string, unknown>,
34 currentWindowId: string,
35): Record<string, unknown> {
36 const coverage =
37 messages.length >= MESSAGE_LIMIT ? { coverage: `Newest ${MESSAGE_LIMIT} messages only; older rows are unavailable` } : {}
38 return { ...answer(messages, params, currentWindowId), ...coverage }
39}
40
41function answer(
42 messages: readonly SessionMessage[],
43 params: Record<string, unknown>,
44 currentWindowId: string,
45): Record<string, unknown> {
46 // Duplicate content is numbered within its window, so one window's rows never renumber another's.
47 const seen = new Map<string, number>()
48 const stableId = (key: string) => {
49 const n = seen.get(`${windowId}:${key}`) ?? 0
50 seen.set(`${windowId}:${key}`, n + 1)
51 return n ? `${key}~${n}` : key
52 }
53 // Rows before the first boundary in view belong to the window it names as previous, or to its own window when it
54 // only repeats that window's marker after Claude Code's compaction; with no boundary in view, every row belongs to
55 // the current window.
56 const markers = messages.map(windowMarker)
57 const first = markers.find((marker) => marker !== undefined)
58 let windowId = first ? (first.repeated ? first.current : (first.previous ?? currentWindowId)) : currentWindowId
59 const windows = new Map<string, HistoryItem[]>([[windowId, []]])
60 const toolNames = new Map<string, string>()
61 for (const [index, message] of messages.entries()) {
62 const boundary = markers[index]
63 if (boundary) {
64 windowId = boundary.current
65 if (!windows.has(windowId)) windows.set(windowId, [])
66 // A window that waited for the user carries its marker on their next prompt.
67 const prompt = promptAfterMarker(message.text)
68 if (prompt)
69 windows.get(windowId)!.push({ window_id: windowId, item_id: stableId(`u-${hash(prompt)}`), role: 'user', content: prompt })
70 continue
71 }
72 const items = windows.get(windowId)!
73 if (message.role === 'assistant') {
74 for (const use of message.toolUses) toolNames.set(use.tool_use_id, use.tool)
75 const calls = message.toolUses.map((use) => JSON.stringify({ tool: use.tool, arguments: use.input }))
76 const content = [message.text, ...calls].filter(Boolean).join('\n')
77 items.push({
78 window_id: windowId,
79 item_id: stableId(message.toolUses[0] ? `call-${message.toolUses[0].tool_use_id}` : `a-${hash(content)}`),
80 role: 'assistant',
81 ...(message.toolUses[0] ? { tool_name: message.toolUses[0].tool } : {}),
82 content,
83 })
84 continue
85 }
86 if (message.text)
87 items.push({ window_id: windowId, item_id: stableId(`u-${hash(message.text)}`), role: 'user', content: message.text })
88 for (const result of message.toolResults ?? []) {
89 const tool = toolNames.get(result.tool_use_id)
90 items.push({
91 window_id: windowId,
92 item_id: stableId(`result-${result.tool_use_id}`),
93 role: 'tool',
94 ...(tool ? { tool_name: tool } : {}),
95 content: result.text,
96 })
97 }
98 }
99
100 const action = params['action']
101 if (action === 'list_windows') {
102 let values = [...windows].filter(([, items]) => items.length)
103 if (params['recent_first'] === true) values = values.reverse()
104 const limit = integer(params['limit'], 20, 100)
105 return {
106 windows: values.slice(0, limit).map(([id, items]) => ({ window_id: id, item_count: items.length })),
107 truncated: values.length > limit,
108 }
109 }
110 if (action === 'read_item') {
111 const item = windows.get(String(params['window_id']))?.find((item) => item.item_id === params['item_id'])
112 if (!item) return { item: null }
113 const offset = integer(params['offset_chars'], 0, item.content.length, 0)
114 const limit = integer(params['limit_chars'], RESULT_LIMIT, RESULT_LIMIT)
115 const content = item.content.slice(offset, offset + limit)
116 return {
117 item: {
118 ...item,
119 content,
120 total_chars: item.content.length,
121 ...(offset + content.length < item.content.length ? { next_offset_chars: offset + content.length } : {}),
122 },
123 }
124 }
125 // list_items or search_contents
126 const query = String(params['query'])
127 let items = [...windows.values()]
128 .flat()
129 .filter(
130 (item) =>
131 (!params['window_id'] || item.window_id === params['window_id']) &&
132 (!params['role'] || item.role === params['role']) &&
133 (!params['tool_name'] || item.tool_name === params['tool_name']) &&
134 (action !== 'search_contents' || item.content.includes(query)),
135 )
136 if (params['recent_first'] === true) items = items.reverse()
137 const limit = integer(params['limit'], 10, 25)
138 const previewChars = integer(params['max_chars_per_item'], 1000, 1000)
139 const previews = []
140 let size = 0
141 for (const item of items) {
142 const { content, ...metadata } = item
143 const preview = { ...metadata, truncated_content: content.slice(0, previewChars), content_chars: content.length }
144 const chars = JSON.stringify(preview).length
145 if (previews.length >= limit || size + chars > RESULT_LIMIT) break
146 previews.push(preview)
147 size += chars
148 }
149 return { items: previews, truncated: previews.length < items.length }
150}
151hooks/notes.ts 174 lines1export interface Note {
2 path: string
3 text: string
4 createdAt: number
5 updatedAt: number
6}
7
8/** The main conversation's agent name; a subagent is `/root/<agentId>`. */
9export const ROOT = '/root'
10const AGENT_ID = '[A-Za-z0-9_-]+'
11
12export const WRITE_ACTIONS: readonly unknown[] = ['write_file', 'append_to_file']
13
14export function agentName(agentId: string | undefined): string {
15 return agentId === undefined ? ROOT : `${ROOT}/${agentId}`
16}
17
18/** agentName's inverse: undefined for root, the subagent's ID otherwise. */
19export function agentIdOf(name: string): string | undefined {
20 if (name === ROOT) return undefined
21 const id = name.slice(ROOT.length + 1)
22 if (!name.startsWith(`${ROOT}/`) || !new RegExp(`^${AGENT_ID}$`).test(id))
23 throw new Error(`Name agents as note paths do: ${ROOT} or ${ROOT}/<agentId>.`)
24 return id
25}
26
27export const notesPrefix = (agent: string) => `${agent}/notes/`
28
29/** Hashed file names keep long virtual paths inside file-name limits. */
30export async function noteFileName(path: string): Promise<string> {
31 const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(path))
32 return `${[...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, '0')).join('')}.json`
33}
34
35export function recentPaths(notes: ReadonlyMap<string, Note>, agent: string): string[] {
36 return [...notes.values()]
37 .sort((a, b) => b.updatedAt - a.updatedAt)
38 .slice(0, 5)
39 .map((note) => notesPrefix(agent) + note.path)
40}
41
42/**
43 * Virtual paths: relative belongs to the calling agent; `<agent>/notes[/path]` names any agent
44 * of this session. Root wins the ambiguity, so `/root/notes/notes/x` is root's `notes/x`.
45 */
46export function resolvePath(path: unknown, self: string, required: boolean): { agent: string; path: string } {
47 if (typeof path !== 'string' || !path.trim()) {
48 if (required) throw new Error('Supply a note path')
49 return { agent: self, path: '' }
50 }
51 let agent = self
52 let value = path
53 if (path.startsWith('/')) {
54 const match = new RegExp(`^(${ROOT}(?:/${AGENT_ID})??)/notes(?:/(.*))?$`).exec(path)
55 if (!match) throw new Error("Use a relative path for your own notes, or <agent>/notes/<path> for another agent's")
56 agent = match[1]!
57 value = match[2] ?? ''
58 }
59 if (
60 (required && !value) ||
61 value.split('/').some((part) => part === '..' || part === '.') ||
62 /[\0\r\n]/.test(value)
63 )
64 throw new Error('Use a virtual note path without dot segments or control characters')
65 return { agent, path: value }
66}
67
68export function integer(value: unknown, fallback: number, max: number, min = 1): number {
69 return typeof value === 'number' && Number.isInteger(value) ? Math.max(min, Math.min(value, max)) : fallback
70}
71
72/** Characters one read or search answers with. */
73const RESULT_LIMIT = 32_000
74
75/**
76 * Runs one action on one agent's notes. Required fields are present (the caller checks them) and
77 * path fields arrive resolved relative to `agent`, whose `<agent>/notes/` prefixes every path shown.
78 * Returns the action's JSON payload, and for a write the note the caller must persist.
79 */
80export function useNotes(
81 notes: ReadonlyMap<string, Note>,
82 params: Record<string, unknown>,
83 now: number,
84 agent: string,
85): { payload: Record<string, unknown>; write?: Note } {
86 const root = notesPrefix(agent)
87 const action = params['action']
88 if (WRITE_ACTIONS.includes(action)) {
89 const path = String(params['path'])
90 const previous = notes.get(path)
91 const next = action === 'append_to_file' ? (previous?.text ?? '') + String(params['text']) : String(params['text'])
92 if (new TextEncoder().encode(next).length > 1_000_000)
93 throw new Error('Note exceeds 1 MB. Split it into separate paths.')
94 return {
95 payload: { path: root + path },
96 write: { path, text: next, createdAt: previous?.createdAt ?? now, updatedAt: now },
97 }
98 }
99 if (action === 'read_file') {
100 const path = String(params['path'])
101 const note = notes.get(path)
102 if (!note) return { payload: { path: root + path, file: null } }
103 const lines = note.text.split('\n')
104 const start = integer(params['start_line'], 1, lines.length + 1)
105 const stop = integer(params['stop_line'], lines.length, lines.length)
106 let text = ''
107 let next = start
108 while (next <= stop) {
109 const line = lines[next - 1] ?? ''
110 if (text.length + line.length > RESULT_LIMIT) {
111 if (!text)
112 throw new Error(`This note line exceeds ${RESULT_LIMIT} characters. Rewrite it as shorter lines to read it.`)
113 break
114 }
115 text += `${next > start ? '\n' : ''}${line}`
116 next++
117 }
118 return {
119 payload: {
120 path: root + path,
121 text,
122 start_line: start,
123 total_lines: lines.length,
124 ...(next <= stop ? { next_start_line: next } : {}),
125 },
126 }
127 }
128 if (action === 'list_files_by_prefix') {
129 const prefix = String(params['prefix'] ?? '')
130 const files = [...notes.values()].filter((note) => note.path.startsWith(prefix))
131 const by = params['file_order_by']
132 files.sort((a, b) =>
133 by === 'created_at'
134 ? a.createdAt - b.createdAt
135 : by === 'updated_at'
136 ? a.updatedAt - b.updatedAt
137 : a.path.localeCompare(b.path),
138 )
139 if (params['file_order'] === 'descending') files.reverse()
140 const maximum = integer(params['max_results'], 100, 100)
141 return {
142 payload: {
143 files: files
144 .slice(0, maximum)
145 .map((note) => ({ path: root + note.path, chars: note.text.length, updated_at: note.updatedAt })),
146 truncated: files.length > maximum,
147 },
148 }
149 }
150 // search_contents
151 const query = String(params['query'])
152 const prefix = String(params['path_prefix'] ?? '')
153 const files = [...notes.values()].filter((note) => note.path.startsWith(prefix))
154 if (params['recent_file_first'] === true) files.sort((a, b) => b.updatedAt - a.updatedAt)
155 const found: { path: string; matches: { line: number; text: string }[]; truncated: boolean }[] = []
156 let chars = 0
157 let truncated = false
158 for (const note of files) {
159 const all = note.text
160 .split('\n')
161 .flatMap((line, i) => (line.includes(query) ? [{ line: i + 1, text: line.slice(0, 1000) }] : []))
162 if (!all.length) continue
163 const matches = all.slice(0, integer(params['max_matches_per_file'], 10, 100))
164 const size = JSON.stringify(matches).length
165 if (found.length >= integer(params['max_files'], 20, 100) || chars + size > RESULT_LIMIT) {
166 truncated = true
167 break
168 }
169 found.push({ path: root + note.path, matches, truncated: matches.length < all.length })
170 chars += size
171 }
172 return { payload: { files: found, truncated } }
173}
174hooks/windows.ts 116 lines1export interface WindowIdentity {
2 firstWindowId: string
3 currentWindowId: string
4 previousWindowId?: string
5 windowNumber: number
6}
7export interface SessionState {
8 window: WindowIdentity
9 /** `<windowId>:reminder` and `<windowId>:urgent`, each sent once per window. */
10 reminded: string[]
11 /** Subagents that wrote notes in this session or that its transcript launched, kept beyond the sliding view. */
12 agents?: string[]
13 /** The Claude Code transcripts folder this session belongs to; prune judges only its own profile's sessions. */
14 projects?: string
15 /** The fork record this session was restored from, which prune keeps while the session stays. */
16 restoredFrom?: string
17 /**
18 * The marker of a window opened from Claude Code's summary that waits for the user (/compact). It leads their next
19 * plain prompt, the one message that can carry it there, and is kept here so a resumed session still delivers it.
20 */
21 unsentMarker?: string
22}
23
24export const GUIDANCE = `<context_window_guidance>
25Notes are recovery state, not a diary. Keep one concise, authoritative note per task or topic at a stable notes path. Task checkpoints cover request, constraints, decisions, status and how it was verified, next steps and identifiers needed to act (history IDs too). Use write_file to replace stale state and mark completion. Link to existing notes instead of copying or summarising their contents. Recording isn't permission to implement.
26
27Batch saves at meaningful milestones, not every reply or intermediate step. Before new_context or handoff, save current state and wait for success; include the checkpoint path in handoffs. After rollover, read the checkpoint, then only needed links, and read again the skills the current task needs: earlier skill reads don't carry into a new window. Don't reread notes still in context unless they may have changed. Use history for missing details.
28</context_window_guidance>`
29
30const WINDOW_OPEN = '<context_window>'
31const WINDOW_CLOSE = '</context_window>'
32/**
33 * How a new window starts. `continue` follows new_context, called mid-task. `resume` follows idle compaction: the
34 * agent ended its last turn, perhaps short of the user's request. `wait` follows /compact typed by the user.
35 */
36export type Opening = 'continue' | 'resume' | 'wait'
37/** The prompt that starts each window that does not wait. */
38export const OPENING_PROMPTS: Readonly<Record<Exclude<Opening, 'wait'>, string>> = {
39 continue: 'Continue.',
40 resume:
41 "Read your checkpoint. If the user's latest request is unfinished and needs nothing more from them, continue it. Otherwise reply in one line with what you are waiting for.",
42}
43const FIRST = 'First context window id: '
44const CURRENT = 'Current context window id: '
45const PREVIOUS = 'Previous context window id: '
46/** Marks a window's marker repeated after Claude Code's own compaction, as opposed to a window boundary. */
47const RECOVERY = 'If no checkpoint is available, use history to recover missing context.'
48
49export function newState(): SessionState {
50 const id = crypto.randomUUID()
51 return { window: { firstWindowId: id, currentWindowId: id, windowNumber: 0 }, reminded: [] }
52}
53
54export function nextWindow(current: WindowIdentity): WindowIdentity {
55 return {
56 firstWindowId: current.firstWindowId,
57 currentWindowId: crypto.randomUUID(),
58 previousWindowId: current.currentWindowId,
59 windowNumber: current.windowNumber + 1,
60 }
61}
62
63/** `repeated` is the marker put back after Claude Code compacted the window on its own: it adds where to look when no checkpoint covers the work. */
64export function windowText(agent: string, ids: WindowIdentity, recentNotes: readonly string[], repeated = false): string {
65 const lines = [`Agent name: ${agent}`, `${FIRST}${ids.firstWindowId}`, `${CURRENT}${ids.currentWindowId}`]
66 if (ids.previousWindowId) lines.push(`${PREVIOUS}${ids.previousWindowId}`)
67 if (recentNotes.length) lines.push(`Recent notes (read them with the notes tool): ${recentNotes.join(', ')}`)
68 if (repeated) lines.push(RECOVERY)
69 return `${WINDOW_OPEN}\n${lines.join('\n')}\n${WINDOW_CLOSE}`
70}
71
72/** A marker message's own prompt after the marker, if any besides the plugin's own opening prompt. */
73export function promptAfterMarker(text: string): string | undefined {
74 const end = text.indexOf(WINDOW_CLOSE)
75 const rest = end < 0 ? '' : text.slice(end + WINDOW_CLOSE.length).trim()
76 return rest && !Object.values(OPENING_PROMPTS).includes(rest) ? rest : undefined
77}
78
79/** The window boundary windowText wrote, read back from a transcript message: on its first or second line. */
80export function windowMarker(message: {
81 role: string
82 text: string
83}): { first?: string; current: string; previous?: string; repeated?: true } | undefined {
84 if (message.role !== 'user') return
85 const { text } = message
86 const open = `${WINDOW_OPEN}\n`
87 const start = text.startsWith(open) ? 0 : text.indexOf('\n') + 1
88 if (!text.startsWith(open, start)) return
89 const lines = text.slice(start).split('\n')
90 const field = (prefix: string) =>
91 lines
92 .find((line) => line.startsWith(prefix))
93 ?.slice(prefix.length)
94 .trim()
95 const current = field(CURRENT)
96 if (!current) return
97 return { first: field(FIRST), current, previous: field(PREVIOUS), ...(lines.includes(RECOVERY) ? { repeated: true as const } : {}) }
98}
99
100/** Both reminders went out in this window: nothing left to measure for. */
101export function remindersDone(state: SessionState): boolean {
102 return state.reminded.includes(`${state.window.currentWindowId}:urgent`)
103}
104
105export function reminderFor(state: SessionState, percentUsed: number | undefined): string | undefined {
106 if (percentUsed === undefined) return
107 const kind = percentUsed >= 90 ? 'urgent' : percentUsed >= 85 ? 'reminder' : undefined
108 const id = state.window.currentWindowId
109 if (!kind || state.reminded.includes(`${id}:${kind}`)) return
110 state.reminded.push(`${id}:reminder`)
111 if (kind === 'urgent') state.reminded.push(`${id}:urgent`)
112 // Estimates lean early and can pass the limit.
113 const remaining = Math.max(0, Math.round((100 - percentUsed) * 10) / 10)
114 return `<context_window_reminder>\n${kind === 'urgent' ? 'Urgent: ' : ''}${remaining}% context remaining. Save the task state in notes, then call new_context ${kind === 'urgent' ? 'now, before other work' : 'before continuing work'}.\n</context_window_reminder>`
115}
116