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