SLOPSHOPPER

changes

See what Claude changed, turn by turn. Keep it or send it back. A per-turn timeline with each file's diff and keep/revert.

panebandspinnerguardcommandtoast
★ 1v0.2.2MITupdated 2026-10-25candygoogy/notary/plugins/changes
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · changes
│ ┃ Changes ✕ › fix the failing auth test and add an audit log call │ ┃ Claude ran shell commands, and this folder │ ┃ isn't a git repository, so Changes can't see ● changes: changes: save failed: undefined is not an object (evaluati │ ┃ what they changed. Edits made with Edit and ⏺ Read(src/auth.ts) │ ┃ Write still show. To track shell changes ⎿ Read 6 lines │ ┃ too, run git init here and start a new ⏺ Update(src/auth.ts) │ ┃ session. This conversation is also open in ⎿ Added 2 lines, removed 1 line │ ┃ another Claude Code window. Its history ⏺ Bash(bun test) │ ┃ shows here, but changes made here are not ⎿ 3 pass, 1 fail │ ┃ saved to it. │ ┃ ── Earlier · Jan 1, 00:00 ── ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ▾ background agent main · 3 files │ ┃ ● all steps ✻ Worked for 42s · done 4:20 PM │ ┃ ○ Edit · 1 file │ ┃ ○ Write · 1 file › /changes │ ┃ ○ Write · 1 file ⎿ changes: Changes pane opened. │ ┃ • src/auth.ts [ Keep ] [ Revert ] │ ┃ loading diff… │ ┃ │ ┃ • src/audit.ts │ ┃ no net change │ ┃ loading diff… │ ┃ │ ┃ • src/cache.ts │ ┃ no net change │ ┃ loading diff… ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Changes
Claude ran shell commands, and this folder isn't a git repository, so Changes can't see what they changed. Edits made with Edit and Write still show. To track shell changes too, run git init here and start a new session. This conversation is also open in another Claude Code window. Its history shows here, but changes made here are not saved to it. ── Earlier · Jan 1, 00:00 ── ▾ background agent main · 3 files ● all steps ○ Edit · 1 file ○ Write · 1 file ○ Write · 1 file • src/auth.ts [ Keep ] [ Revert ] loading diff… • src/audit.ts no net change loading diff… • src/cache.ts no net change loading diff…
README

Changes

See what Claude changed, turn by turn. Keep it or send it back.

A Claude Code mod with one pane, Changes. It shows what Claude changed in each turn of the session, including through subagents and shell commands, with a diff per file and Keep / Revert per file. This page is the reference. For the suite, see the Notary README.

/plugin install changes --marketplace candygoogy/notary

Needs Claude Code 2.1.287 or later; on an older version, Changes shows one notice and stays off. Git is optional. Inside a git repository, Changes also finds files that shell commands changed.

The Changes pane

/changes opens the pane. In the fullscreen layout it docks beside the transcript; otherwise it opens inline. If the window is too narrow for it, the pane waits, and /changes or the band's Open says so and why, once.

  • Timeline, newest turn first. Each row is a turn: its number, its prompt and how many files it changed. Selecting a turn expands its steps:
  • the tool calls that changed files;
  • the subagents it started, with their own calls;
  • changed during this turn (shell or you) for changes no tool call explains.

Select a step to see only its files, or all steps for the whole turn.

  • Diffs, one per file, with the lines added and removed, and Keep and Revert buttons. Notes appear where they apply:
  • line endings only;
  • binary file;
  • too large to show;
  • edited by two agents at once;
  • changed outside Claude between edits; reverting this turn also undoes that.

Edits made between turns are yours. They aren't listed, and the pane doesn't undo them.

After a turn that changed code, a line above the prompt says Turn #12 changed 3 files [Open] [Dismiss]. Open shows only while the pane is shut. The line goes away at your next prompt, or right away with Dismiss, and comes back after the next turn that changes code. Turns that only touched docs, notes, logs, lockfiles or build folders don't show it. Those changes are still listed in the pane.

Keep and Revert

Keep marks a file's change as reviewed and folds it away. Undo keep brings it back. Nothing on disk changes.

Revert puts the file back the way it was before that turn. It takes two presses:

  1. The first press checks the file as it is now and writes nothing.
  2. If the revert can go ahead, the button becomes Confirm revert (#12) for 5 seconds. It names every turn the revert covers. Press it to revert. A confirmation pressed too late does nothing and says so.

Changes only writes when the file on disk is exactly what Claude left. After writing, it reads the file back to make sure. When it can't be sure, it refuses and says why:

You seeWhat it meansWhat you can do
was also changed by #14. Revert those turns together, or none.A later (or, through a subagent, earlier) turn changed the same file.Revert with #14 reverts both turns' changes to the file.
was changed outside Claude between #12 and #14Something else changed the file between Claude's edits, maybe you.Revert anyway also undoes that change.
Can't confirm nothing else changed it between #12 and #14The file was committed in between, so its versions can't be compared.Revert anyway.
The history … was trimmedThe session is long, and older edits to the file are no longer kept.Revert anyway also undoes what's no longer listed.
changed since Claude's last edit, so it was left aloneThe file on disk isn't what Claude left.Nothing to override: look at the file and decide yourself.
is too large to restore / There is no saved copyNo snapshot from before that turn (over 4 MiB, or unreadable).Restore it with git or by hand.

After a revert, Claude gets a short hidden note, for example "The user reverted src/a.ts to its state before turn #12 using the Changes pane. Re-read the file before editing it." Without it, Claude's next edit to that file would fail on text that's no longer there. The tellClaude setting turns the note off.

A revert is recorded too, as a row in the timeline. A later revert of the same file builds on it, so the history stays honest.

Revert a whole turn

Under the selected turn, Revert all (#12) reverts every file that turn changed and you haven't reverted or kept. It takes two presses too:

  1. The first press checks every file as it is now and writes nothing. If a file can't be reverted, the pane says which one and why, with the same words as the table above.
  2. The button becomes Confirm revert all (#12): write 3, skip 1 for 5 seconds. Press it to revert the files that can be.

A file that can't be reverted is skipped and never forced: Revert all has no "anyway". Where the table above offers a way on (Revert with #14, Revert anyway), that button appears on the file's own row afterwards, for that file alone. Kept files are left alone and listed as kept.

Each file is written and checked as a single revert is, and recorded before the next one. If a write can't be confirmed (a full or locked disk, say), Revert all stops there and leaves the remaining files untouched, saying which file to check. The files already reverted stay reverted and recorded.

Claude gets one hidden note listing every file reverted, not one per file.

Settings

SettingDefaultWhat it does
enabledonTurn Changes on or off.
bandonThe line above the prompt after a turn that changed code.
autoOpenoffOpen the pane by itself, once, when the first turn with code changes ends: only in the fullscreen layout, where it docks beside the transcript, and on a terminal at least 144 columns wide.
tellClaudeonThe hidden note to Claude after a revert.
trackShellonIn a git repository, find the files Bash and PowerShell commands changed.
keepHistoryDays7How many days a conversation's copies and history are kept after you last used it, so a resumed conversation can still revert. 0 deletes them at the end of each session.

Change them in the /config menu.

Resumed conversations

Resume a conversation (claude --resume, claude --continue or /resume) and the pane shows its earlier turns again, under a line Earlier · Oct 12, 14:05. Turn numbers carry on from where the conversation was, and Keep and Revert work as before.

A file that changed while no session was watching (you edited it, another conversation's Claude did, you switched branches) is not reverted: Changes only writes when the file is exactly what Claude left, the same check as always. A copy that is no longer on disk is refused before anything is written.

/clear starts a new conversation, so the pane starts empty. The old conversation's history is kept and comes back if you resume it.

If the same conversation is open in two Claude Code windows, the second shows the history but doesn't save to it, and says so. A window that crashed gives up its claim after 10 minutes.

How it works

  • Claude's own edits (Edit, Write, NotebookEdit, in the main conversation or any subagent): Changes reads the file right before and right after each one, and saves a copy.
  • Subagents belong to the turn that started them, even when they keep working after that turn ends.
  • Shell commands (inside a git repository only): Changes compares git status, and the files it lists, before and after each command.
  • Copies of files are stored once per content, under ~/.claude/plugin-data/notary-changes/<conversation>/, with the conversation's history in index.json beside them. They're kept for keepHistoryDays after the conversation was last used (see Privacy).

How it differs from /diff

Claude Code's built-in /diff shows the working tree's git diff. Changes is per turn and can undo:

  • It has Revert, with the checks above.
  • It shows the contents of new files, not just their names.
  • It sees subagent edits, and attributes them to the turn that started the subagent.
  • Outside git, it still tracks Claude's own edits. Only shell tracking needs git.

Limits

  • History is kept for keepHistoryDays. A new session and /clear start an empty pane. A resumed conversation brings its earlier turns back (see Resumed conversations). After keepHistoryDays (7 by default), or sooner if all kept conversations pass 1 GB, a conversation's history is deleted and its turns can't be reverted from the pane. Your files are untouched.
  • Per file, not per change. Revert puts the whole file back to before the turn. You can't keep one hunk and revert another.
  • Shell changes only in git. Outside a git repository, and in gitignored files, changes made by shell commands aren't seen. Outside git, once Claude runs a shell command, the pane says so, and that git init (then a new session) makes them tracked.
  • A rename shows as a delete plus a new file.
  • A large file (over 1 MB) rewritten with the same size and timestamp can be missed.
  • Tracking a command never adds more than about 2 seconds to it. A command that changes more than 200 files, a checkout, reset, pull or commit, or a repository with more than 200 uncommitted files is shown as not tracked, with the reason, instead of being slowed down.
  • If git is too slow to answer in time, shell tracking turns off for the rest of the session, and the pane says so.
  • Reverts are yours, not Claude's. A revert from the pane happens outside Claude's tool calls, so other mods that watch Claude's edits (Receipts, for one) don't count it as an edit. Claude is told about it with a hidden note.
  • Your edits during a turn. If you edit a file in your editor while Claude is working, the change can appear as changed during this turn (shell or you).
  • No merging. If a file changed after Claude's edit, Revert refuses rather than guess.
  • Large files. Files over 4 MiB can only be reverted if they were clean in git before the turn.
  • Folders. Reverting a new file deletes the file, not the folders Claude created for it.
  • Long sessions. The timeline keeps the last 200 turns and 5,000 edits. Older turns can't be reverted.
  • Big diffs. A diff shows 400 lines, then Show all. A file whose diff is over 1 MB isn't drawn. Up to 12 files are drawn at once; select a step to narrow the list.
  • Desktop app. The first click on an unfocused pane may only focus it. Selecting a turn or a step works on that first click, but Keep, Revert and Confirm always need a real click, so a stray focus never changes a file.

Privacy

Changes runs entirely on your machine. It makes no network requests, collects no telemetry, and makes no model calls. Nothing it keeps leaves your machine.

What it keeps, and where. A copy of each file Claude changed, from before and after each change, and the conversation's history of those changes, in ~/.claude/plugin-data/notary-changes/<conversation>/ (under CLAUDE_CONFIG_DIR if you set it). The copies are of whatever Claude changed, so they can include secrets, such as a .env file Claude edited.

For how long. 7 days after you last used the conversation, so that a resumed conversation (claude --resume, --continue, /resume) can still show and revert its changes. Older ones are deleted the next time Changes starts, and all kept conversations together are held under 1 GB, oldest deleted first.

How to keep less.

  • /changes forget deletes the current conversation's copies and history now.
  • Set keepHistoryDays to 0 in /config to delete them at the end of every session, as Changes did before 0.2. Copies left by a crash are then deleted after 7 days.
Source 26 files
hooks/register.tsx 1200 lines
1import type { EngineInterface as Engine, Hook, MatchedHook, Register, Timer } from 'claude-code'
2import { update } from 'claude-code'
3
4import { emptyIndex, statusKey, type Content, type Index } from './core/model.ts'
5import { isCodePath } from './core/noise.ts'
6import { relativeTo, shownPath } from './core/paths.ts'
7import { unexplained } from './core/sweep.ts'
8import type { RevertPlan, RevertRef } from './core/revert-plan.ts'
9import {
10  addAction,
11  addEdit,
12  addUntracked,
13  appendedSize,
14  closeAgent,
15  closeTurn,
16  fitToSize,
17  linkAgent,
18  openTurn,
19  recordRevert,
20  setStatus,
21  STATE_BUDGET_CHARS,
22  timeline,
23  turnFiles,
24  type FileChange,
25  type TimelineRow,
26} from './core/timeline.ts'
27import { capture, keyOf, storeDirOf, type StoreBudget } from './io/blobs.ts'
28import { diffOf, type DiffView } from './io/diffs.ts'
29import { holdsLease, LEASE_RENEW_MS, loadHistory, releaseLease, renewLease, saveHistory, takeLease } from './io/history.ts'
30import { cleanBlobOf, gitBudget, repoRootOf } from './io/git.ts'
31import { platformOf, type Ports } from './io/ports.ts'
32import { planFile, planTurn, revertFile, revertTurn, type RevertOutcome, type TurnFile } from './io/restore.ts'
33import { waitingNote } from './shared/pane.ts'
34import { shellAfter, shellBefore, type ShellToken, type SnapshotCache } from './io/shell.ts'
35import { DAY_MS, overTotalCap, removeTree, staleSessions, STALE_MS, STORE_CAP_BYTES, storeUsage, touch } from './io/store.ts'
36import { bandView } from './ui/band.tsx'
37import { revertAllNotice, revertAllPlanNotice, revertNotice } from './ui/notice.ts'
38import { paneView, type RevertAsk } from './ui/pane.tsx'
39
40// Wiring only (spec §5): events in, core and io calls, state out. Observers
41// always hand back what `next` resolved to; a failure here means "this change
42// is not tracked", never a blocked or altered tool call.
43
44const MIN_VERSION = [2, 1, 287] as const
45const EDIT_TOOLS: readonly string[] = ['Edit', 'Write', 'NotebookEdit']
46const SHELL_TOOLS: readonly string[] = ['Bash', 'PowerShell']
47const AGENT_TOOLS: readonly string[] = ['Agent', 'Task']
48const TOUCH_EVERY_MS = 60_000
49// autoOpen opens the pane only as a sidebar, and only this wide (as /diff does).
50const AUTO_OPEN_COLUMNS = 144
51
52// State references: `plugin` and `key` must be literals in a const of this file.
53const INDEX = { plugin: 'changes', key: 'index' } as const
54const SESSION = { plugin: 'changes', key: 'session' } as const
55const BAND = { plugin: 'changes', key: 'band' } as const
56const VIEW = { plugin: 'changes', key: 'view' } as const
57const PAUSED = { plugin: 'changes', key: 'paused' } as const
58const INACTIVE = { plugin: 'changes', key: 'inactive' } as const
59const STORE_FULL = { plugin: 'changes', key: 'storeFull' } as const
60const AUTO_OPENED = { plugin: 'changes', key: 'autoOpened' } as const
61const SHELL_OFF = { plugin: 'changes', key: 'shellOff' } as const
62const SHELL_UNSEEN = { plugin: 'changes', key: 'shellUnseen' } as const
63const HISTORY_NOTE = { plugin: 'changes', key: 'historyNote' } as const
64
65const PANE = { id: 'changes', title: 'Changes' } as const
66
67type Options = { enabled: boolean; band: boolean; autoOpen: boolean; tellClaude: boolean; trackShell: boolean; keepHistoryDays: number }
68// `token`: this process's claim on the conversation's lease; `writer`: whether
69// it holds the lease, so saves the history; `launchedAt`: turns that started
70// before it came from an earlier launch.
71type Session = {
72  sessionId: string
73  store: string
74  base: string
75  platform: 'windows' | 'posix'
76  root: string | null
77  cwd: string
78  token: string
79  writer: boolean
80  launchedAt: number
81}
82// Typed by the filters the hooks are registered with: `next` is narrowed to them.
83type BandRender = Parameters<MatchedHook<'ui.render', { component: 'AbovePrompt' }>>
84type PaneRender = Parameters<MatchedHook<'ui.render', { component: 'Pane'; requestId: 'changes' }>>
85type TurnRow = Extract<TimelineRow, { kind: 'turn' }>
86
87// Per module copy, rebuilt after a hot reload: the turn sweep's baseline (a
88// lost one skips that turn's sweep), large-file snapshots by mtime, the last
89// touch of the store, and whether the pane opened by itself yet.
90let sweepToken: ShellToken | null = null
91const snapshotCache: SnapshotCache = new Map()
92let lastTouch = 0
93// The layout as the last drawing saw it (a render hook can't write state);
94// unknown until something draws, and then nothing opens by itself.
95let layout: { columns: number; isFullscreen?: boolean } | null = null
96// Room left for this session's snapshots, re-measured at each turn.start and
97// at the first capture after a load.
98const storeBudget: StoreBudget = { used: 0, cap: STORE_CAP_BYTES, full: false }
99let storeMeasured = false
100// A revert running from the pane: a second press while it runs is refused. A
101// reload resets it, and the confirm was disarmed before the revert began.
102let reverting = false
103// The index's JSON size as of the last full measure (-1: unknown since a
104// load), and the saves since; appends are added on, a full measure redone on
105// any other change and every FULL_MEASURE_EVERY saves.
106let indexSize = -1
107let savesSinceMeasure = 0
108const FULL_MEASURE_EVERY = 100
109const SHELL_OFF_NOTE = "git is slow here; shell changes aren't tracked this session"
110const SHELL_UNSEEN_NOTE =
111  "Claude ran shell commands, and this folder isn't a git repository, so Changes can't see what they changed. Edits made with Edit and Write still show. To track shell changes too, run git init here and start a new session."
112// Renews the lease while this process holds it; stopped at the session's end.
113let heartbeat: Timer | null = null
114// keepHistoryDays as this module was registered with (register sets it).
115let keepHistoryDays = 7
116const READ_ONLY_NOTE = 'This conversation is also open in another Claude Code window. Its history shows here, but changes made here are not saved to it.'
117const UNREADABLE_NOTE = 'The history saved for this conversation could not be read, so it starts empty here.'
118// Every kept history together, oldest dropped first past it.
119const TOTAL_CAP_BYTES = 1024 * 1024 * 1024
120
121export const register: Register = (on, options) => {
122  const opts: Options = {
123    enabled: options.enabled !== false,
124    band: options.band !== false,
125    autoOpen: options.autoOpen === true,
126    tellClaude: options.tellClaude !== false,
127    trackShell: options.trackShell !== false,
128    keepHistoryDays: typeof options.keepHistoryDays === 'number' && options.keepHistoryDays >= 0 ? Math.floor(options.keepHistoryDays) : 7,
129  }
130  keepHistoryDays = opts.keepHistoryDays
131
132  on('session.start', async ($, e, next) => {
133    const r = await next(e)
134    try {
135      await $.command.register({
136        name: 'changes',
137        description: 'Open the Changes pane: what Claude changed, turn by turn, with keep and revert. /changes forget deletes this conversation\'s kept history.',
138        argumentHint: '[forget]',
139      })
140    } catch (error) {
141      debug($, 'session.start', error)
142    }
143    if (!opts.enabled) return r
144    try {
145      const { base, version } = await $.session.version()
146      if (isOlder(base ?? version, MIN_VERSION)) {
147        await $.state.set(INACTIVE, true)
148        $.ui.toast(`Changes needs Claude Code ${MIN_VERSION.join('.')} or later; it is off for this session.`)
149        return r
150      }
151      await startSession($, opts)
152    } catch (error) {
153      debug($, 'session.start', error)
154    }
155    return r
156  })
157
158  on('turn.start', async ($, e, next) => {
159    const r = await next(e)
160    const session = await activeSession($, opts)
161    if (session === null) return r
162    try {
163      const at = await $.clock.now()
164      await saveIndex($, index => openTurn(index, { turnId: e.turnId, prompt: e.text, at }))
165      await $.state.set(BAND, null)
166      await touch(portsOf($), session.store, at)
167      lastTouch = at
168      storeBudget.used = await storeUsage(portsOf($), session.store)
169      storeMeasured = true
170      sweepToken = null
171      if (await shellTracked($, opts, session)) {
172        const token = await shellBefore(portsOf($), shellContext(session), snapshotCache)
173        if (token !== null && 'slow' in token) await stopShellTracking($)
174        else sweepToken = token
175      }
176    } catch (error) {
177      debug($, 'turn.start', error)
178    }
179    return r
180  })
181
182  on('tool.call', async ($, e, next) => {
183    const session = await activeSession($, opts)
184    if (session === null) return next(e)
185    if (EDIT_TOOLS.includes(e.tool)) return recordEditCall($, session, e, next)
186    if (SHELL_TOOLS.includes(e.tool) && (await shellTracked($, opts, session))) return recordShellCall($, session, e, next)
187    if (SHELL_TOOLS.includes(e.tool) && opts.trackShell && session.root === null) await noteShellUnseen($)
188    const r = await next(e)
189    if (AGENT_TOOLS.includes(e.tool)) {
190      try {
191        await linkSpawn($, e, r)
192      } catch (error) {
193        debug($, 'tool.call', error)
194      }
195    }
196    return r
197  }).catch(($, e, next) => next(e))
198
199  on('turn.complete', async ($, e, next) => {
200    const r = await next(e)
201    const session = await activeSession($, opts)
202    if (session === null) return r
203    try {
204      const at = await $.clock.now()
205      if (e.agentId !== undefined) {
206        const agentId = e.agentId
207        await saveIndex($, index => closeAgent(index, agentId, at))
208        return r
209      }
210      await saveIndex($, index => closeTurn(index, { turnId: e.turnId, at, reason: e.reason }))
211      await sweepTurn($, session, e.turnId)
212      await showBand($, opts, session, e.turnId)
213      await persist($)
214    } catch (error) {
215      debug($, 'turn.complete', error)
216    }
217    return r
218  })
219
220  on('prompt.submit', async ($, e, next) => {
221    const r = await next(e)
222    try {
223      await $.state.set(BAND, null)
224    } catch (error) {
225      debug($, 'prompt.submit', error)
226    }
227    return r
228  }).catch(($, e, next) => next(e))
229
230  on('session.end', async ($, e, next) => {
231    const r = await next(e)
232    // The history is kept on disk for a resume (keepHistoryDays): the end only
233    // gives the lease up and marks the folder used, within the end's short
234    // bound. With keepHistoryDays 0 the copies go, as before. A /clear or
235    // resume goes on in the same process, so the next hook starts the session
236    // it continues with (no session.start follows a /clear).
237    stopHeartbeat()
238    try {
239      const { value: session = null } = await $.state.get(SESSION)
240      if (session !== null && opts.keepHistoryDays === 0) await removeTree(portsOf($), session.platform, session.store)
241      else if (session !== null) {
242        if (session.writer) await releaseLease(portsOf($), session.store, session.token)
243        await touch(portsOf($), session.store, await $.clock.now())
244      }
245      if (e.reason === 'clear' || e.reason === 'resume') await resetHistory($)
246    } catch (error) {
247      debug($, 'session.end', error)
248    }
249    return r
250  })
251
252  // `/changes` opens the pane: its answer says when the pane waits undrawn,
253  // and why. `/changes forget` deletes this conversation's kept history.
254  on('command.run', { command: 'changes' }, async ($, e) => {
255    if (e.args.trim().toLowerCase() === 'forget') return { text: await forget($) }
256    return { text: (await openPane($)) ?? 'Changes pane opened.' }
257  })
258
259  // The band's [Open] shows only while the pane is shut: closing it (the
260  // person's close mark or key) draws the band again.
261  on('ui.close', { id: 'changes' }, async ($, e, next) => {
262    const r = await next(e)
263    $.ui.invalidate('ui.render')
264    return r
265  }).catch(($, e, next) => next(e))
266
267  on('ui.render', { component: 'AbovePrompt' }, ($, e, next) => renderBand($, opts, e, next))
268
269  // The prompt hint draws on every surface: it tells autoOpen the layout.
270  on('ui.render', { component: 'PromptHint' }, (_$, e, next) => {
271    noteLayout(e.viewport)
272    return next(e)
273  })
274
275  on('ui.render', { component: 'Pane', requestId: 'changes' }, ($, e, next) => renderPane($, opts, e, next))
276
277  on('ui.focus', { requestId: 'changes' }, async ($, e, next) => {
278    const r = await next(e)
279    try {
280      if (e.origin.kind === 'person' && e.element !== undefined) await focusSelects($, e.element)
281    } catch (error) {
282      debug($, 'ui.focus', error)
283    }
284    return r
285  }).catch(($, e, next) => next(e))
286}
287
288// The loader follows `$` only within this file, so io/ gets closures over it.
289function portsOf($: Engine): Ports {
290  return {
291    fs: {
292      read: ((path: string, options?: { as?: 'text' | 'bytes' }) => $.fs.read(path, options as never)) as Ports['fs']['read'],
293      write: (path, text) => $.fs.write(path, text),
294      exists: path => $.fs.exists(path),
295      stat: (path, options) => $.fs.stat(path, options),
296      list: path => $.fs.list(path),
297    },
298    process: { run: (argv, init) => $.process.run(argv, init) },
299    clock: { now: () => $.clock.now() },
300  }
301}
302
303// Where snapshots go and which repository the session runs in; old session
304// folders a crash left behind are removed.
305async function startSession($: Engine, opts: Options): Promise<void> {
306  const io = portsOf($)
307  // A session already set up (a hot reload) goes on while its snapshots do.
308  // One whose folder is gone, or none at all, starts a fresh history: an
309  // index is never kept pointing at snapshots that no longer exist.
310  const { value: existing = null } = await $.state.get(SESSION)
311  if (existing !== null && (await io.fs.exists(existing.store))) {
312    const now = await $.clock.now()
313    await touch(io, existing.store, now)
314    lastTouch = now
315    storeBudget.used = await storeUsage(io, existing.store)
316    storeMeasured = true
317    startHeartbeat($, opts)
318    return
319  }
320  const sessionId = (await $.session.id()).trim()
321  // No id, no folder of our own: nothing is tracked (and nothing deleted).
322  if (sessionId === '') return
323  await resetHistory($)
324  const env = {
325    CLAUDE_CONFIG_DIR: await $.env.get('CLAUDE_CONFIG_DIR'),
326    USERPROFILE: await $.env.get('USERPROFILE'),
327    HOME: await $.env.get('HOME'),
328  }
329  const store = storeDirOf(env, sessionId)
330  const base = store.slice(0, store.lastIndexOf('/'))
331  const platform = platformOf(await $.env.get('OS'))
332  const cwd = (await $.session.root()).replace(/\\/g, '/')
333  const root = opts.trackShell ? await repoRootOf(io, cwd) : null
334  const now = await $.clock.now()
335  const token = `${sessionId}:${now}:${Math.random().toString(36).slice(2)}`
336  // A conversation resumed (same id) finds its history where it was kept. One
337  // process writes it: the lease holder; another shows it read-only.
338  let writer = false
339  let note: string | null = null
340  if (opts.keepHistoryDays > 0) {
341    writer = await takeLease(io, store, token, now)
342    const loaded = await loadHistory(io, store, sessionId)
343    if (loaded !== null && 'index' in loaded) await saveIndex($, () => loaded.index)
344    else if (loaded !== null) note = UNREADABLE_NOTE
345    if (!writer) note = note === null ? READ_ONLY_NOTE : `${note} ${READ_ONLY_NOTE}`
346  }
347  await $.state.set(SESSION, { sessionId, store, base, platform, root, cwd, token, writer, launchedAt: now })
348  await $.state.set(HISTORY_NOTE, note)
349  await touch(io, store, now)
350  lastTouch = now
351  storeBudget.used = await storeUsage(io, store)
352  storeMeasured = true
353  // Histories unused for keepHistoryDays (crash leftovers: a week) go, then
354  // the oldest while all of them together pass the total cap.
355  const keepFor = opts.keepHistoryDays > 0 ? opts.keepHistoryDays * DAY_MS : STALE_MS
356  for (const dir of await staleSessions(io, base, store, now, keepFor)) await removeTree(io, platform, dir)
357  for (const dir of await overTotalCap(io, base, store, TOTAL_CAP_BYTES)) await removeTree(io, platform, dir)
358  startHeartbeat($, opts)
359}
360
361// Saves the history for a resume, while this process holds the lease. A
362// lease taken over meanwhile (this process was idle past LEASE_STALE_MS and
363// another took it) is seen here, before anything is written: from then on
364// this process shows the history read-only.
365async function persist($: Engine): Promise<void> {
366  if (keepHistoryDays === 0) return
367  try {
368    const { value: session = null } = await $.state.get(SESSION)
369    if (session === null || !session.writer) return
370    const io = portsOf($)
371    if (!(await holdsLease(io, session.store, session.token))) {
372      await loseLease($, session)
373      return
374    }
375    const { value: index = emptyIndex() } = await $.state.get(INDEX)
376    if (!(await saveHistory(io, session.platform, session.store, session.sessionId, index as Index, await $.clock.now()))) {
377      debug($, 'history', new Error('the history could not be saved for a resume'))
378    }
379  } catch (error) {
380    debug($, 'history', error)
381  }
382}
383
384async function loseLease($: Engine, session: Session): Promise<void> {
385  await $.state.set(SESSION, { ...session, writer: false })
386  await $.state.set(HISTORY_NOTE, READ_ONLY_NOTE)
387}
388
389// The heartbeat keeps a live holder's lease fresh, so an idle window keeps it
390// and only a crashed one's goes stale.
391function startHeartbeat($: Engine, opts: Options): void {
392  if (heartbeat !== null || opts.keepHistoryDays === 0) return
393  heartbeat = $.clock.every(LEASE_RENEW_MS, () => void beat($))
394}
395
396async function beat($: Engine): Promise<void> {
397  try {
398    const { value: session = null } = await $.state.get(SESSION)
399    if (session === null || !session.writer) return
400    if (!(await renewLease(portsOf($), session.store, session.token, await $.clock.now()))) await loseLease($, session)
401  } catch (error) {
402    debug($, 'lease', error)
403  }
404}
405
406function stopHeartbeat(): void {
407  heartbeat?.cancel()
408  heartbeat = null
409}
410
411// /changes forget: this conversation's kept history and copies are deleted
412// now; the next hook starts it again, empty. Refused while another window
413// holds the lease: it would be deleting under that window.
414async function forget($: Engine): Promise<string> {
415  const { value: session = null } = await $.state.get(SESSION)
416  if (session === null) return 'There is no history to forget.'
417  if (!session.writer) return 'This conversation is open in another Claude Code window. Forget it there.'
418  stopHeartbeat()
419  const removed = await removeTree(portsOf($), session.platform, session.store)
420  await resetHistory($)
421  return removed ? "Changes deleted this conversation's history and its saved copies." : 'Changes could not delete the saved copies. Try again, or delete the folder by hand.'
422}
423
424// Shell writes are tracked in a repository, with the setting on, until git
425// proves slow here.
426async function shellTracked($: Engine, opts: Options, session: Session): Promise<boolean> {
427  if (!opts.trackShell || session.root === null) return false
428  const { value: off = false } = await $.state.get(SHELL_OFF)
429  return !off
430}
431
432// A git call was killed at its timeout: stop shell tracking for the session
433// rather than slow every Bash call; the pane says so.
434async function stopShellTracking($: Engine): Promise<void> {
435  const { value: off = false } = await $.state.get(SHELL_OFF)
436  if (!off) await $.state.set(SHELL_OFF, true)
437}
438
439// Outside a repository a shell command's writes can't be seen: the pane says
440// so once one runs, rather than look empty.
441async function noteShellUnseen($: Engine): Promise<void> {
442  try {
443    const { value: unseen = false } = await $.state.get(SHELL_UNSEEN)
444    if (!unseen) await $.state.set(SHELL_UNSEEN, true)
445  } catch (error) {
446    debug($, 'tool.call', error)
447  }
448}
449
450// After a hot reload the snapshot budget is measured again before the first
451// capture counts against it.
452async function measureStore($: Engine, session: Session): Promise<void> {
453  if (storeMeasured) return
454  storeBudget.used = await storeUsage(portsOf($), session.store)
455  storeMeasured = true
456}
457
458async function activeSession($: Engine, opts: Options): Promise<Session | null> {
459  if (!opts.enabled) return null
460  const { value: inactive = false } = await $.state.get(INACTIVE)
461  if (inactive) return null
462  const { value: session = null } = await $.state.get(SESSION)
463  if (session !== null) return session
464  // No session: after a /clear or a resume (no session.start follows), or
465  // state the host reset. The first hook sets up a fresh one.
466  await startSession($, opts)
467  const { value: started = null } = await $.state.get(SESSION)
468  return started
469}
470
471// An empty history: no index, view or band, no session folder, nothing
472// cached. The next hook starts a session again.
473async function resetHistory($: Engine): Promise<void> {
474  await $.state.set(INDEX, emptyIndex())
475  await $.state.set(VIEW, NO_VIEW)
476  await $.state.set(BAND, null)
477  await $.state.set(SESSION, null)
478  await $.state.set(PAUSED, null)
479  await $.state.set(STORE_FULL, false)
480  await $.state.set(HISTORY_NOTE, null)
481  await $.state.set(SHELL_UNSEEN, false)
482  indexSize = -1
483  savesSinceMeasure = 0
484  sweepToken = null
485  snapshotCache.clear()
486  diffCache.clear()
487  storeBudget.used = 0
488  storeBudget.full = false
489  storeMeasured = false
490}
491
492// Writes the index through `update` (parallel subagents' calls retry on a
493// version miss), trimmed to fit `$.state`. A change that can't fit is not
494// written and tracking shows as paused; the pause lifts once a write fits.
495// Answers whether the change was saved.
496async function saveIndex($: Engine, change: (index: Index) => Index): Promise<boolean> {
497  let fits = true
498  let size: number | null = null
499  let quick = false
500  try {
501    await update($, INDEX, (index = emptyIndex()) => {
502      const prev = index as Index
503      const next = change(prev)
504      // Appends are added onto the size known; anything else, an unknown
505      // size, a size near the budget, or every FULL_MEASURE_EVERY saves, is
506      // measured in full and trimmed to fit.
507      const added = indexSize >= 0 && savesSinceMeasure < FULL_MEASURE_EVERY ? appendedSize(prev, next) : null
508      if (added !== null && indexSize + added <= STATE_BUDGET_CHARS * 0.9) {
509        fits = true
510        quick = true
511        size = indexSize + added
512        return next
513      }
514      const fitted = fitToSize(next)
515      fits = fitted.fits
516      quick = false
517      const kept = fitted.fits ? fitted.index : prev
518      size = JSON.stringify(kept).length
519      return kept
520    })
521    if (size !== null) {
522      indexSize = size
523      savesSinceMeasure = quick ? savesSinceMeasure + 1 : 0
524    }
525  } catch (error) {
526    fits = false
527    indexSize = -1
528    debug($, 'save', error)
529  }
530  const { value: paused = null } = await $.state.get(PAUSED)
531  const wanted = fits ? null : 'Tracking is paused: the history is too large to save.'
532  if (paused !== wanted) await $.state.set(PAUSED, wanted)
533  return fits
534}
535
536function shellContext(session: Session) {
537  return { root: session.root!, store: session.store, budget: storeBudget }
538}
539
540// Once the snapshot budget is spent, the pane says so.
541async function noteStoreFull($: Engine): Promise<void> {
542  if (!storeBudget.full) return
543  const { value: full = false } = await $.state.get(STORE_FULL)
544  if (!full) await $.state.set(STORE_FULL, true)
545}
546
547type ToolEvent = Parameters<Hook<'tool.call'>>[1]
548type ToolNext = Parameters<Hook<'tool.call'>>[2]
549
550// Edit, Write, NotebookEdit: the file before and after, around the call.
551async function recordEditCall($: Engine, session: Session, e: ToolEvent, next: ToolNext) {
552  const input = e as unknown as { file_path?: string; notebook_path?: string; agentId?: string; tool_use_id: string; tool: string }
553  const path = input.file_path ?? input.notebook_path
554  if (path === undefined) return next(e)
555  const io = portsOf($)
556  let key = path
557  let before: Content = { unreadable: 'io' }
558  const startedAt = await $.clock.now()
559  try {
560    await measureStore($, session)
561    key = await keyOf(io, path, session.platform)
562    before = await capture(io, session.store, path, { budget: storeBudget })
563    before = await gitBeforeIfLarge(io, session, path, before)
564  } catch (error) {
565    debug($, 'tool.call', error)
566  }
567  const r = await next(e)
568  try {
569    const result = (r as { result?: { staged?: boolean } }).result
570    if ('deny' in r && r.deny !== undefined) return r
571    if ((r as { isError?: boolean }).isError === true || result?.staged === true) return r
572    const after = await capture(io, session.store, path, { budget: storeBudget })
573    const at = await $.clock.now()
574    await saveIndex($, index =>
575      addEdit(index, { toolUseId: input.tool_use_id, tool: input.tool, via: 'tool', path, key, before, after, startedAt, at, ...agentOf(input) }),
576    )
577    await noteStoreFull($)
578    await touchStore($, session, at)
579  } catch (error) {
580    debug($, 'tool.call', error)
581  }
582  return r
583}
584
585// Bash, PowerShell: what git says the command changed.
586async function recordShellCall($: Engine, session: Session, e: ToolEvent, next: ToolNext) {
587  const input = e as unknown as { agentId?: string; tool_use_id: string; tool: string }
588  const io = portsOf($)
589  const ctx = shellContext(session)
590  const startedAt = await $.clock.now()
591  let token: ShellToken | null = null
592  try {
593    await measureStore($, session)
594    token = await shellBefore(io, ctx, snapshotCache)
595  } catch (error) {
596    debug($, 'tool.call', error)
597  }
598  const r = await next(e)
599  if (token === null || ('deny' in r && r.deny !== undefined)) return r
600  try {
601    const result = await shellAfter(io, ctx, token)
602    const at = await $.clock.now()
603    if ('untracked' in result) {
604      // Too big, a HEAD move, or git too slow: said on the turn, nothing
605      // recorded; a slow git stops shell tracking for the session.
606      if (result.slow) await stopShellTracking($)
607      const reason = result.slow ? SHELL_OFF_NOTE : result.untracked
608      await saveIndex($, index => addUntracked(index, { toolUseId: input.tool_use_id, tool: input.tool, reason, at, ...agentOf(input) }))
609      return r
610    }
611    if (result.changes.length === 0) return r
612    const keyed = await Promise.all(result.changes.map(async c => ({ ...c, key: await keyOf(io, c.path, session.platform) })))
613    await saveIndex($, index =>
614      keyed.reduce(
615        (acc, c) => addEdit(acc, { toolUseId: input.tool_use_id, tool: input.tool, via: 'shell', path: c.path, key: c.key, before: c.before, after: c.after, startedAt, at, ...agentOf(input) }),
616        index,
617      ),
618    )
619    await noteStoreFull($)
620    await touchStore($, session, at)
621  } catch (error) {
622    debug($, 'tool.call', error)
623  }
624  return r
625}
626
627// An Agent call launched a subagent: it belongs to the spawning turn (spec §5.1).
628async function linkSpawn($: Engine, e: ToolEvent, r: unknown): Promise<void> {
629  const result = (r as { result?: { agentId?: unknown } }).result
630  if (typeof result?.agentId !== 'string') return
631  const agentId = result.agentId
632  const input = e as unknown as { tool_use_id: string; agentId?: string; description?: string }
633  await saveIndex($, index =>
634    linkAgent(index, {
635      agentId,
636      parentToolUseId: input.tool_use_id,
637      ...(input.agentId !== undefined ? { spawnedBy: input.agentId } : {}),
638      ...(typeof input.description === 'string' ? { label: input.description } : {}),
639    }),
640  )
641}
642
643// Changes during the turn that no recorded call explains (spec §5.3 step 4).
644async function sweepTurn($: Engine, session: Session, turnId: string): Promise<void> {
645  const token = sweepToken
646  sweepToken = null
647  if (token === null || session.root === null) return
648  const io = portsOf($)
649  const result = await shellAfter(io, shellContext(session), token)
650  const at = await $.clock.now()
651  const { value: current = emptyIndex() } = await $.state.get(INDEX)
652  if ('untracked' in result) {
653    if (result.slow) await stopShellTracking($)
654    // A call of the turn already said why (a commit, a big checkout): the
655    // sweep adds nothing more to say.
656    if (!current.untracked.some(u => u.turnId === turnId)) {
657      const reason = result.slow ? SHELL_OFF_NOTE : result.untracked
658      await saveIndex($, index => addUntracked(index, { turnId, toolUseId: `sweep:${turnId}`, tool: 'turn sweep', reason, at }))
659    }
660    return
661  }
662  if (result.changes.length === 0) return
663  const keyed = await Promise.all(result.changes.map(async c => ({ ...c, key: await keyOf(io, c.path, session.platform) })))
664  const left = unexplained(current as Index, keyed)
665  if (left.length === 0) return
666  await saveIndex($, index =>
667    left.reduce(
668      (acc, c) => addEdit(acc, { turnId, toolUseId: `sweep:${turnId}`, tool: 'unknown', via: 'unattributed', path: c.path, key: c.key, before: c.before, after: c.after, startedAt: at, at }),
669      index,
670    ),
671  )
672}
673
674// The band speaks only for a turn whose recorded calls changed code: docs,
675// notes and changes only the turn sweep found stay quiet.
676async function showBand($: Engine, opts: Options, session: Session, turnId: string): Promise<void> {
677  const { value: index = emptyIndex() } = await $.state.get(INDEX)
678  const bases = session.root === null ? [session.cwd] : [session.root, session.cwd]
679  const files = turnFiles(index as Index, turnId).filter(
680    f => !f.isNoop && f.edits.some(e => e.via !== 'unattributed') && isCodePath(f.path, bases, session.platform === 'windows'),
681  )
682  const turn = index.turns.find(t => t.turnId === turnId)
683  if (files.length === 0 || turn === undefined) return
684  if (opts.band) await $.state.set(BAND, { turnId, ordinal: turn.ordinal, files: files.length })
685  // Once per session (in state, so a hot reload doesn't open it again), and
686  // only where the pane docks beside the transcript in a wide enough terminal.
687  if (opts.autoOpen && layout?.isFullscreen === true && layout.columns >= AUTO_OPEN_COLUMNS) {
688    const { value: opened = false } = await $.state.get(AUTO_OPENED)
689    if (!opened) {
690      await $.state.set(AUTO_OPENED, true)
691      await openPane($)
692    }
693  }
694}
695
696// A file `$.fs` can't read (over 4 MiB) that was clean in git: git holds
697// its before, so a revert can still come from there (spec §5.2).
698async function gitBeforeIfLarge(io: Ports, session: Session, path: string, before: Content): Promise<Content> {
699  if (!('unreadable' in before) || before.unreadable !== 'too-large' || session.root === null) return before
700  const rel = relativeTo(session.root, path, session.platform === 'windows')
701  if (rel === undefined) return before
702  const blob = await cleanBlobOf(io, session.root, rel)
703  return blob === null ? before : { git: blob }
704}
705
706async function touchStore($: Engine, session: Session, now: number): Promise<void> {
707  if (now - lastTouch < TOUCH_EVERY_MS) return
708  lastTouch = now
709  await touch(portsOf($), session.store, now)
710}
711
712// Keep, undo keep and revert, as the pane's buttons call them.
713async function keepFile($: Engine, turnId: string, key: string, path: string, kept: boolean): Promise<void> {
714  const at = await $.clock.now()
715  await saveIndex($, index => addAction(setStatus(index, [{ turnId, key }], kept ? 'kept' : 'pending'), { kind: kept ? 'keep' : 'undo-keep', turnIds: [turnId], key, path, at }))
716  await persist($)
717}
718
719async function revertFromPane(
720  $: Engine,
721  opts: Pick<Options, 'tellClaude'>,
722  ref: { turnId: string; key: string },
723  mode: 'turn' | 'turnAndLater',
724  acceptOutsideChanges: boolean,
725): Promise<{ outcome: RevertOutcome; saved: boolean } | null> {
726  const { value: session = null } = await $.state.get(SESSION)
727  if (session === null) return null
728  const { value: stored = emptyIndex() } = await $.state.get(INDEX)
729  const index = stored as Index
730  const last = [...index.edits].reverse().find(e => e.key === ref.key)
731  if (last === undefined) return null
732  const rel = session.root === null ? undefined : relativeTo(session.root, last.path, session.platform === 'windows')
733  const ctx = { platform: session.platform, store: session.store, ...(session.root !== null ? { root: session.root } : {}) }
734  const outcome = await revertFile(portsOf($), ctx, index, ref, mode, last.path, rel, { acceptOutsideChanges })
735  if (!outcome.ok) return { outcome, saved: true }
736  // The file changed back: whatever happens to the history, Claude is told.
737  const at = await $.clock.now()
738  const saved = await saveIndex($, current => recordRevert(current, { key: ref.key, path: last.path, before: outcome.before, after: outcome.after, refs: outcome.refs, at }))
739  if (opts.tellClaude) await tellReverted($, index, [last.path], outcome.refs)
740  await persist($)
741  return { outcome, saved }
742}
743
744// One hidden note to Claude for the files a revert changed back, however many.
745async function tellReverted($: Engine, index: Index, paths: string[], refs: RevertRef[]): Promise<void> {
746  try {
747    // The history starts fresh at every /clear, so its turn numbers are
748    // the conversation's own; a background agent's bucket has none.
749    const turnIds = [...new Set(refs.map(r => r.turnId))]
750    const turns = turnIds
751      .map(id => index.turns.find(t => t.turnId === id))
752      .filter(t => t !== undefined && t.kind === 'turn')
753      .map(t => `#${t!.ordinal}`)
754    const before = turns.length === turnIds.length && turns.length > 0 ? `turn ${turns.join(', ')}` : 'an earlier turn'
755    const text =
756      paths.length === 1
757        ? `The user reverted ${paths[0]} to its state before ${before} using the Changes pane. Re-read the file before editing it.`
758        : `The user reverted these files to their state before ${before} using the Changes pane: ${paths.join(', ')}. Re-read them before editing them.`
759    await $.session.append({ message: { type: 'user', content: [{ type: 'text', text }] } })
760  } catch (error) {
761    debug($, 'revert note', error)
762  }
763}
764
765function noteLayout(viewport: { columns: number; isFullscreen?: boolean } | undefined): void {
766  if (viewport !== undefined) layout = { columns: viewport.columns, ...(viewport.isFullscreen !== undefined ? { isFullscreen: viewport.isFullscreen } : {}) }
767}
768
769async function renderBand($: Engine, opts: Options, e: BandRender[1], next: BandRender[2]) {
770  noteLayout(e.viewport)
771  if (!opts.band || e.component !== 'AbovePrompt' || e.props.hasSurvey) return next(e)
772  const { value: band = null } = await $.state.get(BAND)
773  if (band === null) return next(e)
774  const elements = $.ui.resolve(e)
775  const mine = bandView(
776    elements,
777    band,
778    (await paneIsUp($)) ? null : () => void openOnTurn($, band.turnId),
779    () => void $.state.set(BAND, null),
780  )
781  // Other mods' bands draw beneath ours, never hidden by it, while there is
782  // room for both (Receipts composes the same way).
783  if (e.props.maxRows < 2) return mine
784  const { Box } = elements
785  const below = await next(e)
786  return (
787    <Box key="changes-above-prompt" flexDirection="column">
788      {mine}
789      {below}
790    </Box>
791  )
792}
793
794// The band's [Open]: the pane opens first, straight from the press, then
795// selects the turn. A pane that waits undrawn says why, once, in a toast.
796async function openOnTurn($: Engine, turnId: string): Promise<void> {
797  const note = await openPane($)
798  if (note !== null) $.ui.toast(note)
799  await update($, VIEW, (v = NO_VIEW) => ({ ...v, turnId, node: null, confirm: null, offer: null, confirmAll: null }))
800}
801
802// Opens the pane, then draws the band again without its [Open]. Answers what
803// to tell the person when the pane waits undrawn (waitingNote), else null.
804async function openPane($: Engine): Promise<string | null> {
805  const opened = await $.ui.open({ id: PANE.id, title: PANE.title })
806  $.ui.invalidate('ui.render')
807  return waitingNote(PANE.title, opened)
808}
809
810// Whether the pane is open and drawn, by the engine's record: one waiting
811// undrawn (a narrow terminal) still needs the band's [Open]. A tab behind
812// another pane counts as up: no event says when tabs switch.
813async function paneIsUp($: Engine): Promise<boolean> {
814  try {
815    return (await $.ui.panes()).some(pane => pane.id === PANE.id && pane.isPlaced)
816  } catch (error) {
817    debug($, 'panes', error)
818    return false
819  }
820}
821
822async function renderPane($: Engine, opts: Options, e: PaneRender[1], next: PaneRender[2]) {
823  if (e.component !== 'Pane' || e.requestId !== PANE.id) return next(e)
824  const { value: stored = emptyIndex() } = await $.state.get(INDEX)
825  const { value: session = null } = await $.state.get(SESSION)
826  const { value: view = NO_VIEW } = await $.state.get(VIEW)
827  const { value: paused = null } = await $.state.get(PAUSED)
828  const { value: storeFull = false } = await $.state.get(STORE_FULL)
829  const index = stored as Index
830  const rows = timeline(index)
831  const firstWithFiles = rows.find((r): r is TurnRow => r.kind === 'turn' && r.files.length > 0)
832  const selected = view.turnId ?? firstWithFiles?.turn.turnId ?? null
833  const files = selected === null ? [] : turnFiles(index, selected, view.node ?? undefined)
834  // A draw only reads diffs already computed: the rest show as loading, and
835  // one fetch runs off the draw, then draws again.
836  const { diffs, missing } = cachedDiffs(files, view.expanded)
837  // Revert all is offered while the selected turn has a file still pending.
838  const pending = selected === null ? 0 : pendingFiles(index, selected).length
839  if (session !== null && missing.length > 0 && !fetchingDiffs) {
840    fetchingDiffs = true
841    $.clock.after(0, () => void fetchDiffs($, session, missing))
842  }
843  const { value: shellOff = false } = await $.state.get(SHELL_OFF)
844  const { value: shellUnseen = false } = await $.state.get(SHELL_UNSEEN)
845  const { value: historyNote = null } = await $.state.get(HISTORY_NOTE)
846  const notes = [
847    paused,
848    storeFull ? 'Snapshots are paused: this session saved 500 MB of copies. New changes are listed but cannot be reverted.' : null,
849    shellOff ? `Shell commands: ${SHELL_OFF_NOTE}.` : null,
850    shellUnseen ? SHELL_UNSEEN_NOTE : null,
851    historyNote,
852  ].filter((n): n is string => n !== null)
853  return paneView($.ui.resolve(e), {
854    rows,
855    selected,
856    node: view.node,
857    files,
858    diffs,
859    expanded: view.expanded,
860    confirm: view.confirm,
861    offer: view.offer,
862    offers: view.offers,
863    confirmAll: view.confirmAll,
864    canRevertAll: pending > 0,
865    notice: view.notice,
866    paused: notes.length > 0 ? notes.join(' ') : null,
867    cwd: session?.cwd ?? '',
868    launchedAt: session?.launchedAt ?? 0,
869    isWindows: session?.platform === 'windows',
870    onSelect: turnId => void selectTurn($, turnId),
871    onNode: node => void selectNode($, node),
872    onKeep: file => void keepFile($, file.turnId, file.key, file.path, file.status !== 'kept'),
873    onRevert: file => void armRevert($, { turnId: file.turnId, key: file.key, path: file.path }, 'turn', false),
874    onConfirm: file => void confirmRevert($, opts, file),
875    onOffer: () => void armOffer($),
876    onOfferFile: ask => void armFileOffer($, ask),
877    onRevertAll: turnId => void armRevertAll($, turnId),
878    onConfirmAll: turnId => void confirmRevertAll($, opts, turnId),
879    onShowAll: file => void update($, VIEW, (v = NO_VIEW) => ({ ...v, expanded: [...new Set([...v.expanded, statusKey(file.turnId, file.key)])] })),
880  })
881}
882
883const NO_VIEW = { turnId: null, node: null, confirm: null, offer: null, notice: null, expanded: [] as string[], confirmAll: null, offers: [] as RevertAsk[] }
884const MAX_DIFF_FILES = 12
885const MAX_DIFF_CHARS = 80_000
886const CONFIRM_MS = 5_000
887
888// Diffs by (before, after, all rows?), across draws; dropped on reload.
889const diffCache = new Map<string, DiffView>()
890// One diff fetch at a time, each within FETCH_BUDGET_MS of git.
891let fetchingDiffs = false
892const FETCH_BUDGET_MS = 5_000
893const LOADING: DiffView = { kind: 'note', text: 'loading diff…' }
894
895type DiffWanted = { id: string; file: FileChange; all: boolean }
896
897function diffId(file: FileChange, all: boolean): string {
898  return `${contentId(file.before)}|${contentId(file.after)}|${all ? 'all' : 'cut'}`
899}
900
901// What a draw can show now, from the cache alone, and what is still missing.
902function cachedDiffs(files: FileChange[], expanded: readonly string[]): { diffs: Record<string, DiffView>; missing: DiffWanted[] } {
903  const diffs: Record<string, DiffView> = {}
904  const missing: DiffWanted[] = []
905  let chars = 0
906  for (const [i, file] of files.entries()) {
907    if (i >= MAX_DIFF_FILES || chars > MAX_DIFF_CHARS) {
908      diffs[file.key] = { kind: 'note', text: 'diff not drawn here: select a step above to narrow the list' }
909      continue
910    }
911    const all = expanded.includes(statusKey(file.turnId, file.key))
912    const id = diffId(file, all)
913    const view = diffCache.get(id)
914    if (view === undefined) {
915      missing.push({ id, file, all })
916      diffs[file.key] = LOADING
917      continue
918    }
919    diffs[file.key] = view
920    if (view.kind === 'diff') chars += view.hunks.length
921  }
922  return { diffs, missing }
923}
924
925// Off the draw: compute what was missing, within one git budget, then draw
926// again. A file whose git was too slow is cached as such, never retried in a
927// loop; one cut short by the budget is fetched on the next round.
928async function fetchDiffs($: Engine, session: Session, wanted: DiffWanted[]): Promise<void> {
929  try {
930    const io = portsOf($)
931    const ctx = { store: session.store, root: session.root, platform: session.platform }
932    const budget = gitBudget(await $.clock.now(), FETCH_BUDGET_MS)
933    for (const want of wanted) {
934      if (budget.over) break
935      const view = await diffOf(io, ctx, want.file, want.all, budget)
936      if (budget.over && !budget.timedOut) break
937      if (diffCache.size > 200) diffCache.clear()
938      diffCache.set(want.id, budget.timedOut && view.kind === 'note' ? { kind: 'note', text: 'diff unavailable: git is slow here' } : view)
939      if (budget.timedOut) break
940    }
941  } catch (error) {
942    debug($, 'diff', error)
943  } finally {
944    fetchingDiffs = false
945    $.ui.invalidate('ui.render')
946  }
947}
948
949function contentId(content: Content): string {
950  if ('hash' in content) return content.hash
951  if ('git' in content) return `git:${content.git.oid}`
952  return 'absent' in content ? 'absent' : `unreadable:${content.unreadable}`
953}
954
955async function selectTurn($: Engine, turnId: string): Promise<void> {
956  await update($, VIEW, (v = NO_VIEW) => (v.turnId === turnId ? v : { ...v, turnId, node: null, confirm: null, offer: null, confirmAll: null }))
957}
958
959async function selectNode($: Engine, node: string | null): Promise<void> {
960  await update($, VIEW, (v = NO_VIEW) => (v.node === node ? v : { ...v, node, confirm: null }))
961}
962
963// The first press of Revert: plan it against the file as it is now. A plan
964// that would land arms the confirmation, naming every turn it reverts; a
965// refusal says why and, where one exists, offers the way on.
966async function armRevert($: Engine, ask: { turnId: string; key: string; path: string }, mode: 'turn' | 'turnAndLater', accept: boolean): Promise<void> {
967  const { value: session = null } = await $.state.get(SESSION)
968  if (session === null) return
969  const { value: stored = emptyIndex() } = await $.state.get(INDEX)
970  const index = stored as Index
971  const current = await capture(portsOf($), session.store, ask.path, { store: false })
972  const plan = await planFile(portsOf($), turnContext(session), index, { turnId: ask.turnId, key: ask.key }, mode, current, { acceptOutsideChanges: accept })
973  const name = turnNamer(index)
974  const shown = shownPath(session.cwd, ask.path, session.platform === 'windows')
975  const now = await $.clock.now()
976  const { value: view = NO_VIEW } = await $.state.get(VIEW)
977  if (plan.ok) {
978    // With a step selected the pane shows that step's diff, but a revert
979    // undoes the whole turn's change to the file: the button says so.
980    const turns = plan.refs.map(r => name(r.turnId)).join(', ')
981    const label = view.node !== null ? `Confirm revert of the whole turn (${turns})` : `Confirm revert (${turns})`
982    const notice = plan.widenedTo ? `This also reverts ${plan.widenedTo.map(name).join(', ')}: an agent it started edited ${shown} later.` : null
983    await update($, VIEW, (v = NO_VIEW) => ({ ...v, confirm: { ...ask, mode, accept, label, until: now + CONFIRM_MS }, offer: null, notice: notice ?? v.notice }))
984    return
985  }
986  const notice = revertNotice(plan, shown, name)
987  const offer = offerFor(plan, ask, mode, accept, name)
988  await update($, VIEW, (v = NO_VIEW) => ({ ...v, confirm: null, offer, notice }))
989}
990
991// The way on that a refusal offers, if any: the later turns together, or, past
992// a link that can't be confirmed, anyway. Always one file at a time.
993function offerFor(
994  plan: Exclude<RevertPlan, { ok: true }>,
995  ask: { turnId: string; key: string; path: string },
996  mode: 'turn' | 'turnAndLater',
997  accept: boolean,
998  name: (turnId: string) => string,
999): RevertAsk | null {
1000  const file = { turnId: ask.turnId, key: ask.key, path: ask.path }
1001  if (plan.reason === 'changed-since') return { ...file, mode: 'turnAndLater', accept, label: `Revert with ${plan.otherTurns.map(name).join(', ')}` }
1002  const isLink = plan.reason === 'user-changed-between' || plan.reason === 'unverifiable-link' || plan.reason === 'history-trimmed'
1003  return isLink ? { ...file, mode, accept: true, label: 'Revert anyway' } : null
1004}
1005
1006// A file's own offer after Revert all, pressed: plan it again and arm its confirm.
1007async function armFileOffer($: Engine, ask: RevertAsk): Promise<void> {
1008  await update($, VIEW, (v = NO_VIEW) => ({ ...v, offers: v.offers.filter(o => o.turnId !== ask.turnId || o.key !== ask.key) }))
1009  await armRevert($, ask, ask.mode, ask.accept)
1010}
1011
1012// The turn's files Revert all acts on: changed, not reverted, not kept.
1013function pendingFiles(index: Index, turnId: string): FileChange[] {
1014  return turnFiles(index, turnId).filter(f => !f.isNoop && f.status === 'pending')
1015}
1016
1017function keptFiles(index: Index, turnId: string): FileChange[] {
1018  return turnFiles(index, turnId).filter(f => !f.isNoop && f.status === 'kept')
1019}
1020
1021function turnFilesOf(session: Session, files: FileChange[]): TurnFile[] {
1022  return files.map(f => {
1023    const rel = session.root === null ? undefined : relativeTo(session.root, f.path, session.platform === 'windows')
1024    return { turnId: f.turnId, key: f.key, path: f.path, ...(rel !== undefined ? { rel } : {}) }
1025  })
1026}
1027
1028function turnContext(session: Session) {
1029  return { platform: session.platform, store: session.store, ...(session.root !== null ? { root: session.root } : {}) }
1030}
1031
1032// The first press of Revert all: plan every pending file against the disk as
1033// it is now, write nothing. The confirm says how many files it writes and
1034// skips; the notice says why each skipped one is.
1035async function armRevertAll($: Engine, turnId: string): Promise<void> {
1036  const { value: session = null } = await $.state.get(SESSION)
1037  if (session === null) return
1038  const { value: stored = emptyIndex() } = await $.state.get(INDEX)
1039  const index = stored as Index
1040  const name = turnNamer(index)
1041  const shown = (p: string) => shownPath(session.cwd, p, session.platform === 'windows')
1042  const plans = await planTurn(portsOf($), turnContext(session), index, turnFilesOf(session, pendingFiles(index, turnId)))
1043  const writes = plans.filter(p => p.plan.ok).length
1044  const skipped = [
1045    ...plans.flatMap(p => (p.plan.ok ? [] : [{ path: shown(p.file.path), why: p.plan as RevertOutcome }])),
1046    ...keptFiles(index, turnId).map(f => ({ path: shown(f.path), why: 'kept' as const })),
1047  ]
1048  const notice = revertAllPlanNotice({ turn: name(turnId), skipped, writes }, name)
1049  const now = await $.clock.now()
1050  const label = `Confirm revert all (${name(turnId)}): write ${writes}, skip ${skipped.length}`
1051  await update($, VIEW, (v = NO_VIEW) => ({
1052    ...v,
1053    confirm: null,
1054    offer: null,
1055    confirmAll: writes > 0 ? { turnId, label, until: now + CONFIRM_MS } : null,
1056    notice: notice === '' ? null : notice,
1057  }))
1058}
1059
1060// The second press: the revertible files are written one by one, each saved
1061// as a single revert is (recordRevert) before the next; a refusal skips its
1062// file and offers its own way on, on its row; a write that did not land stops
1063// the run (io/restore.ts revertTurn). Claude gets one note for all the files.
1064async function confirmRevertAll($: Engine, opts: Options, turnId: string): Promise<void> {
1065  const { value: view = NO_VIEW } = await $.state.get(VIEW)
1066  const ask = view.confirmAll
1067  if (ask === null || ask.turnId !== turnId || reverting) return
1068  reverting = true
1069  let notice: string
1070  let offers: RevertAsk[] = []
1071  try {
1072    const isLate = (await $.clock.now()) > ask.until
1073    await update($, VIEW, (v = NO_VIEW) => ({ ...v, confirm: null, offer: null, confirmAll: null, offers: [], notice: isLate ? v.notice : 'Reverting…' }))
1074    const { value: session = null } = await $.state.get(SESSION)
1075    if (isLate) notice = 'The confirmation timed out: press Revert all again.'
1076    else if (session === null) notice = 'Nothing to revert: this session keeps no history.'
1077    else ({ notice, offers } = await revertAllFromPane($, opts, session, turnId))
1078  } catch (error) {
1079    debug($, 'revert all', error)
1080    notice = 'Revert all stopped with an error: check the files before going on.'
1081  } finally {
1082    reverting = false
1083  }
1084  await update($, VIEW, (v = NO_VIEW) => ({ ...v, confirmAll: null, notice, offers }))
1085}
1086
1087async function revertAllFromPane($: Engine, opts: Pick<Options, 'tellClaude'>, session: Session, turnId: string): Promise<{ notice: string; offers: RevertAsk[] }> {
1088  const { value: stored = emptyIndex() } = await $.state.get(INDEX)
1089  const index = stored as Index
1090  const name = turnNamer(index)
1091  const shown = (p: string) => shownPath(session.cwd, p, session.platform === 'windows')
1092  let saved = true
1093  const result = await revertTurn(portsOf($), turnContext(session), index, turnFilesOf(session, pendingFiles(index, turnId)), async (file, outcome) => {
1094    const at = await $.clock.now()
1095    const ok = await saveIndex($, current => recordRevert(current, { key: file.key, path: file.path, before: outcome.before, after: outcome.after, refs: outcome.refs, at }))
1096    saved = saved && ok
1097    const { value: now = emptyIndex() } = await $.state.get(INDEX)
1098    return now as Index
1099  })
1100  let notice = revertAllNotice(
1101    {
1102      turn: name(turnId),
1103      reverted: result.reverted.map(r => shown(r.file.path)),
1104      skipped: [
1105        ...result.skipped.map(r => ({ path: shown(r.file.path), why: r.outcome as RevertOutcome })),
1106        ...keptFiles(index, turnId).map(f => ({ path: shown(f.path), why: 'kept' as const })),
1107      ],
1108      stopped: result.stopped === null ? null : shown(result.stopped.path),
1109      notTried: result.notTried.length,
1110    },
1111    name,
1112  )
1113  if (result.reverted.length > 0 && !saved) notice += " Some of that history couldn't be saved."
1114  const offers = result.skipped.flatMap(r => {
1115    if (r.outcome.reason === 'io') return []
1116    const offer = offerFor(r.outcome, r.file, 'turn', false, name)
1117    return offer === null ? [] : [offer]
1118  })
1119  if (opts.tellClaude && result.reverted.length > 0) {
1120    await tellReverted($, index, result.reverted.map(r => r.file.path), result.reverted.flatMap(r => r.outcome.refs))
1121  }
1122  await persist($)
1123  return { notice, offers }
1124}
1125
1126// A refusal's offer pressed: plan again with its mode, then confirm as usual.
1127async function armOffer($: Engine): Promise<void> {
1128  const { value: view = NO_VIEW } = await $.state.get(VIEW)
1129  if (view.offer === null) return
1130  await armRevert($, view.offer, view.offer.mode, view.offer.accept)
1131}
1132
1133// The second press: the armed revert runs, within its few seconds, for the
1134// file its button belongs to, and one at a time. The confirmation is disarmed
1135// before the revert starts, so nothing stays armed if the module reloads
1136// mid-revert, and the outcome replaces the "Reverting…" line after.
1137async function confirmRevert($: Engine, opts: Options, file: { turnId: string; key: string }): Promise<void> {
1138  const { value: view = NO_VIEW } = await $.state.get(VIEW)
1139  const ask = view.confirm
1140  if (ask === null || ask.turnId !== file.turnId || ask.key !== file.key) return
1141  if (reverting) return
1142  reverting = true
1143  let notice: string
1144  try {
1145    const isLate = (await $.clock.now()) > ask.until
1146    await update($, VIEW, (v = NO_VIEW) => ({ ...v, confirm: null, offer: null, notice: isLate ? v.notice : 'Reverting…' }))
1147    if (isLate) {
1148      notice = 'The confirmation timed out: press Revert again.'
1149    } else {
1150      const done = await revertFromPane($, opts, { turnId: ask.turnId, key: ask.key }, ask.mode, ask.accept)
1151      const { value: session = null } = await $.state.get(SESSION)
1152      const { value: stored = emptyIndex() } = await $.state.get(INDEX)
1153      const shown = session === null ? ask.path : shownPath(session.cwd, ask.path, session.platform === 'windows')
1154      if (done === null) notice = `Nothing to revert for ${shown}.`
1155      else if (done.outcome.ok && !done.saved) notice = `Reverted ${shown}, but its history couldn't be saved.`
1156      else notice = revertNotice(done.outcome, shown, turnNamer(stored as Index))
1157    }
1158  } catch (error) {
1159    debug($, 'revert', error)
1160    notice = 'The revert stopped with an error: check the file before going on.'
1161  } finally {
1162    reverting = false
1163  }
1164  await update($, VIEW, (v = NO_VIEW) => ({ ...v, confirm: null, offer: null, notice }))
1165}
1166
1167function turnNamer(index: Index): (turnId: string) => string {
1168  return turnId => {
1169    const turn = index.turns.find(t => t.turnId === turnId)
1170    return turn === undefined ? 'an earlier turn' : turn.kind === 'background' ? 'a background agent' : `#${turn.ordinal}`
1171  }
1172}
1173
1174// Desktop's first click on an unfocused pane fires only ui.focus: for the
1175// turn rows and steps, which only select, focus does what the press would.
1176// Keep, Revert and Confirm always need a real press.
1177async function focusSelects($: Engine, element: string): Promise<void> {
1178  if (element.startsWith('select-')) await selectTurn($, element.slice('select-'.length))
1179  else if (element === 'node-all') await selectNode($, null)
1180  else if (element.startsWith('node-')) await selectNode($, element.slice('node-'.length))
1181}
1182
1183function agentOf(input: { agentId?: string }): { agentId?: string } {
1184  return input.agentId === undefined ? {} : { agentId: input.agentId }
1185}
1186
1187function isOlder(version: string, min: readonly number[]): boolean {
1188  const parts = version.split(/[.-]/).map(Number)
1189  for (let i = 0; i < min.length; i++) {
1190    const part = parts[i] ?? 0
1191    if (Number.isNaN(part)) return false
1192    if (part !== min[i]) return part < min[i]!
1193  }
1194  return false
1195}
1196
1197function debug($: Engine, where: string, error: unknown): void {
1198  $.ui.log(`changes: ${where} failed: ${error instanceof Error ? error.message : String(error)}`, { to: 'debug' })
1199}
1200
hooks/core/model.ts 111 lines
1// The Changes engine's data model (spec §3.1). Plain JSON data: the index
2// lives in `$.state`, the blobs it names live on disk.
3
4import type { Eol } from './diff.ts'
5
6export type Content =
7  | { hash: string; size: number; kind: 'text' | 'binary'; eol: Eol; bom: boolean }
8  // Clean in git before the change: the blob in `commit` at the record's path.
9  // Read with `git cat-file --filters` (so autocrlf applies), restored with
10  // `git restore --source=<commit>`, verified with `git hash-object`.
11  | { git: { oid: string; commit: string } }
12  | { absent: true }
13  | { unreadable: 'too-large' | 'io' }
14
15// 'revert' is a revert the person ran from the pane: the disk went from its
16// before to its after. It belongs to no turn (turnId REVERT_TURN) and keeps
17// each file's history one unbroken chain of transitions.
18export type Via = 'tool' | 'shell' | 'unattributed' | 'revert'
19
20export const REVERT_TURN = 'revert'
21
22export type EditRecord = {
23  seq: number
24  turnId: string
25  toolUseId: string
26  tool: string
27  via: Via
28  agentId?: string
29  path: string
30  key: string
31  before: Content
32  after: Content
33  // When the before capture started and the after capture ended.
34  startedAt: number
35  at: number
36  interleaved?: true
37}
38
39export type AgentNode = {
40  agentId: string
41  turnId: string
42  seq: number
43  parentToolUseId?: string
44  parentAgentId?: string
45  label?: string
46  // Set when the agent's run completed (its turn.complete); until then its
47  // turn is never trimmed, since its edits still arrive.
48  endedAt?: number
49}
50
51export type TurnRecord = {
52  turnId: string
53  // Orders turns, background buckets and user actions on one timeline.
54  seq: number
55  // 'background' is the bucket of an agent whose spawning turn is unknown.
56  kind: 'turn' | 'background'
57  ordinal: number
58  prompt: string
59  startedAt: number
60  endedAt?: number
61  reason?: string
62}
63
64export type FileStatus = 'pending' | 'kept' | 'reverted'
65
66// A tool call whose changes were not recorded, and why ("many files
67// changed (5123)", "HEAD moved", "took too long"): shown on its turn so the
68// timeline never claims more than it knows.
69export type UntrackedRecord = { seq: number; turnId: string; toolUseId: string; tool: string; reason: string; at: number }
70
71// Something the person did in the pane, kept in the timeline.
72export type UserAction = { seq: number; kind: 'keep' | 'undo-keep' | 'revert'; turnIds: string[]; key: string; path: string; at: number }
73
74export type Index = {
75  turns: TurnRecord[]
76  edits: EditRecord[]
77  agents: AgentNode[]
78  actions: UserAction[]
79  untracked: UntrackedRecord[]
80  // Keyed by statusKey(turnId, key).
81  status: Record<string, FileStatus>
82  openTurnId?: string
83  nextSeq: number
84  nextOrdinal: number
85  // Per file key, the highest seq of an edit trimmed away: a chain break
86  // after it is Claude's dropped history, not the person's change.
87  trimmed: Record<string, number>
88}
89
90export function emptyIndex(): Index {
91  return { turns: [], edits: [], agents: [], actions: [], untracked: [], status: {}, nextSeq: 1, nextOrdinal: 1, trimmed: {} }
92}
93
94// NUL, built at runtime: the catalogue's UI scanner flags control characters
95// in string literals.
96export const KEY_SEP = String.fromCharCode(0)
97
98export function statusKey(turnId: string, key: string): string {
99  return turnId + KEY_SEP + key
100}
101
102// Whether two captures hold the same content: true, false, or null when it
103// can't be told (unreadable, or a git blob id against a SHA-256 hash).
104export function sameContent(a: Content, b: Content): boolean | null {
105  if ('unreadable' in a || 'unreadable' in b) return null
106  if ('absent' in a || 'absent' in b) return 'absent' in a && 'absent' in b
107  if ('hash' in a && 'hash' in b) return a.hash === b.hash
108  if ('git' in a && 'git' in b) return a.git.oid === b.git.oid
109  return null
110}
111
hooks/core/noise.ts 34 lines
1// Which changed files are worth a line above the prompt. Everything is
2// tracked and shown in the pane; the band speaks only for code, so a turn
3// that only touched notes, docs, logs, data or lockfiles stays quiet.
4
5import { relativeTo } from './paths.ts'
6
7const PROSE = /\.(md|mdx|markdown|rst|adoc|org)$/i
8// Text files that are code or build input, not notes.
9const TEXT_CODE = /^(cmakelists\.txt|(requirements|constraints)([-_.][\w.-]*)?\.txt|robots\.txt)$/i
10const QUIET_EXT = /\.(txt|log|out|csv|tsv|lock)$/i
11const LOCKFILES = new Set([
12  'package-lock.json',
13  'npm-shrinkwrap.json',
14  'pnpm-lock.yaml',
15  'bun.lockb',
16  'go.sum',
17  'packages.lock.json',
18])
19// Matched only below the repository root or the session's folder, never on
20// the absolute path (a project living under C:/Work/Build/ is still code).
21const QUIET_FOLDERS = /(^|\/)(docs?|notes|\.claude|node_modules|dist|build|out|coverage|\.next|target)\//i
22
23export function isCodePath(path: string, bases: readonly string[] = [], isWindows = false): boolean {
24  const normal = path.replace(/\\/g, '/')
25  const name = normal.slice(normal.lastIndexOf('/') + 1).toLowerCase()
26  if (TEXT_CODE.test(name)) return true
27  if (PROSE.test(name) || QUIET_EXT.test(name) || LOCKFILES.has(name)) return false
28  for (const base of bases) {
29    const rel = relativeTo(base, normal, isWindows)
30    if (rel !== undefined) return !QUIET_FOLDERS.test(rel)
31  }
32  return true
33}
34
hooks/core/paths.ts 3 lines
1// Moved to /shared (Scope Cop uses it too); kept here so Changes' imports stay.
2export { relativeTo, shownPath } from '../shared/paths.ts'
3
hooks/core/sweep.ts 23 lines
1// The turn sweep (spec §5.3 step 4): git status at turn.start and at
2// turn.complete catches changes no tool call recorded (a background command,
3// a tool we don't know, the person's editor during the turn).
4
5import { sameContent, type Content, type Index } from './model.ts'
6
7// The changes the index does not account for: a change is accounted for when
8// the file's last recorded transition, in any turn, left exactly this content
9// (an async agent files its edits under the turn that spawned it).
10export function unexplained<T extends { key: string; after: Content }>(index: Index, changes: readonly T[]): T[] {
11  return changes.filter(change => {
12    let last: Content | undefined
13    let lastSeq = -1
14    for (const e of index.edits) {
15      if (e.key === change.key && e.seq > lastSeq) {
16        last = e.after
17        lastSeq = e.seq
18      }
19    }
20    return last === undefined || sameContent(last, change.after) !== true
21  })
22}
23
hooks/core/revert-plan.ts 123 lines
1// What a revert must do, decided from the index and the file as it is on
2// disk now (spec §5.4). Pure: the io layer executes the plan and verifies.
3//
4// A file's history is its chain of transitions in edit order (seq), across
5// turns: Claude's edits and the reverts already run from the pane. A revert
6// restores the before of the first transition it undoes, so it is only safe
7// when every transition from there on links to the next (nothing outside
8// that chain changed the file) and the disk holds the last one's after.
9
10import { REVERT_TURN, sameContent, type Content, type EditRecord, type Index } from './model.ts'
11import { statusOf } from './timeline.ts'
12
13export type Restore =
14  | { kind: 'write-text'; hash: string }
15  | { kind: 'write-bytes'; hash: string }
16  | { kind: 'delete' }
17  | { kind: 'git-restore'; commit: string; oid: string }
18  // The disk already holds the target; only the statuses change.
19  | { kind: 'none' }
20
21export type RevertRef = { turnId: string; key: string }
22
23export type RevertPlan =
24  // `widenedTo`: turns that started before this one and were pulled in by
25  // 'turnAndLater' (an async agent's earlier edits); the confirmation names
26  // every turn in `refs`.
27  | { ok: true; target: Content; restore: Restore; refs: RevertRef[]; widenedTo?: string[] }
28  // Other turns changed the file inside this change's span, before or after
29  // it in time; 'turnAndLater' reverts them together.
30  | { ok: false; reason: 'changed-since'; otherTurns: string[] }
31  // Two transitions in the span don't link, so reverting would also undo
32  // whatever happened between them; `acceptOutsideChanges` goes ahead anyway.
33  // Why, as far as the index can tell:
34  //   history-trimmed      Claude's edits between them were trimmed away;
35  //   unverifiable-link    the two sides can't be compared (a git blob
36  //                        against a hash, after a commit; an unreadable capture);
37  //   user-changed-between something outside Claude changed the file.
38  // `between` names the two sides' turns; REVERT_TURN is an earlier revert.
39  | { ok: false; reason: 'user-changed-between' | 'unverifiable-link' | 'history-trimmed'; between: [string, string] }
40  | {
41      ok: false
42      reason: 'changed-externally' | 'too-large' | 'no-snapshot' | 'io' | 'already-reverted' | 'nothing-to-revert'
43    }
44
45export type RevertOptions = {
46  // The person confirmed that changes outside the chain may be undone too.
47  acceptOutsideChanges?: boolean
48}
49
50// mode 'turn' undoes this turn's change to the file alone, and only when no
51// other turn's live edit to it falls inside the span; 'turnAndLater' undoes
52// everything from the change's first edit on, pulling in every turn with a
53// live edit in that span (an async agent's turn can start before it).
54export function planRevert(
55  index: Index,
56  ref: RevertRef,
57  mode: 'turn' | 'turnAndLater',
58  current: Content,
59  options: RevertOptions = {},
60): RevertPlan {
61  const history = index.edits.filter(e => e.key === ref.key).sort((a, b) => a.seq - b.seq)
62  const own = history.filter(e => e.turnId === ref.turnId && e.via !== 'revert')
63  if (own.length === 0) return { ok: false, reason: 'nothing-to-revert' }
64  if (statusOf(index, ref.turnId, ref.key) === 'reverted') return { ok: false, reason: 'already-reverted' }
65  if ('unreadable' in current) return { ok: false, reason: current.unreadable === 'too-large' ? 'too-large' : 'io' }
66
67  const isLive = (e: EditRecord) => e.via !== 'revert' && statusOf(index, e.turnId, e.key) !== 'reverted'
68  const firstLiveSeq = (turnId: string) => Math.min(...history.filter(e => e.turnId === turnId && isLive(e)).map(e => e.seq))
69
70  let start = own[0]!.seq
71  const involved = new Set([ref.turnId])
72  if (mode === 'turnAndLater') {
73    // Widen to the first live edit of every turn with a live edit in the span,
74    // until no turn reaches further back.
75    for (let widened = true; widened; ) {
76      widened = false
77      for (const e of history) {
78        if (e.seq < start || !isLive(e) || involved.has(e.turnId)) continue
79        involved.add(e.turnId)
80        const first = firstLiveSeq(e.turnId)
81        if (first < start) {
82          start = first
83          widened = true
84        }
85      }
86    }
87  }
88
89  const span = history.filter(e => e.seq >= start)
90  const others = [...new Set(span.filter(e => isLive(e) && !involved.has(e.turnId)).map(e => e.turnId))]
91  if (others.length > 0) return { ok: false, reason: 'changed-since', otherTurns: others }
92
93  if (!options.acceptOutsideChanges) {
94    for (let i = 1; i < span.length; i++) {
95      const link = sameContent(span[i - 1]!.after, span[i]!.before)
96      if (link === true) continue
97      const between: [string, string] = [span[i - 1]!.turnId, span[i]!.turnId]
98      if ((index.trimmed[ref.key] ?? 0) > span[i - 1]!.seq) return { ok: false, reason: 'history-trimmed', between }
99      return { ok: false, reason: link === null ? 'unverifiable-link' : 'user-changed-between', between }
100    }
101  }
102
103  if (sameContent(current, span[span.length - 1]!.after) !== true) return { ok: false, reason: 'changed-externally' }
104
105  const target = span[0]!.before
106  if (mode === 'turn' && span.length === own.length && sameContent(target, current) === true) {
107    return { ok: false, reason: 'nothing-to-revert' }
108  }
109  const refs = [...involved]
110    .filter(turnId => turnId !== REVERT_TURN && span.some(e => e.turnId === turnId && isLive(e)))
111    .sort((a, b) => firstLiveSeq(a) - firstLiveSeq(b))
112    .map(turnId => ({ turnId, key: ref.key }))
113  const widenedTo = refs.map(r => r.turnId).filter(turnId => firstLiveSeq(turnId) < own[0]!.seq)
114  const plan = (restore: Restore): RevertPlan =>
115    widenedTo.length > 0 ? { ok: true, target, restore, refs, widenedTo } : { ok: true, target, restore, refs }
116
117  if (sameContent(current, target) === true) return plan({ kind: 'none' })
118  if ('absent' in target) return plan({ kind: 'delete' })
119  if ('git' in target) return plan({ kind: 'git-restore', commit: target.git.commit, oid: target.git.oid })
120  if ('hash' in target) return plan({ kind: target.kind === 'text' ? 'write-text' : 'write-bytes', hash: target.hash })
121  return { ok: false, reason: target.unreadable === 'too-large' ? 'too-large' : 'no-snapshot' }
122}
123
hooks/core/timeline.ts 407 lines
1// Pure updates and views over the Changes index (spec §3, §5.1, §5.2).
2// Every update returns a new index and leaves the one it was given alone;
3// no field is ever set to undefined, so the index survives `$.state` as is.
4
5import {
6  KEY_SEP,
7  REVERT_TURN,
8  sameContent,
9  statusKey,
10  type AgentNode,
11  type Content,
12  type EditRecord,
13  type FileStatus,
14  type Index,
15  type TurnRecord,
16  type UntrackedRecord,
17  type UserAction,
18  type Via,
19} from './model.ts'
20
21export const MAX_TURNS = 200
22// About 450 characters each in $.state, so 5,000 stay near 2.3 MB.
23export const MAX_EDITS = 5000
24// Stored prompts are cut to this: the pane shows a line of them, and a long
25// pasted prompt must not fill $.state.
26export const PROMPT_CHARS = 200
27export const MAX_UNTRACKED = 200
28
29// An edit as the wiring reports it; the index assigns `seq` and, unless the
30// caller names one (the turn sweep), the turn.
31export type EditInput = Omit<EditRecord, 'seq' | 'turnId' | 'interleaved'> & { turnId?: string }
32
33// One file in one turn: from the first edit's before to the last edit's after.
34export type FileChange = {
35  turnId: string
36  key: string
37  path: string
38  before: Content
39  after: Content
40  edits: EditRecord[]
41  agentIds: string[]
42  status: FileStatus
43  interleaved: boolean
44  // Consecutive edits don't chain: something else changed the file between them.
45  chainBroken: boolean
46  isNoop: boolean
47}
48
49export type CallNode = { kind: 'call'; toolUseId: string; tool: string; via: Via; agentId?: string; seq: number; keys: string[] }
50export type AgentTreeNode = {
51  kind: 'agent'
52  agentId: string
53  label?: string
54  parentToolUseId?: string
55  seq: number
56  keys: string[]
57  children: TimelineNode[]
58}
59export type TimelineNode = CallNode | AgentTreeNode
60
61export type TimelineRow =
62  | { kind: 'turn'; turn: TurnRecord; nodes: TimelineNode[]; files: FileChange[]; untracked: UntrackedRecord[] }
63  | { kind: 'action'; action: UserAction }
64
65export function openTurn(index: Index, input: { turnId: string; prompt: string; at: number }): Index {
66  const turn: TurnRecord = {
67    turnId: input.turnId,
68    seq: index.nextSeq,
69    kind: 'turn',
70    ordinal: index.nextOrdinal,
71    prompt: input.prompt.slice(0, PROMPT_CHARS),
72    startedAt: input.at,
73  }
74  return trim({
75    ...index,
76    turns: [...index.turns, turn],
77    openTurnId: input.turnId,
78    nextSeq: index.nextSeq + 1,
79    nextOrdinal: index.nextOrdinal + 1,
80  })
81}
82
83export function closeTurn(index: Index, input: { turnId: string; at: number; reason: string }): Index {
84  const turns = index.turns.map(t => (t.turnId === input.turnId ? { ...t, endedAt: input.at, reason: input.reason } : t))
85  if (index.openTurnId !== input.turnId) return { ...index, turns }
86  const { openTurnId: _closed, ...rest } = index
87  return { ...rest, turns }
88}
89
90// Records the agent an `Agent` tool call launched: it belongs to the turn of
91// whoever spawned it (the open main turn, or the spawning agent's turn).
92export function linkAgent(index: Index, input: { agentId: string; parentToolUseId?: string; spawnedBy?: string; label?: string }): Index {
93  // The agent's first edit can land before its spawn's result does: it was
94  // recorded then with no parent, so fill in what the spawn knows. Its turn
95  // stays, since its edits are already filed under it.
96  const known = index.agents.find(a => a.agentId === input.agentId)
97  if (known) {
98    const filled: AgentNode = { ...known }
99    if (filled.parentToolUseId === undefined && input.parentToolUseId !== undefined) filled.parentToolUseId = input.parentToolUseId
100    if (filled.parentAgentId === undefined && input.spawnedBy !== undefined) filled.parentAgentId = input.spawnedBy
101    if (filled.label === undefined && input.label !== undefined) filled.label = input.label
102    return { ...index, agents: index.agents.map(a => (a === known ? filled : a)) }
103  }
104  let next = index
105  let turnId: string
106  if (input.spawnedBy !== undefined) {
107    ;({ index: next, turnId } = turnOfAgent(next, input.spawnedBy))
108  } else {
109    ;({ index: next, turnId } = turnForMain(next, input.agentId))
110  }
111  const agent: AgentNode = { agentId: input.agentId, turnId, seq: next.nextSeq }
112  if (input.parentToolUseId !== undefined) agent.parentToolUseId = input.parentToolUseId
113  if (input.spawnedBy !== undefined) agent.parentAgentId = input.spawnedBy
114  if (input.label !== undefined) agent.label = input.label
115  return { ...next, agents: [...next.agents, agent], nextSeq: next.nextSeq + 1 }
116}
117
118export function addEdit(index: Index, input: EditInput): Index {
119  let next = index
120  let turnId: string
121  if (input.turnId !== undefined) turnId = input.turnId
122  else if (input.agentId !== undefined) ({ index: next, turnId } = turnOfAgent(next, input.agentId))
123  else ({ index: next, turnId } = turnForMain(next, 'main'))
124
125  const record: EditRecord = { ...input, turnId, seq: next.nextSeq }
126  let edits = next.edits
127
128  // Interleaving: the last edit of this file finished after this one began,
129  // and this one's before is not what that one left.
130  const previous = lastEditOf(edits, input.key)
131  if (previous && previous.at > input.startedAt && sameContent(previous.after, input.before) === false) {
132    record.interleaved = true
133    edits = edits.map(e => (e === previous ? { ...e, interleaved: true } : e))
134  }
135  return trim({ ...next, edits: [...edits, record], nextSeq: next.nextSeq + 1 })
136}
137
138// A call whose changes were not recorded: filed like an edit (its agent's
139// turn, else the open turn), kept to the newest MAX_UNTRACKED.
140export function addUntracked(index: Index, input: Omit<UntrackedRecord, 'seq' | 'turnId'> & { agentId?: string; turnId?: string }): Index {
141  let next = index
142  let turnId: string
143  if (input.turnId !== undefined) turnId = input.turnId
144  else if (input.agentId !== undefined) ({ index: next, turnId } = turnOfAgent(next, input.agentId))
145  else ({ index: next, turnId } = turnForMain(next, 'main'))
146  const record: UntrackedRecord = { seq: next.nextSeq, turnId, toolUseId: input.toolUseId, tool: input.tool, reason: input.reason, at: input.at }
147  return { ...next, untracked: [...next.untracked, record].slice(-MAX_UNTRACKED), nextSeq: next.nextSeq + 1 }
148}
149
150export function addAction(index: Index, action: Omit<UserAction, 'seq'>): Index {
151  return { ...index, actions: [...index.actions, { ...action, seq: index.nextSeq }], nextSeq: index.nextSeq + 1 }
152}
153
154export function setStatus(index: Index, refs: { turnId: string; key: string }[], status: FileStatus): Index {
155  const next = { ...index.status }
156  for (const ref of refs) {
157    if (status === 'pending') delete next[statusKey(ref.turnId, ref.key)]
158    else next[statusKey(ref.turnId, ref.key)] = status
159  }
160  return { ...index, status: next }
161}
162
163export function statusOf(index: Index, turnId: string, key: string): FileStatus {
164  return index.status[statusKey(turnId, key)] ?? 'pending'
165}
166
167// The turn's files in the order first changed; `node` narrows to one tool
168// call (its toolUseId) or one agent and the agents it spawned.
169export function turnFiles(index: Index, turnId: string, node?: string): FileChange[] {
170  let edits = index.edits.filter(e => e.turnId === turnId)
171  if (node !== undefined) {
172    const agents = agentAndDescendants(index, node)
173    edits = edits.filter(e => e.toolUseId === node || (e.agentId !== undefined && agents.has(e.agentId)))
174  }
175  const byKey = new Map<string, EditRecord[]>()
176  for (const e of edits) byKey.set(e.key, [...(byKey.get(e.key) ?? []), e])
177  return [...byKey.entries()].map(([key, list]) => {
178    const first = list[0]!
179    const last = list[list.length - 1]!
180    const interleaved = list.some(e => e.interleaved === true)
181    const chainBroken = !interleaved && list.some((e, i) => i > 0 && sameContent(list[i - 1]!.after, e.before) === false)
182    return {
183      turnId,
184      key,
185      path: last.path,
186      before: first.before,
187      after: last.after,
188      edits: list,
189      agentIds: [...new Set(list.flatMap(e => (e.agentId === undefined ? [] : [e.agentId])))],
190      status: statusOf(index, turnId, key),
191      interleaved,
192      chainBroken,
193      isNoop: sameContent(first.before, last.after) === true,
194    }
195  })
196}
197
198// Newest first: each turn (or background bucket) with its tree of calls and
199// agents, and the person's actions between them.
200export function timeline(index: Index): TimelineRow[] {
201  const rows: (TimelineRow & { seq: number })[] = [
202    ...index.turns.map(turn => ({
203      kind: 'turn' as const,
204      seq: turn.seq,
205      turn,
206      nodes: treeOf(index, turn.turnId),
207      files: turnFiles(index, turn.turnId),
208      untracked: index.untracked.filter(u => u.turnId === turn.turnId),
209    })),
210    ...index.actions.map(action => ({ kind: 'action' as const, seq: action.seq, action })),
211  ]
212  return rows.sort((a, b) => b.seq - a.seq).map(({ seq: _seq, ...row }) => row as TimelineRow)
213}
214
215function treeOf(index: Index, turnId: string): TimelineNode[] {
216  const edits = index.edits.filter(e => e.turnId === turnId)
217  const agents = index.agents.filter(a => a.turnId === turnId)
218  const agentIds = new Set(agents.map(a => a.agentId))
219
220  const callsOf = (agentId: string | undefined): CallNode[] => {
221    const calls = new Map<string, CallNode>()
222    for (const e of edits) {
223      if (e.agentId !== agentId) continue
224      const call = calls.get(e.toolUseId)
225      if (call) {
226        if (!call.keys.includes(e.key)) call.keys.push(e.key)
227        continue
228      }
229      const node: CallNode = { kind: 'call', toolUseId: e.toolUseId, tool: e.tool, via: e.via, seq: e.seq, keys: [e.key] }
230      if (e.agentId !== undefined) node.agentId = e.agentId
231      calls.set(e.toolUseId, node)
232    }
233    return [...calls.values()]
234  }
235
236  const agentNode = (agent: AgentNode): AgentTreeNode => {
237    const children = [
238      ...callsOf(agent.agentId),
239      ...agents.filter(a => a.parentAgentId === agent.agentId).map(agentNode),
240    ].sort((a, b) => a.seq - b.seq)
241    const node: AgentTreeNode = {
242      kind: 'agent',
243      agentId: agent.agentId,
244      seq: agent.seq,
245      keys: [...new Set(children.flatMap(c => c.keys))],
246      children,
247    }
248    if (agent.label !== undefined) node.label = agent.label
249    if (agent.parentToolUseId !== undefined) node.parentToolUseId = agent.parentToolUseId
250    return node
251  }
252
253  const roots = agents.filter(a => a.parentAgentId === undefined || !agentIds.has(a.parentAgentId))
254  return [...callsOf(undefined), ...roots.map(agentNode)].sort((a, b) => a.seq - b.seq)
255}
256
257function agentAndDescendants(index: Index, agentId: string): Set<string> {
258  const found = new Set<string>()
259  if (!index.agents.some(a => a.agentId === agentId)) return found
260  const queue = [agentId]
261  while (queue.length > 0) {
262    const id = queue.shift()!
263    if (found.has(id)) continue
264    found.add(id)
265    for (const a of index.agents) if (a.parentAgentId === id) queue.push(a.agentId)
266  }
267  return found
268}
269
270function lastEditOf(edits: EditRecord[], key: string): EditRecord | undefined {
271  for (let i = edits.length - 1; i >= 0; i--) if (edits[i]!.key === key) return edits[i]
272  return undefined
273}
274
275// The turn an agent's work belongs to; an agent with no recorded spawn is
276// recorded now against the open turn, or a background bucket of its own.
277function turnOfAgent(index: Index, agentId: string): { index: Index; turnId: string } {
278  const known = index.agents.find(a => a.agentId === agentId)
279  if (known) return { index, turnId: known.turnId }
280  const { index: next, turnId } = turnForMain(index, agentId)
281  const agent: AgentNode = { agentId, turnId, seq: next.nextSeq }
282  return { index: { ...next, agents: [...next.agents, agent], nextSeq: next.nextSeq + 1 }, turnId }
283}
284
285// The open main turn, else the background bucket named for `owner`.
286function turnForMain(index: Index, owner: string): { index: Index; turnId: string } {
287  if (index.openTurnId !== undefined) return { index, turnId: index.openTurnId }
288  const turnId = `background:${owner}`
289  if (index.turns.some(t => t.turnId === turnId)) return { index, turnId }
290  const bucket: TurnRecord = { turnId, seq: index.nextSeq, kind: 'background', ordinal: 0, prompt: '', startedAt: 0 }
291  return { index: trim({ ...index, turns: [...index.turns, bucket], nextSeq: index.nextSeq + 1 }), turnId }
292}
293
294// Keeps at most MAX_TURNS turns and MAX_EDITS edits, dropping the oldest
295// turns whole. A turn that is open, or whose agents are still running, is
296// never dropped: their edits still arrive. A dropped turn's changes stop being
297// revertible, and a later turn whose chain ran through them is refused by
298// planRevert's link check, never restored wrongly.
299function trim(index: Index): Index {
300  let next = index
301  while (next.turns.length > MAX_TURNS || next.edits.length > MAX_EDITS) {
302    const dropped = dropOldest(next)
303    if (dropped === null) break
304    next = dropped
305  }
306  return next
307}
308
309// The index with its oldest droppable turn removed, or null when none is.
310function dropOldest(index: Index): Index | null {
311  const running = new Set(index.agents.filter(a => a.endedAt === undefined).map(a => a.turnId))
312  const victim = [...index.turns]
313    .sort((a, b) => a.seq - b.seq)
314    .find(t => t.turnId !== index.openTurnId && !running.has(t.turnId))
315  if (!victim) return null
316  const gone = victim.turnId
317  const turns = index.turns.filter(t => t.turnId !== gone)
318  // Reverts older than every remaining turn have nothing left to chain to.
319  const oldest = Math.min(...turns.map(t => t.seq), index.nextSeq)
320  const status: Record<string, FileStatus> = {}
321  for (const [k, v] of Object.entries(index.status)) if (k.slice(0, k.indexOf(KEY_SEP)) !== gone) status[k] = v
322  const keep = (e: EditRecord) => (e.via === 'revert' ? e.seq > oldest : e.turnId !== gone)
323  const trimmed = { ...index.trimmed }
324  for (const e of index.edits) if (!keep(e)) trimmed[e.key] = Math.max(trimmed[e.key] ?? 0, e.seq)
325  return {
326    ...index,
327    turns,
328    trimmed,
329    edits: index.edits.filter(keep),
330    agents: index.agents.filter(a => a.turnId !== gone),
331    untracked: index.untracked.filter(u => u.turnId !== gone),
332    actions: index.actions
333      .map(a => ({ ...a, turnIds: a.turnIds.filter(id => id !== gone) }))
334      .filter(a => a.turnIds.length > 0),
335    status,
336  }
337}
338
339// What `$.state` holds per value is 4,194,304 characters; this leaves room.
340export const STATE_BUDGET_CHARS = 4_000_000
341
342// The index trimmed until its JSON fits `budget`; `fits` false when nothing
343// droppable is left and it still doesn't (the caller then skips the write).
344// Measured on the JSON itself: a count of records says nothing about a long
345// path or prompt.
346export function fitToSize(index: Index, budget = STATE_BUDGET_CHARS): { index: Index; fits: boolean } {
347  let next = index
348  while (JSON.stringify(next).length > budget) {
349    const dropped = dropOldest(next)
350    if (dropped === null) return { index: next, fits: false }
351    next = dropped
352  }
353  return { index: next, fits: true }
354}
355
356// The JSON characters `next` adds to `prev` when it only appended records
357// (and changed statuses or counters), so a save can skip measuring the whole
358// index; null when anything else changed (a trim, a record replaced at either
359// end) and only a full measure can tell. A record replaced in the middle (an
360// `interleaved` flag) is missed by a few characters: the caller re-measures
361// in full every so often.
362export function appendedSize(prev: Index, next: Index): number | null {
363  if (prev.trimmed !== next.trimmed) return null
364  let size = 64
365  for (const list of ['turns', 'edits', 'agents', 'actions', 'untracked'] as const) {
366    const before: readonly unknown[] = prev[list]
367    const after: readonly unknown[] = next[list]
368    if (before === after) continue
369    if (after.length < before.length) return null
370    if (before.length > 0 && (after[0] !== before[0] || after[before.length - 1] !== before[before.length - 1])) return null
371    for (let i = before.length; i < after.length; i++) size += JSON.stringify(after[i]).length + 1
372  }
373  if (prev.status !== next.status) size += Math.max(0, JSON.stringify(next.status).length - JSON.stringify(prev.status).length)
374  return size
375}
376
377// The agent's run completed (its turn.complete carried its agentId).
378export function closeAgent(index: Index, agentId: string, at: number): Index {
379  if (!index.agents.some(a => a.agentId === agentId && a.endedAt === undefined)) return index
380  return trim({ ...index, agents: index.agents.map(a => (a.agentId === agentId ? { ...a, endedAt: at } : a)) })
381}
382
383// A revert that landed: the disk transition joins the file's chain, the
384// reverted changes are marked, and the action goes on the timeline.
385export function recordRevert(
386  index: Index,
387  input: { key: string; path: string; before: Content; after: Content; refs: { turnId: string; key: string }[]; at: number },
388): Index {
389  const transition: EditRecord = {
390    seq: index.nextSeq,
391    turnId: REVERT_TURN,
392    toolUseId: `revert:${index.nextSeq}`,
393    tool: 'Changes',
394    via: 'revert',
395    path: input.path,
396    key: input.key,
397    before: input.before,
398    after: input.after,
399    startedAt: input.at,
400    at: input.at,
401  }
402  let next: Index = { ...index, edits: [...index.edits, transition], nextSeq: index.nextSeq + 1 }
403  next = setStatus(next, input.refs, 'reverted')
404  next = addAction(next, { kind: 'revert', turnIds: [...new Set(input.refs.map(r => r.turnId))], key: input.key, path: input.path, at: input.at })
405  return trim(next)
406}
407
hooks/io/blobs.ts 104 lines
1// The snapshot store (spec §5.2, §5.6): content-addressed blobs under
2// `<config>/plugin-data/notary-changes/<sessionId>/blobs/`, `<sha256>.txt`
3// for text a write gives back byte for byte, `<sha256>.b64` for the rest.
4
5import { base64FromBytes, bytesFromBase64, describe } from '../core/content.ts'
6import type { Content } from '../core/model.ts'
7import type { Platform, Ports } from './ports.ts'
8
9// `$.fs` refuses reads over this.
10export const MAX_READ_BYTES = 4 * 1024 * 1024
11
12const slashes = (path: string) => path.replace(/\\/g, '/')
13
14// The variables as register read them with `$.env.get` (names must be literals).
15export type StoreEnv = { CLAUDE_CONFIG_DIR?: string; USERPROFILE?: string; HOME?: string }
16
17export function storeDirOf(env: StoreEnv, sessionId: string): string {
18  const home = env.USERPROFILE ?? env.HOME ?? '.'
19  const config = env.CLAUDE_CONFIG_DIR ?? `${slashes(home).replace(/\/$/, '')}/.claude`
20  return `${slashes(config).replace(/\/$/, '')}/plugin-data/notary-changes/${sessionId}`
21}
22
23export async function sha256Hex(bytes: Uint8Array): Promise<string> {
24  const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', bytes))
25  return Array.from(digest, b => b.toString(16).padStart(2, '0')).join('')
26}
27
28// The bytes a session's new blobs may still take; `full` once one was refused.
29export type StoreBudget = { used: number; cap: number; full: boolean }
30
31// What the file holds now: absent, too large, unreadable, or its hash and
32// kind, with the blob written unless `store` is false (a check, not a
33// snapshot). A blob the budget has no room for is not written, and the
34// capture is `{ unreadable: 'io' }`: never a hash that names no saved copy.
35export async function capture(io: Ports, store: string, path: string, options: { store?: boolean; budget?: StoreBudget } = {}): Promise<Content> {
36  try {
37    if (!(await io.fs.exists(path))) return { absent: true }
38    const stat = await io.fs.stat(path)
39    if (stat.kind !== 'file') return { unreadable: 'io' }
40    if (stat.size > MAX_READ_BYTES) return { unreadable: 'too-large' }
41    const read = await io.fs.read(path, { as: 'bytes' })
42    const bytes = bytesFromBase64(typeof read === 'string' ? read : read.base64)
43    const meta = describe(bytes)
44    const hash = await sha256Hex(bytes)
45    if (options.store !== false) {
46      const blob = `${store}/blobs/${hash}.${meta.kind === 'text' ? 'txt' : 'b64'}`
47      if (!(await io.fs.exists(blob))) {
48        const budget = options.budget
49        if (budget !== undefined && budget.used + bytes.length > budget.cap) {
50          budget.full = true
51          return { unreadable: 'io' }
52        }
53        await io.fs.write(blob, meta.kind === 'text' ? meta.text : base64FromBytes(bytes))
54        if (budget !== undefined) budget.used += bytes.length
55      }
56    }
57    return meta.kind === 'text'
58      ? { hash, size: meta.size, kind: 'text', eol: meta.eol, bom: meta.bom }
59      : { hash, size: meta.size, kind: 'binary', eol: 'none', bom: false }
60  } catch {
61    return { unreadable: 'io' }
62  }
63}
64
65export async function loadText(io: Ports, store: string, hash: string): Promise<string | null> {
66  try {
67    return (await io.fs.read(`${store}/blobs/${hash}.txt`)) as string
68  } catch {
69    return null
70  }
71}
72
73export async function loadBase64(io: Ports, store: string, hash: string): Promise<string | null> {
74  try {
75    return (await io.fs.read(`${store}/blobs/${hash}.b64`)) as string
76  } catch {
77    return null
78  }
79}
80
81// A file's identity across spellings: where the path really lands (links and
82// `..` resolved; for a file not there yet, its folder's real path plus the
83// name), lowercased on Windows, whose file system ignores case.
84export async function keyOf(io: Ports, path: string, platform: Platform): Promise<string> {
85  const normal = slashes(path)
86  let real = normal
87  try {
88    const own = await io.fs.stat(path, { resolve: true })
89    real = own.realPath ?? normal
90  } catch {
91    const cut = normal.lastIndexOf('/')
92    if (cut > 0) {
93      try {
94        const folder = await io.fs.stat(normal.slice(0, cut), { resolve: true })
95        if (folder.realPath) real = `${slashes(folder.realPath).replace(/\/$/, '')}${normal.slice(cut)}`
96      } catch {
97        // The folder is missing too: keep the spelling.
98      }
99    }
100  }
101  real = slashes(real)
102  return platform === 'windows' ? real.toLowerCase() : real
103}
104
hooks/io/diffs.ts 64 lines
1// A file's diff for the pane: each side's text from the blob store, git (its
2// filters applied, so line endings match the working copy) or nothing, then
3// core/diff.ts. Thin: what can't be drawn comes back as a note.
4
5import { diffText, limitHunks } from '../core/diff.ts'
6import type { Content } from '../core/model.ts'
7import { relativeTo } from '../core/paths.ts'
8import { loadText } from './blobs.ts'
9import { filteredText, type GitBudget } from './git.ts'
10import type { Platform, Ports } from './ports.ts'
11
12// As `/diff` draws them: 400 rows per file, then "show all"; no diff of a
13// side over 1 MB.
14export const MAX_DIFF_ROWS = 400
15export const MAX_DIFF_BYTES = 1_000_000
16
17export type DiffView =
18  | { kind: 'diff'; hunks: string; added: number; removed: number; shownRows: number; totalRows: number; eolOnly?: true; bomChanged?: true; capped?: true }
19  | { kind: 'note'; text: string }
20
21export type DiffContext = { store: string; root: string | null; platform: Platform }
22
23type Side = { text: string } | { note: string }
24
25export async function sideText(io: Ports, ctx: DiffContext, content: Content, path: string, budget?: GitBudget): Promise<Side> {
26  if ('absent' in content) return { text: '' }
27  if ('unreadable' in content) return { note: content.unreadable === 'too-large' ? 'too large to show' : 'no saved copy to compare' }
28  if ('git' in content) {
29    const rel = ctx.root === null ? undefined : relativeTo(ctx.root, path, ctx.platform === 'windows')
30    if (rel === undefined) return { note: 'no saved copy to compare' }
31    const text = await filteredText(io, ctx.root!, content.git.commit, rel, budget)
32    if (text === null) return { note: 'no saved copy to compare' }
33    return text.length > MAX_DIFF_BYTES ? { note: 'too large to show' } : { text }
34  }
35  if (content.kind === 'binary') return { note: 'binary file' }
36  if (content.size > MAX_DIFF_BYTES) return { note: 'too large to show' }
37  const text = await loadText(io, ctx.store, content.hash)
38  return text === null ? { note: 'no saved copy to compare' } : { text }
39}
40
41// `all` draws every row; otherwise the first MAX_DIFF_ROWS.
42// `budget` bounds the git reads of a fetch that diffs several files.
43export async function diffOf(io: Ports, ctx: DiffContext, file: { before: Content; after: Content; path: string }, all: boolean, budget?: GitBudget): Promise<DiffView> {
44  const before = await sideText(io, ctx, file.before, file.path, budget)
45  const after = await sideText(io, ctx, file.after, file.path, budget)
46  if ('note' in before) return { kind: 'note', text: before.note }
47  if ('note' in after) return { kind: 'note', text: after.note }
48  const diff = diffText(before.text, after.text)
49  const limited = all ? { hunks: diff.hunks, shownRows: 0, totalRows: 0 } : limitHunks(diff.hunks, MAX_DIFF_ROWS)
50  const rows = all ? diff.hunks.split('\n').filter(r => r !== '' && !r.startsWith('@@')).length : limited.shownRows
51  const view: DiffView = {
52    kind: 'diff',
53    hunks: limited.hunks,
54    added: diff.added,
55    removed: diff.removed,
56    shownRows: rows,
57    totalRows: all ? rows : limited.totalRows,
58  }
59  if (diff.eolOnly) view.eolOnly = true
60  if (diff.bomChanged) view.bomChanged = true
61  if (diff.capped) view.capped = true
62  return view
63}
64
hooks/io/history.ts 141 lines
1// A conversation's history kept on disk, so a resumed conversation
2// (`claude --resume`, `--continue`, `/resume`) shows its turns again
3// (docs/notes/changes-history-persist.md). It lives next to the copies, in
4// `<config>/plugin-data/notary-changes/<sessionId>/index.json`.
5//
6// One process writes it at a time: the holder of `lease.json`. A second
7// process on the same conversation shows the history but never writes it.
8
9import type { Index } from '../core/model.ts'
10import { MAX_READ_BYTES } from './blobs.ts'
11import type { Platform, Ports } from './ports.ts'
12import { cleanUp, moveInto, tmpFor } from './restore.ts'
13
14export const HISTORY_FORMAT = 1
15// A lease not renewed for this long belongs to a process that is gone (a
16// crash, a killed terminal): a live holder renews it every LEASE_RENEW_MS.
17export const LEASE_STALE_MS = 10 * 60 * 1000
18export const LEASE_RENEW_MS = 60 * 1000
19
20const historyFile = (store: string) => `${store}/index.json`
21const leaseFile = (store: string) => `${store}/lease.json`
22
23export type Loaded = { index: Index } | { unreadable: 'corrupt' | 'format' | 'other-session' } | null
24
25// Writes the history as one file in one rename: the text goes to a temp file
26// of its own (tmpFor), which then replaces index.json, so a crash leaves the
27// old file or the new, never half of one. Refused (false) when it would be too
28// large to read back.
29export async function saveHistory(io: Ports, platform: Platform, store: string, sessionId: string, index: Index, now: number): Promise<boolean> {
30  const text = JSON.stringify({ format: HISTORY_FORMAT, sessionId, savedAt: now, index })
31  if (new TextEncoder().encode(text).length > MAX_READ_BYTES) return false
32  // A temp file of this save's own; only it is removed when the save fails.
33  let tmp: string | null = null
34  try {
35    tmp = await tmpFor(io, historyFile(store))
36    if (tmp === null) return false
37    await io.fs.write(tmp, text)
38    return (await moveInto(io, platform, tmp, historyFile(store))) || (await cleanUp(io, platform, tmp))
39  } catch {
40    if (tmp !== null) await cleanUp(io, platform, tmp)
41    return false
42  }
43}
44
45// The history saved for this conversation: null when there is none; a file
46// that does not parse, is of another format or another conversation, or does
47// not hold an index of the right shape, is refused whole, never half-loaded.
48export async function loadHistory(io: Ports, store: string, sessionId: string): Promise<Loaded> {
49  let text: string
50  try {
51    if (!(await io.fs.exists(historyFile(store)))) return null
52    text = String(await io.fs.read(historyFile(store)))
53  } catch {
54    return { unreadable: 'corrupt' }
55  }
56  let saved: unknown
57  try {
58    saved = JSON.parse(text)
59  } catch {
60    return { unreadable: 'corrupt' }
61  }
62  if (!isRecord(saved)) return { unreadable: 'corrupt' }
63  if (saved.format !== HISTORY_FORMAT) return { unreadable: 'format' }
64  if (saved.sessionId !== sessionId) return { unreadable: 'other-session' }
65  return isIndex(saved.index) ? { index: saved.index } : { unreadable: 'corrupt' }
66}
67
68export type Lease = { token: string; at: number }
69
70// Takes the lease, or answers that another live process holds it. A lease
71// that is missing, released (at 0), our own, or not renewed within
72// LEASE_STALE_MS is taken. The write is read back: of two processes taking
73// it at once, the one that reads another token is not the holder. A holder
74// checks the lease again before each save (holdsLease), so a takeover is
75// seen before anything is written.
76export async function takeLease(io: Ports, store: string, token: string, now: number): Promise<boolean> {
77  const current = await readLease(io, store)
78  if (current !== null && current.token !== token && current.at > 0 && now - current.at < LEASE_STALE_MS) return false
79  try {
80    await io.fs.write(leaseFile(store), JSON.stringify({ token, at: now }))
81  } catch {
82    return false
83  }
84  return (await readLease(io, store))?.token === token
85}
86
87export async function holdsLease(io: Ports, store: string, token: string): Promise<boolean> {
88  return (await readLease(io, store))?.token === token
89}
90
91// Renews the lease (a heartbeat), only while it is still ours.
92export async function renewLease(io: Ports, store: string, token: string, now: number): Promise<boolean> {
93  if (!(await holdsLease(io, store, token))) return false
94  try {
95    await io.fs.write(leaseFile(store), JSON.stringify({ token, at: now }))
96    return true
97  } catch {
98    return false
99  }
100}
101
102// Gives the lease up at the session's end (one small write), so the next
103// process takes it at once.
104export async function releaseLease(io: Ports, store: string, token: string): Promise<void> {
105  try {
106    if (await holdsLease(io, store, token)) await io.fs.write(leaseFile(store), JSON.stringify({ token, at: 0 }))
107  } catch {
108    // Best effort: an unreleased lease goes stale on its own.
109  }
110}
111
112async function readLease(io: Ports, store: string): Promise<Lease | null> {
113  try {
114    if (!(await io.fs.exists(leaseFile(store)))) return null
115    const lease: unknown = JSON.parse(String(await io.fs.read(leaseFile(store))))
116    return isRecord(lease) && typeof lease.token === 'string' && typeof lease.at === 'number' ? { token: lease.token, at: lease.at } : null
117  } catch {
118    return null
119  }
120}
121
122function isRecord(value: unknown): value is Record<string, unknown> {
123  return typeof value === 'object' && value !== null && !Array.isArray(value)
124}
125
126// The shape the pane and the planner read; anything else is refused.
127function isIndex(value: unknown): value is Index {
128  if (!isRecord(value)) return false
129  const arrays = ['turns', 'edits', 'agents', 'actions', 'untracked'] as const
130  if (!arrays.every(key => Array.isArray(value[key]))) return false
131  if (!isRecord(value.status) || !isRecord(value.trimmed)) return false
132  if (typeof value.nextSeq !== 'number' || typeof value.nextOrdinal !== 'number') return false
133  const turns = value.turns as unknown[]
134  const edits = value.edits as unknown[]
135  const isTurn = (t: unknown) => isRecord(t) && typeof t.turnId === 'string' && typeof t.ordinal === 'number' && typeof t.seq === 'number' && typeof t.prompt === 'string'
136  const isContent = (c: unknown) => isRecord(c) && ('hash' in c || 'git' in c || 'absent' in c || 'unreadable' in c)
137  const isEdit = (e: unknown) =>
138    isRecord(e) && typeof e.seq === 'number' && typeof e.turnId === 'string' && typeof e.key === 'string' && typeof e.path === 'string' && isContent(e.before) && isContent(e.after)
139  return turns.every(isTurn) && edits.every(isEdit)
140}
141
hooks/io/git.ts 134 lines
1// Git, by argv. Thin: each call answers its value or null and never throws;
2// what the answers mean is decided in core/git-status.ts and core/revert-plan.ts.
3
4import type { ProcessRunResult } from 'claude-code'
5
6import { NUL, parseStatus, type StatusEntry } from '../core/git-status.ts'
7import type { Ports } from './ports.ts'
8
9export const GIT_TIMEOUT_MS = 5000
10
11// Global options on every call: never take the index lock from a git the
12// person is running, read paths literally (no globs), print paths unquoted.
13const LEAD = ['--no-optional-locks', '--literal-pathspecs', '-c', 'core.quotePath=false']
14
15// A deadline several git calls share (the shell budget, a diff fetch): each
16// call's timeout is the time left, at most GIT_TIMEOUT_MS, and none starts
17// once it has passed (`over`). A call killed at its timeout sets `timedOut`:
18// git is slow here.
19export type GitBudget = { deadline: number; over: boolean; timedOut: boolean }
20
21export function gitBudget(now: number, ms: number): GitBudget {
22  return { deadline: now + ms, over: false, timedOut: false }
23}
24
25export async function runGit(io: Ports, cwd: string, args: readonly string[], stdin?: string, budget?: GitBudget): Promise<ProcessRunResult | null> {
26  let timeoutMs = GIT_TIMEOUT_MS
27  if (budget !== undefined) {
28    const left = budget.deadline - (await io.clock.now())
29    if (left <= 0) {
30      budget.over = true
31      return null
32    }
33    timeoutMs = Math.min(timeoutMs, Math.ceil(left))
34  }
35  const startedAt = budget === undefined ? 0 : await io.clock.now()
36  try {
37    return await io.process.run(['git', ...LEAD, ...args], {
38      cwd,
39      env: { LC_ALL: 'C', LANGUAGE: '' },
40      timeoutMs,
41      ...(stdin === undefined ? {} : { stdin }),
42    })
43  } catch {
44    if (budget !== undefined && (await io.clock.now()) - startedAt >= timeoutMs) budget.timedOut = true
45    return null
46  }
47}
48
49async function line(io: Ports, cwd: string, args: readonly string[], budget?: GitBudget): Promise<string | null> {
50  const r = await runGit(io, cwd, args, undefined, budget)
51  if (!r || r.exitCode !== 0) return null
52  const out = r.stdout.trim()
53  return out === '' ? null : out
54}
55
56export async function repoRootOf(io: Ports, cwd: string): Promise<string | null> {
57  return line(io, cwd, ['rev-parse', '--show-toplevel'])
58}
59
60// null on an unborn HEAD (a repository with no commit yet).
61export async function headOf(io: Ports, root: string, budget?: GitBudget): Promise<string | null> {
62  return line(io, root, ['rev-parse', '--verify', '--quiet', 'HEAD'], budget)
63}
64
65// null when git failed or its answer was cut: a partial status would make
66// files look clean that are not.
67export async function statusOf(io: Ports, root: string, budget?: GitBudget): Promise<Map<string, StatusEntry> | null> {
68  const r = await runGit(io, root, ['status', '--porcelain=v1', '-z', '--untracked-files=all'], undefined, budget)
69  if (!r || r.exitCode !== 0 || r.isStdoutTruncated) return null
70  return parseStatus(r.stdout)
71}
72
73// The blob at `rel` in `commit`, or null when the commit has no such path.
74export async function blobAt(io: Ports, root: string, commit: string, rel: string): Promise<string | null> {
75  return line(io, root, ['rev-parse', '--verify', '--quiet', `${commit}:${rel}`])
76}
77
78// The blob at each `rel` in `commit` (null where the commit has none), from
79// one git process. null when git fails.
80export async function blobsAt(io: Ports, root: string, commit: string, rels: readonly string[], budget?: GitBudget): Promise<Map<string, string | null> | null> {
81  if (rels.length === 0) return new Map()
82  const r = await runGit(io, root, ['cat-file', '--batch-check'], rels.map(rel => `${commit}:${rel}`).join('\n') + '\n', budget)
83  if (!r || r.exitCode !== 0 || r.isStdoutTruncated) return null
84  const lines = r.stdout.split('\n').filter(l => l !== '')
85  if (lines.length !== rels.length) return null
86  return new Map(rels.map((rel, i) => [rel, / blob \d+$/.test(lines[i]!) ? lines[i]!.split(' ')[0]! : null]))
87}
88
89// The blob ids the working files would have (clean filters applied), from
90// one git process; every path must exist. null when git fails.
91export async function hashObjects(io: Ports, root: string, rels: readonly string[], budget?: GitBudget): Promise<Map<string, string> | null> {
92  if (rels.length === 0) return new Map()
93  const r = await runGit(io, root, ['hash-object', '--stdin-paths'], rels.join('\n') + '\n', budget)
94  if (!r || r.exitCode !== 0 || r.isStdoutTruncated) return null
95  const lines = r.stdout.split('\n').filter(l => l !== '')
96  if (lines.length !== rels.length) return null
97  return new Map(rels.map((rel, i) => [rel, lines[i]!.trim()]))
98}
99
100// The blob id the working file would have, clean filters (autocrlf) applied.
101export async function hashObject(io: Ports, root: string, rel: string): Promise<string | null> {
102  return line(io, root, ['hash-object', '--', rel])
103}
104
105// The blob's text as a checkout would write it (smudge filters applied).
106export async function filteredText(io: Ports, root: string, commit: string, rel: string, budget?: GitBudget): Promise<string | null> {
107  const r = await runGit(io, root, ['cat-file', '--filters', `${commit}:${rel}`], undefined, budget)
108  if (!r || r.exitCode !== 0 || r.isStdoutTruncated) return null
109  return r.stdout
110}
111
112
113// For a file `$.fs` can't read (over 4 MiB): its blob in HEAD when the
114// working file is clean, so a revert can still come from git (spec §5.2).
115export async function cleanBlobOf(io: Ports, root: string, rel: string): Promise<{ oid: string; commit: string } | null> {
116  const head = await headOf(io, root)
117  if (head === null) return null
118  const r = await runGit(io, root, ['status', '--porcelain=v1', '-z', '--', rel])
119  if (!r || r.exitCode !== 0 || r.stdout !== '') return null
120  const oid = await blobAt(io, root, head, rel)
121  return oid === null ? null : { oid, commit: head }
122}
123
124export async function namesBetween(io: Ports, root: string, from: string, to: string): Promise<string[] | null> {
125  const r = await runGit(io, root, ['diff', '--name-only', '-z', '--no-renames', from, to])
126  if (!r || r.exitCode !== 0 || r.isStdoutTruncated) return null
127  return r.stdout.split(NUL).filter(p => p !== '')
128}
129
130export async function restoreFrom(io: Ports, root: string, commit: string, rel: string): Promise<boolean> {
131  const r = await runGit(io, root, ['restore', `--source=${commit}`, '--worktree', '--', rel])
132  return r !== null && r.exitCode === 0
133}
134
hooks/io/ports.ts 19 lines
1// What io/ may do to the machine, handed in by register.tsx. The loader
2// follows `$` only into functions of the file that uses it, never across an
3// import, so register builds these closures over `$` and io/ never sees `$`.
4
5import type { EngineInterface } from 'claude-code'
6
7export type Ports = {
8  fs: Pick<EngineInterface['fs'], 'read' | 'write' | 'exists' | 'stat' | 'list'>
9  process: Pick<EngineInterface['process'], 'run'>
10  clock: Pick<EngineInterface['clock'], 'now'>
11}
12
13export type Platform = 'windows' | 'posix'
14
15// From `$.env.get('OS')`, read in register (env names must be literals).
16export function platformOf(os: string | undefined): Platform {
17  return os === 'Windows_NT' ? 'windows' : 'posix'
18}
19