@dibssoftware/dibs 0.0.0-stage → 0.0.179

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +594 -0
  2. package/LICENSE +670 -0
  3. package/README.md +85 -2
  4. package/bin/dibs-guard.mjs +7 -0
  5. package/bin/dibs.mjs +548 -0
  6. package/docs/benchmarks.md +193 -0
  7. package/docs/files.md +30 -0
  8. package/docs/guard.md +91 -0
  9. package/docs/later.md +43 -0
  10. package/docs/machines.md +147 -0
  11. package/docs/questions.md +78 -0
  12. package/docs/reference.md +157 -0
  13. package/docs/relay.md +196 -0
  14. package/docs/releasing.md +27 -0
  15. package/docs/scheduling.md +163 -0
  16. package/docs/simulators.md +17 -0
  17. package/package.json +45 -4
  18. package/skills/dibs/SKILL.md +183 -0
  19. package/src/acquire.mjs +700 -0
  20. package/src/admin.mjs +145 -0
  21. package/src/agents.mjs +145 -0
  22. package/src/alerts.mjs +499 -0
  23. package/src/answers.mjs +65 -0
  24. package/src/board.mjs +202 -0
  25. package/src/broker.mjs +369 -0
  26. package/src/commands.mjs +810 -0
  27. package/src/config.mjs +324 -0
  28. package/src/connect.mjs +106 -0
  29. package/src/cool.mjs +160 -0
  30. package/src/diskwarn.mjs +154 -0
  31. package/src/events.mjs +96 -0
  32. package/src/files.mjs +1123 -0
  33. package/src/guard.mjs +613 -0
  34. package/src/history.mjs +247 -0
  35. package/src/hogs.mjs +227 -0
  36. package/src/later.mjs +487 -0
  37. package/src/measure.mjs +262 -0
  38. package/src/news.mjs +101 -0
  39. package/src/nodecheck.mjs +17 -0
  40. package/src/notes.mjs +171 -0
  41. package/src/notices.mjs +160 -0
  42. package/src/ondemand.mjs +572 -0
  43. package/src/overlap.mjs +151 -0
  44. package/src/override.mjs +360 -0
  45. package/src/owner.mjs +30 -0
  46. package/src/plain.mjs +470 -0
  47. package/src/platform.mjs +357 -0
  48. package/src/preempt.mjs +438 -0
  49. package/src/primer.mjs +89 -0
  50. package/src/proc.mjs +99 -0
  51. package/src/progress.mjs +187 -0
  52. package/src/qr.mjs +204 -0
  53. package/src/questions.mjs +389 -0
  54. package/src/quota.mjs +81 -0
  55. package/src/reads.mjs +54 -0
  56. package/src/relay.mjs +779 -0
  57. package/src/remote.mjs +584 -0
  58. package/src/reset.mjs +127 -0
  59. package/src/schedule.mjs +1020 -0
  60. package/src/scratch.mjs +61 -0
  61. package/src/serve.mjs +742 -0
  62. package/src/service.mjs +221 -0
  63. package/src/shard.mjs +59 -0
  64. package/src/simctl.mjs +42 -0
  65. package/src/simpool.mjs +258 -0
  66. package/src/state.mjs +201 -0
  67. package/src/stats.mjs +328 -0
  68. package/src/style.mjs +44 -0
  69. package/src/talk.mjs +702 -0
  70. package/src/thin.sh +130 -0
  71. package/src/trust.mjs +152 -0
  72. package/src/util.mjs +184 -0
  73. package/src/version.mjs +2 -0
  74. package/src/web.mjs +1119 -0
  75. package/src/worker.mjs +318 -0
