/ledger prints each task ledger's goal, current step and next step; /ledger:task writes a backlog ledger for a separate task, or with --here gives the current…

Claude Code re-reads the whole conversation on every turn. So a long session costs more with each turn. You can clear the session to stop that cost, but then the agent forgets the task: the goal, the plan, and what is done.
You: Start a new task: items in the offline queue disappear if the app is killed during a sync.
Agent: (creates a worktree and a ledger, and moves the session into the worktree)
Agent: Plan: 1. Write a test that kills the app during a sync and fails.
item only after the server confirms it. Do you approve?
You: yes
Agent: (writes failing tests, makes the fix, gets it reviewed)
Agent: Clear point. Ledger updated. Type /ledger:next to clear the session and continue, or /ledger:close to clear it and stop.
You: /ledger:next
Agent: (fresh session, reads the ledger, continues with step 3 in the plan)
Next morning:
You: What are we working on?
Agent: One task is open: offline-queue-loss. Steps 1 and 2 are done. Step 3 is in review.
You: go
You do three things: you start the task, you approve the plan, and you type /ledger:next when the agent asks.
A Claude Code multi-agent setup. It gives the top-level session a contract: plan the work, delegate it to subagents, review the result, and keep the state in a file instead of in the conversation. It ships five things:
/ledger and thirteen /ledger: commands. Commands lists each one.To set it up, see Install.
One number drives the design. In eight weeks of one operator's sessions, 86% of the spend was re-reading context, not generating output — 257 tokens read for every one written. Everything you read stays in the session and is paid for again on every later turn.
So the setup pushes verbose work out of the main session. A build log goes to runner, which returns a verdict. A wide code search goes to researcher, which returns a short report. Implementation goes to an implementer, which returns a diff and a report. The main session stays small, and it stays the place where planning, routing, and review happen.
git clone https://github.com/chrfalch/agent-config.git
cd agent-config
bin/deploy --dry-run # print every change, write nothing
bin/deploy
You need Claude Code, Node.js 20.12 or later, bash, git, and jq. Deploy runs on Node. bash runs the git hook dispatcher that deploy installs. Every hook script and the status line use jq. Python is no longer needed. The GitHub CLI, gh, finds merged PRs for /ledger:retire and for the retire hint of /ledger:next and /ledger:go. /ledger:worktrees uses it for its PR column. Without gh, these parts do not show. The first run of bin/deploy runs npm ci, which installs dependencies into node_modules and writes the npm cache in ~/.npm. Codex CLI, the argent MCP server, and the gh stack extension are optional; deploy has a flag to skip each one.
Run bin/deploy with no flags in a terminal to start an interactive wizard. Flags work as before and skip the wizard.
Claude Code reads the plugins in mods/ directly from this checkout, not from a copy. After a plugin change is merged, run git pull here, then restart Claude Code or run /reload-plugins. You do not need to run bin/deploy again.
Then add three variables to your shell profile:
export CLAUDE_AUTOCOMPACT_PCT_OVERRIDE=30
export BASH_MAX_OUTPUT_LENGTH=10000
export MAX_MCP_OUTPUT_TOKENS=10000
That is the happy path. docs/installation.md has the flags, what deploy owns, what it never touches, and how to undo it.
Check that the install worked before you start real work. Open a new terminal so the shell variables load, then start Claude Code in any repo.
ls ~/.claude/agents/. The list should include researcher.md, runner.md, reviewer.md, and opus-implementer.md. The Codex and argent agents appear only if you did not skip them at deploy./ledger and then /ledger:help. Both commands should run. If Claude Code does not know them, the ledger mod did not install.What are we working on?. It should say that no task is open, because this repo has no ledger yet.Start a new task: … with a sentence describing it. You should get a plan and a question asking you to approve it. Answer yes and follow along.If step 1 or step 2 fails, run bin/deploy --dry-run again and read what it would change.
Open Claude Code in your repo and describe the task. The orchestrator starts the task with /ledger:task, which writes a ledger before any plan. When no task is open, the task gets a worktree at once, and the session moves into it and continues there. When another task is open, the ledger waits in a backlog, with no worktree yet. The reply ends with a start: line, /ledger:go <name>, and you type it. The orchestrator then explores, writes a plan, and asks you to approve it. On approval it writes the plan into the ledger, then runs the pipeline:
investigate -> resolve ambiguity -> plan -> ledger -> red tests -> implement -> verify -> review -> clear point -> accept
Three things you take part in: you start the task, you approve the plan, and you type /ledger:next when the orchestrator says so.
Every non-trivial task gets a file at .claude/ledger.md in its worktree. It holds the goal, the approved plan with a status per step, decisions and their reasons, and one line naming the exact next action. The orchestrator writes to it at every step boundary.
The ledger exists because the conversation is expensive and the file is cheap. A session transcript is re-read on every turn. The ledger is read once, when a session starts.
## Next step
Delegate step 3 to opus-implementer at high effort: make the failing
tests in src/sync/__tests__/queue.test.ts pass.
/ledger:next and /ledger:closeWhen one implement-and-review cycle finishes and more work remains, the orchestrator stops and says:
Clear point. Ledger updated. Type
/ledger:nextto clear the session and continue, or/ledger:closeto clear it and stop.
You type /ledger:next. It clears the session and sends go <name>. A hook reads the ledger into the fresh session, so the new session knows the goal, what is done, and what is next. It continues from there. You type nothing else. Type /ledger:close to stop for now, and go later. If either command cannot clear the session, it says so; then type /clear, then go.
This is the core loop. A cold start from the ledger costs a few thousand tokens once. Carrying the finished cycle into the next one costs that on every turn for the rest of the task.
You write plain sentences, and the wording does not have to match these examples.
| You type | What happens |
|---|---|
Start a new task: items in the offline queue disappear if the app is killed during a sync. | The orchestrator runs /ledger:task. When another task is open, it replies with a start: line for you to type. The orchestrator then investigates, writes a plan, and asks you to approve it. Only a small single-file change is made without a plan. |
yes | Approves the plan. The orchestrator writes the plan into the task's ledger and starts on step 1. |
Change step 2: keep the old API and add the new one next to it. | The orchestrator rewrites the plan and asks again. |
What are we working on? | It answers from the ledger: the goal, what is done, and the next step. If several tasks are open, it lists each one. |
go | It continues from the next step in the ledger. Use this after /ledger:close, after a manual /clear, or in a new session the next day. |
go offline-queue-loss | The same as go, when several tasks are open and you want to name one. The session moves into that task's worktree first. |
Why did we drop the retry counter? | It answers from the decisions recorded in the ledger, with the reason for each. |
Explain that in more detail. | Answers start as a short summary. This asks for file paths, function names, and what was ruled out. |
Commit and open a PR. | The orchestrator does not commit on its own. When the last review passes it asks you, and this is the answer. |
docs/usage.md walks through a full task, with the ledger at each stage.
The ledger mod adds these commands. Claude Code puts the plugin name in front of every command that a plugin writes as a markdown file, so a plain /task does not exist.
A hook answers /ledger, /ledger:help, /ledger:worktrees, /ledger:retire, /ledger:archive, /ledger:all, /ledger:parent and /ledger:dashboard directly, without a model turn. Most of them only print. /ledger:retire and the two prune forms of /ledger:worktrees delete files. Add --dry-run to see what they would delete first. The other commands run a model turn, for example to write a ledger, start a task, or switch to one.
| You type | What happens |
|---|---|
/ledger | Prints each task ledger's goal, current step and next step. A parent task in this repo's backlog is listed too, marked (backlog), with its child tasks under it; so is that task's own parent task in the backlog. Other backlog tasks are not listed. |
/ledger <name> | Prints each ledger whose name contains <name>, in any case. More than one ledger can match. |
/ledger:help | Prints one line for each /ledger command. |
/ledger:task <description> | Starts a separate task. The agent picks a short name, writes the goal, and runs bin/cc-task-new. The script writes a ledger with the goal filled in to the backlog, ~/.claude/ledger-backlog/<repo>/<name>.md, with no branch or worktree yet. When no task is open, the session moves into the new worktree and continues there. The agent makes that branch and worktree at once, the same way /ledger:go does. When another task is open, the ledger stays in the backlog, and the reply ends with a start: line, /ledger:go <name>. Type it to clear the session and continue in the new task. Either way, you do not open a new terminal. --stack makes the branch and worktree at once, on top of the current branch. |
/ledger:task --here [<slug>] | Gives the linked worktree this session is in a ledger, instead of a new worktree. Without a slug, the task takes the branch name without its owner prefix. It refuses the main checkout and a worktree that already has a ledger. The reply is the path of the new ledger. |
/ledger:update | Writes the step status, the subagent reports, the decisions and the next step to the task's ledger. After an implement-and-review cycle with work left, the reply is the clear point line. Otherwise it says only that the ledger is updated. With no ledger in the working directory, the agent creates nothing and tells you to use /ledger:task. |
/ledger:close | Writes the ledger the same way, then clears the session. Type go later to continue. It never starts a task: with no ledger in the worktree, it prints why and does nothing. |
/ledger:next | Writes the ledger the same way, clears the session, then sends go <name>, so the fresh session continues from the next step. When every step is done, it first says how to retire the task. Like /ledger:close, it never starts a task. |
/ledger:go <slug> | Switches to the task named <slug>; /ledger shows each name. If the session has a task ledger, the agent writes it first. The session then clears and go <slug> is sent, so the fresh session moves into that task's worktree. If that task was parked, the mark is removed. A backlog task first gets its branch and worktree. The branch starts at the --base ref given when the task was written. Without one, it starts at the commit that origin/HEAD points to. Nothing fetches first, so that commit is from your last git fetch. Without origin/HEAD, the branch starts at the branch that the main checkout is on. A backlog task starts only from a session in its repo. From another repo, /ledger:go names the repo and changes nothing. For a parent task, /ledger:go starts its next child task instead: the first one under ## Children that is not started yet and is still in the backlog. When you leave a task whose steps are all done, it first says how to retire it. |
/ledger:park [<slug>] <reason> | Marks a task parked, with the date and the reason. With the slug of another task, it only marks that task. Without a slug, it writes this task's ledger, parks it, then clears the session. |
/ledger:archive [<term>] [--all] | Lists this repo's archived ledgers in ~/.claude/ledger-archive/, newest first, one line each. A term keeps the ledgers that contain it, in any case, and shows the first matching line. --all lists every repo. |
/ledger:worktrees | Prints a table of the repo's linked git worktrees, largest first, with size, last commit, changed files, ledger and PR. |
/ledger:worktrees prune <name> | Deletes the build folders of that worktree. It keeps node_modules, Pods, .claude and the worktree itself. |
/ledger:worktrees prune <name> --dry-run | Lists those build folders and their sizes. It deletes nothing. |
/ledger:worktrees derived-data | Lists every folder in ~/Library/Developer/Xcode/DerivedData with its size. It groups them by where the project is: the main checkout, a linked worktree, another location, or gone. Folders with no source project, and shared caches, have their own groups. |
/ledger:worktrees prune-orphans | Deletes the DerivedData folders whose project no longer exists. It never deletes shared caches or folders without a recorded project. |
/ledger:worktrees prune-orphans --dry-run | Lists those folders. It deletes nothing. |
/ledger:retire [<slug>] [--force] | Copies the task's ledger and its .claude/evidence/ folder to ~/.claude/ledger-archive/<repo>/, removes its worktree and deletes the worktree's build folders. It also deletes the local branch when every commit on it is in the default branch or in a merged PR. A branch with commits after its PR merged stays. It needs --force for uncommitted changes, for a branch that has commits not in the default branch and no merged PR, and for a parent task with active child tasks. Retiring a child task marks it retired in its parent ledger. A backlog task of this repo has no worktree or branch: its ledger is archived, then deleted from the backlog. Without a slug it takes the task this session is in. |
/ledger:retire [<slug>] --dry-run | Lists what retiring the task would do: its worktree, branch, uncommitted changes and archive path, or for a backlog task its ledger and archive path. It names any active child tasks, which need --force. It deletes nothing. |
/ledger:parent [<name>] | Prints a parent task and, for each child task, its status and next step. Without a name it shows the task this session is in when it has child tasks, or else that task's parent task. |
/ledger:parent <name> add <child> | Makes <child> a child task of <name>. It writes both ledgers. A parent task ties together tasks that ship separately, such as stacked PRs. See Parent tasks. |
/ledger:parent <name> remove <child> | Removes that relation from both ledgers. |
/ledger:all | Prints a table of every task ledger on the machine, from every repo, active and archived, with its next step. Backlog tasks follow in their own section, Backlog. A parked task shows as parked. The list lives in ~/.claude/ledgers.json. A new task, a retire and each session start add to it. |
/ledger:all --scan | Rebuilds ~/.claude/ledgers.json from the ledgers under ~/repos and ~/issues and the archive in ~/.claude/ledger-archive/, then prints the table. |
/ledger:dashboard | Starts a web page on this machine with the /ledger:all list, filters by repo and status, and a search of every ledger's text. You can select more than one status; with none selected it shows every task. A child task comes right after its parent, marked ↳; a child that is not right under its parent, for example because a filter hides the parent, shows the parent's name, and a click on it opens the parent when its ledger is found. Click a task to read its ledger. Its buttons copy go <slug>, park and unpark the task, and retire it after a preview. It prints the page's address, which holds a new access key each start. It keeps running after the session ends. |
/ledger:dashboard stop | Stops the dashboard. |
A build folder whose project is on a disk that is not connected goes in its own group, Disk not connected, and is never deleted.
To remove a finished worktree, use bin/cc-worktree-retire <worktree>. It archives the ledger first, then removes the worktree and its Xcode build folders. Given a backlog ledger, ~/.claude/ledger-backlog/<repo>/<slug>.md, it archives that ledger, then deletes it.
| Document | What it covers |
|---|---|
| docs/usage.md | The daily loop, a worked example, the ledger, clear points |
| docs/installation.md | Prerequisites, every flag, what deploy owns, revert |
| docs/fleet.md | The eight agents, their models, and the routing rules |
| docs/customizing.md | Changing models, gating rules, adding an agent, tests |
| CONTRIBUTING.md | Forking, what to send back, what must never be committed |
| DECISIONS.md | Why the setup is shaped this way |
rules/ the orchestrator contract, one file per topic
agents/ the eight subagents
docs/ this documentation
ledger.template.md copied per task to .claude/ledger.md
notes/ rationale, not rules
DECISIONS.md why the setup is shaped this way
settings.policy.json Claude Code keys this repo asserts
codex/policy.toml Codex keys this repo asserts
mods/ledger/ the /ledger command and its /ledger: commands, /ledger:worktrees included (a Claude Code plugin)
.claude-plugin/ marketplace.json, which lists the plugins in mods/ for Claude Code
hooks/ the six hook scripts that deploy installs
githooks/ the git hook dispatcher that deploy installs
tools/ the deploy code, its wizard and CLI, the settings merge and the rule filter
tests/ the tests for tools/, bin/ and hooks/
bin/deploy installs everything above
bin/cc-dd-path prints the shared Xcode build folder for a worktree
bin/cc-task-new writes a backlog ledger, or makes a task's branch and worktree
bin/cc-worktree-retire archives a worktree's ledger, then removes the worktree; or archives, then deletes a backlog ledger
bin/cc-ledgers keeps ~/.claude/ledgers.json, the list of every task ledger
CONTRIBUTING.md forking, what to send back, what must never be committed
Agents you add under ~/.claude/agents/ that are not in this repo are left alone by deploy. Keep private or employer-specific agents there, not here.
No secrets belong in this repo. Nothing here reads a key or a token.
hooks/register.ts 418 lines1import type { EngineInterface, Register } from 'claude-code'
2
3import { allCommand } from './all-command'
4import {
5 backlogUncheckedMessage,
6 folderSlug,
7 formatAll,
8 GO_FROM_SUBAGENT,
9 GO_USAGE,
10 goArgs,
11 goDeniedMessage,
12 HELP,
13 isGoArgs,
14 lookupFailedMessage,
15 markFailedWarning,
16 noChildToStartMessage,
17 noLedgerMessage,
18 oneSwitchPerTurnMessage,
19 otherRepositoryMessage,
20 PARK_USAGE,
21 park,
22 parkArgs,
23 parkMarker,
24 pickFailedMessage,
25 pickFailedWarning,
26 promotedThenFailedMessage,
27 promoteFailedMessage,
28 removedFolderMessage,
29 retireHint,
30 severalLedgersMessage,
31 sharedSlugMessage,
32 slugExpectedMessage,
33 summarize,
34 unknownTaskMessage,
35 unpark,
36 unparkFailedMessage,
37 worktreeTaskMessage,
38 worktreeWithoutLedgerMessage,
39 type GoFields,
40 type LedgerSummary,
41} from './ledger'
42import { archiveCommand } from './archive-command'
43import { dashboardCommand } from './dashboard-command'
44import {
45 findLedgers,
46 lookUpBranch,
47 lookUpOtherWorktrees,
48 message,
49 sessionFolder,
50 sessionLedger,
51 titleSlug,
52 unlistedAncestors,
53 type Found,
54} from './lookup'
55import { childToStart, familyOf, markStarted, parentCommand, showParent } from './parent-command'
56import { backlogLedgerPath, mainCheckout, otherRepositoryTask, promoteBacklogTask, registeredTasks, type Entry } from './registry'
57import { worktreeOf } from './retire'
58import { retireCommand } from './retire-command'
59import { basename } from './worktrees'
60import { worktreesCommand } from './worktrees-command'
61
62const armed = { plugin: 'ledger', key: 'armed' } as const
63
64type GoArm = { mode: 'go'; slug: string; ledger?: string }
65
66/**
67 * The task a /ledger:go call is starting, from its armed check until it armed the switch or gave up. It is set before the
68 * first await, so a second call that overlaps the first cannot also pass the check.
69 * It assumes the hooks module is loaded once per session; a second instance would hold its own reservation.
70 */
71let goStarting: string | undefined
72
73const uniqueByPath = (ledgers: Found[]): Found[] => ledgers.filter((ledger, index) => ledgers.findIndex(({ path }) => path === ledger.path) === index)
74
75/** A task's ledger in a worktree, or the registry's backlog entries for it, none when the registry missed it. */
76type Place = { ledger: string } | { backlog: Entry[]; isUnregistered: boolean }
77
78/** Where the task `target` is. The text says why it cannot be started: no ledger, or several, has that slug. */
79async function placeOf($: EngineInterface, target: string, found: Found[], tasks: LedgerSummary[], cwd: string): Promise<Place | { text: string }> {
80 const local = found.filter((_, index) => tasks[index]?.slug === target)
81 const matches = uniqueByPath([...local, ...(await lookUpOtherWorktrees($, target, cwd)).ledgers])
82 const [match] = matches
83 const registered = match === undefined ? await registeredTasks($, target) : []
84 if ('error' in registered) return { text: backlogUncheckedMessage(target, tasks, registered.error) }
85 const backlog = registered.filter(entry => entry.status === 'backlog')
86 // The registry write at backlog time is best effort, so an unregistered slug may still have a backlog ledger.
87 const isUnregistered = match === undefined && registered.length === 0
88 if (match === undefined && backlog.length === 0 && !isUnregistered) return { text: unknownTaskMessage(target, tasks) }
89 if (matches.length > 1) return { text: sharedSlugMessage(target, matches.map(ledger => ledger.path)) }
90 return match ? { ledger: match.path } : { backlog, isUnregistered }
91}
92
93/**
94 * Whether the task's ledger lists child tasks. A backlog ledger is read before its promotion, because a parent task in the
95 * backlog is not promoted: where the registry says it is, or where cc-task-new writes it when the registry missed it. One
96 * that cannot be found or read counts as having none.
97 */
98async function hasChildren($: EngineInterface, slug: string, place: Place, main: string | null | undefined): Promise<boolean> {
99 const path =
100 'ledger' in place
101 ? place.ledger
102 : place.isUnregistered
103 ? main && (await backlogLedgerPath($, main, slug).catch(() => null))
104 : place.backlog.find(entry => entry.main === undefined || !main || entry.main === main)?.path
105 if (!path) return false
106 const text = await $.fs.read(path).catch(() => '')
107 return summarize(text, '', 0).children !== undefined
108}
109
110// Read at the turn's end, because the model may have just finished the last step. The line is only advice, so a failure skips it.
111async function showRetireHint($: EngineInterface, ledger: string): Promise<void> {
112 try {
113 const { slug, current } = summarize(await $.fs.read(ledger), folderSlug(ledger), 0)
114 if (current === 'all done') $.ui.log(retireHint(slug, await lookUpBranch($, worktreeOf(ledger))))
115 } catch {}
116}
117
118/**
119 * Everything /ledger:go does before go.md runs: find the task, pick a parent's next child, promote a backlog task, unpark,
120 * mark it started, and arm the clear. A text says why the task was not started; then the clear is not armed, and a clear
121 * this turn already armed stays.
122 */
123async function startGo($: EngineInterface, input: string): Promise<{ target: string; fields: GoFields; args: string; arm: GoArm } | { text: string }> {
124 let promotedWorktree: string | undefined
125 let arm: GoArm | undefined
126 let target = input.trim()
127 if (target === '') return { text: GO_USAGE }
128 if (goStarting !== undefined) return { text: oneSwitchPerTurnMessage({ mode: 'go', slug: goStarting }, target) }
129 goStarting = target
130 try {
131 const { value: alreadyArmed } = await $.state.get(armed)
132 if (alreadyArmed) return { text: oneSwitchPerTurnMessage(alreadyArmed, target) }
133 const found = await findLedgers($)
134 if ('error' in found) return { text: lookupFailedMessage(found.error) }
135 const tasks = await Promise.all(found.map(async ledger => summarize(await $.fs.read(ledger.path), folderSlug(ledger.path), 0)))
136 const folder = await sessionFolder($)
137 const cwd = folder.path
138 let place = await placeOf($, target, found, tasks, cwd)
139 if ('text' in place) return place
140 const active = sessionLedger(found, folder)
141 if (active.kind === 'several') return { text: severalLedgersMessage(cwd, active.paths.map(folderSlug)) }
142 let main: string | null | undefined
143 const otherRepository = async (slug: string, at: Place): Promise<{ text: string } | undefined> => {
144 if ('ledger' in at) return undefined
145 if (main === undefined) main = await mainCheckout($, cwd)
146 const elsewhere = otherRepositoryTask(at.backlog, main)
147 return elsewhere ? { text: otherRepositoryMessage(slug, elsewhere.repo, elsewhere.main) } : undefined
148 }
149 const refused = await otherRepository(target, place)
150 if (refused) return refused
151
152 const warnings: string[] = []
153 let picked: string[] | undefined
154 if (await hasChildren($, target, place, main)) {
155 const chain = await childToStart($, target, cwd)
156 if ('error' in chain) {
157 if (!('ledger' in place)) return { text: pickFailedMessage(target, chain.error) }
158 warnings.push(pickFailedWarning(target, chain.error))
159 } else if (chain.length > 0) {
160 picked = chain
161 target = chain.at(-1) ?? target
162 place = await placeOf($, target, found, tasks, cwd)
163 if ('text' in place) return place
164 const refusedChild = await otherRepository(target, place)
165 if (refusedChild) return refusedChild
166 } else if (!('ledger' in place)) {
167 const shown = await showParent($, target, cwd)
168 return { text: noChildToStartMessage(target, 'error' in shown ? shown : shown.children) }
169 }
170 }
171
172 let ledger: string
173 if ('ledger' in place) ledger = place.ledger
174 else {
175 const promoted = await promoteBacklogTask($, target, cwd)
176 if ('error' in promoted) {
177 return { text: place.isUnregistered && promoted.isMissing ? unknownTaskMessage(target, tasks) : promoteFailedMessage(target, promoted.error) }
178 }
179 ledger = promoted.ledger
180 promotedWorktree = worktreeOf(ledger)
181 }
182 const text = await $.fs.read(ledger)
183 const { text: unparked, parked } = unpark(text)
184 if (parked) {
185 try {
186 await $.fs.write(ledger, unparked)
187 } catch (error) {
188 const reason = `Could not remove the parked marker. ${message(error)}`
189 return { text: promotedWorktree === undefined ? unparkFailedMessage(target, message(error)) : promotedThenFailedMessage(target, promotedWorktree, reason) }
190 }
191 }
192 const current = active.kind === 'one' ? active.path : undefined
193 const task = tasks.find(({ slug }) => slug === target) ?? summarize(text, target, 0)
194 let marked: string | undefined
195 if (task.parent) {
196 const mark = await markStarted($, task.parent, target, cwd)
197 if ('error' in mark) warnings.push(markFailedWarning(target, task.parent, mark.error))
198 else marked = mark.marked
199 }
200 const family = await familyOf($, task, cwd)
201 arm = { mode: 'go', slug: target, ...(current && current !== ledger && { ledger: current }) }
202 await $.state.set(armed, arm)
203 const fields = { parked, family, promotedWorktree, picked, marked, warnings }
204 return { target, fields, args: goArgs(target, current, fields), arm }
205 } catch (error) {
206 if (arm) await disarm($, arm)
207 // Once the worktree exists, saying that nothing was written would be wrong.
208 if (promotedWorktree === undefined) throw error
209 return { text: promotedThenFailedMessage(target, promotedWorktree, message(error)) }
210 } finally {
211 goStarting = undefined
212 }
213}
214
215/**
216 * Clears the switch a /ledger:go call armed, unless something armed another since. State hands back copies, not `arm`.
217 * Known limit: in the test harness $.state.get returns this hook's own last write (unverified in the engine), so an arm
218 * made meanwhile (a typed /ledger:next) may be cleared too. The cost is one missed clear; a "known limit" test in go-start.test.ts pins it.
219 */
220async function disarm($: EngineInterface, arm: GoArm): Promise<void> {
221 const { value } = await $.state.get(armed)
222 if (value?.mode === 'go' && value.slug === arm.slug && value.ledger === arm.ledger) await $.state.set(armed, null)
223}
224
225/** The answer of the hooks after /ledger:go; when they fail, the switch it armed is undone first. */
226async function disarmedOnFailure<T>($: EngineInterface, arm: GoArm, answer: Promise<T>): Promise<T> {
227 try {
228 return await answer
229 } catch (error) {
230 await disarm($, arm)
231 throw error
232 }
233}
234
235// The hook sees the model's raw input: the name may be missing, or carry a leading slash the Skill tool strips later.
236const skillName = (skill: string | undefined): string => (skill ?? '').trim().replace(/^\//, '')
237
238export const register: Register = on => {
239 on('session.start', async ($, e, next) => {
240 await $.command.register({
241 name: 'ledger',
242 description: 'Show each task ledger: goal, current step, next step. /ledger <name> shows one.',
243 })
244 return next(e)
245 })
246
247 on('command.run', { command: 'ledger' }, async ($, e) => {
248 const found = await findLedgers($)
249 if ('error' in found) return { text: `Could not list task ledgers. ${found.error}` }
250 const summaries = await Promise.all(found.map(async ledger => summarize(await $.fs.read(ledger.path), ledger.slug, ledger.mtimeMs)))
251 const ancestors = await unlistedAncestors($, summaries)
252 const filter = e.args.trim().toLowerCase()
253 const matches = (name: string) => name.toLowerCase().includes(filter)
254 const ledgers = [
255 ...summaries.filter((_, index) => matches(found[index]?.slug ?? '')),
256 ...('error' in ancestors ? [] : ancestors.filter(({ slug }) => matches(slug))),
257 ].sort((a, b) => b.editedMs - a.editedMs)
258 const backlogNote = 'error' in ancestors ? [`Parent tasks in the backlog are not shown. ${ancestors.error}`] : []
259 if (ledgers.length === 0) {
260 return { text: [filter ? `No ledger matches "${filter}".` : 'No task ledgers found.', ...backlogNote].join('\n\n') }
261 }
262 return { text: [formatAll(ledgers), ...backlogNote].join('\n\n') }
263 })
264
265 // The markdown command writes to the ledger, so it must not run unless exactly one ledger is active. The exception is
266 // /ledger:close after the session folder was removed: told there is no ledger, it writes nothing, and its turn's end clears.
267 on('command.run', { command: ['ledger:close', 'ledger:next'] }, async ($, e, next) => {
268 const found = await findLedgers($)
269 if ('error' in found) return { text: lookupFailedMessage(found.error) }
270 const folder = await sessionFolder($)
271 const active = sessionLedger(found, folder)
272 if (active.kind === 'none') {
273 if (folder.removed === undefined) return { text: noLedgerMessage(folder.path) }
274 if (e.command === 'ledger:next') return { text: removedFolderMessage(folder.removed) }
275 await $.state.set(armed, { mode: 'close', slug: basename(folder.removed) })
276 return next({ ...e, args: 'ledger: none' })
277 }
278 if (active.kind === 'several') return { text: severalLedgersMessage(folder.path, active.paths.map(folderSlug)) }
279 const slug = await titleSlug($, active.path)
280 if (e.command === 'ledger:next') {
281 await $.state.set(armed, { mode: 'next', slug, ledger: active.path })
282 return next(e)
283 }
284 await $.state.set(armed, { mode: 'close', slug })
285 // Set here, so only this hook can tell close.md that there is no ledger.
286 return next({ ...e, args: `ledger: ${active.path}` })
287 }).catch(async ($, e, next) => {
288 await $.state.set(armed, null)
289 return next.called ? next(e) : { text: lookupFailedMessage(next.error.message ?? next.error.kind) }
290 })
291
292 // A command.run hook cannot clear the session, and an answer of { text } ends no turn, so go.md runs a
293 // model turn even when there is no ledger to write: its turn.complete is what clears.
294 on('command.run', { command: 'ledger:go' }, async ($, e, next) => {
295 // Should an engine raise both command.run and tool.call for one command, the second one sees this hook's own args.
296 if (isGoArgs(e.args ?? '')) return next(e)
297 const started = await startGo($, e.args ?? '')
298 return 'text' in started ? started : disarmedOnFailure($, started.arm, next({ ...e, args: started.args }))
299 }).catch(async ($, e, next) => (next.called ? next(e) : { text: lookupFailedMessage(next.error.message ?? next.error.kind) }))
300
301 // The model starts /ledger:go through the Skill tool, which raises no command.run: the Skill tool expands go.md itself.
302 on('tool.call', { tool: 'Skill' }, async ($, e, next) => {
303 if (skillName(e.skill) !== 'ledger:go') return next(e)
304 // A subagent's turn end does not clear, so the main session would clear at its own turn's end, mid-task.
305 if (e.agentId !== undefined) return { deny: GO_FROM_SUBAGENT }
306 // No slug has a colon, so even one of the lines this hook writes means the model passed them instead of a slug.
307 if (/^(task|ledger):/.test(e.args ?? '')) return { deny: slugExpectedMessage(e.args ?? '') }
308 const started = await startGo($, e.args ?? '')
309 if ('text' in started) return { deny: started.text }
310 // The permission prompt runs inside next(), after the promotion. A promoted worktree stays: the next /ledger:go finds its ledger there.
311 const ran = await disarmedOnFailure($, started.arm, next({ ...e, args: started.args }))
312 // A person's No at the permission prompt comes back as an error result, not as a deny.
313 if (ran.isError === true) {
314 await disarm($, started.arm)
315 const reason = ran.text ?? ''
316 const text = goDeniedMessage(started.target, started.fields, reason)
317 // The engine shows the model its own rejection text instead, so only the person can learn what was done.
318 if (text !== reason) $.ui.log(text)
319 return { ...ran, text }
320 }
321 if (ran.deny === undefined) return ran
322 await disarm($, started.arm)
323 return { ...ran, deny: goDeniedMessage(started.target, started.fields, ran.deny) }
324 }).catch(async ($, e, next) => (next.called ? next(e) : { deny: lookupFailedMessage(next.error.message ?? next.error.kind) }))
325
326 // The first word names a task only when a ledger has that slug; otherwise it is part of the reason.
327 on('command.run', { command: 'ledger:park' }, async ($, e, next) => {
328 const words = (e.args ?? '').split(/\s+/).filter(word => word !== '')
329 if (words.length === 0) return { text: PARK_USAGE }
330 const found = await findLedgers($)
331 if ('error' in found) return { text: lookupFailedMessage(found.error) }
332 const slugs = await Promise.all(found.map(ledger => titleSlug($, ledger.path)))
333 const [first = '', ...rest] = words
334 const folder = await sessionFolder($)
335 const cwd = folder.path
336 const local = found.filter((_, index) => slugs[index] === first)
337 const elsewhere = await lookUpOtherWorktrees($, first, cwd)
338 const named = uniqueByPath([...local, ...elsewhere.ledgers])
339 if (named.length > 1) return { text: sharedSlugMessage(first, named.map(ledger => ledger.path)) }
340 const [target] = named
341 const reason = (target ? rest : words).join(' ')
342 if (reason === '') return { text: PARK_USAGE }
343 if (!target && elsewhere.worktree) {
344 const { path, slug } = elsewhere.worktree
345 return { text: slug === undefined ? worktreeWithoutLedgerMessage(first, path) : worktreeTaskMessage(first, path, slug) }
346 }
347 const marker = parkMarker(new Date(), reason)
348 const active = sessionLedger(found, folder)
349 if (target && !(active.kind === 'one' && active.path === target.path)) {
350 try {
351 await $.fs.write(target.path, park(await $.fs.read(target.path), marker))
352 } catch (error) {
353 return { text: `Could not park ${first}. ${message(error)}` }
354 }
355 return { text: `Parked ${first}. ${marker}` }
356 }
357 if (active.kind === 'none') return { text: folder.removed === undefined ? noLedgerMessage(cwd) : removedFolderMessage(folder.removed) }
358 if (active.kind === 'several') return { text: severalLedgersMessage(cwd, active.paths.map(folderSlug)) }
359 const slug = await titleSlug($, active.path)
360 await $.state.set(armed, { mode: 'park', slug, ledger: active.path, marker })
361 return next({ ...e, args: parkArgs(slug, active.path, reason) })
362 }).catch(async ($, e, next) => {
363 await $.state.set(armed, null)
364 return next.called ? next(e) : { text: lookupFailedMessage(next.error.message ?? next.error.kind) }
365 })
366
367 // Typed as always a string, but `claude plugin test` leaves it undefined when the caller omits it.
368 on('command.run', { command: 'ledger:worktrees' }, async ($, e) => ({ text: await worktreesCommand($, e.args ?? '') }))
369
370 on('command.run', { command: 'ledger:retire' }, async ($, e) => ({ text: await retireCommand($, e.args ?? '') }))
371
372 on('command.run', { command: 'ledger:archive' }, async ($, e) => ({ text: await archiveCommand($, e.args ?? '') }))
373
374 on('command.run', { command: 'ledger:all' }, async ($, e) => ({ text: await allCommand($, e.args ?? '') }))
375
376 on('command.run', { command: 'ledger:parent' }, async ($, e) => ({ text: await parentCommand($, e.args ?? '') }))
377
378 on('command.run', { command: 'ledger:dashboard' }, async ($, e) => ({ text: await dashboardCommand($, e.args ?? '') }))
379
380 on('command.run', { command: 'ledger:help' }, async () => ({ text: HELP }))
381
382 // $.command.run and $.prompt.submit must not be awaited inside a command.run hook, so the clear waits for the turn's end.
383 on('turn.complete', async ($, e, next) => {
384 if (e.agentId !== undefined) return next(e)
385 const { value } = await $.state.get(armed)
386 if (!value) return next(e)
387 await $.state.set(armed, null)
388 if (e.reason !== 'answer') return next(e)
389 // After the model's turn, so its own edits to the ledger cannot move or drop the marker.
390 if (value.mode === 'park') {
391 try {
392 await $.fs.write(value.ledger, park(await $.fs.read(value.ledger), value.marker))
393 } catch (error) {
394 $.ui.log(`/ledger:park could not mark ${value.slug} parked: ${message(error)}. The session was not cleared.`)
395 return next(e)
396 }
397 }
398 const go = `go ${value.slug}`
399 const continues = value.mode === 'next' || value.mode === 'go' ? value : null
400 try {
401 await $.command.run({ command: 'clear' })
402 } catch (error) {
403 const then = continues ? `, then say: ${go}` : ''
404 $.ui.log(`/ledger:${value.mode} could not clear the session: ${message(error)}. Run /clear${then}.`)
405 return next(e)
406 }
407 if (continues) {
408 if (continues.ledger) await showRetireHint($, continues.ledger)
409 try {
410 await $.prompt.submit({ text: go })
411 } catch (error) {
412 $.ui.log(`/ledger:${value.mode} cleared the session but could not send "${go}": ${message(error)}. Say: ${go}.`)
413 }
414 }
415 return next(e)
416 })
417}
418hooks/all-command.ts 111 lines1import type { EngineInterface, ProcessRunResult } from 'claude-code'
2
3import { childOrder, formatTime, groupByParent, summarize, type Grouped } from './ledger'
4import { message, sessionFolder } from './lookup'
5import { type Entry, parseEntries, scriptPath } from './registry'
6
7const USAGE = 'Usage: /ledger:all [--scan]'
8const EMPTY = 'No ledgers registered. Run /ledger:all --scan to rebuild from disk.'
9const NEXT_WIDTH = 80
10
11const cell = (text: string): string => text.replaceAll('|', '\\|')
12
13const truncate = (text: string): string => (text.length > NEXT_WIDTH ? `${text.slice(0, NEXT_WIDTH - 1)}…` : text)
14
15export async function statusAndNext($: EngineInterface, entry: Entry): Promise<[string, string]> {
16 try {
17 const { next, parked } = summarize(await $.fs.read(entry.archivePath ?? entry.path), '', 0)
18 return [parked && entry.status === 'active' ? 'parked' : entry.status, next]
19 } catch {
20 return [entry.status, '(unreadable)']
21 }
22}
23
24const taskKey = (repo: string, slug: string): string => `${repo}\0${slug}`
25
26// A table cell drops leading spaces, but keeps no-break spaces.
27const INDENT = ' '
28
29type Task = { entry: Entry; status: string }
30
31function familyOrder<T extends Task>(newestFirst: T[]): (T & { name: string })[] {
32 const groups = groupByParent(
33 newestFirst,
34 ({ entry }) => taskKey(entry.repo, entry.slug),
35 ({ entry }) => (entry.parent === undefined ? undefined : taskKey(entry.repo, entry.parent)),
36 childOrder(({ status }) => status === 'active', ({ entry }) => Date.parse(entry.updated)),
37 )
38 const descendants = (children: Grouped<T>[], depth: number): (T & { name: string })[] =>
39 children.flatMap(({ item, children: grandchildren }) => [
40 { ...item, name: `${INDENT.repeat(depth)}↳ ${item.entry.slug}` },
41 ...descendants(grandchildren, depth + 1),
42 ])
43 return groups.flatMap(({ item, children }) => [
44 { ...item, name: item.entry.parent ? `${item.entry.slug} (parent: ${item.entry.parent})` : item.entry.slug },
45 ...descendants(children, 0),
46 ])
47}
48
49async function goalOf($: EngineInterface, entry: Entry): Promise<string> {
50 try {
51 return summarize(await $.fs.read(entry.path), '', 0).goal
52 } catch {
53 return '(unreadable)'
54 }
55}
56
57const newestFirst = (entries: Entry[]): Entry[] => [...entries].sort((a, b) => Date.parse(b.updated) - Date.parse(a.updated))
58
59const table = (header: string[], rows: string[][]): string[] =>
60 [header, header.map(() => '---'), ...rows].map(row => `| ${row.join(' | ')} |`)
61
62async function tables($: EngineInterface, entries: Entry[]): Promise<string> {
63 const backlog = newestFirst(entries.filter(entry => entry.status === 'backlog')).map(entry => ({ entry, status: entry.status }))
64 const [tasks, backlogRows] = await Promise.all([
65 Promise.all(
66 newestFirst(entries.filter(entry => entry.status !== 'backlog')).map(async entry => {
67 const [status, next] = await statusAndNext($, entry)
68 return { entry, status, next }
69 }),
70 ),
71 Promise.all(
72 familyOrder(backlog).map(async ({ entry, name }) =>
73 [entry.repo, name, formatTime(Date.parse(entry.updated)), truncate(await goalOf($, entry))].map(cell),
74 ),
75 ),
76 ])
77 const taskRows = familyOrder(tasks).map(({ entry, name, status, next }) =>
78 [entry.repo, name, status, formatTime(Date.parse(entry.updated)), truncate(next)].map(cell),
79 )
80 const active = taskRows.filter(row => row[2] === 'active').length
81 const counts = [`${entries.length} ${entries.length === 1 ? 'task' : 'tasks'}`, `${active} active`]
82 if (backlog.length > 0) counts.push(`${backlog.length} backlog`)
83 // Claude Code puts "ledger: " in front of the first output line; a table on that line does not render.
84 const sections = [[`**All task ledgers** · ${counts.join(', ')}`]]
85 if (taskRows.length > 0) sections.push(table(['repo', 'slug', 'status', 'updated', 'next'], taskRows))
86 if (backlogRows.length > 0) sections.push(['**Backlog**'], table(['repo', 'slug', 'updated', 'goal'], backlogRows))
87 return sections.map(lines => lines.join('\n')).join('\n\n')
88}
89
90export async function allCommand($: EngineInterface, args: string): Promise<string> {
91 const words = args.split(/\s+/).filter(word => word !== '')
92 const unknown = words.find(word => word !== '--scan')
93 if (unknown !== undefined) return `Unknown argument: ${unknown}. ${USAGE}`
94 const scan = words.includes('--scan')
95
96 const script = scriptPath($, 'cc-ledgers')
97 let result: ProcessRunResult
98 try {
99 result = await $.process.run([script, scan ? 'scan' : 'list', '--json'], { cwd: (await sessionFolder($)).path })
100 } catch (error) {
101 return `cc-ledgers did not run: ${message(error)}`
102 }
103 if (result.exitCode !== 0) return `cc-ledgers failed (exit ${result.exitCode}): ${result.stderr.trim().replace(/\s*\n\s*/g, ' ')}`
104 const entries = parseEntries(result.stdout)
105 if (entries === null) return 'cc-ledgers printed something that is not a list of ledgers.'
106
107 const body = entries.length === 0 ? EMPTY : await tables($, entries)
108 const rebuilt = scan ? result.stderr.split('\n').find(line => line.startsWith('rebuilt ')) : undefined
109 return rebuilt === undefined ? body : `${rebuilt}\n\n${body}`
110}
111hooks/ledger.ts 424 lines1export type Row = { number: string; step: string; status: string }
2
3export type Parked = { date: string; reason: string }
4
5/** A line of a parent's Children section, as bin/cc-ledger-parent writes it. */
6export type ChildLine = { slug: string; retired?: string; started?: string }
7
8export type LedgerSummary = {
9 slug: string
10 editedMs: number
11 goal: string
12 current: Row | 'all done' | null
13 next: string
14 parked?: Parked
15 parent?: string
16 children?: ChildLine[]
17 /** A ledger in ~/.claude/ledger-backlog/, shown because it is a parent of a listed task. */
18 isBacklog?: true
19}
20
21const FINISHED = /^(done|accepted|reviewed|dropped|skipped)\b/i
22
23// Location and Children are matched exactly, as bin/cc-ledger-parent does; other headings carry a suffix such as "(approved …)".
24function section(text: string, heading: string, exact = false): string[] {
25 const lines = text.split('\n')
26 const start = lines.findIndex(line => (exact ? line.trimEnd() === `## ${heading}` : line.startsWith(`## ${heading}`)))
27 if (start === -1) return []
28 const rest = lines.slice(start + 1)
29 const end = rest.findIndex(line => line.startsWith('## '))
30 return end === -1 ? rest : rest.slice(0, end)
31}
32
33function firstLine(lines: string[]): string {
34 return lines.map(line => line.trim()).find(line => line !== '') ?? ''
35}
36
37function currentStep(planLines: string[]): Row | 'all done' | null {
38 const rows: Row[] = planLines
39 .filter(line => line.trim().startsWith('|'))
40 .map(line => line.split('|').slice(1, -1).map(cell => cell.trim()))
41 .map(([number = '', step = '', status = '']) => ({ number, step, status }))
42 .filter(row => /^\d+$/.test(row.number))
43 if (rows.length === 0) return null
44 return rows.find(row => !FINISHED.test(row.status)) ?? 'all done'
45}
46
47const NEXT_STEP = '## Next step'
48const PARKED = /^Parked:[ \t]*(\d{4}-\d{2}-\d{2})[ \t]*[—-][ \t]*(.*)$/
49
50function parkedOf(line: string): Parked | null {
51 const match = PARKED.exec(line.trim())
52 return match ? { date: match[1] ?? '', reason: match[2]?.trim() ?? '' } : null
53}
54
55function parentOf(text: string): string | undefined {
56 return section(text, 'Location', true)
57 .map(line => line.trimEnd().match(/^- parent:[ \t]*(\S+)$/)?.[1])
58 .find(value => value !== undefined && !value.startsWith('<'))
59}
60
61const CHILD = /^- ([A-Za-z0-9._-]+)(?: \((retired|started) (\d{4}-\d\d-\d\d)\))?$/
62
63function childrenOf(text: string): ChildLine[] {
64 return section(text, 'Children', true).flatMap(line => {
65 const [, slug, mark, date = ''] = line.trim().match(CHILD) ?? []
66 if (!slug) return []
67 return [{ slug, ...(mark === 'retired' && { retired: date }), ...(mark === 'started' && { started: date }) }]
68 })
69}
70
71export function summarize(text: string, fallbackSlug: string, editedMs: number): LedgerSummary {
72 const title = text.match(/^# Task ledger[ \t]*[—-][ \t]*(.*)$/m)
73 const nextStep = section(text, 'Next step')
74 const parked = parkedOf(firstLine(nextStep))
75 const parent = parentOf(text)
76 const children = childrenOf(text)
77 return {
78 slug: title?.[1]?.trim() || fallbackSlug,
79 editedMs,
80 goal: firstLine(section(text, 'Goal')),
81 current: currentStep(section(text, 'Plan')),
82 next: firstLine(nextStep.filter(line => parkedOf(line) === null)),
83 ...(parked && { parked }),
84 ...(parent && { parent }),
85 ...(children.length > 0 && { children }),
86 }
87}
88
89export type Grouped<T> = { item: T; children: Grouped<T>[] }
90
91/**
92 * Puts each item under the first listed item its parent key names, at any depth. The top level keeps the order of `items`,
93 * and so do the children of each item, unless `compareChildren` sorts them.
94 * An item whose parent is not listed stays at the top, and so does each item of a cycle, with its other children under it.
95 */
96export function groupByParent<T>(
97 items: T[],
98 key: (item: T) => string,
99 parentKey: (item: T) => string | undefined,
100 compareChildren: (a: T, b: T) => number = () => 0,
101): Grouped<T>[] {
102 const first = new Map<string, T>()
103 for (const item of items) if (!first.has(key(item))) first.set(key(item), item)
104 const listedParent = (item: T) => {
105 const parent = parentKey(item)
106 return parent !== undefined && parent !== key(item) && first.has(parent) ? parent : undefined
107 }
108 const isInCycle = (item: T) => {
109 const seen = new Set<string>()
110 for (let parent = listedParent(item); parent !== undefined && !seen.has(parent); ) {
111 if (parent === key(item)) return true
112 seen.add(parent)
113 const next = first.get(parent)
114 parent = next && listedParent(next)
115 }
116 return false
117 }
118 const isTop = (item: T) => listedParent(item) === undefined || isInCycle(item)
119 const group = (item: T): Grouped<T> => ({
120 item,
121 children: first.get(key(item)) === item ? items.filter(child => !isTop(child) && listedParent(child) === key(item)).sort(compareChildren).map(group) : [],
122 })
123 return items.filter(isTop).map(group)
124}
125
126/** The order of a parent's child tasks: the active ones first, then the others, each newest first. */
127export const childOrder =
128 <T>(isActive: (item: T) => boolean, time: (item: T) => number) =>
129 (a: T, b: T): number =>
130 Number(isActive(b)) - Number(isActive(a)) || time(b) - time(a)
131
132export const isoDate = (date: Date): string =>
133 [date.getFullYear(), date.getMonth() + 1, date.getDate()].map(part => String(part).padStart(2, '0')).join('-')
134
135export function parkMarker(today: Date, reason: string): string {
136 return `Parked: ${isoDate(today)} — ${reason.trim().split(/\s+/).join(' ')}`
137}
138
139/** Removes every parked marker under Next step, and reports the first. */
140export function unpark(text: string): { text: string; parked: Parked | null } {
141 const lines = text.split('\n')
142 const start = lines.findIndex(line => line.startsWith(NEXT_STEP))
143 if (start === -1) return { text, parked: null }
144 const rest = lines.slice(start + 1)
145 const end = rest.findIndex(line => line.startsWith('## '))
146 const body = end === -1 ? rest : rest.slice(0, end)
147 const parked = body.map(parkedOf).find(marker => marker !== null) ?? null
148 if (parked === null) return { text, parked }
149 const kept = body.filter(line => parkedOf(line) === null)
150 return { text: [...lines.slice(0, start + 1), ...kept, ...(end === -1 ? [] : rest.slice(end))].join('\n'), parked }
151}
152
153/** Puts the marker first under Next step, replacing any earlier marker, and adds the section when there is none. */
154export function park(text: string, marker: string): string {
155 const unparked = unpark(text).text
156 const lines = unparked.split('\n')
157 const start = lines.findIndex(line => line.startsWith(NEXT_STEP))
158 if (start === -1) return `${unparked.replace(/\n*$/, '')}\n\n${NEXT_STEP}\n${marker}\n`
159 return [...lines.slice(0, start + 1), marker, ...lines.slice(start + 1)].join('\n')
160}
161
162export const PARK_USAGE =
163 'Usage: /ledger:park [<slug>] <reason>. Without a slug it writes this task\'s ledger, parks it and clears the session. Run /ledger to see each slug.'
164
165export function formatTime(ms: number): string {
166 const date = new Date(ms)
167 const two = (value: number) => String(value).padStart(2, '0')
168 return `${date.getFullYear()}-${two(date.getMonth() + 1)}-${two(date.getDate())} ${two(date.getHours())}:${two(date.getMinutes())}`
169}
170
171function formatStep({ current, parked }: LedgerSummary): string {
172 if (parked) return `**Parked:** ${parked.date} — ${parked.reason}`
173 if (current === null) return ''
174 if (current === 'all done') return '**Now:** all plan steps done'
175 return `**Now:** step ${current.number} · ${current.step} — *${current.status}*`
176}
177
178function fields(ledger: LedgerSummary): string[] {
179 return [ledger.goal && `**Goal:** ${ledger.goal}`, formatStep(ledger), ledger.next && `**Next:** ${ledger.next}`].filter(field => field !== '')
180}
181
182const title = (ledger: LedgerSummary): string => (ledger.isBacklog ? `${ledger.slug} (backlog)` : ledger.slug)
183
184function childLines(children: Grouped<LedgerSummary>[], indent: string): string[] {
185 if (children.length === 0) return []
186 return [
187 `${indent}- **Children:**`,
188 ...children.flatMap(({ item, children: grandchildren }) => [
189 `${indent} - **${title(item)}** · edited ${formatTime(item.editedMs)}`,
190 ...fields(item).map(field => `${indent} - ${field}`),
191 ...childLines(grandchildren, `${indent} `),
192 ]),
193 ]
194}
195
196export function format(ledger: LedgerSummary, children: Grouped<LedgerSummary>[] = []): string {
197 return [
198 `#### ${title(ledger)} · edited ${formatTime(ledger.editedMs)}`,
199 ...fields(ledger).map(field => `- ${field}`),
200 ...(ledger.parent ? [`- **Parent:** ${ledger.parent}`] : []),
201 ...childLines(children, ''),
202 ].join('\n')
203}
204
205export function formatAll(ledgers: LedgerSummary[]): string {
206 const groups = groupByParent(
207 ledgers,
208 ledger => ledger.slug,
209 ledger => ledger.parent,
210 childOrder(ledger => !ledger.isBacklog && !ledger.parked, ledger => ledger.editedMs),
211 )
212 const order = groups.some(({ children }) => children.length > 0) ? 'newest first, children under their parent' : 'newest first'
213 const count = ledgers.length === 1 ? '1 ledger' : `${ledgers.length} ledgers, ${order}`
214 return [`**Task ledgers** · ${count}`, ...groups.map(({ item, children }) => format(item, children))].join('\n\n')
215}
216
217export function ledgerPaths(stdout: string): string[] {
218 return stdout
219 .split('\n')
220 .map(line => line.trim())
221 .filter(line => line !== '')
222}
223
224export function folderSlug(ledgerPath: string): string {
225 return ledgerPath.split('/').at(-3) ?? ''
226}
227
228export type ActiveLedger = { kind: 'none' } | { kind: 'one'; path: string } | { kind: 'several'; paths: string[] }
229
230const LEDGER_SUFFIX = '/.claude/ledger.md'
231
232export function activeLedger(paths: string[], cwd: string): ActiveLedger {
233 const matches = paths.filter(path => {
234 const root = path.slice(0, -LEDGER_SUFFIX.length)
235 return path.endsWith(LEDGER_SUFFIX) && (cwd === root || cwd.startsWith(`${root}/`))
236 })
237 const [only] = matches
238 if (only === undefined) return { kind: 'none' }
239 return matches.length === 1 ? { kind: 'one', path: only } : { kind: 'several', paths: matches }
240}
241
242const UNCHANGED = 'Nothing was written, and the session was not cleared.'
243
244export function noLedgerMessage(cwd: string): string {
245 return `No task ledger found for ${cwd}. ${UNCHANGED} Run this command from the task's worktree, or start a task with /ledger:task.`
246}
247
248export function severalLedgersMessage(cwd: string, slugs: string[], outcome = UNCHANGED): string {
249 return `Several task ledgers hold ${cwd}: ${slugs.join(', ')}. ${outcome} Run this command from a task worktree that is not inside another one.`
250}
251
252export function removedFolderMessage(folder: string): string {
253 return `The session folder ${folder} no longer exists, so this session has no task ledger. ${UNCHANGED} Continue another task with /ledger:go <slug>, or run /ledger:close.`
254}
255
256export function lookupFailedMessage(error: string): string {
257 return `Could not check this task's ledger. ${error} ${UNCHANGED}`
258}
259
260/** A child task as `cc-ledger-parent show --json` reports it. */
261export type ChildStatus = { slug: string; status: string; next: string }
262
263export type Family = { parent?: string; children?: ChildStatus[] }
264
265const statusList = (children: ChildStatus[]): string => children.map(({ slug, status }) => `${slug} (${status})`).join(', ')
266
267export type GoFields = {
268 parked?: Parked | null
269 family?: Family
270 promotedWorktree?: string
271 /** The slugs from the parent task the operator named down to the child task /ledger:go picked. */
272 picked?: string[]
273 /** The ledger in which /ledger:go marked the task started. */
274 marked?: string
275 warnings?: string[]
276}
277
278// One field per line, because a slug and a path can both hold spaces. go.md reads this format.
279export function goArgs(
280 target: string,
281 ledgerPath: string | undefined,
282 { parked, family = {}, promotedWorktree, picked, marked, warnings = [] }: GoFields = {},
283): string {
284 const fields = [`task: ${target}`, `ledger: ${ledgerPath ?? 'none'}`]
285 if (parked) fields.push(`parked: ${parked.date} — ${parked.reason}`)
286 if (family.parent) fields.push(`parent: ${family.parent}`)
287 if (family.children?.length) fields.push(`children: ${statusList(family.children)}`)
288 if (promotedWorktree) fields.push(`promoted: ${promotedWorktree}`)
289 if (picked) fields.push(`picked: ${picked.join(' > ')}`)
290 if (marked) fields.push(`marked: ${marked}`)
291 for (const warning of warnings) fields.push(`warning: ${warning}`)
292 return fields.join('\n')
293}
294
295export const isGoArgs = (args: string): boolean => /^task: [^\n]*\nledger: /.test(args)
296
297export const worktreeWithoutLedgerMessage = (word: string, worktree: string): string =>
298 `${word} names the worktree ${worktree}, which has no task ledger. ${UNCHANGED} To give it one, type /ledger:task --here in a session there.`
299
300export const worktreeTaskMessage = (word: string, worktree: string, slug: string): string =>
301 `${word} names the worktree ${worktree}, task ${slug}. ${UNCHANGED} Type /ledger:park ${slug} <reason>.`
302
303export function parkArgs(slug: string, ledgerPath: string, reason: string): string {
304 return [`task: ${slug}`, `ledger: ${ledgerPath}`, `reason: ${reason}`].join('\n')
305}
306
307export const GO_USAGE = 'Usage: /ledger:go <slug>. Run /ledger to see the slug of each task.'
308
309export const GO_FROM_SUBAGENT = `Only the main session can switch tasks with /ledger:go. ${UNCHANGED}`
310
311export function slugExpectedMessage(args: string): string {
312 const slug = /^task: (.*)/.exec(args)?.[1] ?? '<slug>'
313 return `/ledger:go takes a task slug, such as ${slug}, not the task: and ledger: lines it writes itself. ${UNCHANGED}`
314}
315
316const armedTurn = {
317 go: (slug: string) => `switches to task ${slug}`,
318 next: (slug: string) => `ends with /ledger:next, which clears the session and continues task ${slug}`,
319 close: () => 'ends with /ledger:close, which clears the session',
320 park: (slug: string) => `parks task ${slug} and clears the session`,
321}
322
323export function oneSwitchPerTurnMessage(armed: { mode: keyof typeof armedTurn; slug: string }, target: string): string {
324 return `This turn already ${armedTurn[armed.mode](armed.slug)}, so /ledger:go ${target} was not started and nothing was written. A turn switches tasks only once: run /ledger:go ${target} after the session clears.`
325}
326
327/** What /ledger:go did before the Skill call was denied, or the denial alone when it did nothing. */
328export function goDeniedMessage(target: string, { promotedWorktree, parked, marked }: GoFields, denial: string): string {
329 const done = [
330 ...(promotedWorktree ? [`Promoted backlog task ${target}: its branch, worktree and ledger are at ${promotedWorktree}.`] : []),
331 ...(parked ? [`Removed the parked marker from ${target}.`] : []),
332 ...(marked ? [`Marked ${target} started in ${marked}.`] : []),
333 ]
334 if (done.length === 0) return denial
335 return `${done.join(' ')} Then the Skill call was denied: ${sentence(denial)} The session was not cleared.`
336}
337
338export type TaskName = { slug: string; parent?: string }
339
340function taskList(tasks: TaskName[]): string {
341 const groups = groupByParent(tasks, task => task.slug, task => task.parent)
342 const nested = ({ item, children }: Grouped<TaskName>): string =>
343 children.length > 0 ? `${item.slug} (children: ${children.map(nested).join(', ')})` : item.slug
344 const name = (group: Grouped<TaskName>) => (group.children.length === 0 && group.item.parent ? `${group.item.slug} (parent: ${group.item.parent})` : nested(group))
345 return groups.map(name).join(', ')
346}
347
348export function unknownTaskMessage(target: string, tasks: TaskName[], outcome = UNCHANGED): string {
349 return `No task ledger is named "${target}". ${outcome} Task ledgers: ${taskList(tasks) || 'none'}.`
350}
351
352// Script errors have no final period.
353const sentence = (text: string): string => text.replace(/[.\s]*$/, '.')
354
355export function promoteFailedMessage(target: string, error: string): string {
356 return `Could not start backlog task ${target}. ${sentence(error)} ${UNCHANGED}`
357}
358
359export function promotedThenFailedMessage(target: string, worktree: string, error: string): string {
360 return `Promoted backlog task ${target}: its branch, worktree and ledger are at ${worktree}. Then this failed: ${sentence(error)} The session was not cleared.`
361}
362
363export function noChildToStartMessage(target: string, children: ChildStatus[] | { error: string }): string {
364 const listed = 'error' in children ? `Its child tasks could not be listed: ${sentence(children.error)}` : `Child tasks: ${statusList(children)}.`
365 return `Backlog task ${target} has no child task left to start. ${listed} ${UNCHANGED} A parent task in the backlog stays there: continue in a child task with /ledger:go <child>, or add one with /ledger:parent ${target} add <child>.`
366}
367
368export function pickFailedMessage(target: string, error: string): string {
369 return `Could not pick a child task of backlog task ${target} to start: ${sentence(error)} ${UNCHANGED}`
370}
371
372export const pickFailedWarning = (target: string, error: string): string =>
373 `Could not pick a child task of ${target} to start, so this continues in ${target}: ${sentence(error)}`
374
375export const markFailedWarning = (child: string, parent: string, error: string): string =>
376 `Could not mark ${child} started in its parent ${parent}: ${sentence(error)}`
377
378export function otherRepositoryMessage(target: string, repo: string, main: string): string {
379 return `Backlog task ${target} belongs to the ${repo} repository, with its main checkout at ${main}. ${UNCHANGED} Run /ledger:go ${target} from a session in that repository.`
380}
381
382export function backlogUncheckedMessage(target: string, tasks: TaskName[], error: string, outcome = UNCHANGED): string {
383 return `${unknownTaskMessage(target, tasks, outcome)} The backlog could not be checked: ${sentence(error)}`
384}
385
386export function unparkFailedMessage(target: string, error: string): string {
387 return `Could not remove the parked marker from ${target}. ${error} ${UNCHANGED}`
388}
389
390export function sharedSlugMessage(target: string, paths: string[], outcome = UNCHANGED): string {
391 return `Several task ledgers are named "${target}": ${paths.join(', ')}. ${outcome} Give each task its own slug in its ledger's title.`
392}
393
394/** A task branch: commits ahead of origin's default branch, and every PR from it as `gh pr list --state all` lists them. */
395export type BranchState = { ahead: number; prs: { state: string; number: number }[] }
396
397/** The line shown after a finished task's session clears. `null` means git or gh could not tell whether the branch is merged. */
398export function retireHint(slug: string, branch: BranchState | null): string {
399 const finished = `Task ${slug} is finished`
400 if (branch && (branch.ahead === 0 || branch.prs.some(pr => pr.state === 'MERGED'))) {
401 return `${finished} and merged. Retire it with \`/ledger:retire ${slug}\`.`
402 }
403 const open = branch?.prs.find(pr => pr.state === 'OPEN')
404 if (open) return `${finished}. After PR #${open.number} merges, run \`/ledger:retire ${slug}\`.`
405 return `${finished}. Run \`/ledger:retire ${slug} --dry-run\` to see what blocks retiring it.`
406}
407
408export const HELP = [
409 "- `/ledger` — Show each task ledger's goal, current step and next step. A parent task in this repo's backlog is shown too, marked (backlog). `/ledger <name>` shows one.",
410 '- `/ledger:task` — Add a separate task to the backlog: a ledger only, with no branch or worktree yet. `/ledger:go <slug>` starts it. With no current ledger, it starts the task at once and continues in this session. `--here` adds a ledger to this worktree instead.',
411 "- `/ledger:update` — Write the latest results to this task's ledger. Without one, it points to `/ledger:task`.",
412 "- `/ledger:next` — Write this task's ledger, clear the session, and continue from the next step. When every step is done, it first says how to retire the task.",
413 "- `/ledger:close` — Write this task's ledger, then clear the session.",
414 "- `/ledger:go <slug>` — Write this task's ledger, clear the session, and continue in the task named <slug>. A backlog task first gets its branch and worktree, which works only from a session in its repository. A child task is marked started in its parent ledger. A parent task starts its first child task not yet started instead; a parent task in the backlog with none left stays there. When every step of this task is done, it first says how to retire it.",
415 "- `/ledger:park [<slug>] <reason>` — Mark a task parked. Without a slug it writes this task's ledger, parks it, then clears the session.",
416 "- `/ledger:parent [<slug>]` — Show a parent task and each child's status and next step; without a slug, this task or its parent. `<slug> add <child>` and `<slug> remove <child>` change its children.",
417 "- `/ledger:worktrees` — Show each linked git worktree's size, last commit, dirty files, ledger and PR.",
418 "- `/ledger:retire [<slug>]` — Archive a task's ledger, remove its worktree, and delete its branch when all of its commits are merged. A backlog task of this repo has no worktree or branch: its ledger is archived, then deleted. `--dry-run` only shows what it would do. Uncommitted changes, unmerged work and active child tasks need `--force`.",
419 "- `/ledger:archive [<term>]` — List this repo's archived ledgers, newest first; a term keeps those that contain it, and `--all` lists every repo.",
420 '- `/ledger:all` — Show every task ledger on this machine, active, backlog and archived; `--scan` rebuilds the list from disk.',
421 '- `/ledger:dashboard` — Start a web page on this machine that lists every task ledger, with search, details, park and retire. It keeps running after the session ends; `stop` stops it.',
422 '- `/ledger:help` — Show this list.',
423].join('\n')
424hooks/archive-command.ts 94 lines1import type { EngineInterface, ProcessRunResult } from 'claude-code'
2
3import {
4 ARCHIVE_USAGE,
5 emptyArchiveMessage,
6 firstMatch,
7 formatArchive,
8 listFailedMessage,
9 newestFirst,
10 parseArchiveArgs,
11 readArchived,
12 type ArchivedLedger,
13} from './archive'
14import { message, sessionFolder } from './lookup'
15import { basename } from './worktrees'
16
17type Entry = { name: string; kind: string }
18
19type Listing = Entry[] | { error: string }
20
21// A folder that does not exist yet is an empty archive, not an error.
22async function list($: EngineInterface, folder: string, repo: string | null): Promise<Listing> {
23 try {
24 return await $.fs.list(folder)
25 } catch (error) {
26 const exists = await $.fs.exists(folder).catch(() => true)
27 return exists ? { error: listFailedMessage(repo, message(error)) } : []
28 }
29}
30
31const GIT_COMMON_DIR = ['git', 'rev-parse', '--path-format=absolute', '--git-common-dir']
32
33/** Named the way cc-worktree-retire names the archive folder: after the main checkout. */
34async function repoName($: EngineInterface, cwd: string): Promise<{ name: string } | { error: string }> {
35 let failure: string
36 try {
37 const { exitCode, stdout, stderr }: ProcessRunResult = await $.process.run(GIT_COMMON_DIR, { cwd })
38 if (exitCode === 0) return { name: basename(stdout.trim().split('/').slice(0, -1).join('/')) }
39 failure = `failed (exit ${exitCode}): ${stderr.trim()}`
40 } catch (error) {
41 failure = `did not run: ${message(error)}`
42 }
43 return { error: `Could not tell which repo ${cwd} is in. ${GIT_COMMON_DIR.join(' ')} ${failure}. Add --all to list the archive of every repo.` }
44}
45
46async function readFolder($: EngineInterface, root: string, repo: string, term: string): Promise<ArchivedLedger[] | { error: string }> {
47 const folder = `${root}/${repo}`
48 const entries = await list($, folder, repo)
49 if ('error' in entries) return entries
50 const names = entries.filter(({ name, kind }) => kind === 'file' && name.endsWith('.md')).map(({ name }) => name)
51 const ledgers = await Promise.all(
52 names.map(async name => {
53 const path = `${folder}/${name}`
54 const [text, { mtimeMs }] = await Promise.all([$.fs.read(path), $.fs.stat(path)])
55 const ledger = readArchived(repo, name, text, mtimeMs)
56 if (term === '') return ledger
57 const match = firstMatch(text, term)
58 return match === undefined ? null : { ...ledger, match }
59 }),
60 )
61 return ledgers.filter(ledger => ledger !== null)
62}
63
64/** The text /ledger:archive answers with. It only reads. */
65export async function archiveCommand($: EngineInterface, args: string): Promise<string> {
66 const command = parseArchiveArgs(args)
67 if (command.kind === 'usage') return ARCHIVE_USAGE
68 const home = await $.env.get('HOME')
69 if (!home?.startsWith('/')) return 'Could not find the ledger archive: HOME is not set.'
70 const root = `${home}/.claude/ledger-archive`
71
72 let repo: string | null = null
73 let repos: string[]
74 if (command.all) {
75 const entries = await list($, root, null)
76 if ('error' in entries) return entries.error
77 repos = entries.filter(({ kind }) => kind === 'dir').map(({ name }) => name)
78 } else {
79 const found = await repoName($, (await sessionFolder($)).path)
80 if ('error' in found) return found.error
81 repo = found.name
82 repos = [repo]
83 }
84
85 const folders = await Promise.all(repos.map(name => readFolder($, root, name, command.term)))
86 const ledgers: ArchivedLedger[] = []
87 for (const folder of folders) {
88 if ('error' in folder) return folder.error
89 ledgers.push(...folder)
90 }
91 if (ledgers.length === 0) return emptyArchiveMessage(repo, command.term)
92 return formatArchive(ledgers.sort(newestFirst), repo, command.term)
93}
94hooks/dashboard-command.ts 15 lines1import type { EngineInterface } from 'claude-code'
2
3import { run } from './lookup'
4
5export const DASHBOARD_USAGE = 'Usage: /ledger:dashboard [stop]. Without stop it starts the dashboard, or shows the address of the one that runs.'
6
7/** The text /ledger:dashboard answers with: the launcher's own output, which holds the page's address. */
8export async function dashboardCommand($: EngineInterface, args: string): Promise<string> {
9 const words = args.split(/\s+/).filter(word => word !== '')
10 if (words.length > 1 || words.some(word => word !== 'stop')) return DASHBOARD_USAGE
11 const script = `${$.plugin.root}/../../bin/cc-ledger-dashboard`
12 const { stdout, failure } = await run($, [script, ...words], $.plugin.root)
13 return failure === undefined ? stdout.trim() : `cc-ledger-dashboard ${failure}`
14}
15hooks/lookup.ts 204 lines1import type { EngineInterface, ProcessRunResult } from 'claude-code'
2
3import { activeLedger, folderSlug, ledgerPaths, summarize, type ActiveLedger, type BranchState, type LedgerSummary } from './ledger'
4import { defaultBranchOf, dirname, isInside, parseCount, stateFailedMessage } from './retire'
5import { basename, parseWorktrees, type Worktree } from './worktrees'
6import { lookUpPrs } from './worktrees-command'
7
8export type Found = { path: string; slug: string; mtimeMs: number }
9
10export const message = (error: unknown) => (error instanceof Error ? error.message : String(error))
11
12export type Ran = { stdout: string; stderr: string; failure?: string; exitCode?: number }
13
14export async function run($: EngineInterface, argv: string[], cwd: string): Promise<Ran> {
15 try {
16 const { exitCode, stdout, stderr } = await $.process.run(argv, { cwd })
17 return exitCode === 0 ? { stdout, stderr } : { stdout, stderr, exitCode, failure: `failed (exit ${exitCode}): ${stderr.trim()}` }
18 } catch (error) {
19 return { stdout: '', stderr: '', failure: `did not run: ${message(error)}` }
20 }
21}
22
23/**
24 * The folder to run commands in. `removed` is the session's own folder when it no longer exists, as after /ledger:retire
25 * from inside the worktree; `path` is then the nearest folder above it that does.
26 */
27export type SessionFolder = { path: string; removed?: string }
28
29async function exists($: EngineInterface, path: string): Promise<boolean> {
30 return $.fs.stat(path).then(() => true, () => false)
31}
32
33export async function sessionFolder($: EngineInterface): Promise<SessionFolder> {
34 const cwd = await $.session.cwd()
35 if (await exists($, cwd)) return { path: cwd }
36 for (let folder = cwd; folder !== '/'; ) {
37 folder = dirname(folder) || '/'
38 if (await exists($, folder)) return { path: folder, removed: cwd }
39 }
40 // Not even / is there, so fs.stat itself is failing, which says nothing about the session folder.
41 return { path: cwd }
42}
43
44/** The ledger of the session's own task. A removed session folder has none: a ledger above it belongs to another task. */
45export const sessionLedger = (found: Found[], folder: SessionFolder): ActiveLedger =>
46 folder.removed === undefined ? activeLedger(found.map(({ path }) => path), folder.path) : { kind: 'none' }
47
48async function listLedgers($: EngineInterface, mode: 'paths' | 'backlog', slugOf: (path: string) => string): Promise<Found[] | { error: string }> {
49 const script = `${$.plugin.root}/../../hooks/ledger-list.sh`
50 const { path: cwd } = await sessionFolder($)
51 let result: ProcessRunResult
52 try {
53 result = await $.process.run(['bash', script, mode], { cwd })
54 } catch (error) {
55 return { error: `${script} did not run: ${message(error)}` }
56 }
57 const { exitCode, stdout, stderr } = result
58 if (exitCode !== 0) return { error: `${script} failed (exit ${exitCode}): ${stderr.trim()}` }
59 const found = await Promise.all(ledgerPaths(stdout).map(async path => ({ path, slug: slugOf(path), mtimeMs: (await $.fs.stat(path)).mtimeMs })))
60 return found.sort((a, b) => b.mtimeMs - a.mtimeMs)
61}
62
63// The SessionStart hook's own lookup, so /ledger and the hook always agree on which ledgers exist.
64export function findLedgers($: EngineInterface): Promise<Found[] | { error: string }> {
65 return listLedgers($, 'paths', folderSlug)
66}
67
68/** The backlog ledgers of the repository the session is in, matched on its main checkout as cc-task-new and cc-ledger-parent do. */
69export function findBacklogLedgers($: EngineInterface): Promise<Found[] | { error: string }> {
70 return listLedgers($, 'backlog', path => basename(path).replace(/\.md$/, ''))
71}
72
73function summarizeAll($: EngineInterface, found: Found[]): Promise<LedgerSummary[]> {
74 return Promise.all(found.map(async ({ path, slug, mtimeMs }) => summarize(await $.fs.read(path), slug, mtimeMs)))
75}
76
77async function otherWorktreeLedgers($: EngineInterface): Promise<Map<string, LedgerSummary>> {
78 const { path: cwd } = await sessionFolder($)
79 const found = await Promise.all((await otherWorktrees($, cwd)).map(({ path }) => ledgerIn($, path)))
80 // Another session can remove a worktree between the stat and the read; its ledger is then skipped, not an error.
81 const summaries = await Promise.all(
82 found
83 .filter(ledger => ledger !== undefined)
84 .map(({ path, slug, mtimeMs }) => $.fs.read(path).then(text => summarize(text, slug, mtimeMs), () => undefined)),
85 )
86 return new Map(summaries.filter(summary => summary !== undefined).map(summary => [summary.slug, summary]))
87}
88
89/**
90 * The unlisted ledgers that are the parent of a listed task, the parent of that parent, and so on. A parent is looked up
91 * in the backlog, marked as backlog, then in the other worktrees, whose ledgers findLedgers does not list from a linked
92 * worktree. Each walk up stops at a parent that is listed or seen before, or that has no ledger in either place.
93 */
94export async function unlistedAncestors($: EngineInterface, listed: LedgerSummary[]): Promise<LedgerSummary[] | { error: string }> {
95 const seen = new Set(listed.map(({ slug }) => slug))
96 if (listed.every(({ parent }) => parent === undefined || seen.has(parent))) return []
97 const found = await findBacklogLedgers($)
98 if ('error' in found) return found
99 const backlog = new Map<string, LedgerSummary>()
100 for (const summary of await summarizeAll($, found)) if (!backlog.has(summary.slug)) backlog.set(summary.slug, { ...summary, isBacklog: true })
101 let active: Map<string, LedgerSummary> | undefined
102 const ancestors: LedgerSummary[] = []
103 for (const ledger of listed) {
104 for (let parent = ledger.parent; parent !== undefined && !seen.has(parent); ) {
105 seen.add(parent)
106 const ancestor = backlog.get(parent) ?? (active ??= await otherWorktreeLedgers($)).get(parent)
107 if (ancestor) ancestors.push(ancestor)
108 parent = ancestor?.parent
109 }
110 }
111 return ancestors
112}
113
114/** The linked worktrees other than the one holding `cwd`; none from the main checkout, and when git cannot list them. */
115async function otherWorktrees($: EngineInterface, cwd: string): Promise<Worktree[]> {
116 let result: ProcessRunResult
117 try {
118 result = await $.process.run(['git', 'worktree', 'list', '--porcelain', '-z'], { cwd })
119 } catch {
120 return []
121 }
122 if (result.exitCode !== 0) return []
123 const worktrees = parseWorktrees(result.stdout)
124 // The longest match, because a task worktree can sit inside another one.
125 const [own] = worktrees.filter(({ path }) => isInside(cwd, path)).sort((a, b) => b.path.length - a.path.length)
126 return own === undefined ? [] : worktrees.filter(({ path }) => path !== own.path)
127}
128
129async function ledgerIn($: EngineInterface, worktree: string): Promise<Found | undefined> {
130 const path = `${worktree}/.claude/ledger.md`
131 const stat = await $.fs.stat(path).catch(() => undefined)
132 return stat?.kind === 'file' ? { path, slug: folderSlug(path), mtimeMs: stat.mtimeMs } : undefined
133}
134
135const namesWorktree = ({ path, branch }: Worktree, word: string): boolean => [basename(path), branch, branch.split('/').at(-1)].includes(word)
136
137/** A worktree named by its folder or branch; `slug` is its task's, absent when it has no ledger. */
138export type NamedWorktree = { path: string; slug?: string }
139
140export type OtherWorktreeMatch = { ledgers: Found[]; worktree?: NamedWorktree }
141
142/**
143 * From a linked worktree, findLedgers lists only its own ledger; this finds the ledgers in the other linked worktrees whose slug is
144 * `word`, the same slug a match from the main checkout needs. When none matches and `word` names one of those worktrees by its
145 * folder, its branch, or its branch without the owner prefix, `worktree` is that one.
146 */
147export async function lookUpOtherWorktrees($: EngineInterface, word: string, cwd: string): Promise<OtherWorktreeMatch> {
148 const worktrees = await Promise.all(
149 (await otherWorktrees($, cwd)).map(async worktree => {
150 const ledger = await ledgerIn($, worktree.path)
151 return { worktree, ledger, slug: ledger && (await titleSlug($, ledger.path)) }
152 }),
153 )
154 const ledgers = worktrees.flatMap(({ ledger, slug }) => (ledger && slug === word ? [ledger] : []))
155 if (ledgers.length > 0) return { ledgers }
156 const named = worktrees.find(({ worktree }) => namesWorktree(worktree, word))
157 return named ? { ledgers: [], worktree: { path: named.worktree.path, slug: named.slug } } : { ledgers: [] }
158}
159
160export type BranchRead = {
161 /** Empty on a detached HEAD, as `git branch --show-current` prints it. */
162 branch: string
163 /** The commit HEAD points at; empty on a branch with no commits yet. */
164 head: string
165 defaultBranch: string
166 /** Commits ahead of origin/<defaultBranch>, or why git could not count them. */
167 ahead: number | { error: string }
168}
169
170/** The branch checked out in `worktree`, and how far it is ahead of origin's default branch. */
171export async function readBranch($: EngineInterface, worktree: string): Promise<BranchRead | { error: string }> {
172 const git = (...args: string[]) => run($, ['git', '-C', worktree, ...args], worktree)
173 const [branch, head, originHead] = await Promise.all([
174 git('branch', '--show-current'),
175 git('rev-parse', '--verify', '--quiet', 'HEAD'),
176 git('symbolic-ref', '--short', 'refs/remotes/origin/HEAD'),
177 ])
178 if (branch.failure !== undefined) return { error: stateFailedMessage(worktree, 'git branch --show-current', branch.failure) }
179 // Not a stop: a branch made with `git switch --orphan` has no commit yet, and counts as unmerged.
180 const headSha = head.failure === undefined ? head.stdout.trim() : ''
181 const defaultBranch = defaultBranchOf(originHead.failure === undefined ? originHead.stdout : null)
182
183 // Not a stop: with no origin/<default> to compare with, the branch counts as unmerged instead.
184 // Counted at the commit read above, so the merge check and the branch delete describe the same commit.
185 const aheadRun = await git('rev-list', '--count', `origin/${defaultBranch}..${headSha || 'HEAD'}`)
186 const ahead =
187 aheadRun.failure === undefined
188 ? (parseCount(aheadRun.stdout) ?? { error: `git rev-list printed "${aheadRun.stdout.trim()}", not a count` })
189 : { error: aheadRun.stderr.trim() || aheadRun.failure }
190 return { branch: branch.stdout.trim(), head: headSha, defaultBranch, ahead }
191}
192
193/** The branch checked out in `worktree`, or null when git or gh cannot tell, or HEAD is detached. */
194export async function lookUpBranch($: EngineInterface, worktree: string): Promise<BranchState | null> {
195 const read = await readBranch($, worktree)
196 if ('error' in read || read.branch === '' || typeof read.ahead !== 'number') return null
197 const { prs } = await lookUpPrs($, read.branch, worktree)
198 return prs === null ? null : { ahead: read.ahead, prs }
199}
200
201export async function titleSlug($: EngineInterface, path: string): Promise<string> {
202 return summarize(await $.fs.read(path), folderSlug(path), 0).slug
203}
204hooks/parent-command.ts 121 lines1import type { EngineInterface } from 'claude-code'
2
3import { folderSlug, summarize, type ChildStatus, type Family, type LedgerSummary } from './ledger'
4import { findLedgers, message, run, sessionFolder, sessionLedger, type SessionFolder } from './lookup'
5
6const USAGE =
7 'Usage: /ledger:parent [<slug>] shows a parent task and its children; /ledger:parent <slug> add <child> and /ledger:parent <slug> remove <child> change them.'
8
9type Shown = { parent: string; goal: string; children: ChildStatus[] }
10
11function isChildStatus(value: unknown): value is ChildStatus {
12 if (typeof value !== 'object' || value === null) return false
13 const fields: Record<string, unknown> = { ...value }
14 return ['slug', 'status', 'next'].every(key => typeof fields[key] === 'string')
15}
16
17function parseShown(stdout: string): Shown | null {
18 try {
19 const parsed: unknown = JSON.parse(stdout)
20 if (typeof parsed !== 'object' || parsed === null) return null
21 const { parent, goal, children }: Record<string, unknown> = { ...parsed }
22 if (typeof parent !== 'string' || typeof goal !== 'string' || !Array.isArray(children) || !children.every(isChildStatus)) return null
23 return { parent, goal, children }
24 } catch {
25 return null
26 }
27}
28
29const oneLine = (text: string): string => text.trim().replace(/\s*\n\s*/g, ' ')
30
31/** Runs bin/cc-ledger-parent, which finds a slug in every worktree and in the backlog of the repository that holds `cwd`. */
32async function script($: EngineInterface, args: string[], cwd: string): Promise<{ stdout: string; stderr: string; error?: string }> {
33 const ran = await run($, [`${$.plugin.root}/../../bin/cc-ledger-parent`, ...args], cwd)
34 if (ran.failure === undefined) return ran
35 return { ...ran, error: oneLine(ran.stderr) || `cc-ledger-parent ${ran.failure.trim().replace(/:$/, '')}` }
36}
37
38export async function showParent($: EngineInterface, parent: string, cwd: string): Promise<Shown | { error: string }> {
39 const { stdout, error } = await script($, ['show', parent, '--json'], cwd)
40 if (error !== undefined) return { error }
41 return parseShown(stdout) ?? { error: 'cc-ledger-parent printed something that is not a parent and its children.' }
42}
43
44/** The slugs from `parent` down to the child task that /ledger:go <parent> starts; empty when no child is left to start. */
45export async function childToStart($: EngineInterface, parent: string, cwd: string): Promise<string[] | { error: string }> {
46 const { stdout, error } = await script($, ['next', parent], cwd)
47 if (error !== undefined) return { error }
48 const slugs = stdout.split(/\s+/).filter(slug => slug !== '')
49 return slugs.length > 1 ? slugs : []
50}
51
52/** Marks `child` started in its parent's Children section. `marked` is the ledger changed, absent when the line already had a mark. */
53export async function markStarted($: EngineInterface, parent: string, child: string, cwd: string): Promise<{ marked?: string } | { error: string }> {
54 const { stdout, error } = await script($, ['start', parent, child], cwd)
55 if (error !== undefined) return { error }
56 const marked = stdout.match(/^started \S+ in (.+)$/m)?.[1]
57 return marked ? { marked } : {}
58}
59
60/** What /ledger:go tells the next session about a task's parent or children. Best effort: a failed lookup must not stop the switch. */
61export async function familyOf($: EngineInterface, task: LedgerSummary, cwd: string): Promise<Family> {
62 if (task.parent) return { parent: task.parent }
63 if (!task.children) return {}
64 const shown = await showParent($, task.slug, cwd)
65 return 'error' in shown ? {} : { children: shown.children }
66}
67
68function formatShown({ parent, goal, children }: Shown): string {
69 if (children.length === 0) return `${parent} has no child tasks. Add one with \`/ledger:parent ${parent} add <child>\`.`
70 const count = children.length === 1 ? '1 child' : `${children.length} children`
71 const active = children.filter(({ status }) => status === 'active').length
72 return [
73 `**Parent task ${parent}** · ${count}, ${active} active`,
74 ...(goal ? [goal] : []),
75 '',
76 ...children.map(({ slug, status, next }) => `- **${slug}** · ${status}${next ? ` — ${next}` : ''}`),
77 ].join('\n')
78}
79
80async function ownFamily($: EngineInterface, folder: SessionFolder): Promise<{ parent: string | undefined } | { text: string }> {
81 const found = await findLedgers($)
82 if ('error' in found) return { text: `Could not list task ledgers. ${found.error}` }
83 const active = sessionLedger(found, folder)
84 if (active.kind !== 'one') return { parent: undefined }
85 try {
86 const { slug, parent, children } = summarize(await $.fs.read(active.path), folderSlug(active.path), 0)
87 return { parent: children ? slug : parent }
88 } catch (error) {
89 return { text: `Could not read ${active.path}. ${message(error)}` }
90 }
91}
92
93async function show($: EngineInterface, parent: string, cwd: string): Promise<string> {
94 const shown = await showParent($, parent, cwd)
95 return 'error' in shown ? `Could not show ${parent}. ${shown.error}` : formatShown(shown)
96}
97
98async function change($: EngineInterface, verb: 'add' | 'remove', parent: string, child: string, cwd: string): Promise<string> {
99 const { stderr, error } = await script($, [verb, parent, child], cwd)
100 if (error !== undefined) return verb === 'add' ? `Could not add ${child} to ${parent}. ${error}` : `Could not remove ${child} from ${parent}. ${error}`
101 const done = verb === 'add' ? `${parent} is now the parent of ${child}.` : `${child} is no longer a child of ${parent}.`
102 const warning = oneLine(stderr)
103 return warning ? `${done} ${warning}` : done
104}
105
106export async function parentCommand($: EngineInterface, args: string): Promise<string> {
107 const words = args.split(/\s+/).filter(word => word !== '')
108 const folder = await sessionFolder($)
109 const cwd = folder.path
110 const [parent, verb, child] = words
111 if (words.length === 1 && (parent === 'add' || parent === 'remove')) return USAGE
112 if (parent === undefined) {
113 const own = await ownFamily($, folder)
114 if ('text' in own) return own.text
115 return own.parent === undefined ? USAGE : show($, own.parent, cwd)
116 }
117 if (words.length === 1) return show($, parent, cwd)
118 if (words.length === 3 && child !== undefined && (verb === 'add' || verb === 'remove')) return change($, verb, parent, child, cwd)
119 return USAGE
120}
121hooks/registry.ts 83 lines1import type { EngineInterface, ProcessRunResult } from 'claude-code'
2
3import { message, run, sessionFolder } from './lookup'
4import { basename } from './worktrees'
5
6/** One entry of ~/.claude/ledgers.json, as `cc-ledgers list --json` prints it. `parent` is the slug of its parent task. `main` is the main checkout of a backlog task. */
7export type Entry = { repo: string; slug: string; status: string; updated: string; path: string; archivePath?: string; parent?: string; main?: string }
8
9const optionalString = (value: unknown): boolean => value === undefined || typeof value === 'string'
10
11function isEntry(value: unknown): value is Entry {
12 if (typeof value !== 'object' || value === null) return false
13 const fields: Record<string, unknown> = { ...value }
14 const strings = ['repo', 'slug', 'status', 'updated', 'path'].every(key => typeof fields[key] === 'string')
15 return strings && ['archivePath', 'parent', 'main'].every(key => optionalString(fields[key]))
16}
17
18export function parseEntries(stdout: string): Entry[] | null {
19 try {
20 const parsed: unknown = JSON.parse(stdout)
21 return Array.isArray(parsed) && parsed.every(isEntry) ? parsed : null
22 } catch {
23 return null
24 }
25}
26
27export function scriptPath($: EngineInterface, name: string): string {
28 return `${$.plugin.root}/../../bin/${name}`
29}
30
31/** Where cc-task-new keeps the backlog ledger of `slug` for the repository at `main`; null when HOME is not set. */
32export async function backlogLedgerPath($: EngineInterface, main: string, slug: string): Promise<string | null> {
33 const home = await $.env.get('HOME')
34 return home?.startsWith('/') ? `${home}/.claude/ledger-backlog/${basename(main)}/${slug}.md` : null
35}
36
37/** The tasks named `slug` that the registry lists, with any status, in any repository. */
38export async function registeredTasks($: EngineInterface, slug: string): Promise<Entry[] | { error: string }> {
39 let result: ProcessRunResult
40 try {
41 result = await $.process.run([scriptPath($, 'cc-ledgers'), 'list', '--json'], { cwd: (await sessionFolder($)).path })
42 } catch (error) {
43 return { error: `cc-ledgers did not run: ${message(error)}` }
44 }
45 if (result.exitCode !== 0) return { error: `cc-ledgers failed (exit ${result.exitCode}): ${result.stderr.trim()}` }
46 const entries = parseEntries(result.stdout)
47 if (entries === null) return { error: 'cc-ledgers printed something that is not a list of ledgers.' }
48 return entries.filter(entry => entry.slug === slug)
49}
50
51/** The main checkout of the repository `cwd` is in, worked out the way cc-task-new does; null when git cannot tell. */
52export async function mainCheckout($: EngineInterface, cwd: string): Promise<string | null> {
53 const { stdout, failure } = await run($, ['git', 'rev-parse', '--path-format=absolute', '--git-common-dir'], cwd)
54 const common = stdout.trim()
55 return failure === undefined && common.startsWith('/') ? common.slice(0, common.lastIndexOf('/')) || '/' : null
56}
57
58/**
59 * The task among `tasks` that belongs to another main checkout, when none can be promoted from `main`.
60 * Null when one of them is this repository's or names no main checkout, or when `main` is unknown: cc-task-new then decides.
61 */
62export function otherRepositoryTask(tasks: Entry[], main: string | null): (Entry & { main: string }) | null {
63 if (main === null) return null
64 const elsewhere = tasks.filter((task): task is Entry & { main: string } => task.main !== undefined && task.main !== main)
65 return elsewhere.length === tasks.length ? (elsewhere[0] ?? null) : null
66}
67
68/**
69 * Gives the backlog task `slug` its branch and worktree, and moves its ledger there. Runs in `cwd`, because cc-task-new
70 * promotes only a task of the repository it runs in. Returns the ledger's new path, or the script's reason for refusing.
71 * `isMissing` means the script found no backlog ledger named `slug`.
72 */
73export async function promoteBacklogTask(
74 $: EngineInterface,
75 slug: string,
76 cwd: string,
77): Promise<{ ledger: string } | { error: string; isMissing: boolean }> {
78 const { stdout, stderr, failure, exitCode } = await run($, [scriptPath($, 'cc-task-new'), '--promote', slug], cwd)
79 if (failure !== undefined) return { error: stderr.trim().replace(/\s*\n\s*/g, ' ') || `cc-task-new ${failure}`, isMissing: exitCode === 2 }
80 const ledger = stdout.match(/^ledger\s+(\S.*)$/m)?.[1]?.trim()
81 return ledger ? { ledger } : { error: `cc-task-new printed no ledger path: ${stdout.trim()}`, isMissing: false }
82}
83hooks/retire.ts 208 lines1import { isoDate } from './ledger'
2import { basename } from './worktrees'
3
4export type RetireArgs = { kind: 'retire'; slug: string | null; dryRun: boolean; forced: boolean } | { kind: 'usage' }
5
6export const RETIRE_USAGE =
7 'Usage: /ledger:retire [<slug>] [--dry-run] [--force]. --dry-run only shows what would be retired. --force retires a task with uncommitted changes or unmerged work. Run /ledger to see each slug.'
8
9/** `--yes` is still accepted from before retiring was the default, and changes nothing. */
10const RETIRE_FLAGS = new Set(['--dry-run', '--force', '--yes'])
11
12export function parseRetireArgs(args: string): RetireArgs {
13 const words = args.split(/\s+/).filter(word => word !== '')
14 const flags = words.filter(word => word.startsWith('-'))
15 const slugs = words.filter(word => !word.startsWith('-'))
16 if (slugs.length > 1 || flags.some(flag => !RETIRE_FLAGS.has(flag))) return { kind: 'usage' }
17 return { kind: 'retire', slug: slugs[0] ?? null, dryRun: flags.includes('--dry-run'), forced: flags.includes('--force') }
18}
19
20export const worktreeOf = (ledgerPath: string): string => ledgerPath.split('/').slice(0, -2).join('/')
21
22export const dirname = (path: string): string => path.split('/').slice(0, -1).join('/')
23
24export function noTaskMessage(cwd: string): string {
25 return `No task ledger in or above ${cwd}. Give a slug: /ledger:retire <slug>. Run /ledger to see each slug.`
26}
27
28export function mainCheckoutMessage(path: string): string {
29 return `${path} is the main checkout, not a linked worktree. /ledger:retire removes only linked worktrees.`
30}
31
32export function stateFailedMessage(worktree: string, command: string, failure: string): string {
33 return `Could not read the state of ${worktree}. ${command} ${failure}`
34}
35
36/** Reads `git rev-parse --path-format=absolute --git-dir --git-common-dir`; the two are equal only in the main checkout. */
37export function parseGitDirs(stdout: string): { gitDir: string; commonDir: string } | null {
38 const [gitDir, commonDir] = stdout.split('\n').filter(line => line !== '')
39 return gitDir === undefined || commonDir === undefined ? null : { gitDir, commonDir }
40}
41
42export function defaultBranchOf(originHead: string | null): string {
43 return originHead?.trim().replace(/^origin\//, '') || 'main'
44}
45
46export function parseCount(stdout: string): number | null {
47 const text = stdout.trim()
48 return /^\d+$/.test(text) ? Number(text) : null
49}
50
51/** `heads` holds the head commit of each merged PR from a branch with this name. */
52export type MergedPr = { kind: 'merged'; number: number; heads: string[] } | { kind: 'none' } | { kind: 'unknown'; error: string }
53
54/** Reads `gh pr list --json number,headRefOid`. */
55export function parseMergedPr(stdout: string): MergedPr {
56 let parsed: unknown
57 try {
58 parsed = JSON.parse(stdout)
59 } catch {
60 parsed = null
61 }
62 if (!Array.isArray(parsed)) return { kind: 'unknown', error: 'gh pr list printed something that is not a JSON list' }
63 const prs = parsed.map(pr => (pr ?? {}) as Record<string, unknown>)
64 const [first] = prs
65 if (first === undefined) return { kind: 'none' }
66 if (typeof first.number !== 'number') return { kind: 'unknown', error: 'gh pr list printed a PR without a number' }
67 const heads = prs.map(({ headRefOid }) => headRefOid).filter(head => typeof head === 'string')
68 return { kind: 'merged', number: first.number, heads }
69}
70
71export type WorktreeState = {
72 path: string
73 mainCheckout: string
74 /** Empty on a detached HEAD, as `git branch --show-current` prints it. */
75 branch: string
76 /** The commit HEAD points at; empty on a branch with no commits yet. */
77 head: string
78 defaultBranch: string
79 /** Commits ahead of origin/<defaultBranch>, or why git could not count them. */
80 ahead: number | { error: string }
81 dirty: number
82 mergedPr: MergedPr
83}
84
85const plural = (count: number, noun: string): string => `${count} ${noun}${count === 1 ? '' : 's'}`
86
87/** A gh failure counts as no merged PR, and an unknown ahead count as commits ahead. */
88const isWorkMerged = ({ ahead, mergedPr }: WorktreeState): boolean => ahead === 0 || mergedPr.kind === 'merged'
89
90const isHeadMerged = ({ head, mergedPr }: WorktreeState): boolean => head !== '' && mergedPr.kind === 'merged' && mergedPr.heads.includes(head)
91
92/**
93 * Whether retiring may delete the local branch at `head`. The script deletes it without git's merge check, because a squash-merged
94 * branch is never an ancestor of main, and keeps it when it no longer points at `head`.
95 * A merged PR counts only when it ended at HEAD: the branch name may have been reused, or committed to after the merge.
96 */
97export const isBranchMerged = (state: WorktreeState): boolean => state.branch !== '' && (state.ahead === 0 || isHeadMerged(state))
98
99/** Why retiring keeps a branch that isBranchMerged does not hold for. */
100export function keptBranchReason(state: WorktreeState): string {
101 if (state.head === '') return 'it has no commits yet'
102 return isWorkMerged(state) ? 'it has commits that are not in its merged PR' : 'it is not merged'
103}
104
105/** Why retiring needs --force; empty when it does not. */
106export function retireBlockers(state: WorktreeState): string[] {
107 return [
108 state.dirty > 0 ? `it has ${plural(state.dirty, 'uncommitted change')}` : '',
109 isWorkMerged(state) ? '' : 'its branch is not merged',
110 ].filter(reason => reason !== '')
111}
112
113const archiveCopy = (repo: string, slug: string, today: Date): string => `~/.claude/ledger-archive/${repo}/${isoDate(today)}-${slug}.md`
114
115/** Where cc-worktree-retire copies the ledger, named the way the script names it. */
116export function archivePath({ path, mainCheckout, branch }: WorktreeState, today: Date): string {
117 return archiveCopy(basename(mainCheckout), branch.split('/').at(-1) || basename(path), today)
118}
119
120function prLabel(mergedPr: MergedPr): string {
121 switch (mergedPr.kind) {
122 case 'merged':
123 return `merged PR #${mergedPr.number}`
124 case 'none':
125 return 'no merged PR'
126 case 'unknown':
127 return `could not check PRs: ${mergedPr.error}`
128 }
129}
130
131function aheadLabel({ ahead, defaultBranch }: WorktreeState): string {
132 if (typeof ahead !== 'number') return `could not compare with origin/${defaultBranch}: ${ahead.error}`
133 return ahead === 0 ? 'no commits ahead' : `${plural(ahead, 'commit')} ahead of origin/${defaultBranch}`
134}
135
136// cc-worktree-retire refuses, without --force, a parent whose children are not all retired.
137function childrenBlockers(activeChildren: string[]): string[] {
138 if (activeChildren.length === 0) return []
139 return [`it has ${activeChildren.length === 1 ? 'an active child' : 'active children'} (${activeChildren.join(', ')})`]
140}
141
142function planFooter(slug: string, blockers: string[]): string {
143 if (blockers.length === 0) return `Run \`/ledger:retire ${slug}\` to retire it.`
144 return `Retiring it needs --force: ${blockers.join(' and ')}. Run \`/ledger:retire ${slug} --force\` to retire it anyway.`
145}
146
147/**
148 * `footer: false` leaves out the /ledger:retire command that carries out the plan, for the dashboard, which has its own.
149 * `activeChildren` are the task's child tasks not yet retired. `hasEvidence` is whether the worktree's .claude/evidence/ holds anything.
150 */
151export function formatPlan(
152 slug: string,
153 state: WorktreeState,
154 today: Date,
155 { footer = true, activeChildren = [], hasEvidence = false }: { footer?: boolean; activeChildren?: string[]; hasEvidence?: boolean } = {},
156): string {
157 const archive = archivePath(state, today)
158 return [
159 `**Retire ${slug}** — nothing done yet`,
160 `- worktree: ${state.path}`,
161 `- branch: ${state.branch || 'detached HEAD'} · ${aheadLabel(state)} · ${prLabel(state.mergedPr)}`,
162 `- uncommitted changes: ${state.dirty || 'none'}`,
163 `- archive: ${archive}`,
164 ...(hasEvidence ? [`- evidence: ${state.path}/.claude/evidence/ is copied to ${archive.replace(/\.md$/, '/')}`] : []),
165 "- then: git worktree remove, and the worktree's cc-dd-path build folders are deleted",
166 ...(state.branch ? [`- local branch: ${state.branch} is ${isBranchMerged(state) ? 'deleted, because it is merged' : `kept, because ${keptBranchReason(state)}`}`] : []),
167 ...(footer ? ['', planFooter(slug, [...retireBlockers(state), ...childrenBlockers(activeChildren)])] : []),
168 ].join('\n')
169}
170
171/** `ledgerPath` is ~/.claude/ledger-backlog/<repo>/<slug>.md; cc-worktree-retire names the copy after that folder and file. */
172export function formatBacklogPlan(slug: string, ledgerPath: string, today: Date, activeChildren: string[]): string {
173 return [
174 `**Retire ${slug}** — nothing done yet`,
175 `- backlog ledger: ${ledgerPath}`,
176 `- archive: ${archiveCopy(basename(dirname(ledgerPath)), basename(ledgerPath).replace(/\.md$/, ''), today)}`,
177 '- then: the backlog ledger is deleted. A backlog task has no worktree or branch to remove.',
178 '',
179 planFooter(slug, childrenBlockers(activeChildren)),
180 ].join('\n')
181}
182
183export function notRetiredMessage(blockers: string[]): string {
184 return `Not retired: ${blockers.join(' and ')}. Add --force to retire it anyway. Uncommitted changes are lost with the worktree.`
185}
186
187export const isInside = (path: string, folder: string): boolean => path === folder || path.startsWith(`${folder}/`)
188
189const scriptLines = (stdout: string): string[] =>
190 stdout
191 .split('\n')
192 .filter(line => line.trim() !== '')
193 .map(line => `- ${line.trimEnd()}`)
194
195/** `kept` is the branch the script was not asked to delete, and why. */
196export function formatRetired(slug: string, stdout: string, isCwdRemoved: boolean, kept?: { branch: string; reason: string }): string {
197 const lines = [`**Retired ${slug}**`, ...scriptLines(stdout)]
198 if (kept) lines.push(`- kept branch ${kept.branch}, because ${kept.reason}`)
199 if (isCwdRemoved) {
200 lines.push('', "This session's working directory was removed with the worktree. Continue another task with /ledger:go <slug>, or run /ledger:close.")
201 }
202 return lines.join('\n')
203}
204
205export function formatRetireFailed(failure: string, stdout: string): string {
206 return [`cc-worktree-retire ${failure}`, ...scriptLines(stdout)].join('\n')
207}
208hooks/retire-command.ts 159 lines1import type { EngineInterface } from 'claude-code'
2
3import { backlogUncheckedMessage, folderSlug, severalLedgersMessage, sharedSlugMessage, summarize, unknownTaskMessage } from './ledger'
4import { findBacklogLedgers, findLedgers, readBranch, run, sessionFolder, sessionLedger, titleSlug, type SessionFolder } from './lookup'
5import { scriptPath } from './registry'
6import {
7 dirname,
8 formatBacklogPlan,
9 formatPlan,
10 formatRetired,
11 formatRetireFailed,
12 isBranchMerged,
13 isInside,
14 keptBranchReason,
15 mainCheckoutMessage,
16 noTaskMessage,
17 notRetiredMessage,
18 parseGitDirs,
19 parseMergedPr,
20 parseRetireArgs,
21 RETIRE_USAGE,
22 retireBlockers,
23 stateFailedMessage,
24 worktreeOf,
25 type MergedPr,
26 type WorktreeState,
27} from './retire'
28
29type Target = { slug: string; ledgerPath: string; isBacklog?: true } | { text: string }
30
31const UNRETIRED = 'Nothing was retired.'
32
33async function findBacklogTarget($: EngineInterface, slug: string, activeSlugs: string[]): Promise<Target> {
34 const tasks = activeSlugs.map(name => ({ slug: name }))
35 const found = await findBacklogLedgers($)
36 if ('error' in found) return { text: backlogUncheckedMessage(slug, tasks, found.error, UNRETIRED) }
37 const slugs = await Promise.all(found.map(async ({ path, slug: fileSlug }) => summarize(await $.fs.read(path), fileSlug, 0).slug))
38 const matches = found.filter((_, index) => slugs[index] === slug).map(({ path }) => path)
39 const [match] = matches
40 if (match === undefined) return { text: unknownTaskMessage(slug, tasks, UNRETIRED) }
41 if (matches.length > 1) return { text: sharedSlugMessage(slug, matches, UNRETIRED) }
42 return { slug, ledgerPath: match, isBacklog: true }
43}
44
45async function findTarget($: EngineInterface, slug: string | null, folder: SessionFolder): Promise<Target> {
46 const found = await findLedgers($)
47 if ('error' in found) return { text: `Could not list task ledgers. ${found.error}` }
48 const paths = found.map(({ path }) => path)
49 if (slug === null) {
50 const active = sessionLedger(found, folder)
51 if (active.kind === 'none') return { text: noTaskMessage(folder.removed ?? folder.path) }
52 if (active.kind === 'several') return { text: severalLedgersMessage(folder.path, active.paths.map(folderSlug), UNRETIRED) }
53 return { slug: await titleSlug($, active.path), ledgerPath: active.path }
54 }
55 const slugs = await Promise.all(paths.map(path => titleSlug($, path)))
56 const matches = paths.filter((_, index) => slugs[index] === slug)
57 const [match] = matches
58 if (match === undefined) return findBacklogTarget($, slug, slugs)
59 if (matches.length > 1) return { text: sharedSlugMessage(slug, matches, UNRETIRED) }
60 return { slug, ledgerPath: match }
61}
62
63type Read = { stdout: string } | { error: string }
64
65async function readGit($: EngineInterface, worktree: string, args: string[]): Promise<Read> {
66 const { stdout, failure } = await run($, ['git', '-C', worktree, ...args], worktree)
67 return failure === undefined ? { stdout } : { error: stateFailedMessage(worktree, `git ${args.join(' ')}`, failure) }
68}
69
70async function lookUpMergedPr($: EngineInterface, branch: string, cwd: string): Promise<MergedPr> {
71 if (branch === '') return { kind: 'none' }
72 const { stdout, failure } = await run($, ['gh', 'pr', 'list', '--head', branch, '--state', 'merged', '--json', 'number,headRefOid'], cwd)
73 return failure === undefined ? parseMergedPr(stdout) : { kind: 'unknown', error: `gh pr list ${failure}` }
74}
75
76export async function readState($: EngineInterface, path: string): Promise<WorktreeState | { error: string }> {
77 const dirsArgs = ['rev-parse', '--path-format=absolute', '--git-dir', '--git-common-dir']
78 const dirsRead = await readGit($, path, dirsArgs)
79 if ('error' in dirsRead) return dirsRead
80 const dirs = parseGitDirs(dirsRead.stdout)
81 if (dirs === null) return { error: stateFailedMessage(path, `git ${dirsArgs.join(' ')}`, `printed "${dirsRead.stdout.trim()}", not two paths`) }
82 if (dirs.gitDir === dirs.commonDir) return { error: mainCheckoutMessage(path) }
83
84 const [status, branch] = await Promise.all([readGit($, path, ['status', '--porcelain']), readBranch($, path)])
85 if ('error' in status) return status
86 if ('error' in branch) return branch
87 return {
88 path,
89 mainCheckout: dirname(dirs.commonDir),
90 ...branch,
91 dirty: status.stdout.split('\n').filter(line => line !== '').length,
92 mergedPr: await lookUpMergedPr($, branch.branch, path),
93 }
94}
95
96/** The text /ledger:retire answers with for the arguments the operator typed. */
97export async function retireCommand($: EngineInterface, args: string): Promise<string> {
98 const command = parseRetireArgs(args)
99 if (command.kind === 'usage') return RETIRE_USAGE
100 const folder = await sessionFolder($)
101 const target = await findTarget($, command.slug, folder)
102 if ('text' in target) return target.text
103 if (target.isBacklog) return retireBacklogLedger($, target.slug, target.ledgerPath, command, folder.path)
104 return retireLedger($, target.slug, target.ledgerPath, command)
105}
106
107type RetireFlags = { dryRun: boolean; forced: boolean }
108
109// Only for the plan: an unreadable ledger shows no children, and cc-worktree-retire still refuses a parent with active ones.
110async function activeChildrenOf($: EngineInterface, ledgerPath: string): Promise<string[]> {
111 const text = await $.fs.read(ledgerPath).catch(() => '')
112 return (summarize(text, '', 0).children ?? []).filter(({ retired }) => retired === undefined).map(({ slug }) => slug)
113}
114
115// Only for the plan: cc-worktree-retire checks the folder again when it archives it.
116async function hasEvidenceIn($: EngineInterface, worktree: string): Promise<boolean> {
117 const entries = await $.fs.list(`${worktree}/.claude/evidence`).catch(() => [])
118 return entries.length > 0
119}
120
121/** Plans or retires the backlog task whose ledger is `ledgerPath`: it has no worktree or branch, only the ledger. */
122async function retireBacklogLedger(
123 $: EngineInterface,
124 slug: string,
125 ledgerPath: string,
126 { dryRun, forced }: RetireFlags,
127 cwd: string,
128): Promise<string> {
129 if (dryRun) return formatBacklogPlan(slug, ledgerPath, new Date(), await activeChildrenOf($, ledgerPath))
130 const { stdout, failure } = await run($, ['bash', scriptPath($, 'cc-worktree-retire'), ledgerPath, ...(forced ? ['--force'] : [])], cwd)
131 return failure === undefined ? formatRetired(slug, stdout, false) : formatRetireFailed(failure, stdout)
132}
133
134/** Plans or retires the worktree that holds `ledgerPath`, named `slug` in the text. */
135export async function retireLedger(
136 $: EngineInterface,
137 slug: string,
138 ledgerPath: string,
139 { dryRun, forced }: RetireFlags,
140): Promise<string> {
141 const state = await readState($, worktreeOf(ledgerPath))
142 if ('error' in state) return state.error
143 if (dryRun) {
144 const [activeChildren, hasEvidence] = await Promise.all([activeChildrenOf($, ledgerPath), hasEvidenceIn($, state.path)])
145 return formatPlan(slug, state, new Date(), { activeChildren, hasEvidence })
146 }
147 const blockers = retireBlockers(state)
148 if (blockers.length > 0 && !forced) return notRetiredMessage(blockers)
149
150 // From the main checkout, because the worktree is gone once the script returns.
151 const deletesBranch = isBranchMerged(state)
152 const flags = [...(deletesBranch ? ['--delete-branch', state.head] : []), ...(forced ? ['--force'] : [])]
153 const { stdout, failure } = await run($, ['bash', scriptPath($, 'cc-worktree-retire'), state.path, ...flags], state.mainCheckout)
154 if (failure !== undefined) return formatRetireFailed(failure, stdout)
155 const kept = deletesBranch || state.branch === '' ? undefined : { branch: state.branch, reason: keptBranchReason(state) }
156 // The session's own folder, not sessionFolder's fallback: the question is whether this retire removed it.
157 return formatRetired(slug, stdout, isInside(await $.session.cwd(), state.path), kept)
158}
159hooks/worktrees.ts 382 lines1import type { LedgerSummary } from './ledger'
2
3export type Worktree = { path: string; branch: string }
4
5export type PullRequest = { state: string; number: number }
6
7export type WorktreeRow = {
8 name: string
9 sizeGb: number | null
10 lastCommit: string | null
11 dirty: number | null
12 hasLedger: boolean
13 ledgerRole?: string
14 pr: string
15}
16
17export function ledgerRole({ parent, children }: LedgerSummary): string | undefined {
18 if (children) return `parent of ${children.filter(({ retired }) => retired === undefined).length}`
19 return parent ? `child of ${parent}` : undefined
20}
21
22/** Reads `git worktree list --porcelain -z`: fields end in NUL and an empty field ends a block, so a path is never quoted. */
23const worktreeBlocks = (porcelain: string): string[][] =>
24 porcelain
25 .split('\0\0')
26 .map(block => block.split('\0'))
27 .filter(lines => lines.some(line => line.startsWith('worktree ')))
28
29const worktreePath = (lines: string[]): string => lines.find(line => line.startsWith('worktree '))?.slice('worktree '.length) ?? ''
30
31export function parseWorktrees(porcelain: string): Worktree[] {
32 return worktreeBlocks(porcelain)
33 .slice(1)
34 .filter(lines => !lines.some(line => line === 'prunable' || line.startsWith('prunable ')))
35 .map(lines => ({
36 path: worktreePath(lines),
37 branch: lines.find(line => line.startsWith('branch refs/heads/'))?.slice('branch refs/heads/'.length) ?? '',
38 }))
39}
40
41/** git lists the main checkout first. */
42export function parseMainWorktree(porcelain: string): string | null {
43 const [main] = worktreeBlocks(porcelain)
44 return main === undefined ? null : worktreePath(main)
45}
46
47export const basename = (path: string): string => path.split('/').at(-1) ?? path
48
49export function parsePrs(stdout: string): PullRequest[] | null {
50 let parsed: unknown
51 try {
52 parsed = JSON.parse(stdout)
53 } catch {
54 return null
55 }
56 return Array.isArray(parsed) ? parsed.filter(isPullRequest) : null
57}
58
59function isPullRequest(value: unknown): value is PullRequest {
60 if (typeof value !== 'object' || value === null) return false
61 const { state, number } = value as Record<string, unknown>
62 return typeof state === 'string' && typeof number === 'number'
63}
64
65export function prLabel(prs: PullRequest[] | null): string {
66 if (prs === null) return '?'
67 const [pr] = prs
68 return pr ? `${pr.state} #${pr.number}` : 'none'
69}
70
71export function shortDate(stdout: string): string | null {
72 return stdout.trim().match(/^\d{4}-(\d\d-\d\d)$/)?.[1] ?? null
73}
74
75export function sizeGb(duStdout: string): number | null {
76 const kib = duStdout.match(/^\d+/)?.[0]
77 return kib === undefined ? null : (Number(kib) * 1024) / 1e9
78}
79
80export function dirtyCount(statusStdout: string): number {
81 return statusStdout.split('\n').filter(line => line !== '').length
82}
83
84const cell = (value: string | number | null): string => (value === null ? '?' : String(value))
85
86export function formatTable(rows: WorktreeRow[], prError?: string): string {
87 if (rows.length === 0) return 'No linked worktrees.'
88 const sorted = [...rows].sort((a, b) => (b.sizeGb ?? -1) - (a.sizeGb ?? -1))
89 const totalGb = rows.reduce((sum, row) => sum + (row.sizeGb ?? 0), 0)
90 const count = rows.length === 1 ? '1 worktree' : `${rows.length} worktrees, largest first`
91 return [
92 `**Worktrees** · ${count} · ${totalGb.toFixed(1)} GB total`,
93 '',
94 '| Worktree | Size GB | Last commit | Dirty | Ledger | PR |',
95 '|---|---:|---|---:|---|---|',
96 ...sorted.map(row => {
97 const cells = [row.name, cell(row.sizeGb?.toFixed(1) ?? null), cell(row.lastCommit), cell(row.dirty), row.hasLedger ? (row.ledgerRole ?? 'yes') : 'no', row.pr]
98 return `| ${cells.join(' | ')} |`
99 }),
100 ...(prError ? ['', `PR is ? because ${prError}`] : []),
101 ].join('\n')
102}
103
104export type WorktreesCommand =
105 | { kind: 'table' }
106 | { kind: 'prune'; name: string; dryRun: boolean }
107 | { kind: 'derived-data' }
108 | { kind: 'prune-orphans'; dryRun: boolean }
109 | { kind: 'usage' }
110
111export const USAGE =
112 'Usage: `/ledger:worktrees`, `/ledger:worktrees prune <name> [--dry-run]`, `/ledger:worktrees derived-data` or `/ledger:worktrees prune-orphans [--dry-run]`'
113
114/** `--yes` is still accepted from before pruning was the default, and changes nothing. */
115const FINAL_FLAG = /(?:^|\s+)(--dry-run|--yes)$/
116
117/** Flags count only at the end, because a worktree name may hold spaces and words that start with -. */
118function takeFinalFlags(text: string): { rest: string; dryRun: boolean } {
119 let rest = text
120 let dryRun = false
121 for (let found = rest.match(FINAL_FLAG); found !== null; found = rest.match(FINAL_FLAG)) {
122 dryRun ||= found[1] === '--dry-run'
123 rest = rest.slice(0, found.index)
124 }
125 return { rest, dryRun }
126}
127
128export function parseCommand(args: string): WorktreesCommand {
129 const trimmed = args.trim()
130 if (trimmed === '') return { kind: 'table' }
131 if (trimmed === 'derived-data') return { kind: 'derived-data' }
132 const { rest, dryRun } = takeFinalFlags(trimmed)
133 if (rest === 'prune-orphans') return { kind: 'prune-orphans', dryRun }
134 const name = rest.match(/^prune\s+(.+)$/s)?.[1]
135 return name === undefined ? { kind: 'usage' } : { kind: 'prune', name, dryRun }
136}
137
138const BUILD_FOLDER_NAMES = new Set(['.build', '.expo-prebuild', '.cache', 'build', '.DerivedData'])
139
140/** Nothing in these is ever pruned: `.claude` holds agent state, and keeping `node_modules` and `Pods` lets a pruned worktree build without reinstalling. */
141const KEPT_FOLDER_NAMES = new Set(['.claude', 'node_modules', 'Pods'])
142
143export function ignoredBuildFolders(porcelain: string, root: string): string[] {
144 return porcelain
145 .split('\n')
146 .filter(line => line.startsWith('!! ') && line.endsWith('/'))
147 .map(line => line.slice('!! '.length, -1))
148 // git quotes a path with special characters in it; such a path is left alone rather than unquoted.
149 .filter(path => !path.startsWith('"'))
150 .filter(path => {
151 const segments = path.split('/')
152 return BUILD_FOLDER_NAMES.has(segments.at(-1) ?? '') && !segments.some(segment => KEPT_FOLDER_NAMES.has(segment))
153 })
154 .map(path => `${root}/${path}`)
155}
156
157/** The name prefix bin/cc-dd-path gives this worktree's Xcode build folders: `cc-<basename>-<sha1 of the path, 6 hex>-`. */
158export async function derivedDataPrefix(root: string): Promise<string> {
159 const digest = new Uint8Array(await crypto.subtle.digest('SHA-1', new TextEncoder().encode(root)))
160 const hex = [...digest].map(byte => byte.toString(16).padStart(2, '0')).join('')
161 return `cc-${basename(root)}-${hex.slice(0, 6)}-`
162}
163
164/**
165 * Whether a DerivedData folder name is this worktree's: it starts with `prefix`, and what follows has no
166 * `<hex6>-` of its own, which would make it another worktree's whose name starts with `<basename>-<hex6>`.
167 */
168export const isOwnXcodeFolder = (name: string, prefix: string): boolean =>
169 name.startsWith(prefix) && !/(^|-)[0-9a-f]{6}-/.test(name.slice(prefix.length))
170
171export type PruneScope = { root: string; derivedData: string | null; prefix: string }
172
173/** The folder a path may be deleted from: the worktree for a folder strictly inside it and outside any kept folder, DerivedData for one of its own Xcode build folders, else null. */
174export function pruneBase(path: string, { root, derivedData, prefix }: PruneScope): string | null {
175 const segments = path.split('/')
176 if (segments.includes('..') || segments.includes('.')) return null
177 if (path.startsWith(`${root}/`)) {
178 const inside = path.slice(root.length + 1).split('/')
179 return inside.every(segment => segment !== '' && !KEPT_FOLDER_NAMES.has(segment)) ? root : null
180 }
181 if (derivedData === null || !path.startsWith(`${derivedData}/`)) return null
182 const name = path.slice(derivedData.length + 1)
183 return !name.includes('/') && isOwnXcodeFolder(name, prefix) ? derivedData : null
184}
185
186export const isPrunable = (path: string, scope: PruneScope): boolean => pruneBase(path, scope) !== null
187
188/** Why a folder whose real path is `realPath` may not be deleted from the folder whose real path is `realBase`; undefined when it may. */
189export function realPathProblem(realPath: string, realBase: string): string | undefined {
190 const inside = realPath.startsWith(`${realBase}/`) ? realPath.slice(realBase.length + 1) : ''
191 if (inside === '') return `it resolves to ${realPath}, which is not inside ${realBase}.`
192 const kept = inside.split('/').find(segment => KEPT_FOLDER_NAMES.has(segment))
193 if (kept !== undefined) return `it resolves to ${realPath}, inside a ${kept} folder.`
194 return undefined
195}
196
197export type PruneFolder = { path: string; label: string; sizeGb: number | null }
198
199/** Whether the folder's size prints as 0.0; an unknown size does not count as empty. */
200export const isEmptyFolder = ({ sizeGb }: PruneFolder): boolean => sizeGb !== null && sizeGb < 0.05
201
202const DERIVED_DATA_LABEL = '~/Library/Developer/Xcode/DerivedData'
203
204export const folderLabel = (path: string, root: string): string =>
205 path.startsWith(`${root}/`) ? path.slice(root.length + 1) : `${DERIVED_DATA_LABEL}/${basename(path)}`
206
207const gb = (folders: PruneFolder[]): string => folders.reduce((sum, { sizeGb }) => sum + (sizeGb ?? 0), 0).toFixed(1)
208
209const folderCount = (folders: PruneFolder[]): string => (folders.length === 1 ? '1 folder' : `${folders.length} folders`)
210
211function pruneTable(folders: PruneFolder[]): string[] {
212 const sorted = [...folders].sort((a, b) => (b.sizeGb ?? -1) - (a.sizeGb ?? -1))
213 return ['| Folder | Size GB |', '|---|---:|', ...sorted.map(({ label, sizeGb }) => `| ${label} | ${cell(sizeGb?.toFixed(1) ?? null)} |`)]
214}
215
216export function formatPrunePlan(name: string, folders: PruneFolder[]): string {
217 if (folders.length === 0) return `Nothing to prune in ${name}.`
218 return [
219 `**Prune ${name}** · dry run · ${gb(folders)} GB in ${folderCount(folders)}`,
220 '',
221 ...pruneTable(folders),
222 '',
223 'Folders inside a `.claude` folder are never deleted.',
224 '`node_modules` and `Pods` folders are kept, so the worktree still builds.',
225 `Run \`/ledger:worktrees prune ${name}\` to delete them.`,
226 ].join('\n')
227}
228
229export function formatPruned(name: string, deleted: PruneFolder[], failures: string[]): string {
230 return [
231 `**Pruned ${name}** · ${gb(deleted)} GB freed in ${folderCount(deleted)}`,
232 ...(deleted.length > 0 ? ['', ...pruneTable(deleted)] : []),
233 ...(failures.length > 0 ? ['', ...failures] : []),
234 ].join('\n')
235}
236
237/**
238 * `workspacePath` is the WorkspacePath of the folder's info.plist as `workspacePathOf` reads it, null when it has none;
239 * `exists` says whether that path is on disk, and `diskConnected` whether the disk that holds it is mounted.
240 */
241export type DerivedDataEntry = { name: string; workspacePath: string | null; exists: boolean; diskConnected: boolean }
242
243/** `main` is the main checkout, null when git did not name one. */
244export type RepoLayout = { main: string | null; worktrees: Worktree[] }
245
246export type DerivedDataGroup =
247 | { kind: 'main' }
248 | { kind: 'worktree'; path: string }
249 | { kind: 'other' }
250 | { kind: 'disk-not-connected' }
251 | { kind: 'orphan' }
252 | { kind: 'no-source' }
253 | { kind: 'cache' }
254
255export type DerivedDataFolder = PruneFolder & { group: DerivedDataGroup }
256
257/**
258 * Reads the stdout of `plutil -extract WorkspacePath raw`, null when plutil failed. plutil ends the value with a newline;
259 * only an absolute path counts, and its `.` and `..` segments are resolved so a prefix match cannot be fooled by them.
260 */
261export function workspacePathOf(plutilStdout: string | null): string | null {
262 if (plutilStdout === null) return null
263 const path = plutilStdout.endsWith('\n') ? plutilStdout.slice(0, -1) : plutilStdout
264 return path.startsWith('/') ? resolveAbsolute(path) : null
265}
266
267/** What `path.resolve` returns for an absolute path; a hooks module may not import `node:path`. */
268function resolveAbsolute(path: string): string {
269 const segments: string[] = []
270 for (const segment of path.split('/')) {
271 if (segment === '..') segments.pop()
272 else if (segment !== '' && segment !== '.') segments.push(segment)
273 }
274 return `/${segments.join('/')}`
275}
276
277/** The `/Volumes/<name>` folder macOS mounts a disk at, when the path is inside one. */
278export const volumeOf = (path: string): string | null => /^\/Volumes\/[^/]+(?=\/.)/.exec(path)?.[0] ?? null
279
280export type VolumeProbe = {
281 /** `/usr/bin/stat -L -f %d /Volumes/<name>` output; null when stat failed. */
282 device: string | null
283 /** `/usr/bin/stat -f %d /Volumes` output; null when stat failed. */
284 volumesDevice: string | null
285 /** The folder's real path when it is a symbolic link, else null. */
286 linkTarget: string | null
287}
288
289const deviceNumber = (statStdout: string | null): string | null => /^(\d+)\n?$/.exec(statStdout ?? '')?.[1] ?? null
290
291/**
292 * A mounted disk sits on another device than `/Volumes`; an unmount can leave an empty folder behind on the `/Volumes`
293 * device itself. The boot disk is the exception: macOS links it there to `/`, which shares the `/Volumes` device.
294 */
295export function isDiskConnected({ device, volumesDevice, linkTarget }: VolumeProbe): boolean {
296 if (linkTarget === '/') return true
297 const [own, volumes] = [deviceNumber(device), deviceNumber(volumesDevice)]
298 return own !== null && volumes !== null && own !== volumes
299}
300
301/** Groups by the folder's WorkspacePath, never its name; a workspace belongs to the linked worktree with the longest matching root, since linked worktrees can sit inside the main checkout and inside each other. */
302export function classifyDerivedData({ name, workspacePath, exists, diskConnected }: DerivedDataEntry, { main, worktrees }: RepoLayout): DerivedDataGroup {
303 if (name.endsWith('.noindex') || name === 'SDKExplicitPrecompiledModules') return { kind: 'cache' }
304 if (workspacePath === null) return { kind: 'no-source' }
305 if (!exists) return diskConnected ? { kind: 'orphan' } : { kind: 'disk-not-connected' }
306 const [worktree] = worktrees.filter(({ path }) => workspacePath.startsWith(`${path}/`)).sort((a, b) => b.path.length - a.path.length)
307 if (worktree !== undefined) return { kind: 'worktree', path: worktree.path }
308 return main !== null && workspacePath.startsWith(`${main}/`) ? { kind: 'main' } : { kind: 'other' }
309}
310
311export const isOrphan = (entry: DerivedDataEntry, layout: RepoLayout): boolean => classifyDerivedData(entry, layout).kind === 'orphan'
312
313export function isDirectChild(path: string, parent: string): boolean {
314 const name = path.startsWith(`${parent}/`) ? path.slice(parent.length + 1) : ''
315 return name !== '' && name !== '.' && name !== '..' && !name.includes('/')
316}
317
318const GROUP_ORDER: DerivedDataGroup['kind'][] = ['main', 'worktree', 'other', 'disk-not-connected', 'orphan', 'no-source', 'cache']
319
320const GROUP_LABELS = {
321 main: 'Main checkout',
322 other: 'Other location',
323 'disk-not-connected': 'Disk not connected',
324 orphan: 'Orphan',
325 'no-source': 'No source recorded',
326 cache: 'Shared caches',
327} as const
328
329const groupLabel = (group: DerivedDataGroup): string => (group.kind === 'worktree' ? `Linked worktree ${basename(group.path)}` : GROUP_LABELS[group.kind])
330
331const groupKey = (group: DerivedDataGroup): string => (group.kind === 'worktree' ? `worktree ${group.path}` : group.kind)
332
333const byGroup = (a: DerivedDataFolder, b: DerivedDataFolder): number =>
334 GROUP_ORDER.indexOf(a.group.kind) - GROUP_ORDER.indexOf(b.group.kind) ||
335 groupLabel(a.group).localeCompare(groupLabel(b.group)) ||
336 groupKey(a.group).localeCompare(groupKey(b.group))
337
338const ORPHAN_NOTE = 'An orphan was built from a project that no longer exists on disk.'
339
340const DISK_NOT_CONNECTED_NOTE = 'A folder here was built from a project on a disk that is not connected, so it is never deleted.'
341
342function groupLines(members: DerivedDataFolder[]): string[] {
343 const { group } = members[0]
344 return [
345 '',
346 `**${groupLabel(group)}** · ${gb(members)} GB in ${folderCount(members)}`,
347 '',
348 ...pruneTable(members),
349 ...(group.kind === 'disk-not-connected' ? ['', DISK_NOT_CONNECTED_NOTE] : []),
350 ]
351}
352
353export function formatDerivedData(folders: DerivedDataFolder[]): string {
354 if (folders.length === 0) return `No folders in ${DERIVED_DATA_LABEL}.`
355 const groups = new Map<string, DerivedDataFolder[]>()
356 for (const folder of [...folders].sort(byGroup)) {
357 const key = groupKey(folder.group)
358 groups.set(key, [...(groups.get(key) ?? []), folder])
359 }
360 return [
361 `**${DERIVED_DATA_LABEL}** · ${gb(folders)} GB in ${folderCount(folders)}`,
362 ...[...groups.values()].flatMap(groupLines),
363 ...(groups.has('orphan') ? ['', ORPHAN_NOTE, 'Run `/ledger:worktrees prune-orphans` to delete the orphans.'] : []),
364 ].join('\n')
365}
366
367const ORPHANS = `orphans in ${DERIVED_DATA_LABEL}`
368
369export function formatOrphanPlan(orphans: PruneFolder[]): string {
370 if (orphans.length === 0) return `Nothing to prune: no ${ORPHANS}.`
371 return [
372 `**Prune ${ORPHANS}** · dry run · ${gb(orphans)} GB in ${folderCount(orphans)}`,
373 '',
374 ...pruneTable(orphans),
375 '',
376 ORPHAN_NOTE,
377 'Run `/ledger:worktrees prune-orphans` to delete them.',
378 ].join('\n')
379}
380
381export const formatPrunedOrphans = (deleted: PruneFolder[], failures: string[]): string => formatPruned(ORPHANS, deleted, failures)
382hooks/worktrees-command.ts 279 lines1import type { EngineInterface, FsStat } from 'claude-code'
2
3import { summarize } from './ledger'
4import { sessionFolder } from './lookup'
5import {
6 basename,
7 classifyDerivedData,
8 derivedDataPrefix,
9 dirtyCount,
10 folderLabel,
11 formatDerivedData,
12 formatOrphanPlan,
13 formatPruned,
14 formatPrunedOrphans,
15 formatPrunePlan,
16 formatTable,
17 ignoredBuildFolders,
18 isDirectChild,
19 isDiskConnected,
20 isEmptyFolder,
21 isOrphan,
22 isOwnXcodeFolder,
23 ledgerRole,
24 parseCommand,
25 parseMainWorktree,
26 parsePrs,
27 parseWorktrees,
28 prLabel,
29 pruneBase,
30 realPathProblem,
31 shortDate,
32 sizeGb,
33 USAGE,
34 volumeOf,
35 workspacePathOf,
36 type DerivedDataEntry,
37 type DerivedDataFolder,
38 type PruneFolder,
39 type PruneScope,
40 type PullRequest,
41 type RepoLayout,
42 type Worktree,
43 type WorktreeRow,
44} from './worktrees'
45
46type Ran = { stdout: string; failure?: string }
47
48type PrLookup = { prs: PullRequest[] | null; error?: string }
49
50async function run($: EngineInterface, argv: string[], cwd: string): Promise<Ran> {
51 try {
52 const { exitCode, stdout, stderr } = await $.process.run(argv, { cwd })
53 return exitCode === 0 ? { stdout } : { stdout, failure: `failed (exit ${exitCode}): ${stderr.trim()}` }
54 } catch (error) {
55 return { stdout: '', failure: `did not run: ${error instanceof Error ? error.message : String(error)}` }
56 }
57}
58
59const okStdout = ({ stdout, failure }: Ran): string | null => (failure === undefined ? stdout : null)
60
61export async function lookUpPrs($: EngineInterface, branch: string, cwd: string): Promise<PrLookup> {
62 if (branch === '') return { prs: [] }
63 const { stdout, failure } = await run($, ['gh', 'pr', 'list', '--head', branch, '--state', 'all', '--json', 'state,number'], cwd)
64 if (failure !== undefined) return { prs: null, error: `gh pr list ${failure}` }
65 const prs = parsePrs(stdout)
66 return prs ? { prs } : { prs: null, error: 'gh pr list printed something that is not a JSON list' }
67}
68
69async function isFile($: EngineInterface, path: string): Promise<boolean> {
70 try {
71 return (await $.fs.stat(path)).kind === 'file'
72 } catch {
73 return false
74 }
75}
76
77async function ledgerCell($: EngineInterface, ledger: string): Promise<Pick<WorktreeRow, 'hasLedger' | 'ledgerRole'>> {
78 if (!(await isFile($, ledger))) return { hasLedger: false }
79 try {
80 const role = ledgerRole(summarize(await $.fs.read(ledger), '', 0))
81 return role === undefined ? { hasLedger: true } : { hasLedger: true, ledgerRole: role }
82 } catch {
83 return { hasLedger: true }
84 }
85}
86
87async function probe($: EngineInterface, { path, branch }: Worktree, cwd: string): Promise<{ row: WorktreeRow; prError?: string }> {
88 const [du, status, log, ledger, { prs, error }] = await Promise.all([
89 run($, ['du', '-sk', path], cwd),
90 run($, ['git', '-C', path, 'status', '--porcelain'], cwd),
91 run($, ['git', '-C', path, 'log', '-1', '--format=%cs'], cwd),
92 ledgerCell($, `${path}/.claude/ledger.md`),
93 lookUpPrs($, branch, cwd),
94 ])
95 const statusStdout = okStdout(status)
96 const logStdout = okStdout(log)
97 const row = {
98 name: basename(path),
99 // du exits non-zero when it cannot read some file, yet still prints the total of what it could.
100 sizeGb: sizeGb(du.stdout),
101 lastCommit: logStdout === null ? null : shortDate(logStdout),
102 dirty: statusStdout === null ? null : dirtyCount(statusStdout),
103 ...ledger,
104 pr: prLabel(prs),
105 }
106 return { row, prError: error }
107}
108
109async function linkedWorktrees($: EngineInterface, cwd: string): Promise<RepoLayout & { error?: string }> {
110 const list = await run($, ['git', 'worktree', 'list', '--porcelain', '-z'], cwd)
111 if (list.failure !== undefined) return { main: null, worktrees: [], error: `Could not list worktrees. git worktree list ${list.failure}` }
112 const listed = parseWorktrees(list.stdout)
113 const present = await Promise.all(listed.map(({ path }) => $.fs.exists(path)))
114 return { main: parseMainWorktree(list.stdout), worktrees: listed.filter((_, index) => present[index]) }
115}
116
117async function table($: EngineInterface, worktrees: Worktree[], cwd: string): Promise<string> {
118 const probes = await Promise.all(worktrees.map(worktree => probe($, worktree, cwd)))
119 return formatTable(
120 probes.map(({ row }) => row),
121 probes.find(({ prError }) => prError !== undefined)?.prError,
122 )
123}
124
125async function derivedDataPath($: EngineInterface): Promise<string | null> {
126 const home = await $.env.get('HOME')
127 return home?.startsWith('/') ? `${home}/Library/Developer/Xcode/DerivedData` : null
128}
129
130async function pruneScope($: EngineInterface, root: string): Promise<PruneScope> {
131 return { root, derivedData: await derivedDataPath($), prefix: await derivedDataPrefix(root) }
132}
133
134async function xcodeBuildFolders($: EngineInterface, { derivedData, prefix }: PruneScope): Promise<string[]> {
135 if (derivedData === null) return []
136 try {
137 const entries = await $.fs.list(derivedData)
138 return entries.filter(({ name, kind }) => kind === 'dir' && isOwnXcodeFolder(name, prefix)).map(({ name }) => `${derivedData}/${name}`)
139 } catch {
140 return []
141 }
142}
143
144function resolve($: EngineInterface, path: string): Promise<FsStat | undefined> {
145 return $.fs.stat(path, { resolve: true }).catch(() => undefined)
146}
147
148/** Why `rm -rf` must not touch the path, judged on where it really lands rather than how it is spelled; undefined when it may. */
149async function deletionProblem($: EngineInterface, path: string, scope: PruneScope): Promise<string | undefined> {
150 const base = pruneBase(path, scope)
151 if (base === null) return 'it is not a build folder of this worktree.'
152 const [own, allowed] = await Promise.all([resolve($, path), resolve($, base)])
153 if (own?.isLink) return 'it is a symbolic link.'
154 if (own?.realPath === undefined) return 'its real path could not be resolved.'
155 if (allowed?.realPath === undefined) return `the real path of ${base} could not be resolved.`
156 return realPathProblem(own.realPath, allowed.realPath)
157}
158
159async function deleteFolder($: EngineInterface, folder: PruneFolder, problem: string | undefined, cwd: string): Promise<string | undefined> {
160 if (problem !== undefined) return `Skipped ${folder.path}: ${problem}`
161 const { failure } = await run($, ['rm', '-rf', '--', folder.path], cwd)
162 return failure === undefined ? undefined : `Could not delete ${folder.label}: rm ${failure}`
163}
164
165async function prune($: EngineInterface, worktrees: Worktree[], name: string, dryRun: boolean, cwd: string): Promise<string> {
166 const [match, ...others] = worktrees.filter(({ path }) => basename(path) === name)
167 if (match === undefined) {
168 const names = worktrees.map(({ path }) => basename(path)).join(', ') || 'none'
169 return `No linked worktree named "${name}". Worktrees: ${names}`
170 }
171 if (others.length > 0) return `Two or more linked worktrees are named "${name}": ${[match, ...others].map(({ path }) => path).join(', ')}`
172
173 const scope = await pruneScope($, match.path)
174 const [ignored, xcodePaths] = await Promise.all([
175 run($, ['git', '-C', match.path, 'status', '--ignored', '--porcelain'], cwd),
176 xcodeBuildFolders($, scope),
177 ])
178 if (ignored.failure !== undefined) return `Could not read the ignored files of ${name}. git status ${ignored.failure}`
179 const sized = await Promise.all(
180 [...ignoredBuildFolders(ignored.stdout, match.path), ...xcodePaths].map(async path => ({
181 path,
182 label: folderLabel(path, match.path),
183 sizeGb: sizeGb((await run($, ['du', '-sk', path], cwd)).stdout),
184 })),
185 )
186 const folders = sized.filter(folder => !isEmptyFolder(folder))
187 if (dryRun || folders.length === 0) return formatPrunePlan(name, folders)
188
189 const failures = await Promise.all(folders.map(async folder => deleteFolder($, folder, await deletionProblem($, folder.path, scope), cwd)))
190 return formatPruned(
191 name,
192 folders.filter((_, index) => failures[index] === undefined),
193 failures.filter(failure => failure !== undefined),
194 )
195}
196
197async function isVolumeConnected($: EngineInterface, volume: string, cwd: string): Promise<boolean> {
198 // An absolute path, because GNU coreutils can come first on PATH, and its stat -f reports on the file system instead.
199 const [own, volumes, link] = await Promise.all([
200 run($, ['/usr/bin/stat', '-L', '-f', '%d', volume], cwd),
201 run($, ['/usr/bin/stat', '-f', '%d', '/Volumes'], cwd),
202 resolve($, volume),
203 ])
204 return isDiskConnected({ device: okStdout(own), volumesDevice: okStdout(volumes), linkTarget: link?.isLink ? (link.realPath ?? null) : null })
205}
206
207async function readDerivedDataEntry($: EngineInterface, derivedData: string, name: string, cwd: string): Promise<DerivedDataEntry> {
208 // plutil reads the binary and the XML form Xcode writes alike, and fails when the file or the key is missing.
209 const plist = await run($, ['plutil', '-extract', 'WorkspacePath', 'raw', '-o', '-', `${derivedData}/${name}/info.plist`], cwd)
210 const workspacePath = workspacePathOf(okStdout(plist))
211 if (workspacePath === null) return { name, workspacePath, exists: false, diskConnected: true }
212 const volume = volumeOf(workspacePath)
213 const [exists, diskConnected] = await Promise.all([$.fs.exists(workspacePath), volume === null || isVolumeConnected($, volume, cwd)])
214 return { name, workspacePath, exists, diskConnected }
215}
216
217async function derivedDataFolders($: EngineInterface, derivedData: string | null, layout: RepoLayout, cwd: string): Promise<DerivedDataFolder[]> {
218 if (derivedData === null) return []
219 const entries = await $.fs.list(derivedData).catch(() => [])
220 return Promise.all(
221 entries
222 .filter(({ kind }) => kind === 'dir')
223 .map(async ({ name }) => {
224 const path = `${derivedData}/${name}`
225 const [entry, du] = await Promise.all([readDerivedDataEntry($, derivedData, name, cwd), run($, ['du', '-sk', path], cwd)])
226 return { path, label: name, sizeGb: sizeGb(du.stdout), group: classifyDerivedData(entry, layout) }
227 }),
228 )
229}
230
231async function derivedDataReport($: EngineInterface, layout: RepoLayout, cwd: string): Promise<string> {
232 return formatDerivedData(await derivedDataFolders($, await derivedDataPath($), layout, cwd))
233}
234
235/** Why `rm -rf` must not touch the folder: it must really be a folder directly inside DerivedData, and still be an orphan now; undefined when it may. */
236async function orphanDeletionProblem($: EngineInterface, path: string, derivedData: string, layout: RepoLayout, cwd: string): Promise<string | undefined> {
237 if (!isDirectChild(path, derivedData)) return `it is not directly inside ${derivedData}.`
238 const [own, allowed] = await Promise.all([resolve($, path), resolve($, derivedData)])
239 if (own?.isLink) return 'it is a symbolic link.'
240 if (own?.realPath === undefined) return 'its real path could not be resolved.'
241 if (allowed?.realPath === undefined) return `the real path of ${derivedData} could not be resolved.`
242 if (!isDirectChild(own.realPath, allowed.realPath)) return `it resolves to ${own.realPath}, which is not directly inside ${allowed.realPath}.`
243 const entry = await readDerivedDataEntry($, derivedData, basename(path), cwd)
244 return isOrphan(entry, layout) ? undefined : 'it is no longer an orphan.'
245}
246
247async function pruneOrphans($: EngineInterface, layout: RepoLayout, dryRun: boolean, cwd: string): Promise<string> {
248 const derivedData = await derivedDataPath($)
249 const orphans = (await derivedDataFolders($, derivedData, layout, cwd)).filter(({ group }) => group.kind === 'orphan')
250 if (dryRun || derivedData === null || orphans.length === 0) return formatOrphanPlan(orphans)
251
252 const failures = await Promise.all(
253 orphans.map(async folder => deleteFolder($, folder, await orphanDeletionProblem($, folder.path, derivedData, layout, cwd), cwd)),
254 )
255 return formatPrunedOrphans(
256 orphans.filter((_, index) => failures[index] === undefined),
257 failures.filter(failure => failure !== undefined),
258 )
259}
260
261/** The text /ledger:worktrees answers with for the arguments the operator typed. */
262export async function worktreesCommand($: EngineInterface, args: string): Promise<string> {
263 const command = parseCommand(args)
264 if (command.kind === 'usage') return USAGE
265 const { path: cwd } = await sessionFolder($)
266 const { error, ...layout } = await linkedWorktrees($, cwd)
267 if (error !== undefined) return error
268 switch (command.kind) {
269 case 'table':
270 return table($, layout.worktrees, cwd)
271 case 'prune':
272 return prune($, layout.worktrees, command.name, command.dryRun, cwd)
273 case 'derived-data':
274 return derivedDataReport($, layout, cwd)
275 case 'prune-orphans':
276 return pruneOrphans($, layout, command.dryRun, cwd)
277 }
278}
279