Copilot-style review of the files Claude changes: a tree of changed files with +/- counts, accept/reject per file, folder or all, and a VS Code diff to revert…

Review every file Claude touches, like a pull request, without leaving the terminal.
<img src="assets/demo.gif" alt="pending-changes demo: Claude edits files, the review pane lists them, changes are reverted in VS Code and rejected with one click" width="900">
Claude just edited five files. Which ones? What changed? How do you undo only the bad part?
pending-changes docks a GitHub Copilot-style review pane next to your chat. Every file Claude creates, edits or deletes shows up as a tree with green/red line counts. Accept or reject per file, per folder or all at once, or open a side-by-side VS Code diff to revert single blocks. Whatever you decide, Claude is told, so its picture of the code never drifts from what's actually on disk.
/plugin install pending-changes --marketplace comertial/comertial-mods
| 🌳 Changes as a tree | Every changed file with +added -removed counts, a coloured added / modified / deleted status on every file, and collapsible, compact folders. |
| ✅ One-click accept / reject | Per file, per folder or everything. Reject restores originals, deletes new files (and the empty folders Claude made for them) and brings deleted files back. |
| 🔍 Real diffs in VS Code | Click a file for a side-by-side diff. Revert single blocks or edit by hand; the pane updates within ~2 seconds. |
| 🐚 Catches shell changes too | Not just Edit/Write: formatters, codegen, git checkout, npm install, scripts. Anything that moves in git status is tracked. |
| 🧠 Claude stays in sync | Every reject, revert or hand edit is reported back to Claude, so it never works from a stale picture of your code. |
| 💾 Survives sessions | In a git repo, the review list and its originals outlive /clear, /exit and new sessions, and sessions working in one checkout share one list. Pick the review up where you left it. |
▾ demo/config/ +4 -0 [ ✓ ] [ ✗ ]
└─ settings.json added +4 -0 [ ✓ ] [ ✗ ]
▾ testFolder/ +11 -1 [ ✓ ] [ ✗ ]
├─ ▾ sub/ +7 -0 [ ✓ ] [ ✗ ]
│ ├─ deeper.json added +4 -0 [ ✓ ] [ ✗ ]
│ └─ notes.md added +3 -0 [ ✓ ] [ ✗ ]
└─ test.txt modified +1 -1 [ ✓ ] [ ✗ ]
t̶e̶s̶t̶.̶j̶s̶o̶n̶ deleted +0 -3 [ ✓ ] [ ✗ ]
5 files +15 -4 [ Accept all ] [ Reject all ]
Published through the comertial-mods marketplace. In a Claude Code session:
/plugin install pending-changes --marketplace comertial/comertial-mods
Or from a shell:
claude plugin marketplace add comertial/comertial-mods
claude plugin install pending-changes@comertial-mods --scope user
--scope user loads it in every session, in any project. Verify with claude plugin list: it should show pending-changes@comertial-mods with Status: ✔ enabled.
| Update | claude plugin marketplace update comertial-mods, then claude plugin update pending-changes@comertial-mods |
| Auto-update | Off by default for third-party marketplaces. To get new versions on their own, open /plugin → Marketplaces → comertial-mods → Enable auto-update. |
| Remove | claude plugin uninstall pending-changes@comertial-mods |
Requirements
code command on PATH for the diff view. Without it, clicking a file shows a toast.It opens on its own the first time Claude changes a file in the project, or any time with /changes.
| Where it shows | |
|---|---|
/changes | At any width: docked beside the chat on a wide fullscreen terminal (110+ columns), otherwise below the chat, above the prompt. |
| On its own | Claude Code only seats a pane a mod opens unprompted from 144 columns (110 once you've opened it with /changes, until you close it by hand). On a narrower terminal it waits, and a toast tells you to run /changes. |
| Element | What it does |
|---|---|
| File row | File name, then its status: a green added (underlined name) for files Claude created, a yellow modified (italic name) for files Claude edited, or a red deleted (struck-through, dim name) for files Claude deleted. Then green +added and red -removed counts. |
| File name (click) | Opens the VS Code diff for that file. |
| ✓ on a file | Accepts: removes it from the list. The change is already on disk, so nothing else happens. |
| ✗ on a file | Rejects: restores the original, deletes a file Claude created (plus any now-empty folders Claude created), or recreates a file Claude deleted. Then Claude is told. |
| Folder row | Bold colored name with ▾ (expanded) or ▸ (collapsed), plus the combined counts of everything under it. |
| Folder name (click) | Collapses or expands it. The state survives mod reloads. |
| ✓ / ✗ on a folder | Accepts or rejects every file under it, including subfolders. |
| Accept all / Reject all | The same for every file in the list. |
| Hover | The row under the mouse gets a grey background, so it's clear which ✓/✗ belongs to which file. |
other session / earlier | A dim tag on a file another session's Claude changed: one that's still running, or one that has ended. |
other branch | A dim tag on a file changed while another branch was checked out. |
other window | The same session is open in another window: this pane isn't shared, and a file with this tag may be out of date. A banner at the top says so. |
| "N more pending outside this folder" | Pending files elsewhere in the repo, outside the folder this session runs in. Open a session there to review them. |
Layout: folders come before files, each sorted by name. A folder containing only one other folder is merged into one row (▾ demo/config/), like VS Code's compact folders. Dim ├─ └─ │ guides show nesting below the top level. Long names are trimmed from the left with ….
Clicking a file runs code --diff <original> <file>:
Revert single blocks with the gutter arrow between the sides (VS Code calls it "Revert Block"; it copies the original block back over Claude's version), edit the right side by hand, and save. Saves go straight to your project file. Within about 2 seconds:
In a git repo, the list is kept per checkout (each git worktree has its own):
/clear or --resume picks up every file still pending, with its original, so ✓, ✗ and the diff work as before. Claude is told which files have unreviewed changes from an earlier session.other window tag on the files it listed then, or with a toast if the pane isn't open. It shares again once the first window closes.The originals are stored in git's object store and pinned by a hidden ref, refs/pending-changes/*. Nothing is committed, nothing shows in git status or git log, and ordinary pushes and clones don't carry it.
In /config:
| Setting | Default | What it does |
|---|---|---|
Keep pending changes across sessions (persistAcrossSessions) | on | Off: each session has its own list, and a new one starts empty. |
Open the pane at session start (openOnStart) | auto | auto opens the pane when files are pending at start; toast only says so. |
Only files inside the session's working directory. Scratch scripts in temp folders and files elsewhere are ignored.
| Source of the change | How it's caught |
|---|---|
| Claude's Edit, Write, NotebookEdit | Directly: each call is hooked, the file's original is saved before the first touch, and the diff is recomputed after. |
| Claude's Bash / PowerShell, in a git work tree | git status before and after each command that might write. Edits, new files, deletions, renames (shown as delete + new), git checkout/restore, formatters, codegen, npm install, scripts. How the command is written doesn't matter. |
| Claude's shell commands, outside git | Only files already in the list, plus plain deletes of named files: rm, del, erase, Remove-Item, ri. |
| Your own edits to a listed file | The 2-second refresh updates the counts, and Claude is told on your next message. |
Not tracked: gitignored files (node_modules, build output, .env), files outside the project, and your edits to files that aren't listed.
Multi-round changes. The original is saved the first time Claude touches a file; later edits, in the same turn or later ones, add to the same diff. The pane always shows the net change from that first original, so a file Claude changes and then changes back disappears. Files stay listed across prompts, and in a git repo across sessions, until you resolve them. Each session still lists only the files under the folder it runs in.
Notes are delivered to Claude as hidden context (Claude reads them; your chat doesn't show them), at whichever comes first: the next tool result if Claude is mid-task, or your next message.
| Event | Note Claude receives |
|---|---|
| You reject a change | "The user rejected your changes to X: it is back to its content from before you edited it. Re-read it before editing it again." |
| You reject a new file | "The user rejected your new file X: it has been deleted." |
| You reject a deletion | "The user rejected your deletion of X: it has been restored." |
| You revert every block in the diff | "The user reverted all your changes to X…" (or the new-file rejection above) |
| You edit a listed file yourself | "The user modified X after your last edit; re-read it before editing it again." |
| You delete a listed file yourself | "The user deleted X after your last edit." |
| You accept | Nothing. |
With several sessions, a note goes to the Claude that made the change, in whichever session it runs. That Claude is also told when another session's Claude edits one of its files ("X was since edited by another Claude session"). If the session that made a change has ended, a Claude that was told about the file in a later session hears of your edits and reverts to it.
Each of your edits is reported once. As a backstop, Claude Code's Edit tool already refuses to edit a file that changed since Claude last read it.
rm/del/Remove-Item of named files. Edits and new files made by shell commands are missed, as are deletes using globs or variables, inside scripts, or of whole folders. Run inside a git repo for full tracking.git status, so it's invisible.git push --mirror, a refs/*:refs/* refspec, git clone --mirror or git bundle create --all copies the hidden ref, and your originals with it. git fast-export --all (and git filter-repo) warns about it. Ordinary push, --all, --tags and clone don't. See Troubleshooting to remove it.| Symptom | Likely cause / fix | |
|---|---|---|
| The pane doesn't appear | The terminal is too narrow for Claude Code to open it unprompted (see The pane); a toast says so. Run /changes, which opens it at any width. | |
| Clicking a file does nothing / toast "Could not open VS Code" | code isn't on PATH. In VS Code: Command Palette → Shell Command: Install 'code' command in PATH. | |
| Counts don't update after saving in VS Code | The refresh timer isn't running. Any tool call, prompt or /changes restarts it. If it persists, check claude --debug for pending-changes lines. | |
| A shell change wasn't listed | The file is gitignored, outside the project, or the folder isn't a git repo (only plain deletes are caught there). Or the command matched the read-only list. | |
| The hook seems to run twice | The installed copy and a --plugin-dir / session dev copy are both loaded. Use one. | |
| A diff tab shows "deleted" | Its temp file was cleaned up after accept/reject. Close the tab. | |
test.json shows +3 -2 after a PowerShell edit | Windows PowerShell 5.1's -Encoding utf8 adds a byte-order mark to the first line. That's the command, not the mod. | |
| The pane (or a toast) says the session is open in another window | The same session id runs in two Claude Code windows (a --resume of a running session). The later one stops sharing its list, and rows tagged other window may be out of date; it shares again once the other window closes. | |
A row shows other branch | It was changed while another branch was checked out. Review it before ✗: it restores the original from that branch. | |
| You uninstalled the mod and want its data gone | In each repo: `git for-each-ref --format="delete %(refname)" refs/pending-changes/ \ | git update-ref --stdin, then delete the pending-changes folders in .git/ and .git/worktrees/*/`. git's own gc then reclaims the originals. |
See the roadmap for what's planned and where help is wanted. The full reference for how the mod behaves and why, including its internals, design decisions and test coverage, is docs/SPEC.md. Features, bug fixes and research start with a short spec in docs/specs/, and docs/SPEC.md is updated when they ship.
Clone the repository and load the clone directly. If you installed the mod from the marketplace, uninstall it first.
For a single session:
git clone https://github.com/comertial/claude-pending-changes.git
claude --plugin-dir ./claude-pending-changes
To load it in every session, put the clone's absolute path in CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json. Separate several folders with ; on Windows and : elsewhere:
{ "env": { "CLAUDE_CODE_PLUGIN_DIRS": "/path/to/claude-pending-changes" } }
Saves then reload the module on their own, after the current turn ends. Don't run both the installed copy and a --plugin-dir copy in one session, or the hooks run twice.
Checks:
# manifest + module: what it hooks and calls, and anything the engine would refuse
claude plugin validate ./claude-pending-changes
# the test suite
claude plugin test ./claude-pending-changes
Type-checking: once the engine has loaded the mod from a folder it watches, it writes .claude-plugin/types/ and a tsconfig.json, so tsc -p <folder> works. Otherwise use a tsconfig.json kept outside the mod folder. Its include names the engine's claude-code.d.ts (written by the plugin-authoring skill) plus this folder's hooks and types, with "jsx": "react", "jsxFactory": "h".
Debugging: run claude --debug. A hook that throws is skipped and logged. A pane tree that doesn't validate is logged as ui.render (Pane): a hook returned a tree that does not validate, with the reason.
version in .claude-plugin/plugin.json (semver).[Unreleased] notes in CHANGELOG.md under the new version.vX.Y.Z, push the tag and create a GitHub release.Installed users pick up the new version with claude plugin marketplace update comertial-mods, then claude plugin update pending-changes@comertial-mods. If the marketplace entry in comertial/comertial-mods pins a ref, bump it there as well.
GPL-3.0. This is an independent project, not affiliated with or endorsed by Anthropic. Claude and Claude Code are products of Anthropic.
hooks/register.tsx 2334 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, NextBudget, PluginOptions, Register } from 'claude-code'
3
4import type { Review, Tracked } from '../types'
5import { countChanges } from './diff'
6import { folderId, idOf } from './ids'
7import { deleteTargets, isReadOnlyCommand } from './commands'
8import {
9 BLOB_CAP,
10 FOLD_MS,
11 REF_ROOT,
12 STALE_MS,
13 branchOf,
14 byteLength,
15 encodeWorktreeName,
16 foldIn,
17 isFoldable,
18 liveness,
19 mergeShards,
20 note,
21 parseCatFileBatch,
22 parseHeartbeat,
23 parseLsTree,
24 parseShard,
25 pruneTombstones,
26 refFor,
27 slotOf,
28 treeInput,
29 zeroId,
30} from './persist'
31import type { Event, GoneReason, Merged, MergeResult, RejectKind, Shard } from './persist'
32
33const PANE = 'pending-changes'
34const TITLE = 'Changes'
35const POLL_MS = 2000
36const STALE_TEMP_MS = 24 * 60 * 60 * 1000
37/** `$.state` refuses a value longer than 4,194,304 characters; this leaves room for the rest of the list. */
38const STATE_CAP = 4_194_304 - 64 * 1024
39/** The row under the mouse is tinted, so its ✓/✗ read as its own. */
40const ROW_HOVER = 'inactive'
41
42const files = atom({ plugin: 'pending-changes', key: 'files' } as const, {} as Record<string, Tracked>)
43const notices = atom({ plugin: 'pending-changes', key: 'notices' } as const, [] as string[])
44const collapsed = atom({ plugin: 'pending-changes', key: 'collapsed' } as const, [] as string[])
45const outside = atom({ plugin: 'pending-changes', key: 'outside' } as const, 0)
46const sessions = atom({ plugin: 'pending-changes', key: 'sessions' } as const, {} as Record<string, 'live' | 'ended'>)
47const loadedFor = atom({ plugin: 'pending-changes', key: 'loadedFor' } as const, '')
48const resumeNoted = atom({ plugin: 'pending-changes', key: 'resumeNoted' } as const, [] as string[])
49const knows = atom({ plugin: 'pending-changes', key: 'knows' } as const, {} as Record<string, string | null>)
50const resolvedWhileOff = atom({ plugin: 'pending-changes', key: 'resolvedWhileOff' } as const, {} as Record<string, { at: number; rel: string }>)
51const instanceAtom = atom({ plugin: 'pending-changes', key: 'instance' } as const, '')
52const branchNow = atom({ plugin: 'pending-changes', key: 'branchNow' } as const, '')
53const secondWindow = atom({ plugin: 'pending-changes', key: 'secondWindow' } as const, false)
54
55type $ = EngineInterface
56
57/** The `userConfig` values this load was given. */
58let options: PluginOptions = {}
59
60// ---------------------------------------------------------------- context
61
62type GitCtx = {
63 gitDir: string
64 commonDir: string
65 /** `refs/pending-changes/<worktree id>`. */
66 ref: string
67 objectFormat: string
68 /** The cwd relative to the work tree root: `sub/`, or ''. */
69 prefix: string
70 /** `<gitDir>/pending-changes`: the shards and heartbeats. */
71 shardDir: string
72}
73
74type Ctx = {
75 cwd: string
76 isWindows: boolean
77 /** `<OS temp>/claude-pending-changes`: the only place temp cleanup may delete. */
78 tmpRoot: string
79 /** The git work tree holding cwd, `/`-separated; null outside git (shell changes then fall back to delete commands). */
80 gitRoot: string | null
81 /** Set when git is new enough to name its dirs; null means no persistence. */
82 git: GitCtx | null
83 /** `<tmpRoot>/<sessionId>`: this session's review copies. */
84 sessionDir: string
85 /** The session id `sessionDir` belongs to. */
86 sessionId: string
87}
88
89let ctxPromise: Promise<Ctx> | undefined
90
91/** Session ids whose session.end ran in this process: never loaded again unless a session.start revives one. */
92const endedIds = new Set<string>()
93
94function ctx($: $): Promise<Ctx> {
95 ctxPromise ??= (async () => {
96 const cwd = slash(await $.session.cwd())
97 const isWindows = (await $.env.get('OS')) === 'Windows_NT'
98 const tmp =
99 (await $.env.get('TEMP')) ?? (await $.env.get('TMPDIR')) ?? (await $.env.get('TMP')) ?? '/tmp'
100 const tmpRoot = `${slash(tmp)}/claude-pending-changes`
101 const sessionId = await $.session.id()
102 const sessionDir = `${tmpRoot}/${sessionId}`
103 const { gitRoot, git } = await findGit($, cwd)
104 return { cwd, isWindows, tmpRoot, sessionDir, sessionId, gitRoot, git }
105 })().catch(error => {
106 ctxPromise = undefined
107 throw error
108 })
109 return ctxPromise
110}
111
112/** Persistence is on: the setting allows it, and git named its dirs. */
113const persistOn = (c: Ctx): c is Ctx & { git: GitCtx; gitRoot: string } =>
114 options.persistAcrossSessions !== false && c.git !== null && c.gitRoot !== null
115
116// ---------------------------------------------------------------- paths
117
118function slash(path: string): string {
119 return path.replace(/\\/g, '/').replace(/\/+$/, '')
120}
121
122function keyOf(path: string, isWindows: boolean): string {
123 return isWindows ? slash(path).toLowerCase() : slash(path)
124}
125
126function isInside(path: string, root: string, isWindows: boolean): boolean {
127 return keyOf(path, isWindows).startsWith(`${keyOf(root, isWindows)}/`)
128}
129
130function native(path: string, isWindows: boolean): string {
131 return isWindows ? path.replace(/\//g, '\\') : path
132}
133
134function fit(text: string, room: number): string {
135 return text.length <= room ? text : `…${text.slice(text.length - Math.max(1, room - 1))}`
136}
137
138/** The worktree-relative path of a file under cwd: the cwd's prefix plus its cwd-relative path. */
139const gitRelOf = (c: Ctx & { git: GitCtx }, rel: string) => `${c.git.prefix}${rel}`
140const gitKeyOf = (c: Ctx, gitRel: string) => (c.isWindows ? gitRel.toLowerCase() : gitRel)
141
142/** Where a worktree-relative path is: under cwd as the session spells it, otherwise under the git root. */
143function pathOfGitRel(c: Ctx & { git: GitCtx; gitRoot: string }, gitRel: string): string {
144 const prefix = c.git.prefix
145 const under = c.isWindows ? gitRel.toLowerCase().startsWith(prefix.toLowerCase()) : gitRel.startsWith(prefix)
146 return under ? `${c.cwd}/${gitRel.slice(prefix.length)}` : `${c.gitRoot}/${gitRel}`
147}
148
149type Status = 'added' | 'modified' | 'deleted'
150const statusOf = (f: Tracked): Status => (f.original === null ? 'added' : f.isDeleted ? 'deleted' : 'modified')
151const STATUS_COLOR = { added: 'success', modified: 'warning', deleted: 'error' } as const
152/** The name is styled to match its status, so the status reads without colour. */
153const NAME_STYLE = {
154 added: { underline: true },
155 modified: { italic: true },
156 deleted: { strikethrough: true, dimColor: true },
157} as const
158
159// ---------------------------------------------------------------- host io
160
161async function readOrNull($: $, path: string): Promise<string | null> {
162 return (await $.fs.exists(path)) ? await $.fs.read(path) : null
163}
164
165/** Deletes a file or folder, refusing anything outside `allowedRoot`. */
166async function removePath($: $, c: Ctx, path: string, allowedRoot: string): Promise<void> {
167 if (!isInside(path, allowedRoot, c.isWindows)) return
168 if (!(await $.fs.exists(path))) return
169 const p = native(path, c.isWindows)
170 if (!c.isWindows) {
171 await $.process.run(['rm', '-rf', p])
172 return
173 }
174 const { kind } = await $.fs.stat(path)
175 await $.process.run(kind === 'dir' ? ['cmd', '/c', 'rmdir', '/s', '/q', p] : ['cmd', '/c', 'del', '/f', '/q', p])
176}
177
178async function openInVsCode($: $, c: Ctx, review: Review, source: string): Promise<void> {
179 const left = native(review.originalCopy, c.isWindows)
180 const right = native(source, c.isWindows)
181 const argv = c.isWindows ? ['cmd', '/c', 'code', '--diff', left, right] : ['code', '--diff', left, right]
182 try {
183 const { exitCode, stderr } = await $.process.run(argv)
184 if (exitCode !== 0) $.ui.toast(`Could not open VS Code (is \`code\` on PATH?) ${stderr.trim().slice(0, 200)}`)
185 } catch {
186 $.ui.toast('Could not open VS Code: is `code` on PATH?')
187 }
188}
189
190// ---------------------------------------------------------------- state
191
192async function queueNotice($: $, text: string): Promise<void> {
193 await update($, notices, list => [...list, text])
194}
195
196type Base = Pick<Tracked, 'path' | 'rel' | 'original' | 'createdDirs'>
197
198/**
199 * Who a settle speaks for: Claude's own change takes ownership and is recorded;
200 * an observed one (the refresh, a load, a prompt) keeps the owner and records only
201 * a drop; a peer's is applied from its record and recorded nowhere.
202 */
203type From = 'claude' | 'observed' | 'peer'
204
205type SettleOptions = {
206 from?: From
207 /** Why an observed drop happened, for the resolve record. */
208 reason?: GoneReason
209 /** A resolve this change starts after (see Event.epoch). */
210 epoch?: number
211 /** The refresh may update counts but not drop (a peer is mid-write). */
212 noDrop?: boolean
213}
214
215/** Records `current` against the original, or drops the entry when they match again. */
216async function settle(
217 $: $,
218 key: string,
219 base: Base,
220 current: string | null,
221 seenByClaude: string | null | undefined,
222 opts: SettleOptions = {},
223): Promise<{ wasEmpty: boolean; dropped?: Tracked }> {
224 const from = opts.from ?? 'observed'
225 const c = await ctx($)
226 const persist = persistOn(c)
227 const me = await $.session.id()
228 const at = persist && from !== 'peer' ? await nextAt($) : undefined
229 let wasEmpty = false
230 let dropped: Tracked | undefined
231 let written: Tracked | undefined
232 await update($, files, all => {
233 wasEmpty = Object.keys(all).length === 0
234 const prev = all[key]
235 const next = { ...all }
236 if (current === base.original) {
237 if (opts.noDrop) return all
238 dropped = prev
239 delete next[key]
240 return next
241 }
242 const { added, removed } = countChanges(base.original, current)
243 const isDeleted = current === null
244 if (
245 prev &&
246 seenByClaude === undefined &&
247 prev.added === added &&
248 prev.removed === removed &&
249 Boolean(prev.isDeleted) === isDeleted
250 ) {
251 return all
252 }
253 const keep: Partial<Tracked> = prev ?? {}
254 written = {
255 path: base.path,
256 rel: base.rel,
257 original: base.original,
258 ...(base.createdDirs?.length ? { createdDirs: base.createdDirs } : {}),
259 added,
260 removed,
261 lastSeenByClaude: seenByClaude !== undefined ? seenByClaude : prev ? prev.lastSeenByClaude : current,
262 ...(current === null ? { isDeleted: true } : {}),
263 ...(prev?.review ? { review: prev.review } : {}),
264 ...(keep.owner ? { owner: keep.owner } : {}),
265 ...(keep.gitRel ? { gitRel: keep.gitRel } : {}),
266 ...(keep.at !== undefined ? { at: keep.at } : {}),
267 ...(keep.branch ? { branch: keep.branch } : {}),
268 ...(keep.sessionOnly ? { sessionOnly: true } : {}),
269 // A row a second window had when it yielded keeps its tag until this window's own Claude changes it.
270 ...(keep.otherWindow && from !== 'claude' ? { otherWindow: true } : {}),
271 }
272 if (from === 'claude') {
273 written.owner = me
274 if (persist) {
275 written.gitRel = gitRelOf(c, base.rel)
276 written.at = at
277 written.branch = rt.branch
278 }
279 }
280 next[key] = written
281 return next
282 })
283 if (persist && from !== 'peer') {
284 if (dropped?.gitRel) recordGone(c, dropped, me, at!, opts.reason ?? 'settled')
285 else if (from === 'claude' && written) recordLive(c, written, me, opts.epoch)
286 } else if (!persist && dropped && from !== 'peer') {
287 await noteResolvedWhileOff($, c, dropped)
288 }
289 return { wasEmpty, dropped }
290}
291
292async function forget($: $, key: string): Promise<void> {
293 await update($, files, all => {
294 if (!(key in all)) return all
295 const next = { ...all }
296 delete next[key]
297 return next
298 })
299}
300
301async function cleanupReview($: $, review: Review | undefined): Promise<void> {
302 if (!review) return
303 const c = await ctx($)
304 await removePath($, c, review.originalCopy, c.tmpRoot)
305 if (review.deletedCopy) await removePath($, c, review.deletedCopy, c.tmpRoot)
306}
307
308// ---------------------------------------------------------------- persistence
309//
310// Each session keeps its records in a shard in the worktree's git dir, merges
311// every session's shards on each refresh, and pins the originals it records in
312// git's object store through one tree ref per worktree. See docs/SPEC.md,
313// "Persistence", for the rules this follows.
314
315type Slot = { mtimeMs: number; size: number; shard?: Shard }
316type Peer = {
317 slots: Partial<Record<'a' | 'b', Slot>>
318 shard?: Shard
319 /** No slot parses: never release or fold on its account. */
320 torn: boolean
321 beat?: { mtimeMs: number; size: number; busy: boolean; detached?: boolean }
322 /** Each slot's mtime as listed, parsed or not: a shard that never parses still ages. */
323 listed: Partial<Record<'a' | 'b', number>>
324 /** Its last sign of life: the heartbeat's mtime, or its newest slot's without one. */
325 beatMs?: number
326 /** Its files are gone from the folder; its events stay until another shard or a resolve covers them. */
327 vanished?: boolean
328 state: 'live' | 'ended'
329}
330
331/** Module state: it survives `/clear` but not a reload; `ensureLoaded` rebuilds it from disk. */
332const newRuntime = () => ({
333 /** The session id this module loaded for. */
334 id: undefined as string | undefined,
335 shard: undefined as Shard | undefined,
336 /** Shards of ids that ended in this process, still to be flushed. */
337 frozen: [] as Shard[],
338 peers: new Map<string, Peer>(),
339 merged: { live: new Map(), gone: new Map() } as MergeResult,
340 /** Blob text by SHA, and SHA by text. */
341 texts: new Map<string, string>(),
342 shaOf: new Map<string, string>(),
343 /** Texts still to hash, by `<session>\0<gitKey>`. */
344 pending: new Map<string, { original?: string | null; seen?: string | null }>(),
345 /** What each event was last written as, for writes that can't wait for hashing. */
346 written: new Map<string, Event>(),
347 releases: new Set<string>(),
348 tree: { known: false, sha: null as string | null, shas: new Set<string>() },
349 canRead: true,
350 canWrite: true,
351 writeFailures: 0,
352 retryAt: 0,
353 dirty: false,
354 /** Texts still to hash after a failure or while git backs off. */
355 hashPending: false,
356 treeDirty: false,
357 loading: undefined as Promise<void> | undefined,
358 polling: false,
359 busy: false,
360 /** Ticks left during which a peer counts as mid-write. */
361 quietTicks: 0,
362 lastBeat: 0,
363 lastAt: 0,
364 branch: '',
365 instance: '',
366 secondWindow: false,
367 /** This process's own files as it last wrote them: anything else there was written by another process. */
368 ownFiles: new Map<string, { mtimeMs: number; size: number }>(),
369 /** Blobs that couldn't be fetched, by SHA: when to try again. */
370 failedShas: new Map<string, number>(),
371 /** Peer entries left out because the list would pass `$.state`'s cap; said once per load. */
372 overCap: false,
373 /** The session id this process last cleared its list for. */
374 clearedFor: undefined as string | undefined,
375 /** Set while session.end flushes: the bound its git work must fit in. */
376 endBudget: undefined as NextBudget | undefined,
377})
378const rt = newRuntime()
379
380let lock: Promise<unknown> = Promise.resolve()
381function withLock<T>(fn: () => Promise<T>): Promise<T> {
382 const run = lock.then(fn, fn)
383 lock = run.catch(() => {})
384 return run
385}
386
387async function nextAt($: $): Promise<number> {
388 rt.lastAt = Math.max(await $.clock.now(), rt.lastAt + 1)
389 return rt.lastAt
390}
391
392const pendingKey = (session: string, gitKey: string) => `${session}\0${gitKey}`
393const sessionOfPending = (key: string) => key.slice(0, key.indexOf('\0'))
394
395/** Records Claude's change to `entry` in this session's shard. */
396function recordLive(c: Ctx, entry: Tracked, me: string, epoch?: number): void {
397 const shard = rt.shard
398 if (!shard || !entry.gitRel || entry.sessionOnly) return
399 const gitKey = gitKeyOf(c, entry.gitRel)
400 const prev = shard.entries[gitKey]
401 const originalSha = entry.original === null ? null : rt.shaOf.get(entry.original)
402 const seenSha = entry.lastSeenByClaude === null ? null : rt.shaOf.get(entry.lastSeenByClaude)
403 const event: Event = {
404 at: entry.at ?? rt.lastAt,
405 by: me,
406 owner: entry.owner ?? me,
407 rel: entry.gitRel,
408 branch: entry.branch ?? rt.branch,
409 // A record replacing this session's own resolve keeps cutting off everything before it,
410 // or another shard's older record of the file would come back with its pre-resolve original.
411 ...(() => {
412 const cut = Math.max(epoch ?? -Infinity, prev?.gone ? prev.at : -Infinity, prev?.epoch ?? -Infinity)
413 return cut > -Infinity ? { epoch: cut } : {}
414 })(),
415 added: entry.added,
416 removed: entry.removed,
417 ...(entry.isDeleted ? { isDeleted: true as const } : {}),
418 ...(entry.createdDirs?.length && persistOn(c)
419 ? { createdDirs: entry.createdDirs.map(d => gitRelOf(c, slash(d).slice(c.cwd.length + 1))) }
420 : {}),
421 }
422 const waiting: { original?: string | null; seen?: string | null } = {}
423 if (originalSha !== undefined) event.original = originalSha
424 else waiting.original = entry.original
425 if (seenSha !== undefined) event.seen = seenSha
426 else waiting.seen = entry.lastSeenByClaude
427 if ('original' in waiting || 'seen' in waiting) rt.pending.set(pendingKey(shard.session, gitKey), waiting)
428 else rt.pending.delete(pendingKey(shard.session, gitKey))
429 shard.entries[gitKey] = event
430 rt.dirty = true
431}
432
433/** Records that this session resolved `entry`, and releases its originals. */
434function recordGone(c: Ctx, entry: Tracked, me: string, at: number, reason: GoneReason, rejectKind?: RejectKind): void {
435 const shard = rt.shard
436 if (!shard || !entry.gitRel) return
437 const gitKey = gitKeyOf(c, entry.gitRel)
438 const prev = shard.entries[gitKey]
439 for (const sha of [prev?.original, prev?.seen]) if (sha) rt.releases.add(sha)
440 for (const text of [entry.original, entry.lastSeenByClaude]) {
441 const sha = text === null ? undefined : rt.shaOf.get(text)
442 if (sha) rt.releases.add(sha)
443 }
444 rt.pending.delete(pendingKey(shard.session, gitKey))
445 shard.entries[gitKey] = {
446 at,
447 by: me,
448 owner: entry.owner ?? me,
449 rel: entry.gitRel,
450 branch: entry.branch ?? rt.branch,
451 gone: true,
452 goneReason: reason,
453 ...(rejectKind ? { rejectKind } : {}),
454 }
455 rt.dirty = true
456}
457
458/** Records that this session found a merged entry resolved (back at its original), releasing its originals. */
459function recordGoneMerged(c: Ctx, m: Merged, me: string, at: number): void {
460 const shard = rt.shard
461 if (!shard) return
462 for (const sha of [m.original, m.seen]) if (sha) rt.releases.add(sha)
463 shard.entries[gitKeyOf(c, m.rel)] = { at, by: me, owner: m.owner, rel: m.rel, branch: m.branch, gone: true, goneReason: 'settled' }
464 rt.dirty = true
465}
466
467/** With persistence off, remembers the resolve so turning it back on tombstones it (and nothing else). */
468async function noteResolvedWhileOff($: $, c: Ctx, entry: Tracked): Promise<void> {
469 if (!c.git || options.persistAcrossSessions !== false) return
470 const gitKey = gitKeyOf(c, `${c.git.prefix}${entry.rel}`)
471 const at = await $.clock.now()
472 await update($, resolvedWhileOff, all => ({ ...all, [gitKey]: { at, rel: `${c.git!.prefix}${entry.rel}` } }))
473}
474
475async function git($: $, c: Ctx, args: string[], stdin?: string) {
476 return $.process.run(['git', ...args], { cwd: c.gitRoot ?? c.cwd, ...(stdin !== undefined ? { stdin } : {}) })
477}
478
479/** Fetches blob texts into `rt.texts`, in as many `cat-file --batch` calls as the output cap needs. Returns the unreadable SHAs. */
480async function fetchTexts($: $, c: Ctx, shas: Iterable<string>): Promise<Set<string>> {
481 const failed = new Set<string>()
482 const now = await $.clock.now()
483 let want = [...new Set(shas)].filter(sha => {
484 if (rt.texts.has(sha)) return false
485 // A blob that couldn't be fetched isn't asked for again until its backoff passes.
486 if ((rt.failedShas.get(sha) ?? 0) > now) {
487 failed.add(sha)
488 return false
489 }
490 return true
491 })
492 while (want.length > 0) {
493 const { exitCode, stdout, isStdoutTruncated } = await git($, c, ['cat-file', '--batch'], `${want.join('\n')}\n`)
494 if (exitCode !== 0) {
495 for (const sha of want) failed.add(sha)
496 break
497 }
498 const { blobs, missing, read: count } = parseCatFileBatch(stdout)
499 for (const [sha, text] of blobs) {
500 rt.texts.set(sha, text)
501 rt.shaOf.set(text, sha)
502 }
503 for (const sha of missing) failed.add(sha)
504 if (count === 0) {
505 // The first blob alone overflows the output: it can't come back this way.
506 failed.add(want[0]!)
507 want = want.slice(1)
508 continue
509 }
510 want = want.slice(count)
511 if (!isStdoutTruncated) {
512 for (const sha of want) if (!rt.texts.has(sha)) failed.add(sha)
513 break
514 }
515 }
516 for (const sha of failed) if (!rt.failedShas.has(sha) || rt.failedShas.get(sha)! <= now) rt.failedShas.set(sha, now + 30_000)
517 return failed
518}
519
520/** Hashes texts with no SHA yet, through one `hash-object` over files staged outside the review copies. */
521async function hashTexts($: $, c: Ctx & { git: GitCtx }, texts: (string | null)[]): Promise<void> {
522 const todo = [...new Set(texts.filter((t): t is string => t !== null && !rt.shaOf.has(t)))].filter(
523 t => byteLength(t) <= BLOB_CAP,
524 )
525 if (todo.length === 0) return
526 const dir = `${c.tmpRoot}/${c.sessionId}.blobs/${await nextAt($)}`
527 const paths: string[] = []
528 for (const [i, text] of todo.entries()) {
529 const path = `${dir}/${i}`
530 await $.fs.write(path, text)
531 paths.push(native(path, c.isWindows))
532 }
533 try {
534 const { exitCode, stdout } = await git($, c, ['hash-object', '-w', '--no-filters', '--stdin-paths'], `${paths.join('\n')}\n`)
535 if (exitCode !== 0) throw new Error('hash-object failed')
536 const shas = stdout.trim().split('\n')
537 if (shas.length !== todo.length) throw new Error('hash-object answered short')
538 todo.forEach((text, i) => {
539 rt.shaOf.set(text, shas[i]!)
540 rt.texts.set(shas[i]!, text)
541 })
542 } finally {
543 await removePath($, c, dir, c.tmpRoot).catch(() => {})
544 }
545}
546
547/** The event as it can be written now: pending SHAs fall back to the last written ones, or it waits. */
548function writable(session: string, gitKey: string, event: Event): Event | undefined {
549 if (event.gone) return event
550 if (event.original !== undefined && event.seen !== undefined) return event
551 const last = rt.written.get(pendingKey(session, gitKey))
552 if (!last || last.gone) return undefined
553 return {
554 ...event,
555 original: event.original !== undefined ? event.original : last.original,
556 seen: event.seen !== undefined ? event.seen : last.seen,
557 }
558}
559
560/** Writes a shard to its next slot. The lock keeps the slot and `seq` of concurrent writers apart. */
561async function writeShard($: $, c: Ctx & { git: GitCtx }, shard: Shard): Promise<void> {
562 // A second window never writes the shard it shares with the first: that record is the first window's.
563 if (rt.secondWindow && shard.session === (await $.session.id())) return
564 await withLock(async () => {
565 const entries: Record<string, Event> = {}
566 for (const [gitKey, event] of Object.entries(shard.entries)) {
567 const out = writable(shard.session, gitKey, event)
568 if (out) entries[gitKey] = out
569 }
570 shard.seq++
571 const { v, seq, session, instance, endedAt, endReason } = shard
572 const body = { v, seq, session, instance, ...(endedAt !== undefined ? { endedAt, endReason } : {}), entries }
573 const path = `${c.git.shardDir}/${session}.${slotOf(seq)}.json`
574 await $.fs.write(path, JSON.stringify(body))
575 if (session === rt.shard?.session) await rememberOwn($, path)
576 for (const [gitKey, event] of Object.entries(entries)) rt.written.set(pendingKey(session, gitKey), event)
577 })
578}
579
580/** Notes how this process left one of its own files, so a write by another process shows. */
581async function rememberOwn($: $, path: string): Promise<void> {
582 const { mtimeMs, size } = await $.fs.stat(path)
583 rt.ownFiles.set(path.slice(path.lastIndexOf('/') + 1), { mtimeMs, size })
584}
585
586/** When an instance was made: its id carries the time, base 36. Unknown is oldest. */
587const instanceSince = (instance: string) => parseInt(instance.split('-')[1] ?? '', 36) || 0
588
589/** Whether the pane is on screen now: open, the tab shown, and placed. */
590async function paneVisible($: $): Promise<boolean> {
591 try {
592 return (await $.ui.panes()).some(p => p.id === PANE && p.isShown && p.isPlaced)
593 } catch {
594 return false
595 }
596}
597
598/**
599 * Another process writes under this session id (a second window). The one
600 * started later yields: it goes session-only and says so.
601 */
602async function foreignWriter($: $, other: string): Promise<void> {
603 if (rt.secondWindow || other === rt.instance) return
604 const mine = instanceSince(rt.instance)
605 const theirs = instanceSince(other)
606 if (theirs > mine || (theirs === mine && other > rt.instance)) return // They're the later one: they yield.
607 rt.secondWindow = true
608 rt.canRead = false
609 rt.canWrite = false
610 // The pane says so with its banner; a toast only when the pane isn't on screen to say it.
611 if (!(await paneVisible($))) {
612 $.ui.toast("This session is open in another window too; pending changes here aren't shared.", { timeoutMs: 8000 })
613 }
614 // What the pane lists now came from the shared list and may go out of date.
615 await update($, secondWindow, () => true)
616 await update($, files, all => {
617 const out: Record<string, Tracked> = {}
618 for (const [key, entry] of Object.entries(all)) out[key] = { ...entry, otherWindow: true }
619 return out
620 })
621}
622
623/** Backs off a failed write step, and tells peers this session is detached after five in a row. */
624async function writeFailed($: $): Promise<void> {
625 rt.writeFailures++
626 rt.retryAt = (await $.clock.now()) + Math.min(60_000, POLL_MS * 2 ** (rt.writeFailures - 1))
627}
628
629let flushRun: Promise<void> | undefined
630let flushAgain = false
631
632/** Hashes, writes and pins what changed. Single-flight: a call during a run gets one more run. */
633function flush($: $): Promise<void> {
634 if (flushRun) {
635 flushAgain = true
636 return flushRun
637 }
638 flushRun = (async () => {
639 do {
640 flushAgain = false
641 await flushOnce($)
642 } while (flushAgain)
643 })()
644 .catch(() => {})
645 .finally(() => {
646 flushRun = undefined
647 })
648 return flushRun
649}
650
651async function flushOnce($: $): Promise<void> {
652 const c = await ctx($)
653 if (!persistOn(c) || !rt.canRead || !rt.canWrite) return
654 const now = await $.clock.now()
655 // Git work backs off after a failure; writing the shards never waits, so resolves always land.
656 const gitDue = now >= rt.retryAt && !(rt.endBudget && rt.endBudget.remainingMs < 500)
657 // This session's own shard is written only once it has loaded for its id: never from an empty list.
658 const own = rt.shard && rt.id === rt.shard.session && !rt.loading ? [rt.shard] : []
659 const shards = [...rt.frozen, ...own]
660 const hashDue = rt.hashPending && gitDue
661 if (!rt.dirty && !hashDue && !rt.treeDirty && rt.releases.size === 0) return
662 let failed = false
663 if (rt.dirty || hashDue) {
664 rt.dirty = false
665 rt.hashPending = false
666 // 1. Hash what's waiting, on its own: a failure here mustn't keep accepts and rejects off disk.
667 const texts: (string | null)[] = []
668 for (const shard of shards) {
669 for (const gitKey of Object.keys(shard.entries)) {
670 const waiting = rt.pending.get(pendingKey(shard.session, gitKey))
671 if (waiting?.original !== undefined) texts.push(waiting.original)
672 if (waiting?.seen !== undefined) texts.push(waiting.seen)
673 }
674 }
675 if (texts.length > 0) {
676 if (!gitDue) rt.hashPending = true
677 else {
678 try {
679 await hashTexts($, c, texts)
680 } catch {
681 failed = true
682 rt.hashPending = true
683 }
684 }
685 }
686 for (const shard of shards) {
687 for (const [gitKey, event] of Object.entries(shard.entries)) {
688 const key = pendingKey(shard.session, gitKey)
689 const waiting = rt.pending.get(key)
690 if (!waiting) continue
691 // A text too large to come back through cat-file stays session-only.
692 const tooBig = [waiting.original, waiting.seen].some(t => typeof t === 'string' && byteLength(t) > BLOB_CAP)
693 if (tooBig) {
694 rt.pending.delete(key)
695 delete shard.entries[gitKey]
696 await markSessionOnly($, c, event.rel)
697 continue
698 }
699 let left = false
700 for (const field of ['original', 'seen'] as const) {
701 if (!(field in waiting)) continue
702 const text = waiting[field]!
703 const sha = text === null ? null : rt.shaOf.get(text)
704 if (sha === undefined) left = true
705 else {
706 event[field] = sha
707 delete waiting[field]
708 }
709 }
710 if (left) rt.hashPending = true
711 else rt.pending.delete(key)
712 }
713 }
714 // 2. The shards: what's still waiting for a SHA goes as it was last written, or waits.
715 try {
716 for (const shard of shards) await writeShard($, c, shard)
717 // An ended shard is done once nothing of it waits for a SHA.
718 const waitingFor = new Set([...rt.pending.keys()].map(sessionOfPending))
719 rt.frozen = rt.frozen.filter(s => waitingFor.has(s.session))
720 rt.treeDirty = true
721 } catch {
722 failed = true
723 rt.dirty = true
724 }
725 }
726 // 3. The tree.
727 if (gitDue && (rt.treeDirty || rt.releases.size > 0)) {
728 try {
729 if (!(await updateTree($, c, false))) failed = true
730 } catch {
731 failed = true
732 }
733 }
734 if (failed) await writeFailed($)
735 else if (!rt.hashPending) rt.writeFailures = 0
736}
737
738async function markSessionOnly($: $, c: Ctx, gitRel: string): Promise<void> {
739 if (!persistOn(c)) return
740 const key = keyOf(pathOfGitRel(c, gitRel), c.isWindows)
741 await update($, files, all => (all[key] ? { ...all, [key]: { ...all[key]!, sessionOnly: true } } : all))
742}
743
744/** Every SHA a shard references. */
745function shasOf(shards: readonly Shard[]): Set<string> {
746 const out = new Set<string>()
747 for (const shard of shards) {
748 for (const event of Object.values(shard.entries)) {
749 if (event.original) out.add(event.original)
750 if (event.seen) out.add(event.seen)
751 }
752 }
753 return out
754}
755
756async function readTree($: $, c: Ctx & { git: GitCtx }): Promise<void> {
757 const head = await git($, c, ['rev-parse', '-q', '--verify', c.git.ref])
758 const sha = head.exitCode === 0 ? head.stdout.trim() : null
759 const shas = new Set<string>()
760 if (sha) {
761 const listed = await git($, c, ['ls-tree', sha])
762 if (listed.exitCode !== 0) throw new Error('ls-tree failed')
763 for (const s of parseLsTree(listed.stdout)) shas.add(s)
764 }
765 rt.tree = { known: true, sha, shas }
766}
767
768/**
769 * Moves the worktree's ref to a tree of every SHA in use. A normal update adds
770 * this session's SHAs to the current tree and removes only what it released and
771 * nothing uses; a rebuild pins exactly the merged set. Compare-and-swap, three
772 * tries, then it waits for the next tick.
773 */
774async function updateTree($: $, c: Ctx & { git: GitCtx }, rebuild: boolean): Promise<boolean> {
775 if (rt.endBudget && rt.endBudget.remainingMs < 500) {
776 rt.treeDirty = true
777 return true
778 }
779 for (let attempt = 0; attempt < 3; attempt++) {
780 if (!rt.tree.known) await readTree($, c)
781 // What this attempt releases, taken before the sync so the merge already holds each one's resolve.
782 // A release recorded while git runs belongs to the next attempt.
783 const releasing = new Set(rt.releases)
784 await syncPeers($, c)
785 const settled = () => {
786 for (const sha of releasing) rt.releases.delete(sha)
787 if (rt.releases.size === 0) rt.treeDirty = false
788 }
789 const anyTorn = [...rt.peers.values()].some(p => p.torn)
790 const inUse = new Set<string>()
791 for (const m of rt.merged.live.values()) {
792 if (m.original) inUse.add(m.original)
793 if (m.seen) inUse.add(m.seen)
794 }
795 const own = shasOf([...rt.frozen, ...(rt.shard ? [rt.shard] : [])])
796 for (const peer of rt.peers.values()) for (const s of shasOf(peer.shard ? [peer.shard] : [])) inUse.add(s)
797 let want: Set<string>
798 if (rebuild && !anyTorn) {
799 want = new Set([...inUse, ...own])
800 } else {
801 want = new Set([...rt.tree.shas, ...own])
802 if (!anyTorn) for (const sha of releasing) if (!inUse.has(sha) && !own.has(sha)) want.delete(sha)
803 }
804 const same = want.size === rt.tree.shas.size && [...want].every(s => rt.tree.shas.has(s))
805 if (same && (rt.tree.sha !== null || want.size === 0)) {
806 settled()
807 return true
808 }
809 const made = await git($, c, ['mktree', '--missing'], treeInput(want))
810 if (made.exitCode !== 0) throw new Error('mktree failed')
811 const tree = made.stdout.trim()
812 const swap = await git($, c, ['update-ref', c.git.ref, tree, rt.tree.sha ?? zeroId(c.git.objectFormat)])
813 if (swap.exitCode === 0) {
814 rt.tree = { known: true, sha: tree, shas: want }
815 settled()
816 return true
817 }
818 if (/Unable to create '.*\.lock'/.test(swap.stderr)) {
819 // A writer killed mid-update left its lock: back off (the caller counts the failure), and
820 // reconcile removes the lock once it's old.
821 rt.treeDirty = true
822 return false
823 }
824 rt.tree.known = false // Lost the swap: re-read and try again.
825 }
826 rt.treeDirty = true
827 return true
828}
829
830async function readBranch($: $, c: Ctx & { git: GitCtx }): Promise<string> {
831 const read1 = async (p: string) => ((await $.fs.exists(p)) ? await $.fs.read(p) : null)
832 const rebase =
833 (await read1(`${c.git.gitDir}/rebase-merge/head-name`)) ?? (await read1(`${c.git.gitDir}/rebase-apply/head-name`))
834 return branchOf(await read1(`${c.git.gitDir}/HEAD`), rebase)
835}
836
837/** Writes this session's heartbeat: the file's mtime is the beat, its content says whether a tool is mid-write. */
838async function beat($: $, c: Ctx): Promise<void> {
839 if (!persistOn(c) || !rt.canRead || !rt.shard || rt.shard.endedAt !== undefined || rt.secondWindow) return
840 try {
841 const detached = rt.writeFailures >= 5
842 const name = `${rt.shard.session}.alive`
843 const path = `${c.git.shardDir}/${name}`
844 // Look before overwriting: a first window still running beats here too, and this write would
845 // hide its beat from the sync that follows.
846 const mine = rt.ownFiles.get(name)
847 if (mine && (await $.fs.exists(path))) {
848 const { mtimeMs, size } = await $.fs.stat(path)
849 if (mtimeMs !== mine.mtimeMs || size !== mine.size) {
850 const text = await readQuiet($, path)
851 const writer = text === undefined ? undefined : parseHeartbeat(text)?.instance
852 if (writer) await foreignWriter($, writer)
853 if (rt.secondWindow) return
854 }
855 }
856 await $.fs.write(path, JSON.stringify({ busy: rt.busy, instance: rt.instance, ...(detached ? { detached } : {}) }))
857 await rememberOwn($, path)
858 rt.lastBeat = await $.clock.now()
859 } catch {
860 rt.canRead = false // Can't even say it's alive: session-only from here.
861 }
862}
863
864async function clearBusyIfIdle($: $): Promise<void> {
865 if (toolsInFlight > 0 || flushRun || !rt.busy) return
866 rt.busy = false
867 await beat($, await ctx($))
868}
869
870/** A read that may fail without failing the sync. */
871async function readQuiet($: $, path: string): Promise<string | undefined> {
872 try {
873 return await $.fs.read(path)
874 } catch {
875 return undefined
876 }
877}
878
879/**
880 * Reads the shards that changed since the last call, merges every session's,
881 * and applies the result to this session's list.
882 */
883async function syncPeers($: $, c: Ctx, opts: { prevBeat?: number; loading?: boolean } = {}): Promise<void> {
884 if (!persistOn(c) || !rt.canRead || !rt.shard) return
885 const me = rt.shard.session
886 const now = await $.clock.now()
887 const dir = c.git.shardDir
888 const listed = (await $.fs.exists(dir)) ? await $.fs.list(dir) : []
889 const seen = new Set<string>()
890 let ownListed = false
891 for (const entry of listed) {
892 const shardMatch = /^(.+)\.(a|b)\.json$/.exec(entry.name)
893 const aliveMatch = /^(.+)\.alive$/.exec(entry.name)
894 const id = shardMatch?.[1] ?? aliveMatch?.[1]
895 if (!id) continue
896 if (id === me) {
897 if (shardMatch) ownListed = true
898 const mine = rt.ownFiles.get(entry.name)
899 if (mine && mine.mtimeMs === entry.mtimeMs && mine.size === entry.size) continue
900 rt.ownFiles.set(entry.name, { mtimeMs: entry.mtimeMs, size: entry.size })
901 const text = await readQuiet($, `${dir}/${entry.name}`)
902 const writer = text === undefined ? undefined : (shardMatch ? parseShard(text) : parseHeartbeat(text))?.instance
903 if (writer) await foreignWriter($, writer)
904 if (rt.secondWindow) return
905 continue
906 }
907 seen.add(id)
908 const peer: Peer = rt.peers.get(id) ?? { slots: {}, listed: {}, torn: false, state: 'live' }
909 peer.vanished = false
910 rt.peers.set(id, peer)
911 if (shardMatch) {
912 const slot = shardMatch[2] as 'a' | 'b'
913 peer.listed[slot] = entry.mtimeMs
914 const known = peer.slots[slot]
915 if (!known || known.mtimeMs !== entry.mtimeMs || known.size !== entry.size) {
916 // A read that fails (a sharing violation mid-write) counts as torn.
917 const text = await readQuiet($, `${dir}/${entry.name}`)
918 const parsed = text === undefined ? undefined : parseShard(text)
919 // A torn read keeps the last good copy, and its mtime isn't marked seen, so the next tick reads it again.
920 if (parsed) peer.slots[slot] = { mtimeMs: entry.mtimeMs, size: entry.size, shard: parsed }
921 else if (!known) peer.slots[slot] = { mtimeMs: -1, size: -1 }
922 }
923 } else {
924 const known = peer.beat
925 if (!known || known.mtimeMs !== entry.mtimeMs || known.size !== entry.size) {
926 const text = await readQuiet($, `${dir}/${entry.name}`)
927 const parsed = text === undefined ? undefined : parseHeartbeat(text)
928 if (parsed) peer.beat = { mtimeMs: entry.mtimeMs, size: entry.size, busy: parsed.busy, ...(parsed.detached ? { detached: true } : {}) }
929 else if (known) peer.beat = { ...known, mtimeMs: entry.mtimeMs }
930 else peer.beat = { mtimeMs: entry.mtimeMs, size: -1, busy: false }
931 }
932 }
933 }
934 if (!ownListed && rt.shard.seq > 0) rt.dirty = true // Someone removed this session's shard: write it again.
935
936 const asleep = opts.prevBeat !== undefined && opts.prevBeat > 0 && now - opts.prevBeat > STALE_MS
937 for (const [id, peer] of rt.peers) {
938 if (!seen.has(id)) peer.vanished = true
939 const parsed = [peer.slots.a?.shard, peer.slots.b?.shard].filter((s): s is Shard => s !== undefined)
940 peer.shard = parsed.sort((x, y) => y.seq - x.seq)[0] ?? peer.shard
941 peer.torn = !peer.vanished && parsed.length === 0
942 const slotTimes = [peer.listed.a, peer.listed.b].filter((m): m is number => m !== undefined)
943 peer.beatMs = peer.beat?.mtimeMs ?? (slotTimes.length > 0 ? Math.max(...slotTimes) : undefined)
944 if (!asleep) peer.state = liveness(peer.beatMs, peer.shard?.endedAt, now)
945 }
946 // A reject recorded for a live owner that ended (or was folded away) without reading it:
947 // this Claude is told instead, once. Checked before vanished shards are pruned, while their last records are known.
948 for (const [gitKey, event] of Object.entries(rt.shard.entries)) {
949 if (!event.gone || event.goneReason !== 'rejected' || event.by !== me || event.rerouted || event.owner === me) continue
950 const owner = rt.peers.get(event.owner)
951 const theirs = owner?.shard?.entries[gitKey]
952 if (!owner || (owner.state !== 'ended' && !owner.vanished) || !theirs || theirs.gone || theirs.at >= event.at) continue
953 event.rerouted = true
954 rt.dirty = true
955 const rel = slash(pathOfGitRel(c, event.rel)).slice(c.cwd.length + 1)
956 await queueNotice($, rejectNote(rel, event.rejectKind ?? 'change'))
957 }
958
959 // A vanished shard's events stay until another shard or a resolve covers them.
960 for (const [id, peer] of rt.peers) {
961 if (!peer.vanished || !peer.shard) {
962 if (peer.vanished) rt.peers.delete(id)
963 continue
964 }
965 const others = [rt.shard, ...[...rt.peers.values()].filter(p => p !== peer && !p.vanished).map(p => p.shard)]
966 for (const [key, event] of Object.entries(peer.shard.entries)) {
967 if (others.some(s => s?.entries[key] && s.entries[key]!.at >= event.at)) delete peer.shard.entries[key]
968 }
969 if (Object.keys(peer.shard.entries).length === 0) rt.peers.delete(id)
970 }
971
972 const peerShards = [...rt.peers.values()].map(p => p.shard).filter((s): s is Shard => s !== undefined)
973 rt.merged = mergeShards([rt.shard, ...peerShards])
974 // A resolve elsewhere closes this session's own record of that path.
975 for (const [gitKey, event] of Object.entries(rt.shard.entries)) {
976 const gone = rt.merged.gone.get(gitKey)
977 if (!event.gone && gone && gone.by !== me && gone.at > event.at) {
978 delete rt.shard.entries[gitKey]
979 rt.pending.delete(pendingKey(me, gitKey))
980 rt.dirty = true
981 }
982 }
983 if (pruneTombstones(rt.shard, peerShards, now)) rt.dirty = true
984
985 const busyPeer = [...rt.peers.values()].some(p => p.state === 'live' && p.beat?.busy)
986 if (busyPeer) rt.quietTicks = 2
987
988 const states: Record<string, 'live' | 'ended'> = { [me]: 'live' }
989 for (const [id, peer] of rt.peers) states[id] = peer.state
990 const prior = await read($, sessions)
991 if (JSON.stringify(prior) !== JSON.stringify(states)) await update($, sessions, () => states)
992
993 await applyMerged($, c, me, opts.loading === true)
994}
995
996/** Brings this session's list in line with the merged records: peer changes, handovers, and resolves made elsewhere. */
997async function applyMerged($: $, c: Ctx & { git: GitCtx; gitRoot: string }, me: string, loading: boolean): Promise<void> {
998 const now = await read($, files)
999 const known = await read($, knows)
1000 const states = await read($, sessions)
1001 const live = (id: string | undefined) => id !== undefined && id !== me && states[id] === 'live'
1002 let outsideCount = 0
1003 const fetch: string[] = []
1004 const changes: [string, Merged][] = []
1005 /** This session recorded the file, but another recorded it first: its original is the real one. */
1006 const adopt: [string, Merged][] = []
1007 for (const [gitKey, m] of rt.merged.live) {
1008 const path = pathOfGitRel(c, m.rel)
1009 if (!isInside(path, c.cwd, c.isWindows)) {
1010 outsideCount++
1011 continue
1012 }
1013 const key = keyOf(path, c.isWindows)
1014 const cur = now[key]
1015 if (m.by === me && cur) {
1016 const own = rt.shard?.entries[gitKey]
1017 if (own && !own.gone && own.at > m.firstAt) {
1018 adopt.push([gitKey, m])
1019 if (m.original) fetch.push(m.original)
1020 }
1021 continue
1022 }
1023 if (cur && cur.at !== undefined && cur.at >= m.at && cur.owner === m.owner) continue
1024 changes.push([gitKey, m])
1025 for (const sha of [m.original, m.seen]) if (sha) fetch.push(sha)
1026 }
1027 const failed = changes.length + adopt.length > 0 ? await fetchTexts($, c, fetch) : new Set<string>()
1028 for (const [gitKey, m] of adopt) {
1029 if (m.original && failed.has(m.original)) continue
1030 const original = m.original ? rt.texts.get(m.original)! : null
1031 const key = keyOf(pathOfGitRel(c, m.rel), c.isWindows)
1032 const cur = (await read($, files))[key]
1033 if (!cur || cur.original === original) continue
1034 let current: string | null
1035 try {
1036 current = await readOrNull($, cur.path)
1037 } catch {
1038 continue
1039 }
1040 const createdDirs = m.createdDirs?.length ? m.createdDirs.map(d => pathOfGitRel(c, d)) : undefined
1041 const { added, removed } = countChanges(original, current)
1042 await update($, files, all => {
1043 const prev = all[key]
1044 if (!prev) return all
1045 const next: Tracked = { ...prev, original, added, removed }
1046 if (createdDirs) next.createdDirs = createdDirs
1047 else delete next.createdDirs
1048 return { ...all, [key]: next }
1049 })
1050 const own = rt.shard?.entries[gitKey]
1051 if (own) {
1052 own.original = m.original
1053 if (m.createdDirs) own.createdDirs = m.createdDirs
1054 else delete own.createdDirs
1055 const waiting = rt.pending.get(pendingKey(me, gitKey))
1056 if (waiting) delete waiting.original
1057 rt.dirty = true
1058 }
1059 }
1060 const handovers: string[] = []
1061 // $.state holds one value up to STATE_CAP characters: leave out what would pass it, and say so once.
1062 let size = JSON.stringify(await read($, files)).length
1063 for (const [, m] of changes) {
1064 if ((m.original && failed.has(m.original)) || (m.seen && failed.has(m.seen))) continue
1065 const path = pathOfGitRel(c, m.rel)
1066 const key = keyOf(path, c.isWindows)
1067 const original = m.original ? rt.texts.get(m.original)! : null
1068 const seen = m.seen ? rt.texts.get(m.seen)! : null
1069 let current: string | null
1070 try {
1071 current = await readOrNull($, path)
1072 } catch {
1073 continue
1074 }
1075 if (current === original) {
1076 // Back at its original: on a load that re-settles it, so it drops off and releases its originals.
1077 if (loading) recordGoneMerged(c, m, me, await nextAt($))
1078 continue
1079 }
1080 const cur = (await read($, files))[key]
1081 if (cur && cur.owner === me && m.owner !== me && m.by !== me) {
1082 handovers.push(cur.rel)
1083 await update($, knows, all => ({ ...all, [key]: current }))
1084 }
1085 const growth = (original?.length ?? 0) + (seen?.length ?? 0) + path.length * 3 + 400
1086 if (!cur && size + growth > STATE_CAP) {
1087 if (!rt.overCap) $.ui.toast('Some pending files from other sessions are too large to list in this session.', { timeoutMs: 8000 })
1088 rt.overCap = true
1089 continue
1090 }
1091 size += growth
1092 const { added, removed } = countChanges(original, current)
1093 const rel = slash(path).slice(c.cwd.length + 1)
1094 const next: Tracked = {
1095 path,
1096 rel,
1097 original,
1098 ...(m.createdDirs?.length ? { createdDirs: m.createdDirs.map(d => pathOfGitRel(c, d)) } : {}),
1099 added,
1100 removed,
1101 lastSeenByClaude: m.owner === me && cur ? cur.lastSeenByClaude : seen,
1102 ...(current === null ? { isDeleted: true } : {}),
1103 ...(cur?.review ? { review: cur.review } : {}),
1104 owner: m.owner,
1105 gitRel: m.rel,
1106 at: m.at,
1107 branch: m.branch,
1108 }
1109 await update($, files, all => ({ ...all, [key]: next }))
1110 }
1111 for (const rel of handovers) await queueNotice($, note.handover(rel))
1112
1113 // Resolves made elsewhere: drop the entry, and tell the Claude that owned it.
1114 for (const [key, entry] of Object.entries(await read($, files))) {
1115 if (!entry.gitRel) continue
1116 const gone = rt.merged.gone.get(gitKeyOf(c, entry.gitRel))
1117 if (!gone || gone.by === me || (entry.at !== undefined && gone.at < entry.at)) continue
1118 await forget($, key)
1119 await cleanupReview($, entry.review)
1120 if (entry.owner === me) {
1121 const text = goneNote(entry, gone)
1122 if (text) await queueNotice($, text)
1123 } else if (!live(entry.owner) && gone.goneReason === 'reverted' && key in known) {
1124 await queueNotice($, note.earlierReverted(entry.rel))
1125 await update($, knows, all => {
1126 const out = { ...all }
1127 delete out[key]
1128 return out
1129 })
1130 }
1131 }
1132 if ((await read($, outside)) !== outsideCount) await update($, outside, () => outsideCount)
1133}
1134
1135/** The note a resolve made in another session sends this session's Claude, which owned the file. */
1136function goneNote(entry: Tracked, gone: Event): string | undefined {
1137 if (gone.goneReason === 'rejected') return rejectNote(entry.rel, gone.rejectKind ?? 'change')
1138 if (gone.goneReason === 'reverted') return revertNote(entry.rel)
1139 return undefined
1140}
1141
1142const rejectNote = (rel: string, kind: RejectKind) =>
1143 kind === 'new'
1144 ? `The user rejected your new file \`${rel}\`: it has been deleted.`
1145 : kind === 'deletion'
1146 ? `The user rejected your deletion of \`${rel}\`: it has been restored.`
1147 : `The user rejected your changes to \`${rel}\`: it is back to its content from before you edited it. Re-read it before editing it again.`
1148
1149const revertNote = (rel: string) =>
1150 `The user reverted all your changes to \`${rel}\`: it is back to its content from before you edited it. Re-read it before editing it again.`
1151
1152/**
1153 * Loads the persisted list for the current session id, once per id and per load
1154 * of this module. Every hook goes through it before touching the list.
1155 */
1156async function ensureLoaded($: $): Promise<void> {
1157 const c = await ctx($)
1158 if (!persistOn(c) || !rt.canRead) return
1159 const id = await $.session.id()
1160 // An id whose session.end ran stays ended in this process: a refresh tick before the process
1161 // quits must not load it again, which would clear its end marker and beat for a session that's gone.
1162 if (endedIds.has(id)) return
1163 if (rt.loading) await rt.loading
1164 if (rt.id === id && (await read($, loadedFor)) === id) return
1165 rt.loading ??= load($, c, id).finally(() => {
1166 rt.loading = undefined
1167 })
1168 await rt.loading
1169}
1170
1171async function load($: $, c: Ctx & { git: GitCtx; gitRoot: string }, id: string): Promise<void> {
1172 const fresh = (await read($, loadedFor)) !== id
1173 let instance = await read($, instanceAtom)
1174 if (!instance) {
1175 instance = `${id.slice(0, 8)}-${(await $.clock.now()).toString(36)}-${Math.random().toString(36).slice(2, 8)}`
1176 await update($, instanceAtom, () => instance)
1177 }
1178 rt.instance = instance
1179 if (rt.shard && rt.shard.session !== id && rt.shard.endedAt === undefined) {
1180 rt.frozen.push(rt.shard)
1181 rt.dirty = true
1182 }
1183 if (fresh && rt.clearedFor !== id) {
1184 // A new id (start, /clear): this process's old list belongs to the earlier id, which persisted it.
1185 // Once per id, before anything can return early: a load that runs again (a retry, a second
1186 // window taking over) must not clear what this id's Claude changed since.
1187 await update($, files, () => ({}))
1188 await update($, knows, () => ({}))
1189 await update($, outside, () => 0)
1190 }
1191 rt.clearedFor = id
1192 // Seed from this session's shard on disk: a reload must never rewrite it from an empty list.
1193 let seed: Shard | undefined
1194 for (const slot of ['a', 'b'] as const) {
1195 const path = `${c.git.shardDir}/${id}.${slot}.json`
1196 const parsed = (await $.fs.exists(path)) ? parseShard(await $.fs.read(path)) : undefined
1197 if (parsed && (!seed || parsed.seq > seed.seq)) seed = parsed
1198 }
1199 // A shard another process wrote is taken over here. If that process is still running (a second
1200 // window), it beats again within one refresh, and the sync's check makes the later one yield; ahooks/diff.ts 56 lines1/** Splits text into lines; a trailing newline does not add an empty line. */
2export function lines(text: string | null): string[] {
3 if (text === null || text === '') return []
4 const all = text.split(/\r?\n/)
5 if (all[all.length - 1] === '') all.pop()
6 return all
7}
8
9/**
10 * Lines added and removed between two texts, from the edit distance of a
11 * Myers O(ND) diff. Past `maxD` edits it settles for the length difference
12 * bounds, which only a wholesale rewrite of a huge file reaches.
13 */
14export function countChanges(
15 before: string | null,
16 after: string | null,
17 maxD = 20000,
18): { added: number; removed: number } {
19 const a = lines(before)
20 const b = lines(after)
21 let start = 0
22 while (start < a.length && start < b.length && a[start] === b[start]) start++
23 let endA = a.length
24 let endB = b.length
25 while (endA > start && endB > start && a[endA - 1] === b[endB - 1]) {
26 endA--
27 endB--
28 }
29 const x = a.slice(start, endA)
30 const y = b.slice(start, endB)
31 const n = x.length
32 const m = y.length
33 if (n === 0 || m === 0) return { added: m, removed: n }
34
35 const max = Math.min(n + m, maxD)
36 const offset = max + 1
37 const v = new Int32Array(2 * max + 3)
38 for (let d = 0; d <= max; d++) {
39 for (let k = -d; k <= d; k += 2) {
40 const goDown = k === -d || (k !== d && v[offset + k - 1]! < v[offset + k + 1]!)
41 let i = goDown ? v[offset + k + 1]! : v[offset + k - 1]! + 1
42 let j = i - k
43 while (i < n && j < m && x[i] === y[j]) {
44 i++
45 j++
46 }
47 v[offset + k] = i
48 if (i >= n && j >= m) {
49 const common = (n + m - d) / 2
50 return { added: m - common, removed: n - common }
51 }
52 }
53 }
54 return { added: m, removed: n }
55}
56hooks/ids.ts 12 lines1/** A short stable id for element keys, so a press never lands on a shifted row. */
2export function idOf(key: string): string {
3 let hash = 5381
4 for (let i = 0; i < key.length; i++) hash = ((hash * 33) ^ key.charCodeAt(i)) >>> 0
5 return hash.toString(36)
6}
7
8/** The key of a folder row's buttons: `accept-dir-…` and `reject-dir-…`. */
9export function folderId(relDir: string): string {
10 return idOf(`dir:${relDir}`)
11}
12hooks/commands.ts 33 lines1// Pure readings of a shell command's text: no host access, so tests import them directly.
2
3const READ_ONLY_COMMAND =
4 /^(ls|dir|cat|type|head|tail|less|more|wc|grep|egrep|rg|find|pwd|cd|echo|which|where|tree|stat|file|du|df|env|printenv|git\s+(log|diff|status|show|branch|rev-parse|ls-files|blame|remote|fetch)|Get-ChildItem|gci|Get-Content|gc|Get-Item|Get-Location|Select-String|Test-Path|Resolve-Path|Measure-Object|Write-Output|Write-Host|Set-Location)\b/i
5
6/** True when every part of the command only reads: then no git status runs around it. */
7export function isReadOnlyCommand(command: string): boolean {
8 if (/>|\b(tee|xargs|sed\s+-i)\b|-exec\b|-delete\b|Out-File|Set-Content|Add-Content|New-Item|Copy-Item|Move-Item|Remove-Item/i.test(command)) {
9 return false
10 }
11 return command.split(/&&|\|\||[;|\n]/).every(part => part.trim() === '' || READ_ONLY_COMMAND.test(part.trim()))
12}
13
14/** Splits a command into words, honouring single and double quotes. */
15export function words(text: string): string[] {
16 return [...text.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map(m => m[1] ?? m[2] ?? m[3] ?? '')
17}
18
19/** The plain file arguments of delete commands, for folders outside git. */
20export function deleteTargets(command: string): string[] {
21 const targets: string[] = []
22 for (const part of command.split(/&&|\|\||[;|\n]/)) {
23 const [verb, ...args] = words(part.trim())
24 if (!verb || !/^(rm|del|erase|Remove-Item|ri)$/i.test(verb)) continue
25 for (const arg of args) {
26 if (/^-/.test(arg) || /^\/[a-z]$/i.test(arg)) continue
27 targets.push(arg)
28 }
29 }
30 return targets
31}
32
33hooks/persist.ts 369 lines1// Pure helpers for keeping the pending list across sessions: the shard format,
2// merging shards, liveness, folding, and the git plumbing's text formats. No host
3// access; register.tsx does the I/O.
4
5/** A session counts as ended after this long without a heartbeat. */
6export const STALE_MS = 30_000
7/** An ended session's shard, a heartbeat without one, and an unneeded tombstone are removed after this long. */
8export const FOLD_MS = 24 * 60 * 60 * 1000
9/** Blobs larger than this can't come back through one `cat-file` (process.run returns 4 MiB). */
10export const BLOB_CAP = 4 * 1024 * 1024 - 1024
11
12export type GoneReason = 'accepted' | 'rejected' | 'reverted' | 'settled'
13export type RejectKind = 'change' | 'new' | 'deletion'
14
15/** One session's record of one file. Each shard holds at most one per path. */
16export type Event = {
17 /** When it was recorded (wall clock, ms). */
18 at: number
19 /** The session that recorded it. */
20 by: string
21 /** The session whose Claude last changed the file. */
22 owner: string
23 /** The path relative to the worktree root, `/`-separated, case kept. */
24 rel: string
25 /** `<git-dir>/HEAD` when it was recorded: `ref: refs/heads/x`, or a detached SHA. */
26 branch: string
27 /** Events at or before this are superseded for this path (a resolve folded away). */
28 epoch?: number
29 gone?: true
30 goneReason?: GoneReason
31 rejectKind?: RejectKind
32 /** For a reject: its owner ended without reading it, so the session that recorded it told its own Claude. */
33 rerouted?: true
34 /** For a tombstone: when no other shard first stopped needing it. */
35 unneededSince?: number
36 /** Blob SHAs; null = no file. */
37 original?: string | null
38 seen?: string | null
39 added?: number
40 removed?: number
41 isDeleted?: true
42 /** Folders a new file created, worktree-relative, outermost first. */
43 createdDirs?: string[]
44}
45
46export type Shard = {
47 v: 1
48 seq: number
49 session: string
50 /** Per process: a second process under the same session id has another. */
51 instance: string
52 endedAt?: number
53 endReason?: string
54 /** Keyed by `gitKey`: the worktree-relative path, lower-cased on Windows. */
55 entries: Record<string, Event>
56}
57
58export type Heartbeat = {
59 busy: boolean
60 detached?: true
61 /** The process writing it: a second process under the same session id writes another. */
62 instance?: string
63}
64
65/** A path's merged state: the latest live event, with the original from the earliest. */
66export type Merged = Event & { firstAt: number }
67
68export type MergeResult = {
69 live: Map<string, Merged>
70 /** The latest resolve per path, for paths with no live event after it. */
71 gone: Map<string, Event>
72}
73
74const later = (a: Event, b: Event) => a.at > b.at || (a.at === b.at && a.by > b.by)
75
76/**
77 * Merges every shard's events per path. The latest resolve (or a live event's
78 * epoch) cuts off everything before it; of what's left, the latest event gives
79 * the owner, `seen` and counts, and the earliest gives the original.
80 */
81export function mergeShards(shards: readonly Shard[]): MergeResult {
82 const byKey = new Map<string, Event[]>()
83 for (const shard of shards) {
84 for (const [key, event] of Object.entries(shard.entries)) {
85 const list = byKey.get(key)
86 if (list) list.push(event)
87 else byKey.set(key, [event])
88 }
89 }
90 const live = new Map<string, Merged>()
91 const gone = new Map<string, Event>()
92 for (const [key, events] of byKey) {
93 let lastGone: Event | undefined
94 let cut = -Infinity
95 for (const e of events) {
96 if (e.gone) {
97 if (!lastGone || later(e, lastGone)) lastGone = e
98 cut = Math.max(cut, e.at)
99 } else if (e.epoch !== undefined) {
100 cut = Math.max(cut, e.epoch)
101 }
102 }
103 const alive = events.filter(e => !e.gone && e.at > cut)
104 if (alive.length === 0) {
105 if (lastGone) gone.set(key, lastGone)
106 continue
107 }
108 let latest = alive[0]!
109 let earliest = alive[0]!
110 for (const e of alive) {
111 if (later(e, latest)) latest = e
112 if (later(earliest, e)) earliest = e
113 }
114 live.set(key, {
115 ...latest,
116 original: earliest.original,
117 ...(earliest.createdDirs ? { createdDirs: earliest.createdDirs } : {}),
118 firstAt: earliest.at,
119 })
120 }
121 return { live, gone }
122}
123
124export type Liveness = 'live' | 'ended'
125
126/** A heartbeat this close after an end marker was written with it, not after a resume. */
127const SAME_WRITE_MS = 1000
128const endedSince = (beatMs: number, endedAt: number) => endedAt + SAME_WRITE_MS >= beatMs
129
130/**
131 * Whether a peer is live: a heartbeat within STALE_MS and no end marker newer
132 * than it. `beatMs` is its heartbeat's mtime, or its shard's when it has none.
133 */
134export function liveness(beatMs: number | undefined, endedAt: number | undefined, now: number): Liveness {
135 if (beatMs === undefined) return endedAt !== undefined ? 'ended' : 'live'
136 if (endedAt !== undefined && endedSince(beatMs, endedAt)) return 'ended'
137 return now - beatMs > STALE_MS ? 'ended' : 'live'
138}
139
140/** A shard may be folded into a live one: ended by its marker, or silent for FOLD_MS. */
141export function isFoldable(beatMs: number | undefined, endedAt: number | undefined, now: number): boolean {
142 if (endedAt !== undefined && (beatMs === undefined || endedSince(beatMs, endedAt))) return true
143 return beatMs !== undefined && now - beatMs > FOLD_MS
144}
145
146/**
147 * Copies an ended shard's events into `into`: those the merge still uses, and
148 * resolves still shadowing an older live event elsewhere. A path both hold keeps
149 * the per-field merge. Returns whether `into` changed.
150 */
151export function foldIn(into: Shard, ended: Shard, others: readonly Shard[]): boolean {
152 let changed = false
153 for (const [key, event] of Object.entries(ended.entries)) {
154 if (event.gone) {
155 const shadows = others.some(s => {
156 const o = s.entries[key]
157 return o !== undefined && !o.gone && o.at < event.at
158 })
159 if (!shadows) continue
160 } else {
161 const newerGone = [into, ...others].some(s => {
162 const o = s.entries[key]
163 return o?.gone === true && o.at > event.at
164 })
165 if (newerGone) continue
166 }
167 const mine = into.entries[key]
168 if (!mine) {
169 into.entries[key] = { ...event }
170 changed = true
171 continue
172 }
173 const { live } = mergeShards([{ ...into, entries: { [key]: mine } }, { ...ended, entries: { [key]: event } }])
174 const merged = live.get(key)
175 if (!merged) {
176 // Both resolved, or a resolve wins: keep the newer of the two.
177 const keep = later(event, mine) ? event : mine
178 if (keep !== mine) {
179 into.entries[key] = { ...keep }
180 changed = true
181 }
182 continue
183 }
184 const { firstAt: _, ...next } = merged
185 const cut = event.gone ? event.at : mine.gone ? mine.at : undefined
186 const result: Event = cut !== undefined ? { ...next, epoch: Math.max(next.epoch ?? cut, cut) } : next
187 if (JSON.stringify(result) !== JSON.stringify(mine)) {
188 into.entries[key] = result
189 changed = true
190 }
191 }
192 return changed
193}
194
195/**
196 * Drops this shard's tombstones that no other shard has needed for FOLD_MS:
197 * needed = another shard holds an older live event for the path. Returns whether it changed.
198 */
199export function pruneTombstones(own: Shard, others: readonly Shard[], now: number): boolean {
200 let changed = false
201 for (const [key, event] of Object.entries(own.entries)) {
202 if (!event.gone) continue
203 const needed = others.some(s => {
204 const o = s.entries[key]
205 return o !== undefined && !o.gone && o.at < event.at
206 })
207 if (needed) {
208 if (event.unneededSince !== undefined) {
209 delete event.unneededSince
210 changed = true
211 }
212 } else if (event.unneededSince === undefined) {
213 event.unneededSince = now
214 changed = true
215 } else if (now - event.unneededSince > FOLD_MS) {
216 delete own.entries[key]
217 changed = true
218 }
219 }
220 return changed
221}
222
223/** `git mktree` input pinning every SHA once, each under its own name. */
224export function treeInput(shas: Iterable<string>): string {
225 return [...new Set(shas)]
226 .sort()
227 .map(sha => `100644 blob ${sha}\t${sha}\n`)
228 .join('')
229}
230
231/** The SHAs a `git ls-tree` listing names. */
232export function parseLsTree(stdout: string): string[] {
233 const shas: string[] = []
234 for (const line of stdout.split('\n')) {
235 const match = /^\d+ blob ([0-9a-f]+)\t/.exec(line)
236 if (match) shas.push(match[1]!)
237 }
238 return shas
239}
240
241/** UTF-8 byte length of one UTF-16 code unit sequence position, walking surrogate pairs. */
242function utf8Length(text: string, from: number, bytes: number): number {
243 let i = from
244 let left = bytes
245 while (left > 0 && i < text.length) {
246 const code = text.codePointAt(i)!
247 const size = code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4
248 left -= size
249 i += code > 0xffff ? 2 : 1
250 }
251 return left === 0 ? i : -1
252}
253
254/**
255 * Parses `git cat-file --batch` output up to its last complete record. Blob
256 * sizes are in bytes, the output is text, so lengths are walked as UTF-8.
257 */
258export function parseCatFileBatch(stdout: string): { blobs: Map<string, string>; missing: string[]; read: number } {
259 const blobs = new Map<string, string>()
260 const missing: string[] = []
261 let pos = 0
262 let read = 0
263 while (pos < stdout.length) {
264 const eol = stdout.indexOf('\n', pos)
265 if (eol < 0) break
266 const header = stdout.slice(pos, eol).split(' ')
267 if (header[1] === 'missing') {
268 missing.push(header[0]!)
269 pos = eol + 1
270 read++
271 continue
272 }
273 if (header.length !== 3) break
274 const size = Number(header[2])
275 const end = utf8Length(stdout, eol + 1, size)
276 if (end < 0 || stdout[end] !== '\n') break
277 blobs.set(header[0]!, stdout.slice(eol + 1, end))
278 pos = end + 1
279 read++
280 }
281 return { blobs, missing, read }
282}
283
284/** UTF-8 byte length of a text. */
285export function byteLength(text: string): number {
286 let bytes = 0
287 for (const ch of text) {
288 const code = ch.codePointAt(0)!
289 bytes += code < 0x80 ? 1 : code < 0x800 ? 2 : code < 0x10000 ? 3 : 4
290 }
291 return bytes
292}
293
294/** A worktree name made safe for a ref: `%XX` for anything outside `[A-Za-z0-9_-]`. */
295export function encodeWorktreeName(name: string): string {
296 let out = ''
297 for (const ch of name) {
298 if (/[A-Za-z0-9_-]/.test(ch)) {
299 out += ch
300 continue
301 }
302 const code = ch.codePointAt(0)!
303 const bytes =
304 code < 0x80
305 ? [code]
306 : code < 0x800
307 ? [0xc0 | (code >> 6), 0x80 | (code & 63)]
308 : code < 0x10000
309 ? [0xe0 | (code >> 12), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63)]
310 : [0xf0 | (code >> 18), 0x80 | ((code >> 12) & 63), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63)]
311 out += bytes.map(b => `%${b.toString(16).toUpperCase().padStart(2, '0')}`).join('')
312 }
313 return out
314}
315
316export const REF_ROOT = 'refs/pending-changes'
317
318/** The worktree's pin ref: `main` for the main worktree, `worktrees/<name>` for a linked one. */
319export function refFor(gitDir: string, commonDir: string): string {
320 const norm = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
321 if (norm(gitDir) === norm(commonDir)) return `${REF_ROOT}/main`
322 const name = gitDir.replace(/\\/g, '/').replace(/\/+$/, '').split('/').pop()!
323 return `${REF_ROOT}/worktrees/${encodeWorktreeName(name)}`
324}
325
326export function zeroId(objectFormat: string): string {
327 return '0'.repeat(objectFormat === 'sha256' ? 64 : 40)
328}
329
330/** The branch a record belongs to: HEAD, or during a rebase the branch being rebased. */
331export function branchOf(head: string | null, rebaseHeadName: string | null): string {
332 if (rebaseHeadName?.trim()) return `ref: ${rebaseHeadName.trim()}`
333 return (head ?? '').trim()
334}
335
336/** The shard slot a write with this `seq` goes to: they alternate, so a torn write never leaves the only copy. */
337export const slotOf = (seq: number): 'a' | 'b' => (seq % 2 === 1 ? 'a' : 'b')
338
339/** Parses a shard slot; undefined when torn or foreign. */
340export function parseShard(text: string): Shard | undefined {
341 try {
342 const value = JSON.parse(text) as Shard
343 return value && value.v === 1 && typeof value.seq === 'number' && value.entries ? value : undefined
344 } catch {
345 return undefined
346 }
347}
348
349export function parseHeartbeat(text: string): Heartbeat | undefined {
350 try {
351 const value = JSON.parse(text) as Heartbeat
352 return value && typeof value.busy === 'boolean' ? value : undefined
353 } catch {
354 return undefined
355 }
356}
357
358/** The notes the new behaviour sends, worded as the spec has them. */
359export const note = {
360 resume: (rels: readonly string[]) =>
361 `These files have unreviewed changes from an earlier session: ${rels.map(r => `\`${r}\``).join(', ')}. They are listed in the review pane.`,
362 handover: (rel: string) =>
363 `\`${rel}\` was since edited by another Claude session; the user's decisions on it go to that session now.`,
364 earlierModified: (rel: string) =>
365 `\`${rel}\`, changed in an earlier session, was modified by the user; re-read it before editing it.`,
366 earlierReverted: (rel: string) =>
367 `The user reverted \`${rel}\`, changed in an earlier session, to its original; re-read it before editing it.`,
368}
369types/index.d.ts 70 lines1/** The VS Code diff opened for one tracked file. */
2export type Review = {
3 /** Temp copy of the original: the read-only left side; the source is the right. */
4 originalCopy: string
5 /** Empty stand-in for the right side, written when the file was deleted at the time of opening. */
6 deletedCopy?: string
7}
8
9/** One file Claude changed that you have not resolved yet. */
10export type Tracked = {
11 /** The path as the tool named it, absolute. */
12 path: string
13 /** The path relative to the session's working directory, `/`-separated. */
14 rel: string
15 /** The text before Claude's first touch; null when Claude created the file. */
16 original: string | null
17 added: number
18 removed: number
19 /** For a file Claude created: the folders the write created, outermost first. */
20 createdDirs?: string[]
21 /** True while the file is gone from disk (a deletion to accept or reject). */
22 isDeleted?: boolean
23 /** The text right after Claude's last change, or the last note it was sent; null when that left it deleted. */
24 lastSeenByClaude: string | null
25 review?: Review
26 /** With persistence: the session whose Claude last changed it. */
27 owner?: string
28 /** With persistence: the path relative to the worktree root, case kept. */
29 gitRel?: string
30 /** With persistence: when the record this entry reflects was made. */
31 at?: number
32 /** With persistence: the branch checked out when it was recorded. */
33 branch?: string
34 /** Never persisted (too large, or the write failed): kept in this session only. */
35 sessionOnly?: boolean
36 /** In a second window: listed when it yielded, from the shared list, so it may be out of date. */
37 otherWindow?: boolean
38}
39
40declare module 'claude-code' {
41 interface PluginState {
42 'pending-changes': {
43 /** Keyed by the normalised absolute path. */
44 files: Record<string, Tracked>
45 /** Folders collapsed in the pane, by their path relative to the working directory. */
46 collapsed: string[]
47 /** Notes waiting to reach Claude with the next prompt. */
48 notices: string[]
49 /** Pending entries in the worktree outside the working directory, for the footer. */
50 outside: number
51 /** Other sessions in the worktree, by id. */
52 sessions: Record<string, 'live' | 'ended'>
53 /** The session id the persisted list was last loaded for. */
54 loadedFor: string
55 /** Session ids whose Claude has had the resume note. */
56 resumeNoted: string[]
57 /** Files this Claude was told about by a resume or handover note, by key: the text it was told about. */
58 knows: Record<string, string | null>
59 /** Resolve times of files resolved while persistence was off, by worktree key. */
60 resolvedWhileOff: Record<string, { at: number; rel: string }>
61 /** This process's id, telling a second process under the same session id apart. */
62 instance: string
63 /** The branch checked out now, for the `other branch` tag. */
64 branchNow: string
65 /** This process yielded to another window open on the same session. */
66 secondWindow: boolean
67 }
68 }
69}
70