package/src/files.mjs ADDED
@@ -0,0 +1,1123 @@
1
+ // File leases: `dibs hold files:src/auth/**` keeps other agents' edits off
2
+ // those paths, and the guard hook turns their Edit, Write and obvious Bash
3
+ // writes away while the lease lasts. A lease is a resource named
4
+ // files:<absolute path or glob>, queued and reaped like any other hold. The
5
+ // hook half of this file runs on every tool call: it imports nothing from dibs
6
+ // but util.mjs, reads state.json without the lock (it's written by rename) and
7
+ // spawns nothing unless another session's lease covers the path.
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { execFileSync } from 'node:child_process';
12
+ import { dur, clock, fakeFull, callerPid } from './util.mjs';
13
+
14
+ export const FILES = 'files:';
15
+ export const isFiles = r => typeof r === 'string' && r.startsWith(FILES);
16
+ // What a file lease costs: one holder at a time per path, and nothing from the
17
+ // memory, CPU or disk budgets, since holding a path runs nothing.
18
+ export const FILES_COST = { slots: 1, mem: 0, cpu: 0, disk: 0, pausable: false };
19
+
20
+ // * and ? stay inside one folder, ** crosses folders. [ is literal: Next.js
21
+ // routes are named [id].
22
+ const GLOB = /[*?]/;
23
+
24
+ export function gitRoot(dir) {
25
+ for (let d = path.resolve(dir); ; d = path.dirname(d)) {
26
+ if (fs.existsSync(path.join(d, '.git'))) return d;
27
+ if (path.dirname(d) === d) return null;
28
+ }
29
+ }
30
+
31
+ // Whether lease l was taken from another worktree of the repo whose worktree
32
+ // w a git write rewrites. git stash or reset --hard in wt-a never touches
33
+ // wt-b's copy of a file, which is all wt-b's lease covers; mapping every
34
+ // worktree onto one name made the whole repo look leased to anyone stashing
35
+ // in Atlas's 70 worktrees. A lease with no cwd (an older dibs) still counts.
36
+ function sibling(l, w) {
37
+ if (!w || typeof l.cwd !== 'string') return false;
38
+ const theirs = worktreeOf(real(path.resolve(l.cwd)));
39
+ return !!theirs && theirs[1] === w[1] && theirs[0] !== w[0];
40
+ }
41
+
42
+ // ----- other sessions' temp folders -----
43
+ // Claude Code keeps each session's scratch files in <tmp>/claude-<uid>/<project
44
+ // folder>/<session id>/. The person's rule: an agent deletes or overwrites
45
+ // only in its own session's folder there (subagents share their parent's
46
+ // session id). A cleanup deleted another agent's live folder twice on
47
+ // 2026-10-16. Reads are fine anywhere.
48
+
49
+ // Every spelling of the temp root: as written, and with symlinks resolved.
50
+ let tmpRoots = null;
51
+ export function claudeTmp() {
52
+ if (tmpRoots) return tmpRoots;
53
+ const uid = process.getuid?.();
54
+ if (uid == null) return (tmpRoots = []);
55
+ // DIBS_CLAUDE_TMP: tests put the temp folder somewhere of their own.
56
+ const bases = process.env.DIBS_CLAUDE_TMP ? [process.env.DIBS_CLAUDE_TMP]
57
+ : ['/tmp', '/private/tmp', os.tmpdir(), process.env.TMPDIR, process.env.CLAUDE_CODE_TMPDIR].filter(Boolean);
58
+ const roots = new Set();
59
+ for (const b of bases) {
60
+ const r = path.join(path.resolve(b), `claude-${uid}`);
61
+ roots.add(r);
62
+ roots.add(real(r));
63
+ }
64
+ return (tmpRoots = [...roots]);
65
+ }
66
+
67
+ // For path p, written to: null when it's outside the temp root or in session's
68
+ // own folder, else the folder that isn't the caller's (the root, a project
69
+ // folder, another session's, or a glob that could be any of them).
70
+ function othersTmp(p, session) {
71
+ for (const root of claudeTmp()) {
72
+ if (!overlap(p, root)) continue;
73
+ const rel = p.startsWith(root + '/') ? p.slice(root.length + 1).split('/') : [];
74
+ if (rel.length >= 2 && rel[1] === session) return null;
75
+ return rel.length >= 2 && !GLOB.test(rel[1]) ? path.join(root, rel[0], rel[1]) : root + (rel.length ? '/' + rel.slice(0, 2).join('/') : '');
76
+ }
77
+ return null;
78
+ }
79
+
80
+ // A $VAR path counts only when its literal start names another session: /private/tmp/claude-503/proj/<id>/$X.
81
+ function guessedOthers(prefix, session) {
82
+ for (const root of claudeTmp()) {
83
+ if (!prefix.startsWith(root + '/')) continue;
84
+ const whole = prefix.slice(root.length + 1).split('/').slice(0, -1);
85
+ if (whole.length >= 2 && whole[1] !== session && !GLOB.test(whole[1])) return path.join(root, whole[0], whole[1]);
86
+ }
87
+ return null;
88
+ }
89
+
90
+ // Inside a session's own folder its subagents share the scratchpad, so a
91
+ // recursive delete there could still take a sibling's work. dibs remembers
92
+ // which agent first wrote into each folder at the top of the scratchpad
93
+ // (scratch/<session>/<folder> in DIBS_HOME, made with wx so the first one
94
+ // wins without a lock), and a recursive delete of one is that agent's alone.
95
+ const UNTRACKED_MAX = 20; // files: an older folder this small is cheap to lose, one bigger may be someone's work
96
+ const makersDir = session => path.join(dibsHome(), 'scratch', session);
97
+ const agentOf = input => input.agent_id || 'main';
98
+
99
+ // [session folder, the path's parts under it] when p is in one of the temp root's session folders.
100
+ function inSession(p) {
101
+ for (const root of claudeTmp()) {
102
+ if (!p.startsWith(root + '/')) continue;
103
+ const rel = p.slice(root.length + 1).split('/');
104
+ if (rel.length >= 2) return [path.join(root, rel[0], rel[1]), rel.slice(2)];
105
+ }
106
+ return null;
107
+ }
108
+
109
+ // Subagents of a session that have stopped (SubagentStop), so the main thread may clear
110
+ // what they left in the scratchpad. A teammate that takes another message starts again
111
+ // and loses the mark. The name can't be a folder's: encodeURIComponent never makes a bare %.
112
+ const stopMark = (session, agent) => path.join(makersDir(session), '%stopped', encodeURIComponent(agent));
113
+ export function subagentState(input) {
114
+ if (typeof input?.session_id !== 'string' || typeof input.agent_id !== 'string' || !input.agent_id) return;
115
+ const f = stopMark(input.session_id, input.agent_id);
116
+ try {
117
+ if (input.hook_event_name === 'SubagentStop') { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, String(Date.now())); }
118
+ else if (input.hook_event_name === 'SubagentStart') fs.rmSync(f, { force: true });
119
+ } catch {}
120
+ }
121
+ const stopped = (session, agent) => fs.existsSync(stopMark(session, agent));
122
+
123
+ // Folders that rebuild themselves: a browser profile's caches, Xcode's and Swift's build
124
+ // output, a bundler's. Any agent of the session may clear them in its own scratchpad
125
+ // (on 2026-11-03 an agent had to ask a teammate to delete Chrome caches in its own session).
126
+ const CACHES = new Set(['Cache', 'Caches', 'Code Cache', 'GPUCache', 'DerivedData', '.build', 'build', 'dist', '.next', '.turbo', '.cache']);
127
+
128
+ export function maker(session, name) {
129
+ try { return JSON.parse(fs.readFileSync(path.join(makersDir(session), encodeURIComponent(name)), 'utf8')); } catch { return null; }
130
+ }
131
+
132
+ // Whether the folder at dir holds more than max files, stopping as soon as it does.
133
+ function bigger(dir, max) {
134
+ const stack = [dir];
135
+ let n = 0;
136
+ while (stack.length) {
137
+ let list;
138
+ try { list = fs.readdirSync(stack.pop(), { withFileTypes: true }); } catch { continue; }
139
+ for (const e of list) {
140
+ if (e.isDirectory()) stack.push(path.join(e.parentPath ?? e.path, e.name));
141
+ else if (++n > max) return true;
142
+ }
143
+ }
144
+ return false;
145
+ }
146
+
147
+ const agentName = m => (m.agent === 'main' ? 'the main thread' : m.type ? `${m.type} (${m.agent})` : m.agent);
148
+
149
+ // Why a recursive delete of p, in the caller's own session folder, would take
150
+ // what isn't the caller's to take, or null when it's fine.
151
+ function ownDelete(p, t, input) {
152
+ const at = inSession(p);
153
+ if (!at) return null;
154
+ const [folder, rest] = at, pad = path.join(folder, 'scratchpad');
155
+ const whole = what => `${p} is ${what}, which every agent of your session keeps its scratch files in, so ${t.why} can't delete all of it.\n`
156
+ + 'Delete the folders in it that you made instead. If it really must all go, have the person delete it.';
157
+ if (!rest.length) return whole("your session's temp folder");
158
+ if (!overlap(path.join(folder, rest[0]), pad)) return null;
159
+ if (rest.length === 1) return whole("your session's scratchpad");
160
+ if (!GLOB.test(rest.slice(1).join('/')) && rest.slice(1).some(n => CACHES.has(n))) return null;
161
+ let names = [rest[1]];
162
+ if (GLOB.test(rest[1])) {
163
+ try { names = fs.readdirSync(pad).filter(n => overlap(path.join(pad, rest[1]), path.join(pad, n))); } catch { names = []; }
164
+ }
165
+ for (const n of names) {
166
+ const m = maker(input.session_id, n), dir = path.join(pad, n);
167
+ // The main thread may clear what a subagent of its own left, once that subagent has stopped.
168
+ if (m && m.agent !== agentOf(input) && !(agentOf(input) === 'main' && m.agent !== 'main' && stopped(input.session_id, m.agent)))
169
+ return `${dir} in your session's scratchpad was made by ${agentName(m)}, another agent of your session, so ${t.why} can't delete it.\n`
170
+ + `Ask ${m.agent === 'main' ? 'the main thread' : m.type || m.agent} whether it's done with it, or have the person delete it. Deleting single files in it is fine, `
171
+ + `and so is a cache or build folder in it (${[...CACHES].join(', ')})${agentOf(input) === 'main' ? '. Once that subagent has finished, you may delete the folder' : ''}.`;
172
+ if (!m && !namedBy(input.session_id, n, agentOf(input)) && bigger(names.length > 1 || rest.length === 2 ? dir : p, UNTRACKED_MAX))
173
+ return `${dir} in your session's scratchpad holds more than ${UNTRACKED_MAX} files, and dibs can't tell which agent of your session made it (it's older than dibs's record), so ${t.why} can't delete it all.\n`
174
+ + 'Ask the agents of your session whose it is, or have the person delete it. Deleting single files in it is fine.';
175
+ }
176
+ return null;
177
+ }
178
+
179
+ // Note the agent behind each write into a scratchpad folder nobody has written into yet.
180
+ // A program can make a scratchpad folder dibs doesn't see it write
181
+ // (xcodebuild -derivedDataPath scratchpad/dd made fix-app's 0.5 GB of derived
182
+ // data on 2026-10-18), so a folder that doesn't exist yet and is named
183
+ // anywhere in a command counts as made by whoever ran it. And an agent whose
184
+ // command named a folder dibs has no record of may delete it, whatever its size.
185
+ function noteMakers(input, split, written) {
186
+ const made = new Set(), named = new Set(), gone = new Set();
187
+ const top = p => {
188
+ const at = inSession(real(p));
189
+ return at && at[1][0] === 'scratchpad' && at[1].length >= 2 && !GLOB.test(at[1][1]) && path.basename(at[0]) === input.session_id
190
+ ? [at[1][1], path.join(at[0], 'scratchpad', at[1][1])] : null;
191
+ };
192
+ for (const t of written) {
193
+ if (t.guess != null) continue;
194
+ const f = top(t.path);
195
+ // A folder deleted whole (this call got past the guard) takes its record with it, for whoever makes the next one.
196
+ if (f && t.recursive && real(t.path) === f[1]) gone.add(f[0]);
197
+ if (f && !t.recursive && !['rm', 'rmdir', 'unlink', 'shred', 'find'].includes(t.why)) made.add(f[0]);
198
+ }
199
+ for (const p of namedPaths(input, split)) {
200
+ const f = top(p);
201
+ if (!f) continue;
202
+ named.add(f[0]);
203
+ if (!fs.existsSync(f[1])) made.add(f[0]);
204
+ }
205
+ for (const n of gone) { made.delete(n); named.delete(n); }
206
+ if (!made.size && !named.size && !gone.size) return;
207
+ // Best effort: a full disk or a race costs only a record, never the call.
208
+ try {
209
+ const dir = makersDir(input.session_id);
210
+ fs.mkdirSync(dir, { recursive: true });
211
+ for (const n of gone) {
212
+ const k = encodeURIComponent(n);
213
+ for (const f of fs.readdirSync(dir)) if (f === k || f.startsWith(`${k}@`)) fs.rmSync(path.join(dir, f), { force: true });
214
+ }
215
+ let fresh = false;
216
+ for (const n of made) {
217
+ try { fs.writeFileSync(path.join(dir, encodeURIComponent(n)), JSON.stringify({ agent: agentOf(input), type: input.agent_type || null, at: Date.now() }), { flag: 'wx' }); fresh = true; }
218
+ catch {}
219
+ }
220
+ // name@agent: encodeURIComponent turns any @ into %40, so these never meet a folder's own record.
221
+ for (const n of named) fs.writeFileSync(path.join(dir, `${encodeURIComponent(n)}@${encodeURIComponent(agentOf(input))}`), '');
222
+ if (fresh) pruneMakers();
223
+ } catch {}
224
+ }
225
+ const namedBy = (session, name, agent) => fs.existsSync(path.join(makersDir(session), `${encodeURIComponent(name)}@${encodeURIComponent(agent)}`));
226
+
227
+ // Every word of a Bash command that could be a path in this session's folder,
228
+ // absolute: arguments anywhere (after dibs run's --, too), and --out=<path> values.
229
+ function namedPaths(input, split) {
230
+ const cmd = input.tool_name === 'Bash' && input.tool_input?.command;
231
+ if (typeof cmd !== 'string' || !(cmd.includes(input.session_id) || String(input.cwd).includes(input.session_id))) return [];
232
+ return namedIn(cmd, typeof input.cwd === 'string' ? input.cwd : process.cwd(), input.session_id, split, 0);
233
+ }
234
+ // A script handed to a shell with -c is read the same way, from the folder the shell starts in:
235
+ // dibs run xcode-build -- sh -c '... -derivedDataPath <scratchpad>/dd-test' made 177 MB on
236
+ // 2026-10-20 that nobody could delete, since the path was one quoted word.
237
+ const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh']);
238
+ const NESTED = 3; // sh -c "bash -c '...'" is as deep as anyone goes
239
+ function namedIn(cmd, cwd, session, split, depth) {
240
+ const segs = split(cmd);
241
+ if (!segs) return [];
242
+ const out = [];
243
+ for (const { name, args, dir } of commands(segs, cwd)) {
244
+ if (!name) continue;
245
+ args.forEach((w, k) => {
246
+ // A script's own $VARS are its business: it's split again, with its own assignments.
247
+ const shell = args[k - 1]?.text === '-c' && (k > 1 ? SHELLS.has(path.basename(args[k - 2].text)) : SHELLS.has(name));
248
+ if (shell && depth < NESTED && dir) { out.push(...namedIn(w.text, dir, session, split, depth + 1)); return; }
249
+ if (w.opaque) return;
250
+ const v = w.text.startsWith('-') ? w.text.split('=').slice(1).join('=') : w.text;
251
+ const p = v && expand(v);
252
+ if (!p || (!path.isAbsolute(p) && !dir)) return;
253
+ const abs = path.resolve(dir || '/', p);
254
+ if (abs.includes(session)) out.push(abs);
255
+ });
256
+ }
257
+ return out;
258
+ }
259
+
260
+ // Records of sessions whose temp folder is gone.
261
+ function pruneMakers() {
262
+ const top = path.join(dibsHome(), 'scratch'), live = new Set();
263
+ for (const root of claudeTmp()) {
264
+ let projects = [];
265
+ try { projects = fs.readdirSync(root); } catch {}
266
+ for (const p of projects) { try { for (const s of fs.readdirSync(path.join(root, p))) live.add(s); } catch {} }
267
+ }
268
+ if (!live.size) return; // the temp folder couldn't be read: keep everything
269
+ for (const s of fs.readdirSync(top)) if (!live.has(s)) fs.rmSync(path.join(top, s), { recursive: true, force: true });
270
+ }
271
+
272
+ // mkdir's folders, which bashWrites leaves out: making a folder isn't a write to a leased file.
273
+ function mkdirs(input, split) {
274
+ const segs = input.tool_name === 'Bash' && typeof input.tool_input?.command === 'string' && /\bmkdir\b/.test(input.tool_input.command) && split(input.tool_input.command);
275
+ if (!segs) return [];
276
+ const out = [];
277
+ for (const { name, args, dir } of commands(segs, typeof input.cwd === 'string' ? input.cwd : process.cwd()))
278
+ if (name === 'mkdir') for (const w of operands(args, new Set(['-m', '--mode']))) { const f = from(dir, w); if (f) out.push({ path: f.text, why: 'mkdir' }); }
279
+ return out;
280
+ }
281
+
282
+ // The hook's answer for one tool call: a deny when it would delete or write in
283
+ // a temp folder that isn't this session's, or recursively delete what another
284
+ // agent of the session made in its own, else null.
285
+ export function tmpGuard(input, split) {
286
+ if (!EDITS.has(input?.tool_name) && input?.tool_name !== 'Bash') return null;
287
+ const session = input.session_id;
288
+ if (typeof session !== 'string' || !session || !claudeTmp().length) return null;
289
+ const written = targets(input, split, true);
290
+ for (const t of written) {
291
+ // interop's sweep of the shared scratchpad was find $S ... -exec rm -rf {} +, on 2026-10-16.
292
+ if (t.bare) return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason:
293
+ `dibs: ${t.why} would delete everything in a folder named only by a variable dibs can't see the value of, so it's turned away: it might be another agent's or another session's folder.\n`
294
+ + 'Write the path out, or set the variable earlier in the same command (S=/path/to/dir; rm -rf "$S"), so dibs can check it. A path with a literal end, like "$S/build", is fine.' } };
295
+ const other = t.guess != null ? guessedOthers(t.guess, session) : othersTmp(real(t.path), session);
296
+ const own = !other && t.recursive && t.guess == null ? ownDelete(real(t.path), t, input) : null;
297
+ if (own) return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: `dibs: ${own}` } };
298
+ if (!other) continue;
299
+ const root = claudeTmp().find(r => other === r || other.startsWith(r + '/'));
300
+ const shown = t.guess != null ? other : real(t.path);
301
+ const whose = path.relative(root, other).split('/').length === 2 && !GLOB.test(other) ? "another Claude Code session's scratch folder"
302
+ : "Claude Code's temp folder, which holds every session's scratch folders";
303
+ return { hookSpecificOutput: {
304
+ hookEventName: 'PreToolUse',
305
+ permissionDecision: 'deny',
306
+ permissionDecisionReason: `dibs: ${shown} ${shown === root ? `is ${whose}` : shown.startsWith(root + '/') ? `is in ${whose}` : `holds ${root}, every Claude Code session's temp folder`}, so ${t.why} can't delete or write there. `
307
+ + `The person's rule: never delete or overwrite anything under ${root} except in your own session's folder (${session}). `
308
+ + 'Another agent may be using those files right now. Ask the person, or that session, instead. Reading them is fine.',
309
+ } };
310
+ }
311
+ noteMakers(input, split, [...written, ...mkdirs(input, split)]);
312
+ return null;
313
+ }
314
+
315
+ // The path with symlinks resolved up to its first wildcard, so /tmp/x and
316
+ // /private/tmp/x are the same lease. The native call also returns the name as
317
+ // it is on disk: on macOS SRC/A.ts opens src/a.ts, and the JS one keeps the
318
+ // case you typed. Parts that don't exist yet stay as written.
319
+ function real(abs) {
320
+ const segs = abs.split('/');
321
+ let k = segs.findIndex(s => GLOB.test(s));
322
+ if (k < 0) k = segs.length;
323
+ for (let i = k; i > 1; i--) {
324
+ try { return [fs.realpathSync.native(segs.slice(0, i).join('/')), ...segs.slice(i)].join('/'); } catch {}
325
+ }
326
+ return abs;
327
+ }
328
+
329
+ // macOS and Windows disks ignore letter case (and macOS Unicode normalization),
330
+ // so names that don't exist yet compare that way too. A case-sensitive volume
331
+ // there can only cause a refusal too many, never a write let through.
332
+ const FOLD = ['darwin', 'win32'].includes(process.platform);
333
+ const folded = s => (FOLD ? s.normalize('NFC').toLowerCase() : s);
334
+
335
+ // Every git worktree of a repo keys a file the same way: by its path in the
336
+ // main worktree (the one whose .git is a folder), so agents editing one file
337
+ // from two worktrees collide. Found by reading .git files, never by running
338
+ // git, since the hook does this on every tool call. Anything unexpected keeps
339
+ // the path as it is.
340
+ const trees = new Map(); // folder -> [the worktree it's in, that repo's main worktree], or null outside git
341
+
342
+ // The project a folder belongs to, for a resource that's one at a time per project
343
+ // (exclusiveBy: "repo", deploys): its repo's origin URL, the same in every clone and
344
+ // worktree of it; else that repo's main worktree; else the folder itself.
345
+ export function projectKey(dir) {
346
+ const abs = path.resolve(dir);
347
+ const wt = worktreeOf(real(abs));
348
+ if (!wt) return abs;
349
+ try {
350
+ const url = fs.readFileSync(path.join(wt[1], '.git', 'config'), 'utf8').match(/\[remote "origin"\][^[]*?\burl\s*=\s*(\S+)/)?.[1];
351
+ if (url) return url;
352
+ } catch {}
353
+ return wt[1];
354
+ }
355
+
356
+ function worktreeOf(dir) {
357
+ if (trees.has(dir)) return trees.get(dir);
358
+ let st = null, found = null;
359
+ try { st = fs.statSync(path.join(dir, '.git')); } catch {}
360
+ if (st?.isDirectory()) found = [dir, dir];
361
+ else if (st?.isFile()) found = [dir, mainOf(dir) || dir];
362
+ else if (path.dirname(dir) !== dir) found = worktreeOf(path.dirname(dir));
363
+ trees.set(dir, found);
364
+ return found;
365
+ }
366
+
367
+ // The main worktree of a linked worktree at dir, or null when its .git file
368
+ // isn't one: a submodule's points into .git/modules and has no commondir.
369
+ function mainOf(dir) {
370
+ try {
371
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(fs.readFileSync(path.join(dir, '.git'), 'utf8'));
372
+ if (!m) return null;
373
+ const gitdir = path.resolve(dir, m[1]);
374
+ let common;
375
+ try { common = path.resolve(gitdir, fs.readFileSync(path.join(gitdir, 'commondir'), 'utf8').trim()); }
376
+ catch {
377
+ if (path.basename(path.dirname(gitdir)) !== 'worktrees') return null;
378
+ common = path.dirname(path.dirname(gitdir));
379
+ }
380
+ if (path.basename(common) === '.git') return fs.realpathSync(path.dirname(common));
381
+ // A submodule's own worktrees: its checkout is core.worktree. A bare repo has none, so the repo itself stands in.
382
+ let config = '';
383
+ try { config = fs.readFileSync(path.join(common, 'config'), 'utf8'); } catch {}
384
+ const w = /^\s*worktree\s*=\s*(.+?)\s*$/m.exec(config);
385
+ return fs.realpathSync(w ? path.resolve(common, w[1]) : common);
386
+ } catch { return null; }
387
+ }
388
+
389
+ // An absolute path or glob with symlinks resolved (real), moved from the
390
+ // worktree it's in to the same place in the main one.
391
+ function canon(p) {
392
+ if (!path.isAbsolute(p)) return p;
393
+ try {
394
+ const segs = p.split('/');
395
+ let k = segs.findIndex(s => GLOB.test(s));
396
+ if (k < 0) k = segs.length;
397
+ const w = worktreeOf(segs.slice(0, k).join('/') || '/');
398
+ return !w || w[0] === w[1] ? p : w[1] + p.slice(w[0].length);
399
+ } catch { return p; }
400
+ }
401
+
402
+ // A stored file lease under the key this version gives it: an older dibs may
403
+ // have taken it under a worktree's own path.
404
+ export const fileKey = r => (isFiles(r) ? FILES + canon(r.slice(FILES.length)) : r);
405
+
406
+ // ' in another copy of this repo (wt-trust)' when lease l was taken from a
407
+ // different worktree of the repo cwd is in, else ''.
408
+ export function elsewhere(l, cwd = process.cwd()) {
409
+ try {
410
+ if (typeof l?.cwd !== 'string') return '';
411
+ const mine = worktreeOf(real(path.resolve(cwd))), theirs = worktreeOf(real(l.cwd));
412
+ if (!mine || !theirs || mine[1] !== theirs[1] || mine[0] === theirs[0]) return '';
413
+ return ` in another copy of this repo (${path.basename(theirs[0])})`;
414
+ } catch { return ''; }
415
+ }
416
+
417
+ const expand = p => (p === '~' || p.startsWith('~/') ? os.homedir() + p.slice(1) : p);
418
+
419
+ // files:<path or glob> as stored: absolute, relative paths taken from the git
420
+ // root (or the folder, outside git), and in the main worktree (canon). Null
421
+ // for an empty one.
422
+ // A list of resources as typed, split at its commas, with each file lease's
423
+ // braces expanded the way a shell would: 'files:src/{a.ts,b/c.ts},test' is
424
+ // files:src/a.ts, files:src/b/c.ts and test. dibs's globs don't know braces,
425
+ // and a comma inside them split one lease into two on 2026-10-15, the second
426
+ // a resource named after a file that waited on the machine like a job.
427
+ const BRACES = 64; // more names than this from one lease is a typo, not a list
428
+ export function resList(text) {
429
+ const out = [];
430
+ let depth = 0, cur = '';
431
+ for (const c of text) {
432
+ if (c === '{') depth++;
433
+ else if (c === '}' && depth) depth--;
434
+ if (c === ',' && !depth) { out.push(cur); cur = ''; } else cur += c;
435
+ }
436
+ out.push(cur);
437
+ return out.filter(Boolean).flatMap(r => (isFiles(r) ? braces(r) : [r]));
438
+ }
439
+ function braces(r) {
440
+ const open = r.indexOf('{');
441
+ let depth = 0, close = -1;
442
+ for (let i = open; open >= 0 && i < r.length; i++) {
443
+ if (r[i] === '{') depth++;
444
+ else if (r[i] === '}' && !--depth) { close = i; break; }
445
+ }
446
+ if (close < 0) return [r];
447
+ const parts = [];
448
+ let cur = '';
449
+ depth = 0;
450
+ for (const c of r.slice(open + 1, close)) {
451
+ if (c === '{') depth++;
452
+ else if (c === '}') depth--;
453
+ if (c === ',' && !depth) { parts.push(cur); cur = ''; } else cur += c;
454
+ }
455
+ parts.push(cur);
456
+ if (parts.length < 2) return [r];
457
+ return parts.flatMap(p => braces(r.slice(0, open) + p + r.slice(close + 1))).slice(0, BRACES);
458
+ }
459
+
460
+ export function fileRes(r, cwd = process.cwd()) {
461
+ if (!isFiles(r)) return r;
462
+ const p = r.slice(FILES.length).trim();
463
+ if (!p) return null;
464
+ return FILES + canon(real(path.resolve(gitRoot(cwd) || cwd, expand(p))));
465
+ }
466
+
467
+ // How a lease reads to a person: relative to the git root you're in, else from ~.
468
+ export function short(r, cwd = process.cwd()) {
469
+ if (!isFiles(r)) return r;
470
+ const p = r.slice(FILES.length);
471
+ const root = gitRoot(cwd) && real(gitRoot(cwd));
472
+ for (const r of root ? [canon(root), root] : []) if (p.startsWith(r + '/')) return FILES + p.slice(r.length + 1);
473
+ const home = os.homedir();
474
+ return FILES + (p.startsWith(home + '/') ? `~${p.slice(home.length)}` : p);
475
+ }
476
+
477
+ function segRe(s) {
478
+ return new RegExp(`^${s.replace(/\*+/g, '*').split('').map(c => (c === '*' ? '.*' : c === '?' ? '.' : c.replace(/[.+^${}()|[\]\\]/g, '\\$&'))).join('')}$`);
479
+ }
480
+
481
+ // Could one path name match both segments? Two wildcards are compared only by
482
+ // what's fixed at each end; anything subtler counts as a yes.
483
+ function segment(x, y) {
484
+ const gx = GLOB.test(x), gy = GLOB.test(y);
485
+ if (!gx && !gy) return x === y;
486
+ if (!gx) return segRe(y).test(x);
487
+ if (!gy) return segRe(x).test(y);
488
+ const head = s => s.slice(0, s.search(GLOB));
489
+ const tail = s => s.slice(Math.max(s.lastIndexOf('*'), s.lastIndexOf('?')) + 1);
490
+ const [hx, hy, tx, ty] = [head(x), head(y), tail(x), tail(y)];
491
+ return (hx.startsWith(hy) || hy.startsWith(hx)) && (tx.endsWith(ty) || ty.endsWith(tx));
492
+ }
493
+
494
+ // One running out before the other means a folder and something inside it.
495
+ function walk(a, i, b, j) {
496
+ if (i === a.length || j === b.length) return true;
497
+ if (a[i] === '**') return walk(a, i + 1, b, j) || walk(a, i, b, j + 1);
498
+ if (b[j] === '**') return walk(a, i, b, j + 1) || walk(a, i + 1, b, j);
499
+ return segment(a[i], b[j]) && walk(a, i + 1, b, j + 1);
500
+ }
501
+
502
+ // Do two paths or globs (with or without files:) share any file? The same
503
+ // file, a folder and anything under it, or globs some name could match both.
504
+ // Unsure counts as yes. Both are keyed by the main worktree first (canon), so
505
+ // a lease an older dibs stored under a worktree's own path still counts.
506
+ export function overlap(a, b) {
507
+ const segs = p => folded(canon(p.replace(FILES, ''))).split('/').filter(Boolean);
508
+ return walk(segs(a), 0, segs(b), 0);
509
+ }
510
+
511
+ // Two resource names that can't both be held by different sessions at once.
512
+ export const clash = (a, b) => a === b || (isFiles(a) && isFiles(b) && overlap(a, b));
513
+
514
+ // ----- the hook -----
515
+
516
+ const EDITS = new Set(['Edit', 'Write', 'MultiEdit', 'NotebookEdit']);
517
+ const dibsHome = () => process.env.DIBS_HOME || path.join(os.homedir(), '.dibs');
518
+ const statePath = () => path.join(dibsHome(), 'state.json');
519
+
520
+ // A pid still running. EPERM means it runs as someone else, which still counts.
521
+ const running = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
522
+
523
+ // Live file leases, read without the lock: state.json is replaced by rename,
524
+ // so a read sees a whole file. A dead holder or a hold past its time no longer
525
+ // counts, though only the next dibs call takes it off the books.
526
+ function leases(t = Date.now()) {
527
+ let s;
528
+ try { s = JSON.parse(fs.readFileSync(statePath(), 'utf8')); } catch (e) { if (e.code === 'ENOENT') return []; throw e; }
529
+ return (s.leases || []).filter(l => Array.isArray(l.res) && l.res.some(isFiles)
530
+ && (l.kind !== 'hold' || t < l.expires) && (!l.pid || running(l.pid)));
531
+ }
532
+
533
+ // The pids above this hook, from one process-table read. Claude Code runs the
534
+ // hook, so its session is among them.
535
+ let above = null;
536
+ function ancestors() {
537
+ if (above) return above;
538
+ const up = new Map();
539
+ for (const line of execFileSync('ps', ['-A', '-o', 'pid=,ppid='], { encoding: 'utf8', timeout: 2000 }).trim().split('\n')) {
540
+ const [pid, ppid] = line.trim().split(/\s+/).map(Number);
541
+ up.set(pid, ppid);
542
+ }
543
+ above = new Set();
544
+ for (let p = callerPid(); p > 1 && !above.has(p); p = up.get(p)) above.add(p);
545
+ return above;
546
+ }
547
+
548
+ // A lease is the caller's when it was taken by the same agent (when stamped)
549
+ // of the session running this hook. Without a session (a terminal, a test),
550
+ // the same DIBS_AGENT name. A lease the main thread took covers its own
551
+ // subagents (coversAgent).
552
+ function mine(l, input) {
553
+ if (!coversAgent(l, { agentId: input.agent_id || 'main' })) return false;
554
+ if (l.sessionId && typeof input.session_id === 'string') return l.sessionId === input.session_id;
555
+ const session = l.spid || (l.kind === 'hold' ? l.pid : null);
556
+ if (session) return ancestors().has(session);
557
+ return !!process.env.DIBS_AGENT && [l.who, l.agent].includes(process.env.DIBS_AGENT);
558
+ }
559
+
560
+ // Words before the program that don't change what it writes, each with its
561
+ // flags that take a value.
562
+ const PREFIXES = {
563
+ sudo: ['-u', '-g', '-C', '-D', '-h', '-p', '-U', '-r', '-t', '-T'], command: [], nohup: [], time: ['-o'], exec: ['-a'], builtin: [],
564
+ nice: ['-n'], env: ['-u', '--unset', '-C', '--chdir', '-S'], caffeinate: ['-t', '-w'], npx: ['-p', '--package'], bunx: ['-p', '--package'],
565
+ timeout: ['-s', '-k', '--signal', '--kill-after'], gtimeout: ['-s', '-k', '--signal', '--kill-after'],
566
+ xargs: ['-I', '-J', '-L', '-n', '-P', '-s', '-d', '-E', '-a', '-R', '-S'],
567
+ };
568
+ const KEYWORDS = new Set(['then', 'do', 'else', 'elif', 'if', 'while', 'until', '!']);
569
+ const ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/;
570
+ const PM = new Set(['npm', 'pnpm', 'yarn', 'bun']);
571
+ const RUN = new Set(['exec', 'dlx', 'x']);
572
+
573
+ // The words that aren't flags. Everything after -- counts, and a flag that
574
+ // takes a value takes the next word with it.
575
+ function operands(args, valued = new Set()) {
576
+ const out = [];
577
+ for (let k = 0; k < args.length; k++) {
578
+ const t = args[k].text;
579
+ if (t === '--') { out.push(...args.slice(k + 1)); break; }
580
+ if (t.startsWith('-') && t.length > 1) { if (valued.has(t)) k++; continue; }
581
+ out.push(args[k]);
582
+ }
583
+ return out;
584
+ }
585
+
586
+ // sed -i (GNU) and sed -i '' (macOS): every word after the script is a file it rewrites.
587
+ function sedFiles(args) {
588
+ let inPlace = false, script = false;
589
+ const files = [];
590
+ for (let k = 0; k < args.length; k++) {
591
+ const t = args[k].text;
592
+ if (t === '-i' || t === '-I') {
593
+ inPlace = true;
594
+ const n = args[k + 1]?.text;
595
+ if (n === '' || n?.startsWith('.')) k++; // macOS takes the backup suffix as its own word
596
+ }
597
+ else if (t.startsWith('--in-place') || /^-[a-zA-Z]*i/.test(t)) inPlace = true;
598
+ else if (t === '-e' || t === '-f') { script = true; k++; }
599
+ else if (t.startsWith('--expression') || t.startsWith('--file')) script = true;
600
+ else if (t.startsWith('-') && t.length > 1) continue;
601
+ else if (!script) script = true;
602
+ else files.push(args[k]);
603
+ }
604
+ return inPlace ? files : [];
605
+ }
606
+
607
+ // perl -pi -e '...' files.
608
+ function perlFiles(args) {
609
+ if (!args.some(w => /^-[a-zA-Z]*i/.test(w.text))) return [];
610
+ let code = false;
611
+ const files = [];
612
+ for (let k = 0; k < args.length; k++) {
613
+ const t = args[k].text;
614
+ if (/^-[a-zA-Z]*[eE]$/.test(t)) { code = true; k++; }
615
+ else if (!t.startsWith('-')) files.push(args[k]);
616
+ }
617
+ return code ? files : files.slice(1);
618
+ }
619
+
620
+ // A word as an absolute path from folder dir, or null when that can't be known.
621
+ function from(dir, w) {
622
+ const p = !w.opaque && expand(w.text);
623
+ return p && (dir || path.isAbsolute(p)) ? { ...w, text: path.resolve(dir || '/', p) } : null;
624
+ }
625
+ const isDir = (dir, w) => { try { return fs.statSync(from(dir, w).text).isDirectory(); } catch { return false; } };
626
+ const exists = (dir, w) => { try { return !!fs.statSync(from(dir, w).text); } catch { return false; } };
627
+
628
+ // Where cp, mv, ln, install and rsync write. Into a folder, each source lands
629
+ // under its own name: cp a.ts src/ writes src/a.ts and nothing else there. A
630
+ // recursive copy of a folder's contents (cp -R lib/ src) can overwrite
631
+ // anything in it, so that counts as the whole folder. mv also takes its
632
+ // sources away, which writes them too.
633
+ function copies(name, args, dir) {
634
+ const t = args.findIndex(w => w.text === '-t' || w.text === '--target-directory');
635
+ const o = operands(args, new Set(['-S', '--suffix', '-t', '--target-directory']));
636
+ const to = t >= 0 ? args[t + 1] : o.length >= 2 ? o.at(-1) : null;
637
+ if (!to) return [];
638
+ // rsync --delete removes whatever else is in the folder it copies into.
639
+ if (name === 'rsync' && args.some(w => w.text.startsWith('--delete'))) return [{ ...to, recursive: true }];
640
+ const srcs = t >= 0 ? o : o.slice(0, -1);
641
+ const gone = name === 'mv' ? srcs : [];
642
+ const folder = t >= 0 || (!args.some(w => w.text === '-T') && (to.text.endsWith('/') || isDir(dir, to)));
643
+ if (!folder || to.opaque) return [...gone, to];
644
+ const recursive = name === 'rsync' || args.some(w => /^-[a-zA-Z]*[rRa]/.test(w.text) || w.text === '--recursive' || w.text === '--archive');
645
+ const whole = srcs.some(s => s.opaque || (recursive && s.text.endsWith('/')));
646
+ return [...gone, ...(whole ? [to] : srcs.map(s => ({ ...to, text: path.join(to.text, path.basename(s.text)) })))];
647
+ }
648
+
649
+ // git -C <dir> runs in that folder. rm, mv, restore and checkout write the
650
+ // paths they name: after --, or ones that exist (git checkout . reverts them
651
+ // all; git checkout main is a branch). stash, reset --hard, apply, clean,
652
+ // checkout -f, switch --discard-changes and an --autostash pull, rebase or
653
+ // merge rewrite files nobody named, so they count as writing the whole repo.
654
+ // Those, and checkout, restore and clean of named paths, only touch the copy
655
+ // in the worktree they run in (tree), never a sibling worktree's.
656
+ const GIT_VALUED = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path', '--config-env']);
657
+ function gitWrites(args, dir, input) {
658
+ let k = 0, at = dir;
659
+ for (; args[k]?.text.startsWith('-'); k += GIT_VALUED.has(args[k].text) ? 2 : 1)
660
+ if (args[k].text === '-C') at = args[k + 1] ? from(at, args[k + 1])?.text ?? null : null;
661
+ const sub = args[k]?.text, rest = args.slice(k + 1), has = (...f) => rest.some(w => f.includes(w.text));
662
+ const root = () => (at ? [{ text: gitRoot(at) || at, opaque: false, tree: true }] : []);
663
+ let out = [];
664
+ if (sub === 'rm' || sub === 'mv') return operands(rest).map(w => from(at, w)).filter(Boolean);
665
+ if (sub === 'restore') {
666
+ // --staged alone changes the index, not a file.
667
+ if (has('-S', '--staged') && !has('-W', '--worktree', '-SW', '-WS')) return [];
668
+ out = operands(rest, new Set(['-s', '--source']));
669
+ }
670
+ else if (sub === 'checkout') {
671
+ const dd = rest.findIndex(w => w.text === '--');
672
+ out = dd >= 0 ? rest.slice(dd + 1) : operands(rest, new Set(['-b', '-B', '--orphan'])).filter(w => exists(at, w));
673
+ if (!out.length && has('-f', '--force')) return root();
674
+ }
675
+ else if (sub === 'switch') return has('-f', '--force', '--discard-changes') ? root() : [];
676
+ else if (['pull', 'rebase', 'merge'].includes(sub)) return has('--autostash') ? root() : [];
677
+ else if (sub === 'stash') return ['list', 'show', 'drop', 'clear', 'create', 'store'].includes(rest[0]?.text) ? [] : root();
678
+ else if (sub === 'reset') return has('--hard', '--merge', '--keep') ? root() : [];
679
+ else if (sub === 'apply' || sub === 'am') return has('--check', '--stat', '--numstat', '--summary', '--cached', '--show-current-patch') ? [] : patched(rest, at, input);
680
+ else if (sub === 'clean') {
681
+ if (has('-n', '--dry-run')) return [];
682
+ out = operands(rest, new Set(['-e', '--exclude']));
683
+ if (!out.length) return root();
684
+ }
685
+ return out.map(w => from(at, w)).filter(Boolean).map(w => ({ ...w, tree: true }));
686
+ }
687
+
688
+ // The files a git apply or git am writes, read from the patches it's given:
689
+ // new content, so each counts as an edit to that file, with the
690
+ // cross-worktree check edits get. A patch dibs can't read (stdin, a pipe, a
691
+ // $VAR, a missing or huge file, a quoted name) or an am picking up where it
692
+ // stopped counts as writing the whole repo, every worktree's leases included.
693
+ const PATCH_VALUED = new Set(['-p', '-C', '--exclude', '--include', '--directory', '--whitespace', '--build-fake-ancestor', '--patch-format', '--resolvemsg']);
694
+ const PATCH_MAX = 4 << 20; // bytes: the hook stays fast, and a patch this big is a release, not an edit
695
+ function patched(rest, at, input) {
696
+ const whole = at ? [{ text: gitRoot(at) || at, opaque: false }] : [];
697
+ const named = operands(rest, PATCH_VALUED);
698
+ const files = named.length ? named : input ? [{ text: input, opaque: false }] : [];
699
+ if (!files.length || rest.some(w => /^--(continue|skip|abort|quit|resolved|retry)$|^-r$/.test(w.text))) return whole;
700
+ let strip = 1, dir = '';
701
+ rest.forEach((w, k) => {
702
+ const v = w.text === '-p' ? rest[k + 1]?.text : /^-p(\d+)$/.exec(w.text)?.[1];
703
+ if (v != null && /^\d+$/.test(v)) strip = +v;
704
+ if (w.text === '--directory') dir = rest[k + 1]?.text ?? '';
705
+ else if (w.text.startsWith('--directory=')) dir = w.text.slice(12);
706
+ });
707
+ const base = path.join(gitRoot(at || '/') || at || '/', dir);
708
+ const out = [];
709
+ for (const f of files) {
710
+ const names = f.text !== '-' && readNames(from(at, f)?.text, strip);
711
+ if (!names) return whole;
712
+ out.push(...names.map(n => ({ text: path.join(base, n), opaque: false })));
713
+ }
714
+ return out;
715
+ }
716
+
717
+ // The paths in the patch file at abs, -p strip removed, or null when it can't be read.
718
+ function readNames(abs, strip) {
719
+ try { return abs && fs.statSync(abs).size <= PATCH_MAX ? patchNames(fs.readFileSync(abs, 'utf8'), strip) : null; } catch { return null; }
720
+ }
721
+
722
+ // patch writes the file it's given (patch x.c fix.diff), its -o output, or
723
+ // the files its patch names, from -i or < file, relative to -d. Without -p
724
+ // GNU and BSD patch disagree on what's left of a name, and a patch read from a
725
+ // pipe can't be seen, so those count as writing the whole folder.
726
+ const PATCHER_VALUED = new Set(['-d', '--directory', '-i', '--input', '-o', '--output', '-p', '--strip', '-D', '--ifdef', '-F', '--fuzz',
727
+ '-r', '--reject-file', '-B', '--prefix', '-Y', '--basename-prefix', '-z', '--suffix', '-V', '--version-control', '-g', '--get', '--quoting-style']);
728
+ function patchWrites(args, dir, input) {
729
+ if (args.some(w => ['--dry-run', '-C', '--check'].includes(w.text))) return [];
730
+ const value = (short, long) => {
731
+ for (let k = 0; k < args.length; k++) {
732
+ const t = args[k].text;
733
+ if (t === short || t === long) return args[k + 1] ?? null;
734
+ if (t.startsWith(`${long}=`)) return { ...args[k], text: t.slice(long.length + 1) };
735
+ if (t.length > 2 && t.startsWith(short)) return { ...args[k], text: t.slice(2) };
736
+ }
737
+ return null;
738
+ };
739
+ const d = value('-d', '--directory'), out = value('-o', '--output'), ops = operands(args, PATCHER_VALUED);
740
+ if (out) return out.text === '-' ? [] : [out];
741
+ if (ops.length) return [ops[0]];
742
+ const at = d ? from(dir, d)?.text ?? null : dir;
743
+ const whole = d ? [d] : [{ text: '.', opaque: false }];
744
+ const p = value('-p', '--strip'), i = value('-i', '--input');
745
+ if (!at || !p || p.opaque || !/^\d+$/.test(p.text) || i?.opaque) return whole;
746
+ const names = readNames(i ? from(at, i)?.text : input, +p.text); // patch moves to -d before it reads -i
747
+ return names ? names.map(n => ({ text: path.join(at, n), opaque: false })) : whole;
748
+ }
749
+
750
+ // The paths a unified or git diff touches, relative to where it applies, or
751
+ // null when one can't be read safely. --- and +++ count only as a pair right
752
+ // before a hunk, so a removed line starting with -- doesn't name a file.
753
+ function patchNames(text, strip) {
754
+ const lines = text.split('\n'), out = new Set();
755
+ const cut = p => {
756
+ if (p === '/dev/null') return true;
757
+ if (p.startsWith('"')) return false;
758
+ const segs = p.split('/');
759
+ if (segs.length <= strip) return false;
760
+ out.add(segs.slice(strip).join('/'));
761
+ return true;
762
+ };
763
+ for (let i = 0; i < lines.length; i++) {
764
+ const l = lines[i].replace(/\r$/, '');
765
+ const m = /^(rename|copy) (from|to) (.+)$/.exec(l);
766
+ if (m) { if (m[3].startsWith('"')) return null; out.add(m[3]); continue; }
767
+ const g = /^diff --git (\S+) (\S+)$/.exec(l);
768
+ if (g) { if (!cut(g[1]) || !cut(g[2])) return null; continue; }
769
+ if (l.startsWith('diff --git ')) return null; // a name with a space or quotes
770
+ if (l.startsWith('--- ') && lines[i + 1]?.startsWith('+++ ') && lines[i + 2]?.startsWith('@@')) {
771
+ // A tab ends the name in plain diffs (a timestamp follows).
772
+ for (const side of [l.slice(4), lines[i + 1].slice(4)]) if (!cut(side.replace(/\r$/, '').split('\t')[0])) return null;
773
+ i += 2;
774
+ }
775
+ }
776
+ return out.size ? [...out] : null;
777
+ }
778
+
779
+ // Formatters and fixers that rewrite the files they're given in place: when
780
+ // one of `when` is there (none: always), unless one of `unless` is. sub: their
781
+ // subcommands, which aren't files. all: given no files, they do the whole folder.
782
+ const FORMATTERS = {
783
+ prettier: { when: ['--write', '-w'] },
784
+ eslint: { when: ['--fix'], all: true },
785
+ gofmt: { when: ['-w'] },
786
+ goimports: { when: ['-w'] },
787
+ 'clang-format': { when: ['-i'] },
788
+ 'swift-format': { when: ['-i', '--in-place'], sub: ['format', 'lint'] },
789
+ swiftformat: { unless: ['--lint', '--dryrun'] },
790
+ rustfmt: { unless: ['--check'] },
791
+ black: { unless: ['--check', '--diff'], all: true },
792
+ ruff: { when: ['format', '--fix'], unless: ['--check', '--diff'], sub: ['format', 'check'], all: true },
793
+ biome: { when: ['--write', '--apply', '--fix'], sub: ['format', 'check', 'lint'], all: true },
794
+ };
795
+ const FORMAT_VALUED = new Set(['-c', '--config', '--config-path', '--ignore-path', '--plugin', '--log-level', '--parser', '--ext', '--rule',
796
+ '-f', '--format', '-o', '--output-file', '--max-warnings', '--cache-location', '--swiftversion', '--rules', '--disable', '--enable',
797
+ '--exclude', '--indent', '--line-length', '--target-version', '--edition']);
798
+ function formatted(f, args) {
799
+ const has = list => args.some(w => list.includes(w.text));
800
+ if ((f.when && !has(f.when)) || (f.unless && has(f.unless))) return [];
801
+ const o = operands(args, FORMAT_VALUED);
802
+ if (f.sub?.includes(o[0]?.text)) o.shift();
803
+ return o.length || !f.all ? o : [{ text: '.', opaque: false }];
804
+ }
805
+
806
+ // find -delete, or find -exec rm (and the like), removes what it finds under
807
+ // its starting points: the words before its first test, or the folder it runs in.
808
+ const FIND_REMOVERS = new Set(['rm', 'rmdir', 'unlink', 'shred', 'truncate', 'mv']);
809
+ function findDeletes(args) {
810
+ const removes = args.some((w, k) => w.text === '-delete' || (/^-(exec|execdir|ok|okdir)$/.test(w.text) && FIND_REMOVERS.has(path.basename(args[k + 1]?.text || ''))));
811
+ return removes ? findRoots(args).map(w => ({ ...w, recursive: true })) : [];
812
+ }
813
+ function findRoots(args) {
814
+ const k = args.findIndex(w => /^[-(!]/.test(w.text));
815
+ const from = args.slice(0, k < 0 ? args.length : k);
816
+ return from.length ? from : [{ text: '.', opaque: false }];
817
+ }
818
+
819
+ // $NAME and ${NAME} in a word, from assignments earlier in the same command
820
+ // (S=/x; find $S, export S=/x) or the hook's own environment, so a path in a
821
+ // variable is checked like one typed out. Anything else ($(...), ${X:-y}, $1,
822
+ // a name set nowhere) leaves the word unknown.
823
+ function resolved(w, vars) {
824
+ if (!w.opaque || /\$\(|`/.test(w.text)) return w;
825
+ let unknown = false;
826
+ const text = w.text.replace(/\$\{(\w+)\}|\$([A-Za-z_]\w*)/g, (m, a, b) => {
827
+ const v = vars[a || b] ?? process.env[a || b];
828
+ if (v == null) unknown = true;
829
+ return v ?? m;
830
+ });
831
+ return unknown || text.includes('$') ? w : { ...w, text, opaque: false };
832
+ }
833
+ const assign = (w, vars) => { const k = w.text.indexOf('='); vars[w.text.slice(0, k)] = w.text.slice(k + 1); };
834
+
835
+ // The words a command writes to, for the commands that obviously write, from
836
+ // folder dir. Most are as typed; ones worked out here are absolute.
837
+ function writtenBy(name, args, dir, input) {
838
+ const ops = (valued = []) => operands(args, new Set(valued));
839
+ if (FORMATTERS[name]) return formatted(FORMATTERS[name], args);
840
+ switch (name) {
841
+ // A recursive delete takes a whole folder: rm -r, rmdir -p.
842
+ case 'rm': case 'rmdir': {
843
+ const deep = args.some(w => (name === 'rm' ? /^-[a-zA-Z]*[rR]/.test(w.text) || w.text === '--recursive' : /^-[a-zA-Z]*p/.test(w.text) || w.text === '--parents'));
844
+ return deep ? ops().map(w => ({ ...w, recursive: true })) : ops();
845
+ }
846
+ case 'unlink': case 'shred': case 'touch': case 'tee': return ops();
847
+ case 'truncate': return ops(['-s', '--size', '-r', '--reference']);
848
+ case 'cp': case 'mv': case 'ln': case 'install': case 'rsync': return copies(name, args, dir);
849
+ case 'sed': case 'gsed': return sedFiles(args);
850
+ case 'perl': return perlFiles(args);
851
+ case 'find': return findDeletes(args);
852
+ case 'dd': return args.filter(w => w.text.startsWith('of=')).map(w => ({ ...w, text: w.text.slice(3) }));
853
+ case 'git': return gitWrites(args, dir, input);
854
+ case 'patch': return patchWrites(args, dir, input);
855
+ default: return [];
856
+ }
857
+ }
858
+
859
+ // Is this redirect target written to? Read the operator just before it:
860
+ // > >> &> >| <> write, < and <<< read, and >&2 is a file descriptor.
861
+ function redirOp(src, w) {
862
+ let k = w.start - 1;
863
+ while (src[k] === ' ' || src[k] === '\t') k--;
864
+ let op = '';
865
+ while (k >= 0 && '<>&|'.includes(src[k])) op = src[k--] + op;
866
+ return op;
867
+ }
868
+ function redirWrites(src, w) {
869
+ const op = redirOp(src, w);
870
+ return op.includes('>') && !(op.endsWith('&') && /^(\d+|-)$/.test(w.text));
871
+ }
872
+
873
+ // Each simple command of a split shell line: its program, its arguments, all
874
+ // its words, and the folder it runs in, following cd, pushd and popd. A cd in
875
+ // a ( ) subshell ends with it. After a cd we can't follow, the folder is null
876
+ // and only absolute paths are known. A command run by xargs also gets the
877
+ // words of the command piped into it, which is where its files come from.
878
+ function* commands(segs, cwd) {
879
+ let dir = cwd, last = null, depth = 0, prev = null; // last: where cd - goes
880
+ const outer = [], pushed = [], vars = {};
881
+ for (const seg of segs) {
882
+ const d = seg.depth ?? 0;
883
+ while (depth < d) outer[depth++] = [dir, last];
884
+ while (depth > d) [dir, last] = outer[--depth];
885
+ const words = seg.filter(w => !w.redir).map(w => resolved(w, vars));
886
+ let i = 0, xargs = null;
887
+ for (let t; (t = words[i]) && !t.opaque;) {
888
+ const b = path.basename(t.text);
889
+ if (ASSIGN.test(t.text)) assign(t, vars);
890
+ if (KEYWORDS.has(t.text) || ASSIGN.test(t.text)) { i++; continue; }
891
+ // npx prettier, pnpm exec eslint, yarn prettier: the tool they run.
892
+ const next = words[i + 1]?.text;
893
+ if (PM.has(b) && (RUN.has(next) || FORMATTERS[next])) { i += RUN.has(next) ? 2 : 1; continue; }
894
+ if (!PREFIXES[b]) break;
895
+ const at = i++;
896
+ while (words[i]?.text.startsWith('-')) i += PREFIXES[b].includes(words[i].text) ? 2 : 1;
897
+ if (b === 'timeout' || b === 'gtimeout') i++; // the duration
898
+ if (b === 'xargs') xargs = words.slice(at + 1, i);
899
+ }
900
+ const [prog, ...own] = words.slice(i);
901
+ const name = prog && !prog.opaque ? path.basename(prog.text) : null;
902
+ if (name === 'export' || name === 'declare' || name === 'readonly') for (const w of own) if (ASSIGN.test(w.text) && !w.opaque) assign(w, vars);
903
+ // xargs -I puts its input where it likes, so the files can't be placed.
904
+ // What find prints is everything under its starting points, so find | xargs rm deletes them all.
905
+ const fed = xargs && seg.pipe && prev && !xargs.some(w => /^-[IJ]/.test(w.text)) ? prev : null;
906
+ const piped = !fed ? [] : path.basename(fed[0]?.text || '') === 'find' ? findRoots(fed.slice(1)).map(w => ({ ...w, recursive: true })) : operands(fed.slice(1));
907
+ const args = [...own, ...piped];
908
+ if (name === 'cd' || name === 'pushd') {
909
+ const to = args.find(w => w.text === '-' || !w.text.startsWith('-'));
910
+ const p = to && !to.opaque && expand(to.text);
911
+ const was = dir;
912
+ if (name === 'pushd') pushed.push(dir);
913
+ if (!to) dir = name === 'cd' ? os.homedir() : null;
914
+ else if (p === '-' && name === 'cd') dir = last;
915
+ else if (!p || p === '-' || /^[+-]\d+$/.test(p)) dir = null; // pushd +1 goes where we didn't follow
916
+ else dir = path.isAbsolute(p) ? p : dir && path.resolve(dir, p);
917
+ last = was;
918
+ }
919
+ else if (name === 'popd') dir = pushed.length ? pushed.pop() : null;
920
+ yield { seg, name, args, dir };
921
+ prev = words;
922
+ }
923
+ }
924
+
925
+ // Paths a Bash command writes: redirect targets, and the files of rm, mv, cp,
926
+ // tee, touch, sed -i and the like, from the folder it runs in (following cd).
927
+ // Words built from $VARS or $(...) can't be known and are skipped.
928
+ // guesses: also each $VAR word's text up to its first $ or `, as { guess },
929
+ // and whether the word is only a variable or $(...) ($S, "$S"/*, "$(pwd)"): bare.
930
+ const BARE = /^(\$(\{\w+\}|\w+)|\$\([^)]*\)|`[^`]*`)(\/\*?)?$/;
931
+ export function bashWrites(cmd, split, cwd, guesses = false) {
932
+ const segs = typeof cmd === 'string' && split(cmd);
933
+ if (!segs) return [];
934
+ const out = [];
935
+ for (const { seg, name, args, dir } of commands(segs, cwd)) {
936
+ const add = (w, why) => {
937
+ if (w.opaque && guesses) out.push({ guess: expand(w.text.split(/[$`]/)[0]), why, ...(w.recursive && { recursive: true, bare: BARE.test(w.text) }) });
938
+ if (w.opaque) return;
939
+ const p = expand(w.text);
940
+ if (!p || p.startsWith('/dev/') || (!path.isAbsolute(p) && !dir)) return;
941
+ out.push({ path: path.resolve(dir || '/', p), why, ...(w.tree && { tree: true }), ...(w.recursive && { recursive: true }) });
942
+ };
943
+ for (const w of seg) if (w.redir && redirWrites(cmd, w)) add(w, 'a > redirect');
944
+ // A file fed in with <, which git apply and patch read their patch from.
945
+ const fed = seg.find(w => w.redir && redirOp(cmd, w) === '<');
946
+ const input = fed && !fed.opaque ? from(dir, fed)?.text ?? null : null;
947
+ if (name && name !== 'cd') for (const w of writtenBy(name, args, dir, input)) add(w, name);
948
+ }
949
+ return out;
950
+ }
951
+
952
+ // ----- which agent of a session took a lease -----
953
+ // Claude Code tells a hook which subagent or teammate made a tool call
954
+ // (agent_id), but gives the Bash command itself nothing to tell them apart. So
955
+ // when the hook sees `dibs hold|run|release` with files: in a Bash call, it
956
+ // leaves a note saying which agent asked, and that dibs claims the note and
957
+ // stamps its lease. The main thread is the agent "main". A lease without a
958
+ // stamp (no guard, or dibs run from a script) belongs to its whole session.
959
+
960
+ // A note waits this long for its command: a permission prompt can sit a while.
961
+ const NOTE_LIFE = 10 * 6e4;
962
+ const notesDir = () => path.join(dibsHome(), 'agents');
963
+ const noteKey = (verb, res) => `${verb}|${res.filter(isFiles).sort().join(',')}`;
964
+ const LEASE_VERBS = new Set(['hold', 'run', 'release']);
965
+ // Looks at the board and the queue, noted too, so they can tell the calling
966
+ // subagent's own jobs from its siblings' (dibs why, dibs mine, plain dibs).
967
+ const READ_VERBS = new Set(['status', 'why', 'mine', 'who', 'when', 'yield']);
968
+ // Acting on a job, noted so dibs can tell whether it's the caller's own (src/override.mjs).
969
+ const ACT_VERBS = new Set(['boost', 'pause', 'resume', 'stop']);
970
+ const ALIASES = { done: 'release', renew: 'hold', ls: 'status', board: 'status' };
971
+ // dibs say and dibs question go in the asking agent's own thread (src/talk.mjs),
972
+ // dibs later tells that thread how the job ended (src/later.mjs), and a dibs
973
+ // progress task belongs to the subagent that posts it (src/progress.mjs). Their
974
+ // note is keyed by the words, so subagents saying "done" at once each get
975
+ // their own. A word the hook can't read ($VAR) matches any one word.
976
+ // Every other call is keyed the same way, by all its words, so two subagents
977
+ // running `dibs run sim -- ...` at once each claim their own note.
978
+ const TALK_VERBS = new Set(['say', 'question', 'later', 'progress', 'listen']);
979
+ export const talkKey = (verb, words) => `${verb}|${words.join('\0')}`;
980
+ // A word the hook can't read ("files:$R/a.ts", $(...)) stands for any one word.
981
+ const WILD = '\u0001';
982
+ const wordsKey = (verb, words) => talkKey(verb, words.map(w => (w.opaque ? WILD : w.text)));
983
+ const keyWords = k => { const i = k.indexOf('|'); return [k.slice(0, i), ...k.slice(i + 1).split('\0')]; };
984
+ function fits(noted, key) {
985
+ if (noted === key || !noted.includes(WILD)) return noted === key;
986
+ const a = keyWords(noted), b = keyWords(key);
987
+ return a.length === b.length && a.every((w, i) => w === b[i] || (i > 0 && w === WILD));
988
+ }
989
+
990
+ // The key dibs claims its note by: its own arguments after the verb, as the hook saw them.
991
+ export function callKey(verb, argv = process.argv.slice(2)) {
992
+ const first = ALIASES[argv[0]] || argv[0];
993
+ return talkKey(verb, first === verb ? argv.slice(1) : argv);
994
+ }
995
+
996
+ // The dibs calls in a Bash command, by verb, with the file leases they name
997
+ // as dibs itself will name them, and the key their note goes under.
998
+ export function dibsCalls(cmd, split, cwd) {
999
+ const segs = typeof cmd === 'string' && /\bdibs/.test(cmd) && split(cmd);
1000
+ if (!segs) return [];
1001
+ const out = [];
1002
+ for (const { name, args, dir } of commands(segs, cwd)) {
1003
+ if (!/^dibs(\.mjs)?$/.test(name || '') || !dir) continue;
1004
+ const dd = args.findIndex(w => w.text === '--');
1005
+ const own = dd < 0 ? args : args.slice(0, dd);
1006
+ const res = own.filter(w => !w.opaque).flatMap(w => resList(w.text)).filter(isFiles).map(r => fileRes(r, dir)).filter(Boolean);
1007
+ let verb = ALIASES[own[0]?.text] || own[0]?.text;
1008
+ if (TALK_VERBS.has(verb)) {
1009
+ out.push({ verb, res: [], key: wordsKey(verb, own.slice(1)) });
1010
+ continue;
1011
+ }
1012
+ // No verb: with a command after -- it's a run (dibs sim -- cmd); with only flags, the board.
1013
+ const typed = LEASE_VERBS.has(verb) || READ_VERBS.has(verb) || ACT_VERBS.has(verb);
1014
+ if (!typed) { if (dd >= 0) verb = 'run'; else if (!verb || verb.startsWith('-')) verb = 'status'; else continue; }
1015
+ out.push({ verb, res, key: wordsKey(verb, typed ? args.slice(1) : args) });
1016
+ }
1017
+ return out;
1018
+ }
1019
+
1020
+ function noteAgent(input, split) {
1021
+ if (input.tool_name !== 'Bash' || typeof input.session_id !== 'string') return;
1022
+ const calls = dibsCalls(input.tool_input?.command, split, typeof input.cwd === 'string' ? input.cwd : process.cwd());
1023
+ if (!calls.length) return;
1024
+ // Only a nicety (naming the subagent): a full disk must not cost the lease check after it.
1025
+ try {
1026
+ fs.mkdirSync(notesDir(), { recursive: true });
1027
+ for (const c of calls) {
1028
+ const note = { at: Date.now(), session: input.session_id, agent: input.agent_id || 'main', type: input.agent_type || null, key: c.key ?? noteKey(c.verb, c.res) };
1029
+ fakeFull('notes');
1030
+ fs.writeFileSync(path.join(notesDir(), `${note.at}-${process.pid}-${Math.random().toString(36).slice(2)}.json`), JSON.stringify(note));
1031
+ }
1032
+ } catch {}
1033
+ }
1034
+
1035
+ // The agent the guard saw ask for this, or null: the newest note from this
1036
+ // session whose words are this call's, claimed by rename so two dibs can't
1037
+ // both take it. Old notes go. key overrides the lease key (dibs say and
1038
+ // question pass talkKey's). When notes from two agents of the session both
1039
+ // fit (the same words, or words the hook couldn't read), nobody can tell
1040
+ // which one this is, so it's none: a lease without a stamp is the whole
1041
+ // session's, and a stamp from the wrong subagent turned its sibling away from
1042
+ // its own lease on 2026-10-16.
1043
+ export function takeAgent(verb, res, key = noteKey(verb, res)) {
1044
+ const session = process.env.CLAUDE_CODE_SESSION_ID;
1045
+ let names;
1046
+ try { names = fs.readdirSync(notesDir()).filter(n => n.endsWith('.json')).sort().reverse(); } catch { return null; }
1047
+ const found = [];
1048
+ for (const n of names) {
1049
+ const f = path.join(notesDir(), n);
1050
+ let x;
1051
+ try { x = JSON.parse(fs.readFileSync(f, 'utf8')); } catch { continue; }
1052
+ if (Date.now() - x.at > NOTE_LIFE) { fs.rmSync(f, { force: true }); continue; }
1053
+ if (session && x.session === session && typeof x.key === 'string' && fits(x.key, key)) found.push({ f, x });
1054
+ }
1055
+ if (new Set(found.map(n => n.x.agent)).size !== 1) return null;
1056
+ const got = found.find(n => n.x.key === key) || found[0];
1057
+ try { fs.renameSync(got.f, `${got.f}.taken`); } catch { return null; }
1058
+ fs.rmSync(`${got.f}.taken`, { force: true });
1059
+ return { agentId: got.x.agent, agentType: got.x.type };
1060
+ }
1061
+
1062
+ // Two leases or requests from one session belong to the same agent, unless
1063
+ // both are stamped with different ones.
1064
+ export const sameAgent = (a, b) => !a.agentId || !b.agentId || a.agentId === b.agentId;
1065
+ // Whether a lease lets this agent of its session through. The usual pattern is
1066
+ // a lead taking the lease and handing the edit to a subagent, who would
1067
+ // otherwise be turned away with nobody free to release it. So a lease the main
1068
+ // thread took counts for its subagents, the way an unstamped one counts for the
1069
+ // whole session. A subagent's lease still keeps its siblings and the main
1070
+ // thread out, and only the agent that took a lease can release it (sameAgent).
1071
+ export const coversAgent = (held, asking) => sameAgent(held, asking) || held.agentId === 'main';
1072
+
1073
+ // A list of resources as one shell word an agent can paste: a glob in it is
1074
+ // quoted, or zsh expands files:src/** itself and fails with "no matches found".
1075
+ export const shellRes = rs => {
1076
+ const s = [].concat(rs).join(',');
1077
+ return /[*?[\]{}~ ]/.test(s) ? `'${s.replace(/'/g, `'\\''`)}'` : s;
1078
+ };
1079
+
1080
+ // The paths a tool call would write, absolute.
1081
+ function targets(input, split, guesses = false) {
1082
+ const ti = input.tool_input || {};
1083
+ const cwd = typeof input.cwd === 'string' ? input.cwd : process.cwd();
1084
+ if (input.tool_name === 'Bash') return bashWrites(ti.command, split, cwd, guesses);
1085
+ const p = ti.file_path ?? ti.notebook_path;
1086
+ return typeof p === 'string' && p ? [{ path: path.resolve(cwd, expand(p)), why: input.tool_name }] : [];
1087
+ }
1088
+
1089
+ // The hook's answer for one tool call: a deny naming the holder when it would
1090
+ // write under another session's file lease, else null. split is the guard's
1091
+ // shell reader, passed in so this file needn't load the guard's rules.
1092
+ export function fileGuard(input, split) {
1093
+ if (!EDITS.has(input?.tool_name) && input?.tool_name !== 'Bash') return null;
1094
+ noteAgent(input, split);
1095
+ const live = leases();
1096
+ if (!live.length) return null;
1097
+ const cwd = typeof input.cwd === 'string' ? input.cwd : process.cwd();
1098
+ const t = Date.now();
1099
+ for (const target of targets(input, split)) {
1100
+ if (target.guess != null) continue;
1101
+ const p = canon(real(target.path));
1102
+ const tree = target.tree ? worktreeOf(real(target.path)) : null;
1103
+ for (const l of live) {
1104
+ const r = l.res.find(x => isFiles(x) && overlap(x, p));
1105
+ if (!r || mine(l, input) || sibling(l, tree)) continue;
1106
+ const name = l.agent || l.who;
1107
+ const holder = l.agentId && l.agentId !== 'main' ? `${name}'s subagent ${l.agentId}` : name;
1108
+ const until = l.kind === 'hold' ? `until ${clock(l.expires)}` : 'while its command runs';
1109
+ const ask = !(l.sessionId && l.sessionId === input.session_id) ? `Or SendMessage ${name} and ask.`
1110
+ : input.agent_id ? 'Another agent of your own session holds it: wait, or ask whoever is coordinating you.'
1111
+ : `Your own subagent ${l.agentId} holds it: wait for it to finish, or have it run dibs release.`;
1112
+ return { hookSpecificOutput: {
1113
+ hookEventName: 'PreToolUse',
1114
+ permissionDecision: 'deny',
1115
+ permissionDecisionReason: `dibs: ${short(FILES + p, cwd).slice(FILES.length)} is leased to ${holder}${elsewhere(l, cwd)}${l.label && l.label !== name ? ` (${l.label})` : ''}`
1116
+ + `${l.purpose ? ` for "${l.purpose}"` : ''} (${short(r, cwd)}, held ${dur(t - l.start)}, ${until}), so ${target.why} can't write to it now.\n`
1117
+ + `See when it frees up: dibs when ${shellRes(short(r, cwd))}\n`
1118
+ + `Wait for it and take it yourself: dibs hold ${shellRes(short(r, cwd))} -m "why". ${ask} Reading it is fine.`,
1119
+ } };
1120
+ }
1121
+ }
1122
+ return null;
1123
+ }