A status line naming the session's loom role and the members beside it, plus guards that keep an owner inside its own worktree and ask before a removal loses…

A Claude Code mod for sessions that follow the loom skill. It names the session's role in the status line under the prompt, lists the members beside it, and turns the skill's rules into guards. The skill is unchanged; without the mod, loom works as before.
The name is historical. The mod once drew a pane of the repo's worktrees; the pane is gone, and the name stays because enabledPlugins on every machine keys on it.
At session.start the mod runs git rev-parse --show-toplevel and --git-common-dir; the canonical checkout is the parent of the common git dir. The first main-loop turn after /clear, an in-process /resume or an update from an older version runs them again. It knows those turns by a session id the state doesn't hold. It then reads git worktree list --porcelain from the canonical checkout, once, for the paths the guards judge by, and reads it again when the session claims a worktree. Nothing polls git on a timer. The role follows from there:
~/.worktrees/<repo>/<slug>, or a Bash command in the main loop enters one (cd ~/.worktrees/<repo>/<slug>, git worktree add ~/.worktrees/<repo>/<slug> ...) and runs; a command that a guard, belt or the person denies claims nothing. The skill's own flow claims from the canonical checkout and commits with cd <worktree> && git commit, so this is how the role usually turns up. The status line reads owner <slug>./loom weave was typed, run as the skill, or sent as a slash command, in any checkout of the repo. A weaver stays a weaver when it cds into a worktree to rebase. The line reads weaver · 3 worktrees, counting the linked worktrees git listed.The engine prefixes a plugin's status line with its name, so on screen the line reads loom-pane: owner feat-pane; the text itself never repeats the name.
After the role, the line lists who works beside this session, each as name, role, worktree, model and effort, with a session's state after them: weaver · 3 worktrees · members w1 (owner, agent-a1b2, -, -), band fixer (owner, fix-band, -, -) blocked. With no role the members stand alone; with neither the line is cleared.
~/.worktrees/<repo>/<slug>) or an isolation worktree (.claude/worktrees/agent-<id>). Then each session claude agents --json --all lists in such a worktree, unless it is done or is this session. A plain named teammate is not a member.owner, for an agent or session in a worktree. This session's own role, owner or weaver, is the part before members.worktree tag of the agent's newest subagent-start entry in belt's ledger. That tag comes from the hook payload's cwd, which can be the parent's, so it never counts when it names this session's own worktree. For a session, the worktree its cwd is in.model and effort tags of the agent's newest subagent-start entry, never the agent type. belt 2.9.0 and later tag both when ledger.agent_types in its config maps the agent's type. Its keys end in *, because a named spawn reports its name as its agent type. An unmapped agent shows dashes.A field no source recorded shows -. The line is read again at session start, after a spawn starts its agent, and when a main-loop turn ends. Only one refresh runs at a time and none starts within 5 s of the last; one trailing refresh at the 5 s mark catches up whatever was skipped. claude agents and the events service (localhost:7430, source belt-ledger) get 400 ms each. A source that fails, refuses or runs out of time reads as empty, so the line falls back to the role alone and never errors. With members off nothing is probed, and members stored earlier are dropped at the next session start.
Active while guards is on (the default), and only for the main loop: a tool call with an agentId (a subagent, which owns its own isolation worktree) passes untouched.
Write and Edit on a path under the canonical checkout or under any other worktree of the repo are denied. Other worktrees mean the ~/.worktrees/<repo>/* layout and nested ones such as .claude/worktrees/*. The reason reads loom-pane: <path> belongs to the canonical checkout; owners edit only their own worktree. The path is normalized first, so .. doesn't slip through. Its own worktree and paths outside the repo are allowed.Bash command is read for cd (a subshell's cd ends with it), git -C <path> and redirections. A mutating git verb acting in the canonical checkout or another worktree, or a > into one, is denied the same way. Mutating verbs: commit, add, checkout, switch, reset, rebase, merge, push, rm, mv, restore, stash (except stash list and stash show), cherry-pick, revert, clean, pull, apply, am. Path operands count for add, rm, mv, checkout, restore and clean only; -m and -F values never do. command git, time git and /usr/bin/git read as git.git worktree remove <path> asks only for a forced removal of a dirty tree, or a detached head with commits ahead of the default branch. Git itself refuses a dirty tree without --force, and a merged branch's tree is a clean teardown. git branch -D <name> asks only when the branch's commits exist nowhere else, or its worktree is dirty. Nowhere else means ahead of the default branch, not on origin/<name> (or with no upstream at all), and not integrated. Integrated means a merged tree equal to the default branch's tree (git merge-tree --write-tree, git 2.38 or later), so a squash-merged branch goes without a question. A failed or conflicting merge-tree still asks. The dialog reads <target> has 2 unmerged commits and uncommitted changes. Remove anyway? with Proceed and Cancel; Cancel denies. A dismissed dialog denies too in an interactive session; headless (-p) nobody can be asked and the call passes. A branch of some other repo (git -C /elsewhere branch -D x) isn't judged.Weaver and none sessions get no edit guards.
A guard that can't be sure lets the call through. A command with a substitution, a heredoc, a variable in a path, bash -c, sudo, xargs, GIT_DIR= or GIT_WORK_TREE=, or an unbalanced quote isn't parsed and passes. A guard that throws or outruns its 10 s budget logs one debug line and passes. Writes the parser doesn't see: cp, mv, rm, tee, sed -i, python3 -c, and NotebookEdit. Path checks compare spellings, not inodes, so a symlinked spelling into the canonical checkout slips by. belt remains the fail-closed guard; this mod is a second opinion on top of it.
| Field | Type | Default | Meaning |
|---|---|---|---|
guards | boolean | true | run the three guards above |
members | boolean | true | list the members beside the role |
claude --plugin-dir mods/loom-pane # from a checkout; a save hot-reloads
claude plugin validate mods/loom-pane # what the engine would refuse
node --test mods/loom-pane/test/*.test.mjs # the parsers, the member line and the status text in lib/
claude plugin test mods/loom-pane # the guards and the member line against the engine's test kit
The engine writes .claude-plugin/types/ beside the mod on load; npx -p typescript tsc -p mods/loom-pane type-checks against it.
hooks/register.tsx 467 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { LoomPaneMember, LoomPaneRole } from '../types'
5import {
6 AGENTS_ARGV,
7 GIT_BUDGET_MS,
8 LEDGER_URL,
9 PROBE_BUDGET_MS,
10 analyzeBash,
11 classifyPath,
12 composeStatus,
13 denyReason,
14 detectLayout,
15 isIntegratedTree,
16 isLive,
17 isRefreshDue,
18 isWeaveArgs,
19 loomArgsOf,
20 membersFrom,
21 mergeTreeArgs,
22 ownerClaimFrom,
23 parseCount,
24 parseDefaultRef,
25 parseLedger,
26 parseSessions,
27 parseWorktreeList,
28 removalQuestion,
29 resolvePath,
30 shouldAskBranchDeletion,
31 shouldAskWorktreeRemoval,
32 statusText,
33 trailingDelay,
34 worktreeAt,
35 worktreeOfBranch,
36} from '../lib/loom'
37import type { AgentLike, Layout, LedgerFacts, Removal, WorktreeEntry } from '../lib/loom'
38
39const role = atom({ plugin: 'loom-pane', key: 'role' } as const, 'none' as LoomPaneRole)
40const canonical = atom({ plugin: 'loom-pane', key: 'canonical' } as const, null as string | null)
41const ownWorktree = atom({ plugin: 'loom-pane', key: 'ownWorktree' } as const, null as string | null)
42const worktreeRoot = atom({ plugin: 'loom-pane', key: 'worktreeRoot' } as const, null as string | null)
43const worktrees = atom({ plugin: 'loom-pane', key: 'worktrees' } as const, [] as string[])
44const repo = atom({ plugin: 'loom-pane', key: 'repo' } as const, null as string | null)
45const weaveSeen = atom({ plugin: 'loom-pane', key: 'weaveSeen' } as const, false)
46const isInteractive = atom({ plugin: 'loom-pane', key: 'isInteractive' } as const, false)
47const members = atom({ plugin: 'loom-pane', key: 'members' } as const, [] as LoomPaneMember[])
48// The session the role was last detected for. `/clear` puts it back to null
49// and a state from before the key existed reads null too, so either way the
50// next main-loop turn detects again.
51const detectedSession = atom({ plugin: 'loom-pane', key: 'sessionId' } as const, null as string | null)
52
53type Logger = { ui: { log: (text: string, options: { to: 'debug' }) => void } }
54type Failed<E, R> = ((e: E) => R) & { event: string; error: { kind: string; message?: string } }
55
56// The one .catch every hook below carries: say why in the debug log, then
57// let the chain beneath answer as if the hook were absent. A guard that
58// throws or times out lets the call through; belt stays the fail-closed one.
59const skipOnFailure = <E, R>($: Logger, e: E, next: Failed<E, R>): R => {
60 const why = next.error.message === undefined ? next.error.kind : `${next.error.kind}: ${next.error.message}`
61 $.ui.log(`loom-pane: ${next.event} skipped (${why})`, { to: 'debug' })
62 return next(e)
63}
64
65// One git call under the budget: its stdout, or null when it failed, exited
66// non-zero or outran the budget (the run rejects then). Never throws.
67async function git($: EngineInterface, args: readonly string[], cwd: string): Promise<string | null> {
68 try {
69 const ran = await $.process.run(['git', ...args], { cwd, timeoutMs: GIT_BUDGET_MS })
70 return ran.exitCode === 0 ? ran.stdout : null
71 } catch {
72 return null
73 }
74}
75
76async function layoutOf($: EngineInterface): Promise<Layout> {
77 return {
78 canonical: await read($, canonical),
79 ownWorktree: await read($, ownWorktree),
80 worktreeRoot: await read($, worktreeRoot),
81 worktrees: await read($, worktrees),
82 }
83}
84
85async function showStatus($: EngineInterface): Promise<void> {
86 $.ui.status(composeStatus(statusText(await read($, role), await layoutOf($)), await read($, members)))
87}
88
89// This session's agents, or none when the engine cannot list them.
90async function listAgents($: EngineInterface): Promise<AgentLike[]> {
91 try {
92 return await $.agent.list()
93 } catch {
94 return []
95 }
96}
97
98async function sessionId($: EngineInterface): Promise<string | null> {
99 try {
100 return await $.session.id()
101 } catch {
102 return null
103 }
104}
105
106// What `work` answers, or null when it fails or the 400 ms probe budget
107// runs out first.
108async function withinBudget<T>($: EngineInterface, work: Promise<T | null>): Promise<T | null> {
109 const timedOut = $.clock
110 .sleep(PROBE_BUDGET_MS)
111 .then(() => null)
112 .catch(() => null)
113 return Promise.race([work.catch(() => null), timedOut])
114}
115
116// The engine's session list, or null when `claude` is missing, fails or
117// outruns the budget (the child is killed at the same budget).
118async function listSessions($: EngineInterface): Promise<string | null> {
119 const ran = $.process
120 .run(AGENTS_ARGV, { timeoutMs: PROBE_BUDGET_MS })
121 .then(result => (result.exitCode === 0 ? result.stdout : null))
122 return withinBudget($, ran)
123}
124
125// belt's subagent-start entries from the events service, or null when it
126// is down, answers an error or outruns the budget.
127async function fetchLedger($: EngineInterface): Promise<string | null> {
128 const fetched = $.http.fetch(LEDGER_URL).then(response => (response.ok ? response.text : null))
129 return withinBudget($, fetched)
130}
131
132// The member refresh throttle: one refresh at a time, and none within
133// MEMBERS_REFRESH_GAP_MS of the last one's start, so a chatty session never
134// queues probes. A refresh the throttle skips marks the line stale, and one
135// trailing refresh at the gap boundary catches it up; further skips fold
136// into that one. Module variables, so a hot reload starts it over (and
137// cancels the timer), which costs one extra refresh at most.
138let isRefreshing = false
139let isStale = false
140let isTrailingScheduled = false
141let lastRefreshAt: number | null = null
142
143const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))
144
145// Re-reads who works beside this session, unless the throttle says no.
146// Nothing here throws.
147async function refreshMembers($: EngineInterface): Promise<void> {
148 if (isRefreshing) {
149 isStale = true
150 return
151 }
152 isRefreshing = true
153 let now: number | null = null
154 try {
155 now = await $.clock.now()
156 if (!isRefreshDue(now, lastRefreshAt)) {
157 isStale = true
158 return
159 }
160 lastRefreshAt = now
161 isStale = false
162 await readMembers($)
163 } catch (err) {
164 $.ui.log(`loom-pane: members not refreshed (${errorText(err)})`, { to: 'debug' })
165 } finally {
166 isRefreshing = false
167 if (isStale && now !== null) scheduleTrailing($, now)
168 }
169}
170
171// Schedules the one trailing refresh at the gap boundary, unless one is
172// already waiting.
173function scheduleTrailing($: EngineInterface, now: number): void {
174 if (isTrailingScheduled) return
175 isTrailingScheduled = true
176 try {
177 $.clock.after(trailingDelay(now, lastRefreshAt), () => {
178 isTrailingScheduled = false
179 void refreshMembers($)
180 })
181 } catch (err) {
182 isTrailingScheduled = false
183 $.ui.log(`loom-pane: trailing refresh not scheduled (${errorText(err)})`, { to: 'debug' })
184 }
185}
186
187// Asks every source, stores the members and pins the status line again.
188// Every source that fails reads as empty, so the line degrades to the role
189// alone.
190async function readMembers($: EngineInterface): Promise<void> {
191 const layout = await layoutOf($)
192 const agents = layout.canonical === null ? [] : await listAgents($)
193 const hasLinked = layout.worktrees.some(path => path !== layout.canonical)
194 const sessions = hasLinked ? parseSessions(await listSessions($)) : []
195 const ledger: Map<string, LedgerFacts> = agents.some(isLive) ? parseLedger(await fetchLedger($)) : new Map()
196 const found = membersFrom({ agents, sessions, ledger, layout, selfSessionId: await sessionId($) })
197 await update($, members, () => found)
198 await showStatus($)
199}
200
201async function listWorktrees($: EngineInterface, canon: string): Promise<WorktreeEntry[] | null> {
202 const listed = await git($, ['worktree', 'list', '--porcelain'], canon)
203 return listed === null ? null : parseWorktreeList(listed).filter(entry => !entry.isBare)
204}
205
206// Re-reads the worktree list and stores the paths the guards judge by. Runs
207// when the role is detected and when the session claims a worktree, never
208// on a timer. A failed list keeps the paths already known.
209async function refreshWorktrees($: EngineInterface): Promise<void> {
210 const canon = await read($, canonical)
211 if (canon === null) {
212 await update($, worktrees, () => [])
213 return
214 }
215 const entries = await listWorktrees($, canon)
216 if (entries === null) {
217 $.ui.log('loom-pane: worktree list failed', { to: 'debug' })
218 return
219 }
220 await update($, worktrees, () => entries.map(entry => entry.path))
221}
222
223// Finds the repo around `cwd` and the session's role in its loom, writes
224// both to the state and pins the status line.
225async function detect($: EngineInterface, cwd: string): Promise<void> {
226 const toplevel = await git($, ['rev-parse', '--show-toplevel'], cwd)
227 let commonDir: string | null = null
228 if (toplevel !== null) {
229 // --path-format=absolute needs git 2.31; older gits answer the plain
230 // form, relative to cwd, which detectLayout resolves.
231 commonDir =
232 (await git($, ['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd)) ??
233 (await git($, ['rev-parse', '--git-common-dir'], cwd))
234 }
235 const home = await $.env.get('HOME')
236 const found = detectLayout({
237 cwd,
238 toplevel,
239 commonDir,
240 home: home ?? null,
241 weaveSeen: await read($, weaveSeen),
242 })
243 await update($, canonical, () => found.canonical)
244 await update($, ownWorktree, () => found.ownWorktree)
245 await update($, worktreeRoot, () => found.worktreeRoot)
246 await update($, repo, () => found.repo)
247 await update($, role, () => found.role)
248 await refreshWorktrees($)
249 await showStatus($)
250 $.ui.log(
251 found.canonical === null
252 ? `loom-pane: no git repo at ${cwd}`
253 : `loom-pane: repo ${found.repo} canonical ${found.canonical} role ${found.role}`,
254 { to: 'debug' },
255 )
256}
257
258// Detects the role for session `id` in `cwd` and records the id, dropping
259// stored members first when the listing is off.
260async function redetect($: EngineInterface, cwd: string, id: string | null, isListing: boolean): Promise<void> {
261 if (!isListing) await update($, members, () => [])
262 await detect($, cwd)
263 await update($, detectedSession, () => id)
264 if (isListing) await refreshMembers($)
265}
266
267// A Bash command that enters a worktree of the loom layout, by `cd` or by
268// `git worktree add`, makes this session its owner; a weaver stays a weaver.
269async function claimOwner($: EngineInterface, claims: readonly string[]): Promise<void> {
270 if (await read($, weaveSeen)) return
271 const claimed = ownerClaimFrom(claims, await read($, worktreeRoot))
272 if (claimed === null || claimed === (await read($, ownWorktree))) return
273 await update($, ownWorktree, () => claimed)
274 await update($, role, () => 'owner')
275 await refreshWorktrees($)
276 await showStatus($)
277 $.ui.log(`loom-pane: owner of ${claimed}`, { to: 'debug' })
278}
279
280async function markWeave($: EngineInterface, cwd: string): Promise<void> {
281 await update($, weaveSeen, () => true)
282 await detect($, cwd)
283}
284
285// Asks before a removal that would lose work. A dismissed dialog keeps the
286// target in an interactive session; headless (`-p`), nobody can be asked and
287// the removal goes ahead.
288async function askToRemove($: EngineInterface, label: string, ahead: number | null, isDirty: boolean): Promise<boolean> {
289 try {
290 const answer = await $.ui.ask(removalQuestion(label, ahead, isDirty), ['Proceed', 'Cancel'])
291 return answer === 'Proceed'
292 } catch (err) {
293 const interactive = await read($, isInteractive)
294 $.ui.log(`loom-pane: removal dialog closed (${err instanceof Error ? err.message : String(err)}); ${interactive ? 'kept' : 'headless, allowed'}`, { to: 'debug' })
295 return !interactive
296 }
297}
298
299// True when the removal may go ahead: nothing would be lost, or the person
300// chose Proceed. A git call that fails reads as nothing at risk.
301async function confirmRemoval(
302 $: EngineInterface,
303 removal: Removal,
304 entries: readonly WorktreeEntry[],
305 defaultRef: string,
306): Promise<boolean> {
307 if (removal.kind === 'worktree') {
308 const entry = worktreeAt(entries, removal.path)
309 const status = removal.isForce ? await git($, ['status', '--porcelain'], removal.path) : null
310 const isDirty = status !== null && status.trim() !== ''
311 const isDetached = entry?.isDetached === true
312 const ahead = isDetached ? parseCount(await git($, ['rev-list', '--count', `${defaultRef}..HEAD`], removal.path)) : null
313 if (!shouldAskWorktreeRemoval({ isForce: removal.isForce, isDirty, isDetached, ahead })) return true
314 return askToRemove($, removal.path, ahead, isDirty)
315 }
316 const linked = worktreeOfBranch(entries, removal.name)
317 // One round, all at once: run one after another behind the worktree
318 // listing and the default ref, these calls could outlast the engine's
319 // 10 s hook limit, and a skipped hook lets the delete through.
320 const [status, aheadOut, remoteAheadOut, isIntegrated] = await Promise.all([
321 linked === null ? null : git($, ['status', '--porcelain'], linked.path),
322 git($, ['rev-list', '--count', `${defaultRef}..${removal.name}`], removal.location),
323 git($, ['rev-list', '--count', `origin/${removal.name}..${removal.name}`], removal.location),
324 isIntegratedBranch($, removal.name, removal.location, defaultRef),
325 ])
326 const isWorktreeDirty = status !== null && status.trim() !== ''
327 const ahead = parseCount(aheadOut)
328 const remoteAhead = parseCount(remoteAheadOut)
329 if (!shouldAskBranchDeletion({ ahead, remoteAhead, isIntegrated, isWorktreeDirty })) return true
330 return askToRemove($, removal.name, ahead, isWorktreeDirty)
331}
332
333// True when the default branch already holds the branch's changes: a merge
334// would write the default branch's own tree. Unlike the counts beside it, a
335// failure here (git before 2.38, a conflict, a call past its budget) keeps
336// the question.
337async function isIntegratedBranch($: EngineInterface, branch: string, cwd: string, defaultRef: string): Promise<boolean> {
338 const [merged, tree] = await Promise.all([
339 git($, mergeTreeArgs(defaultRef, branch), cwd),
340 git($, ['rev-parse', `${defaultRef}^{tree}`], cwd),
341 ])
342 return isIntegratedTree(merged, tree)
343}
344
345export const register: Register = (on, options) => {
346 const isGuarding = options.guards !== false
347 const isListing = options.members !== false
348
349 // A session start (a hot reload after `members` was switched off included)
350 // drops members a past refresh left in the state, so the line never shows
351 // them with the listing off.
352 on('session.start', async ($, e, next) => {
353 const started = await next(e)
354 $.ui.log('loom-pane: loaded', { to: 'debug' })
355 await update($, isInteractive, () => e.isInteractive)
356 await redetect($, e.cwd, await sessionId($), isListing)
357 return started
358 }).catch(skipOnFailure)
359
360 // `/clear` puts the state back to its defaults and an in-process `/resume`
361 // switches sessions; neither raises session.start, and a plugin seated
362 // above this one can skip classic.SessionStart. So the first main-loop turn
363 // whose session id the state does not hold detects again, before the
364 // turn's first model call and so before any of its tools run.
365 on('turn.start', async ($, e, next) => {
366 if (e.agentId === undefined) {
367 const id = await sessionId($)
368 if (id !== (await read($, detectedSession))) await redetect($, await $.session.cwd(), id, isListing)
369 }
370 return next(e)
371 }).catch(skipOnFailure)
372
373 // The member line follows the agents: re-read once a spawn has started
374 // its agent, and when a main-loop turn ends (a member reported, stopped
375 // or went idle). Observers only; the results pass on unchanged.
376 on('agent.spawn', async ($, e, next) => {
377 const spawned = await next(e)
378 if (isListing) await refreshMembers($)
379 return spawned
380 }).catch(skipOnFailure)
381
382 on('turn.complete', async ($, e, next) => {
383 const completed = await next(e)
384 if (isListing && e.agentId === undefined) await refreshMembers($)
385 return completed
386 }).catch(skipOnFailure)
387
388 // `/loom weave`, typed at the prompt or run as the skill, makes a session
389 // of this repo the weaver. The skill runs as it always did; this only
390 // watches.
391 on('prompt.submit', { text: /^\/loom\b/ }, async ($, e, next) => {
392 const args = loomArgsOf(e.text)
393 if (args !== null && isWeaveArgs(args)) await markWeave($, await $.session.cwd())
394 return next(e)
395 }).catch(skipOnFailure)
396
397 on('command.run', { command: 'loom' }, async ($, e, next) => {
398 if (isWeaveArgs(e.args)) await markWeave($, await $.session.cwd())
399 return next(e)
400 }).catch(skipOnFailure)
401
402 on('tool.call', { tool: 'Skill', skill: 'loom' }, async ($, e, next) => {
403 if (e.agentId === undefined && isWeaveArgs(e.args ?? '')) await markWeave($, await $.session.cwd())
404 return next(e)
405 }).catch(skipOnFailure)
406
407 // Owner guards, main loop only: an owner edits its own worktree and nothing
408 // else of the repo. Paths outside the repo are none of the loom's business,
409 // and a subagent in an isolation worktree is its own owner.
410 on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {
411 if (!isGuarding || e.agentId !== undefined || (await read($, role)) !== 'owner') return next(e)
412 const home = await $.env.get('HOME')
413 const path = resolvePath(e.file_path, await $.session.cwd(), home ?? null)
414 if (path === null) return next(e)
415 const cls = classifyPath(path, await layoutOf($))
416 if (cls === 'canonical' || cls === 'other') return { deny: denyReason(path, cls) }
417 return next(e)
418 }).catch(skipOnFailure)
419
420 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
421 if (e.agentId !== undefined) return next(e)
422 const home = await $.env.get('HOME')
423 const analysis = analyzeBash(e.command, { cwd: await $.session.cwd(), home: home ?? null })
424 if (analysis.isUncertain) return next(e)
425 if (isGuarding && (await read($, role)) === 'owner') {
426 const layout = await layoutOf($)
427 for (const path of analysis.writes) {
428 const cls = classifyPath(path, layout)
429 if (cls === 'canonical' || cls === 'other') return { deny: denyReason(path, cls) }
430 }
431 }
432 // A claim counts once the command ran: a call this guard, belt or the
433 // person denied leaves the role where it was. A failure from here on is
434 // logged, never handed to .catch, which would run the command again.
435 const ran = await next(e)
436 if (ran.deny !== undefined || ran.isError === true) return ran
437 try {
438 await claimOwner($, analysis.claims)
439 } catch (err) {
440 $.ui.log(`loom-pane: claim not recorded (${errorText(err)})`, { to: 'debug' })
441 }
442 return ran
443 }).catch(skipOnFailure)
444
445 // Any role, main loop only: a force-delete or worktree removal that would
446 // lose commits or uncommitted changes asks first. Cancel denies the call.
447 on('tool.call', { tool: 'Bash', command: /\bgit\b[\s\S]*\b(branch|worktree)\b/ }, async ($, e, next) => {
448 if (!isGuarding || e.agentId !== undefined) return next(e)
449 const canon = await read($, canonical)
450 if (canon === null) return next(e)
451 const home = await $.env.get('HOME')
452 const analysis = analyzeBash(e.command, { cwd: await $.session.cwd(), home: home ?? null })
453 if (analysis.isUncertain || analysis.removals.length === 0) return next(e)
454 const layout = await layoutOf($)
455 const entries = (await listWorktrees($, canon)) ?? []
456 const defaultRef = parseDefaultRef(await git($, ['symbolic-ref', 'refs/remotes/origin/HEAD'], canon))
457 for (const removal of analysis.removals) {
458 // A branch of some other repo is not this loom's to judge.
459 if (removal.kind === 'branch' && classifyPath(removal.location, layout) === 'outside') continue
460 if (await confirmRemoval($, removal, entries, defaultRef)) continue
461 const label = removal.kind === 'branch' ? removal.name : removal.path
462 return { deny: `loom-pane: ${label} kept; the removal was not confirmed` }
463 }
464 return next(e)
465 }).catch(skipOnFailure)
466}
467lib/loom.ts 949 lines1// Pure helpers behind the loom-pane mod: no `$`, no I/O, so `node --test`
2// covers them without the engine. register.tsx is the only caller.
3
4export type Role = 'owner' | 'weaver' | 'none'
5
6/** One entry of `git worktree list --porcelain`. */
7export type WorktreeEntry = {
8 path: string
9 head: string | null
10 branch: string | null
11 isBare: boolean
12 isDetached: boolean
13}
14
15/** Where the repo's checkouts are, as far as the mod knows. */
16export type Layout = {
17 canonical: string | null
18 ownWorktree: string | null
19 worktreeRoot: string | null
20 /** Every worktree path git listed, nested ones under the canonical checkout included. */
21 worktrees: readonly string[]
22}
23
24export type PathClass = 'own' | 'canonical' | 'other' | 'outside'
25
26export type Detected = Omit<Layout, 'worktrees'> & { repo: string | null; role: Role }
27
28/** How long one git call may take. */
29export const GIT_BUDGET_MS = 2_000
30
31/** The ref the ahead count compares against when origin names no HEAD. */
32export const DEFAULT_BRANCH = 'main'
33
34// The git verbs that change a working tree, its index or its refs. The loom
35// skill's list, plus the verbs that do the same under another name.
36const MUTATING_GIT_VERBS = new Set([
37 'commit',
38 'add',
39 'checkout',
40 'switch',
41 'reset',
42 'rebase',
43 'merge',
44 'push',
45 'rm',
46 'mv',
47 'restore',
48 'stash',
49 'cherry-pick',
50 'revert',
51 'clean',
52 'pull',
53 'apply',
54 'am',
55])
56
57// The verbs whose path operands name what they change; the others take
58// messages, refs and patch files, whose spelling says nothing about writes.
59const OPERAND_VERBS = new Set(['add', 'rm', 'mv', 'checkout', 'restore', 'clean'])
60
61// Flags that take the next word as a value, so that word is not a path.
62const VALUE_FLAGS = new Set(['-m', '-F', '--message', '--file', '-b', '-B', '--reason', '-C'])
63
64// Commands that run another command the tokenizer cannot see into.
65const OPAQUE_COMMANDS = new Set(['sh', 'bash', 'zsh', 'eval', 'exec', 'xargs', 'sudo', 'env', 'popd'])
66
67// Prefixes that run the command after them unchanged.
68const PASSTHROUGH_COMMANDS = new Set(['command', 'time'])
69
70const CONTROL_OPS = new Set(['&&', '||', ';', ';;', '|', '|&', '&', '\n'])
71
72const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)=/
73
74const GIT_ENV = new Set(['GIT_DIR', 'GIT_WORK_TREE', 'GIT_COMMON_DIR', 'GIT_INDEX_FILE'])
75
76function trimSlash(path: string): string {
77 const trimmed = path.replace(/\/+$/, '')
78 return trimmed === '' ? '/' : trimmed
79}
80
81/** Collapses `.`, `..` and repeated slashes in an absolute path. */
82export function normalizePath(path: string): string {
83 const parts: string[] = []
84 for (const part of path.split('/')) {
85 if (part === '' || part === '.') continue
86 if (part === '..') {
87 parts.pop()
88 continue
89 }
90 parts.push(part)
91 }
92 return `/${parts.join('/')}`
93}
94
95export function baseName(path: string): string {
96 const parts = trimSlash(path).split('/')
97 return parts[parts.length - 1] ?? ''
98}
99
100export function dirName(path: string): string {
101 const trimmed = trimSlash(path)
102 const cut = trimmed.lastIndexOf('/')
103 return cut <= 0 ? '/' : trimmed.slice(0, cut)
104}
105
106function isSamePath(a: string | null, b: string | null): boolean {
107 return a !== null && b !== null && trimSlash(a) === trimSlash(b)
108}
109
110/** True when `path` is `root` or lies below it, by spelling (not by inode). */
111export function isUnder(path: string, root: string): boolean {
112 const p = trimSlash(path)
113 const r = trimSlash(root)
114 return p === r || p.startsWith(r === '/' ? '/' : `${r}/`)
115}
116
117/**
118 * The absolute path a shell word names, or null when it cannot be known
119 * without running the shell: a variable or substitution, `~user`, `-`, or
120 * `~` with no home.
121 */
122export function resolvePath(word: string, cwd: string, home: string | null): string | null {
123 if (word === '' || word === '-' || /[$`]/.test(word)) return null
124 if (word.startsWith('/')) return normalizePath(word)
125 if (word === '~' || word.startsWith('~/')) {
126 return home === null ? null : normalizePath(`${home}${word.slice(1)}`)
127 }
128 if (word.startsWith('~')) return null
129 return normalizePath(`${cwd}/${word}`)
130}
131
132/**
133 * Which checkout a path falls in: the longest root that holds it wins, so a
134 * worktree nested under the canonical checkout counts as a worktree and the
135 * own worktree wins over the `~/.worktrees/<repo>` root above it.
136 */
137export function classifyPath(path: string, layout: Layout): PathClass {
138 const roots: Array<{ root: string; cls: PathClass }> = []
139 if (layout.ownWorktree !== null) roots.push({ root: layout.ownWorktree, cls: 'own' })
140 if (layout.canonical !== null) roots.push({ root: layout.canonical, cls: 'canonical' })
141 if (layout.worktreeRoot !== null) roots.push({ root: layout.worktreeRoot, cls: 'other' })
142 for (const worktree of layout.worktrees) {
143 const cls: PathClass = isSamePath(worktree, layout.ownWorktree)
144 ? 'own'
145 : isSamePath(worktree, layout.canonical)
146 ? 'canonical'
147 : 'other'
148 roots.push({ root: worktree, cls })
149 }
150 let best: { root: string; cls: PathClass } | null = null
151 for (const candidate of roots) {
152 if (!isUnder(path, candidate.root)) continue
153 if (best === null || trimSlash(candidate.root).length > trimSlash(best.root).length) best = candidate
154 }
155 return best === null ? 'outside' : best.cls
156}
157
158export function denyReason(path: string, cls: 'canonical' | 'other'): string {
159 const holder = cls === 'canonical' ? 'the canonical checkout' : 'another worktree'
160 return `loom-pane: ${path} belongs to ${holder}; owners edit only their own worktree`
161}
162
163/**
164 * The canonical checkout behind `git rev-parse --git-common-dir`: the parent
165 * of the common git dir, which git prints relative to `cwd` from the main
166 * worktree and absolute from a linked one.
167 */
168export function canonicalFrom(commonDir: string | null, cwd: string): string | null {
169 const trimmed = commonDir?.trim() ?? ''
170 if (trimmed === '') return null
171 const absolute = trimmed.startsWith('/') ? normalizePath(trimmed) : normalizePath(`${cwd}/${trimmed}`)
172 return dirName(absolute)
173}
174
175/** `~/.worktrees/<repo>`, the loom's layout for one repo. */
176export function worktreeRootFor(home: string | null, repo: string): string | null {
177 return home === null || home === '' ? null : `${trimSlash(home)}/.worktrees/${repo}`
178}
179
180/**
181 * The worktree a path claims in the loom layout: `~/.worktrees/<repo>/<slug>`
182 * for a path at or below it, null for anything else.
183 */
184export function worktreeClaimedBy(path: string, worktreeRoot: string | null): string | null {
185 if (worktreeRoot === null) return null
186 const root = trimSlash(worktreeRoot)
187 const candidate = trimSlash(path)
188 if (candidate === root || !isUnder(candidate, root)) return null
189 const slug = candidate.slice(root.length + 1).split('/')[0] ?? ''
190 return slug === '' ? null : `${root}/${slug}`
191}
192
193/** The first worktree a command's `cd` or `git worktree add` claims in the layout. */
194export function ownerClaimFrom(claims: readonly string[], worktreeRoot: string | null): string | null {
195 for (const claim of claims) {
196 const worktree = worktreeClaimedBy(claim, worktreeRoot)
197 if (worktree !== null) return worktree
198 }
199 return null
200}
201
202/**
203 * The repo around the session and its role in the loom: `weaver` anywhere in
204 * the repo once a weave was asked for, `owner` inside
205 * `~/.worktrees/<repo>/<slug>`, `none` anywhere else or outside git.
206 */
207export function detectLayout(input: {
208 cwd: string
209 toplevel: string | null
210 commonDir: string | null
211 home: string | null
212 weaveSeen: boolean
213}): Detected {
214 const none: Detected = { canonical: null, ownWorktree: null, worktreeRoot: null, repo: null, role: 'none' }
215 const toplevel = input.toplevel?.trim() ?? ''
216 const canonical = canonicalFrom(input.commonDir, input.cwd)
217 if (toplevel === '' || canonical === null) return none
218 const repo = baseName(canonical)
219 const worktreeRoot = worktreeRootFor(input.home, repo)
220 const top = trimSlash(toplevel)
221 if (input.weaveSeen) return { canonical, ownWorktree: null, worktreeRoot, repo, role: 'weaver' }
222 if (worktreeRoot !== null && dirName(top) === worktreeRoot) {
223 return { canonical, ownWorktree: top, worktreeRoot, repo, role: 'owner' }
224 }
225 return { canonical, ownWorktree: null, worktreeRoot, repo, role: 'none' }
226}
227
228/** The entries of `git worktree list --porcelain`, in git's order. */
229export function parseWorktreeList(porcelain: string): WorktreeEntry[] {
230 const entries: WorktreeEntry[] = []
231 let current: WorktreeEntry | null = null
232 for (const raw of porcelain.split('\n')) {
233 const line = raw.trimEnd()
234 if (line.startsWith('worktree ')) {
235 if (current !== null) entries.push(current)
236 current = { path: line.slice('worktree '.length), head: null, branch: null, isBare: false, isDetached: false }
237 continue
238 }
239 if (current === null) continue
240 if (line.startsWith('HEAD ')) current.head = line.slice('HEAD '.length)
241 else if (line.startsWith('branch ')) current.branch = line.slice('branch '.length).replace(/^refs\/heads\//, '')
242 else if (line === 'bare') current.isBare = true
243 else if (line === 'detached') current.isDetached = true
244 }
245 if (current !== null) entries.push(current)
246 return entries
247}
248
249export function worktreeOfBranch(entries: readonly WorktreeEntry[], branch: string): WorktreeEntry | null {
250 return entries.find(entry => entry.branch === branch) ?? null
251}
252
253export function worktreeAt(entries: readonly WorktreeEntry[], path: string): WorktreeEntry | null {
254 return entries.find(entry => isSamePath(entry.path, path)) ?? null
255}
256
257/** `origin/main` from `git symbolic-ref refs/remotes/origin/HEAD`; `main` when it failed. */
258export function parseDefaultRef(stdout: string | null): string {
259 const line = stdout?.trim().split('\n')[0] ?? ''
260 const short = line.replace(/^refs\/remotes\//, '')
261 return short === '' || short === line ? DEFAULT_BRANCH : short
262}
263
264export function parseCount(stdout: string | null): number | null {
265 const n = Number.parseInt(stdout?.trim() ?? '', 10)
266 return Number.isNaN(n) ? null : n
267}
268
269/** The `/loom` arguments that make the session the weaver: `weave` as the first word. */
270export function isWeaveArgs(args: string): boolean {
271 return /^\s*weave(\s|$)/.test(args)
272}
273
274/** The arguments of a `/loom ...` prompt, or null when the prompt is not one. */
275export function loomArgsOf(text: string): string | null {
276 const match = /^\/loom(?:\s+([\s\S]*))?$/.exec(text.trim())
277 return match === null ? null : (match[1] ?? '').trim()
278}
279
280type Token = { kind: 'word'; text: string } | { kind: 'op'; text: string }
281
282type Tokenized = { tokens: Token[]; isUncertain: boolean }
283
284/**
285 * Splits a shell command into words and operators the way a POSIX shell
286 * would, quotes removed. Gives up (`isUncertain`) on what it cannot follow
287 * without running it: substitutions, heredocs, an unbalanced quote.
288 */
289export function tokenizeShell(command: string): Tokenized {
290 const tokens: Token[] = []
291 const uncertain: Tokenized = { tokens, isUncertain: true }
292 let word = ''
293 let hasWord = false
294 const flush = (): void => {
295 if (!hasWord) return
296 tokens.push({ kind: 'word', text: word })
297 word = ''
298 hasWord = false
299 }
300 const push = (text: string): void => {
301 flush()
302 tokens.push({ kind: 'op', text })
303 }
304 const n = command.length
305 let i = 0
306 while (i < n) {
307 const c = command[i] ?? ''
308 if (c === "'") {
309 const end = command.indexOf("'", i + 1)
310 if (end < 0) return uncertain
311 word += command.slice(i + 1, end)
312 hasWord = true
313 i = end + 1
314 continue
315 }
316 if (c === '"') {
317 let j = i + 1
318 let closed = false
319 while (j < n) {
320 const d = command[j] ?? ''
321 if (d === '\\' && j + 1 < n) {
322 word += command[j + 1]
323 j += 2
324 continue
325 }
326 if (d === '"') {
327 closed = true
328 break
329 }
330 if (d === '`') return uncertain
331 word += d
332 j += 1
333 }
334 if (!closed) return uncertain
335 hasWord = true
336 i = j + 1
337 continue
338 }
339 if (c === '\\') {
340 const escaped = command[i + 1]
341 if (escaped !== undefined && escaped !== '\n') {
342 word += escaped
343 hasWord = true
344 }
345 i += 2
346 continue
347 }
348 if (c === '`' || (c === '$' && command[i + 1] === '(')) return uncertain
349 if (c === '#' && !hasWord) {
350 const end = command.indexOf('\n', i)
351 i = end < 0 ? n : end
352 continue
353 }
354 if (c === ' ' || c === '\t' || c === '\r') {
355 flush()
356 i += 1
357 continue
358 }
359 if (c === '\n') {
360 push('\n')
361 i += 1
362 continue
363 }
364 if (c === '<') {
365 if (command[i + 1] === '<') return uncertain
366 push('<')
367 i += 1
368 continue
369 }
370 if (c === '>') {
371 let op = ''
372 if (hasWord && /^\d$/.test(word)) {
373 op = word
374 word = ''
375 hasWord = false
376 }
377 flush()
378 op += '>'
379 i += 1
380 if (command[i] === '>') {
381 op += '>'
382 i += 1
383 }
384 if (command[i] === '&') {
385 op += '&'
386 i += 1
387 } else if (command[i] === '|') {
388 i += 1
389 }
390 push(op)
391 continue
392 }
393 if (c === '&') {
394 if (command[i + 1] === '&') {
395 push('&&')
396 i += 2
397 continue
398 }
399 if (command[i + 1] === '>') {
400 let op = '&>'
401 i += 2
402 if (command[i] === '>') {
403 op += '>'
404 i += 1
405 }
406 push(op)
407 continue
408 }
409 push('&')
410 i += 1
411 continue
412 }
413 if (c === '|') {
414 const two = command[i + 1] === '|' ? '||' : command[i + 1] === '&' ? '|&' : null
415 push(two ?? '|')
416 i += two === null ? 1 : 2
417 continue
418 }
419 if (c === ';') {
420 const two = command[i + 1] === ';'
421 push(two ? ';;' : ';')
422 i += two ? 2 : 1
423 continue
424 }
425 if (c === '(' || c === ')') {
426 push(c)
427 i += 1
428 continue
429 }
430 word += c
431 hasWord = true
432 i += 1
433 }
434 flush()
435 return { tokens, isUncertain: false }
436}
437
438type Segment = Token[] | '(' | ')'
439
440/** The simple commands in order, with the subshell parentheses kept as markers. */
441function segmentsOf(tokens: readonly Token[]): Segment[] {
442 const segments: Segment[] = []
443 let current: Token[] = []
444 const close = (): void => {
445 if (current.length > 0) segments.push(current)
446 current = []
447 }
448 for (const token of tokens) {
449 if (token.kind === 'op' && (token.text === '(' || token.text === ')')) {
450 close()
451 segments.push(token.text)
452 continue
453 }
454 if (token.kind === 'op' && CONTROL_OPS.has(token.text)) {
455 close()
456 continue
457 }
458 current.push(token)
459 }
460 close()
461 return segments
462}
463
464type Parts = { argv: string[]; assignments: string[]; redirectTargets: string[] }
465
466/** A simple command's argv, its leading assignments, and the files its redirections write. */
467function partsOf(simple: readonly Token[]): Parts {
468 const argv: string[] = []
469 const assignments: string[] = []
470 const redirectTargets: string[] = []
471 for (let i = 0; i < simple.length; i += 1) {
472 const token = simple[i]
473 if (token === undefined) break
474 if (token.kind === 'word') {
475 argv.push(token.text)
476 continue
477 }
478 const target = simple[i + 1]
479 i += 1
480 if (token.text.endsWith('&') || token.text === '<') continue
481 if (target?.kind === 'word') redirectTargets.push(target.text)
482 }
483 while (argv.length > 0) {
484 const match = ASSIGNMENT.exec(argv[0] ?? '')
485 if (match === null) break
486 assignments.push(match[1] ?? '')
487 argv.shift()
488 }
489 return { argv, assignments, redirectTargets }
490}
491
492/** The argv from `git` on, when the command is git by any of its spellings; else null. */
493function gitArgvOf(argv: readonly string[]): readonly string[] | null {
494 const head = argv[0]
495 if (head === undefined) return null
496 if (head === 'git' || (head.includes('/') && baseName(head) === 'git')) return argv
497 return null
498}
499
500type GitCall = { location: string; verb: string | null; args: string[] }
501
502/** `git [-C p] [-c k=v] [--flag] verb args...`; null when the repo it acts on cannot be known. */
503function parseGit(argv: readonly string[], cwd: string, home: string | null): GitCall | null {
504 let location = cwd
505 let i = 1
506 while (i < argv.length) {
507 const arg = argv[i] ?? ''
508 if (arg === '-C' || (arg.startsWith('-C') && arg.length > 2)) {
509 const spelled = arg === '-C' ? argv[i + 1] : arg.slice(2)
510 if (spelled === undefined) return null
511 const resolved = resolvePath(spelled, location, home)
512 if (resolved === null) return null
513 location = resolved
514 i += arg === '-C' ? 2 : 1
515 continue
516 }
517 if (arg === '-c') {
518 i += 2
519 continue
520 }
521 if (/^--(work-tree|git-dir)(=|$)/.test(arg)) return null
522 if (arg.startsWith('-')) {
523 i += 1
524 continue
525 }
526 return { location, verb: arg, args: argv.slice(i + 1) }
527 }
528 return { location, verb: null, args: [] }
529}
530
531/** The operands of a verb with the flag values dropped. */
532function operandsOf(args: readonly string[]): string[] {
533 const operands: string[] = []
534 for (let i = 0; i < args.length; i += 1) {
535 const arg = args[i] ?? ''
536 if (VALUE_FLAGS.has(arg)) {
537 i += 1
538 continue
539 }
540 if (arg.startsWith('-')) continue
541 operands.push(arg)
542 }
543 return operands
544}
545
546function isMutating(call: GitCall): boolean {
547 if (call.verb === null) return false
548 if (call.verb === 'stash') {
549 const sub = operandsOf(call.args)[0]
550 return sub !== 'list' && sub !== 'show'
551 }
552 return MUTATING_GIT_VERBS.has(call.verb)
553}
554
555export type Removal =
556 | { kind: 'branch'; name: string; location: string }
557 | { kind: 'worktree'; path: string; isForce: boolean }
558
559/** What a `git branch -D` or `git worktree remove` names; null when a path cannot be resolved. */
560function removalsOf(call: GitCall, home: string | null): Removal[] | null {
561 const flags = call.args.filter(arg => arg.startsWith('-'))
562 const short = flags.filter(flag => /^-[A-Za-z]+$/.test(flag)).join('')
563 const isForce = short.includes('f') || flags.includes('--force')
564 if (call.verb === 'branch') {
565 const isDelete = short.includes('d') || flags.includes('--delete')
566 if (!(short.includes('D') || (isDelete && isForce))) return []
567 return operandsOf(call.args).map(name => ({ kind: 'branch', name, location: call.location }))
568 }
569 if (call.verb === 'worktree' && call.args[0] === 'remove') {
570 const removals: Removal[] = []
571 for (const spelled of operandsOf(call.args.slice(1))) {
572 const path = resolvePath(spelled, call.location, home)
573 if (path === null) return null
574 removals.push({ kind: 'worktree', path, isForce })
575 }
576 return removals
577 }
578 return []
579}
580
581export type BashAnalysis = {
582 /** True when the command could not be followed; the caller lets it through. */
583 isUncertain: boolean
584 /** Where a mutating git verb acts (its repo, and path operands for the verbs that take them) and what redirections write. */
585 writes: string[]
586 /** The branches and worktrees the command force-deletes or removes. */
587 removals: Removal[]
588 /** Where the command goes: every `cd` target and `git worktree add` path, resolved. */
589 claims: string[]
590}
591
592/**
593 * Reads a Bash command for what it would change on disk: `cd` moves the
594 * working directory for what follows (a subshell's `cd` ends with it),
595 * `git -C` names the repo a verb acts on, `>` names a file. Anything it
596 * cannot follow makes the whole reading uncertain rather than a guess.
597 */
598export function analyzeBash(command: string, env: { cwd: string; home: string | null }): BashAnalysis {
599 const uncertain: BashAnalysis = { isUncertain: true, writes: [], removals: [], claims: [] }
600 const { tokens, isUncertain } = tokenizeShell(command)
601 if (isUncertain) return uncertain
602 const analysis: BashAnalysis = { isUncertain: false, writes: [], removals: [], claims: [] }
603 let cwd = normalizePath(env.cwd)
604 const outer: string[] = []
605 for (const segment of segmentsOf(tokens)) {
606 if (segment === '(') {
607 outer.push(cwd)
608 continue
609 }
610 if (segment === ')') {
611 cwd = outer.pop() ?? cwd
612 continue
613 }
614 const { argv: words, assignments, redirectTargets } = partsOf(segment)
615 for (const target of redirectTargets) {
616 const path = resolvePath(target, cwd, env.home)
617 if (path === null) return uncertain
618 analysis.writes.push(path)
619 }
620 if (assignments.some(name => GIT_ENV.has(name))) return uncertain
621 let argv: string[] = words
622 while (argv.length > 0 && PASSTHROUGH_COMMANDS.has(argv[0] ?? '')) argv = argv.slice(1)
623 const head = argv[0]
624 if (head === undefined) continue
625 if (OPAQUE_COMMANDS.has(head)) return uncertain
626 if (head === 'cd' || head === 'pushd') {
627 const spelled = argv.slice(1).find(arg => arg === '-' || !arg.startsWith('-'))
628 const next = spelled === undefined ? env.home : resolvePath(spelled, cwd, env.home)
629 if (next === null) return uncertain
630 cwd = next
631 analysis.claims.push(cwd)
632 continue
633 }
634 const gitArgv = gitArgvOf(argv)
635 if (gitArgv === null) continue
636 const call = parseGit(gitArgv, cwd, env.home)
637 if (call === null) return uncertain
638 if (isMutating(call)) {
639 analysis.writes.push(call.location)
640 if (call.verb !== null && OPERAND_VERBS.has(call.verb)) {
641 for (const operand of operandsOf(call.args)) {
642 if (!operand.startsWith('/') && !operand.startsWith('~')) continue
643 const path = resolvePath(operand, call.location, env.home)
644 if (path !== null) analysis.writes.push(path)
645 }
646 }
647 }
648 if (call.verb === 'worktree' && call.args[0] === 'add') {
649 const spelled = operandsOf(call.args.slice(1))[0]
650 if (spelled !== undefined) {
651 const path = resolvePath(spelled, call.location, env.home)
652 if (path === null) return uncertain
653 analysis.claims.push(path)
654 }
655 }
656 const removals = removalsOf(call, env.home)
657 if (removals === null) return uncertain
658 analysis.removals.push(...removals)
659 }
660 return analysis
661}
662
663/**
664 * Whether `git worktree remove` needs a word first: git itself refuses a
665 * dirty tree without `--force`, so only a forced removal of a dirty tree, or
666 * a detached head whose commits sit on no branch, can lose work.
667 */
668export function shouldAskWorktreeRemoval(input: {
669 isForce: boolean
670 isDirty: boolean
671 isDetached: boolean
672 ahead: number | null
673}): boolean {
674 if (input.isForce && input.isDirty) return true
675 return input.isDetached && input.ahead !== null && input.ahead > 0
676}
677
678/** The tree a merge of `branch` into `ref` would write, conflicts or not; needs git 2.38. */
679export function mergeTreeArgs(ref: string, branch: string): string[] {
680 return ['merge-tree', '--write-tree', ref, branch]
681}
682
683/**
684 * True when the tree a merge into the default branch would write is the
685 * default branch's own tree: the branch's changes are already there, by a
686 * fast-forward or a squash merge. False when either is unknown (git before
687 * 2.38, a conflict, no default branch).
688 */
689export function isIntegratedTree(mergeTreeOut: string | null, defaultTree: string | null): boolean {
690 const merged = mergeTreeOut?.trim().split('\n')[0] ?? ''
691 return merged !== '' && defaultTree !== null && merged === defaultTree.trim()
692}
693
694/**
695 * Whether `git branch -D` needs a word first: when the branch's commits exist
696 * nowhere else (ahead of the default branch, not on `origin/<branch>` with
697 * `remoteAhead` null meaning no such upstream, and not integrated), or its
698 * worktree is dirty. A squash-merged branch is ahead and has no upstream
699 * once its remote branch is gone, yet loses nothing.
700 */
701export function shouldAskBranchDeletion(input: {
702 ahead: number | null
703 remoteAhead: number | null
704 isIntegrated: boolean
705 isWorktreeDirty: boolean
706}): boolean {
707 if (input.isWorktreeDirty) return true
708 const isUnpushed = input.remoteAhead === null || input.remoteAhead > 0
709 return isUnpushed && !input.isIntegrated && input.ahead !== null && input.ahead > 0
710}
711
712/**
713 * The status line for a role, or undefined (clear) when the session has
714 * none. The engine prefixes the line with the mod's name, so the text
715 * never repeats it: `owner feat-pane`, `weaver · 3 worktrees`.
716 */
717export function statusText(role: Role, layout: Layout): string | undefined {
718 if (role === 'owner') {
719 return `owner ${layout.ownWorktree === null ? '?' : baseName(layout.ownWorktree)}`
720 }
721 if (role !== 'weaver') return undefined
722 const linked = layout.worktrees.filter(path => !isSamePath(path, layout.canonical))
723 if (linked.length === 0) return 'weaver'
724 const noun = linked.length === 1 ? 'worktree' : 'worktrees'
725 return `weaver · ${linked.length} ${noun}`
726}
727
728/** The question before a removal that would lose work. */
729export function removalQuestion(label: string, ahead: number | null, isDirty: boolean): string {
730 const risks: string[] = []
731 if (ahead !== null && ahead > 0) risks.push(`${ahead} unmerged ${ahead === 1 ? 'commit' : 'commits'}`)
732 if (isDirty) risks.push('uncommitted changes')
733 return `${label} has ${risks.join(' and ')}. Remove anyway?`
734}
735
736// The member line: who else works this repo's loom, read from the engine's
737// agent list, the session list of `claude agents --json --all` and belt's
738// ledger. The caller hands in what those sources answered.
739
740/** What the member line shows for a field no source recorded. */
741export const UNKNOWN = '-'
742
743/** How long `claude agents --json --all` and the events service may each take. */
744export const PROBE_BUDGET_MS = 400
745
746/** The shortest gap between the starts of two member refreshes. */
747export const MEMBERS_REFRESH_GAP_MS = 5_000
748
749/** belt's subagent-start ledger entries on the local events service, newest first. */
750export const LEDGER_URL = 'http://localhost:7430/api/events?source=belt-ledger&q=subagent-start&limit=200'
751
752/** The argv of the engine's session list. */
753export const AGENTS_ARGV = ['claude', 'agents', '--json', '--all'] as const
754
755// Agent statuses after which the engine keeps an agent listed only until it
756// drops the task.
757const FINISHED = new Set(['completed', 'failed', 'killed'])
758
759// The session state `claude agents` gives a session that has finished.
760const SESSION_DONE = 'done'
761
762/** One agent of this session, as `$.agent.list()` returns it. */
763export type AgentLike = { id: string; name?: string; type: string; status: string }
764
765/** One session row of `claude agents --json --all`; `state` is a background row's `state` or an interactive row's `status`. */
766export type SessionRow = { sessionId: string | null; name: string | null; cwd: string | null; state: string | null }
767
768/** What belt's ledger recorded when a subagent started. */
769export type LedgerFacts = { worktree: string | null; model: string | null; effort: string | null }
770
771/** One member as the line shows it; a field nobody recorded is `-`, and `state` is a session's CLI state. */
772export type Member = { name: string; role: string; worktree: string; model: string; effort: string; state: string | null }
773
774function isRecord(value: unknown): value is Record<string, unknown> {
775 return typeof value === 'object' && value !== null && !Array.isArray(value)
776}
777
778function textOf(value: unknown): string | null {
779 return typeof value === 'string' && value !== '' ? value : null
780}
781
782function parseArray(text: string | null): unknown[] {
783 if (text === null) return []
784 try {
785 const parsed: unknown = JSON.parse(text)
786 return Array.isArray(parsed) ? parsed : []
787 } catch {
788 return []
789 }
790}
791
792/** The rows of `claude agents --json --all`; empty when the output is not that JSON array. */
793export function parseSessions(stdout: string | null): SessionRow[] {
794 const rows: SessionRow[] = []
795 for (const item of parseArray(stdout)) {
796 if (!isRecord(item)) continue
797 rows.push({
798 sessionId: textOf(item.sessionId),
799 name: textOf(item.name) ?? textOf(item.id),
800 cwd: textOf(item.cwd),
801 state: textOf(item.state) ?? textOf(item.status),
802 })
803 }
804 return rows
805}
806
807/**
808 * The newest subagent-start facts per agent id from the events service's
809 * answer (newest first); empty when the answer is not an event array.
810 */
811export function parseLedger(body: string | null): Map<string, LedgerFacts> {
812 const facts = new Map<string, LedgerFacts>()
813 for (const item of parseArray(body)) {
814 if (!isRecord(item) || !isRecord(item.tags)) continue
815 const tags = item.tags
816 const agentId = textOf(tags.agent_id)
817 if (tags.event !== 'subagent-start' || agentId === null || facts.has(agentId)) continue
818 facts.set(agentId, { worktree: textOf(tags.worktree), model: textOf(tags.model), effort: textOf(tags.effort) })
819 }
820 return facts
821}
822
823/** True when no refresh started in the last `MEMBERS_REFRESH_GAP_MS`. */
824export function isRefreshDue(now: number, lastRefreshAt: number | null): boolean {
825 return lastRefreshAt === null || now - lastRefreshAt >= MEMBERS_REFRESH_GAP_MS
826}
827
828/** How long until the gap since the last refresh has passed: 0 when it already has. */
829export function trailingDelay(now: number, lastRefreshAt: number | null): number {
830 return lastRefreshAt === null ? 0 : Math.max(0, lastRefreshAt + MEMBERS_REFRESH_GAP_MS - now)
831}
832
833/** True when an agent could be a member, so the ledger is worth asking. */
834export function isLive(agent: AgentLike): boolean {
835 return !FINISHED.has(agent.status)
836}
837
838/** The isolation worktree path the Agent tool uses for `agentId`. */
839function isolationPathOf(agentId: string, canonical: string): string {
840 return `${canonical}/.claude/worktrees/agent-${agentId}`
841}
842
843/** True for a loom worktree (`~/.worktrees/<repo>/<slug>`) or an isolation worktree (`.claude/worktrees/agent-<id>`). */
844export function isMemberWorktree(worktree: string, layout: Layout): boolean {
845 if (layout.worktreeRoot !== null && dirName(worktree) === layout.worktreeRoot) return true
846 return layout.canonical !== null && dirName(worktree) === `${layout.canonical}/.claude/worktrees` && baseName(worktree).startsWith('agent-')
847}
848
849/** The linked worktree of the repo that holds `path`, the innermost one; null for the canonical checkout or outside. */
850export function linkedWorktreeOf(path: string, layout: Layout): string | null {
851 let best: string | null = null
852 for (const worktree of layout.worktrees) {
853 if (worktree === layout.canonical || !isUnder(path, worktree)) continue
854 if (best === null || worktree.length > best.length) best = worktree
855 }
856 return best
857}
858
859/** The worktree the Agent tool's isolation mode made for `agentId`, when git lists it. */
860export function isolationWorktreeOf(agentId: string, layout: Layout): string | null {
861 if (layout.canonical === null) return null
862 const path = isolationPathOf(agentId, layout.canonical)
863 return layout.worktrees.includes(path) ? path : null
864}
865
866/**
867 * Where an agent works: the isolation worktree git lists for its id first,
868 * then the ledger's worktree tag. The tag comes from the hook payload's cwd,
869 * which can be the parent's, so it counts only for a member worktree that
870 * is not this session's own.
871 */
872export function agentWorktreeOf(agentId: string, tag: string | null, layout: Layout): string | null {
873 const isolated = isolationWorktreeOf(agentId, layout)
874 if (isolated !== null) return isolated
875 if (tag === null || tag === layout.ownWorktree || !isMemberWorktree(tag, layout)) return null
876 return tag
877}
878
879function agentMember(agent: AgentLike, ledger: ReadonlyMap<string, LedgerFacts>, layout: Layout): Member | null {
880 if (!isLive(agent)) return null
881 const facts = ledger.get(agent.id)
882 const worktree = agentWorktreeOf(agent.id, facts?.worktree ?? null, layout)
883 if (worktree === null) return null
884 return {
885 name: agent.name ?? agent.id,
886 role: 'owner',
887 worktree: baseName(worktree),
888 model: facts?.model ?? UNKNOWN,
889 effort: facts?.effort ?? UNKNOWN,
890 state: null,
891 }
892}
893
894function sessionMember(row: SessionRow, layout: Layout, selfSessionId: string | null): Member | null {
895 if (row.cwd === null || row.state === SESSION_DONE) return null
896 if (selfSessionId !== null && row.sessionId === selfSessionId) return null
897 const worktree = linkedWorktreeOf(row.cwd, layout)
898 if (worktree === null || !isMemberWorktree(worktree, layout)) return null
899 return {
900 name: row.name ?? row.sessionId ?? UNKNOWN,
901 role: 'owner',
902 worktree: baseName(worktree),
903 model: UNKNOWN,
904 effort: UNKNOWN,
905 state: row.state,
906 }
907}
908
909/**
910 * The members beside this session: its live agents that work in a loom or
911 * isolation worktree, then the sessions in such a worktree that are not done,
912 * this one left out. A plain named agent is no member. Model and effort come
913 * from the ledger alone.
914 */
915export function membersFrom(input: {
916 agents: readonly AgentLike[]
917 sessions: readonly SessionRow[]
918 ledger: ReadonlyMap<string, LedgerFacts>
919 layout: Layout
920 selfSessionId: string | null
921}): Member[] {
922 const members: Member[] = []
923 for (const agent of input.agents) {
924 const member = agentMember(agent, input.ledger, input.layout)
925 if (member !== null) members.push(member)
926 }
927 for (const row of input.sessions) {
928 const member = sessionMember(row, input.layout, input.selfSessionId)
929 if (member !== null) members.push(member)
930 }
931 return members
932}
933
934/** `w1 (owner, agent-a1, -, -)`, a session's state after it: `fixer (owner, fix-band, -, -) idle`. */
935export function memberText(member: Member): string {
936 const fields = `${member.name} (${member.role}, ${member.worktree}, ${member.model}, ${member.effort})`
937 return member.state === null ? fields : `${fields} ${member.state}`
938}
939
940/**
941 * The status line: the role text, then the members after `members`, or
942 * undefined (clear) when there is neither.
943 */
944export function composeStatus(roleText: string | undefined, members: readonly Member[]): string | undefined {
945 const memberPart = members.length === 0 ? undefined : `members ${members.map(memberText).join(', ')}`
946 const parts = [roleText, memberPart].filter((part): part is string => part !== undefined)
947 return parts.length === 0 ? undefined : parts.join(' · ')
948}
949types/index.d.ts 30 lines1export type LoomPaneRole = 'owner' | 'weaver' | 'none'
2
3/** One member on the status line; a field no source recorded is `-`, `state` is a session's CLI state. */
4export type LoomPaneMember = {
5 name: string
6 role: string
7 worktree: string
8 model: string
9 effort: string
10 state: string | null
11}
12
13declare module 'claude-code' {
14 interface PluginState {
15 'loom-pane': {
16 role: LoomPaneRole
17 canonical: string | null
18 ownWorktree: string | null
19 worktreeRoot: string | null
20 worktrees: string[]
21 repo: string | null
22 weaveSeen: boolean
23 isInteractive: boolean
24 members: LoomPaneMember[]
25 /** The session the role was last detected for; null until the first detect. */
26 sessionId: string | null
27 }
28 }
29}
30