@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.
Files changed (72) hide show
  1. package/CHANGELOG.md +577 -0
  2. package/LICENSE +670 -0
  3. package/README.md +234 -2
  4. package/bin/dibs-guard.mjs +7 -0
  5. package/bin/dibs.mjs +526 -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/relay.md +196 -0
  13. package/docs/releasing.md +25 -0
  14. package/docs/scheduling.md +163 -0
  15. package/docs/simulators.md +17 -0
  16. package/package.json +44 -4
  17. package/skills/dibs/SKILL.md +162 -0
  18. package/src/acquire.mjs +697 -0
  19. package/src/admin.mjs +145 -0
  20. package/src/agents.mjs +145 -0
  21. package/src/alerts.mjs +437 -0
  22. package/src/answers.mjs +65 -0
  23. package/src/board.mjs +202 -0
  24. package/src/broker.mjs +369 -0
  25. package/src/commands.mjs +801 -0
  26. package/src/config.mjs +320 -0
  27. package/src/connect.mjs +106 -0
  28. package/src/cool.mjs +160 -0
  29. package/src/diskwarn.mjs +161 -0
  30. package/src/events.mjs +94 -0
  31. package/src/files.mjs +1100 -0
  32. package/src/guard.mjs +583 -0
  33. package/src/history.mjs +247 -0
  34. package/src/hogs.mjs +214 -0
  35. package/src/later.mjs +487 -0
  36. package/src/measure.mjs +262 -0
  37. package/src/nodecheck.mjs +17 -0
  38. package/src/notices.mjs +121 -0
  39. package/src/ondemand.mjs +572 -0
  40. package/src/overlap.mjs +151 -0
  41. package/src/override.mjs +351 -0
  42. package/src/owner.mjs +30 -0
  43. package/src/plain.mjs +467 -0
  44. package/src/platform.mjs +357 -0
  45. package/src/preempt.mjs +438 -0
  46. package/src/primer.mjs +61 -0
  47. package/src/proc.mjs +98 -0
  48. package/src/progress.mjs +158 -0
  49. package/src/qr.mjs +204 -0
  50. package/src/questions.mjs +389 -0
  51. package/src/quota.mjs +81 -0
  52. package/src/reads.mjs +54 -0
  53. package/src/relay.mjs +779 -0
  54. package/src/remote.mjs +584 -0
  55. package/src/reset.mjs +127 -0
  56. package/src/schedule.mjs +995 -0
  57. package/src/scratch.mjs +61 -0
  58. package/src/serve.mjs +736 -0
  59. package/src/service.mjs +221 -0
  60. package/src/shard.mjs +59 -0
  61. package/src/simctl.mjs +42 -0
  62. package/src/simpool.mjs +258 -0
  63. package/src/state.mjs +201 -0
  64. package/src/stats.mjs +328 -0
  65. package/src/style.mjs +44 -0
  66. package/src/talk.mjs +523 -0
  67. package/src/thin.sh +130 -0
  68. package/src/trust.mjs +152 -0
  69. package/src/util.mjs +184 -0
  70. package/src/version.mjs +2 -0
  71. package/src/web.mjs +1117 -0
  72. package/src/worker.mjs +318 -0
package/src/guard.mjs ADDED
@@ -0,0 +1,583 @@
1
+ // dibs guard: a Claude Code PreToolUse hook that catches heavy Bash commands
2
+ // run outside dibs, and either wraps them in `dibs run` or sends the agent back
3
+ // with the exact command to use. It reads the shell command, never runs it, and
4
+ // takes no lock. Anything it can't read, or any error, lets the command through
5
+ // unchanged: blocking legit work is worse than missing a build. It also turns
6
+ // away edits to paths another session holds a file lease on (src/files.mjs).
7
+ import fs from 'node:fs';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { tmpGuard, fileGuard, resList } from './files.mjs';
12
+
13
+ const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
14
+ const HOOK_BIN = path.join(ROOT, 'bin', 'dibs-guard.mjs');
15
+ // The same folder as config.mjs's HOME, worked out here because the hook loads no other module.
16
+ const DIBS_HOME = process.env.DIBS_HOME || path.join(os.homedir(), '.dibs');
17
+ const CONFIG = path.join(DIBS_HOME, 'config.json');
18
+ const STATE = path.join(DIBS_HOME, 'state.json');
19
+ const LOG = path.join(DIBS_HOME, 'guard.log');
20
+ // Who has a message from the person waiting: { session_id: [agent ids] }, or
21
+ // no file at all. src/talk.mjs keeps it; the hook only reads it.
22
+ const INBOX = path.join(DIBS_HOME, 'inbox.json');
23
+ // The threads themselves, which the hook only searches for a subagent's id.
24
+ const MESSAGES = path.join(DIBS_HOME, 'messages.json');
25
+ const SETTINGS = process.env.DIBS_CLAUDE_SETTINGS || path.join(os.homedir(), '.claude', 'settings.json');
26
+
27
+ // What counts as heavy: the command's first words, once env, npx, time, cd and
28
+ // friends are peeled off, and the resource it needs. A word may use * and the
29
+ // first is matched by its basename; $ means "and nothing after". Any argument in
30
+ // `unless` makes it a quick read, as does `reads` returning true for the
31
+ // arguments; `with` needs one of its arguments present.
32
+ // Add or switch these off in ~/.dibs/config.json under guard.rules.
33
+ // A command aimed at a pool simulator ($SIM, a dibs-pool-N name, or the udid of
34
+ // one) belongs to sim-own. Queueing it for the shared sim would wait on a
35
+ // device it never touches.
36
+ const POOL_REF = /\$\{?SIM(_NAME)?\b|\bdibs-pool-\d+/;
37
+ let udids = null;
38
+ function poolUdids() {
39
+ try { udids ??= (JSON.parse(fs.readFileSync(STATE, 'utf8')).pool || []).map(d => d.udid).filter(Boolean); } catch { udids = []; }
40
+ return udids;
41
+ }
42
+ const ownSim = argv => argv.some(a => POOL_REF.test(a) || poolUdids().some(u => a.includes(u)));
43
+ const sim = argv => (ownSim(argv) ? 'sim-own' : 'sim');
44
+ // simctl subcommands that need no simulator turn: reads, and managing devices
45
+ // that aren't running (create, delete, erase, which refuses a booted one, and
46
+ // runtimes). Queueing those behind the shared sim and its disk floor would stop
47
+ // an agent deleting simulators to free disk until disk is free. Some read or
48
+ // write by their arguments: `ui <device> appearance` reads, with a value it sets.
49
+ const SIMCTL_READS = new Set(['list', 'help', '--help', '-h', '--version', 'getenv', 'get_app_container', 'listapps', 'appinfo', 'pbpaste',
50
+ 'create', 'delete', 'erase', 'runtime']);
51
+ function simctlRead(rest) {
52
+ const i = rest[0] === '--set' ? 2 : 0; // --set <path> picks a device set and comes first
53
+ const [sub, a, b, c] = rest.slice(i);
54
+ if (SIMCTL_READS.has(sub)) return true;
55
+ if (sub === 'ui') return c == null;
56
+ if (sub === 'status_bar') return b === 'list';
57
+ if (sub === 'io') return b === 'enumerate';
58
+ if (sub === 'bootstatus') return !rest.includes('-b'); // -b boots it first
59
+ return false;
60
+ }
61
+ // A simulator named by its udid alone (-destination id=<udid>) is a simulator
62
+ // too. Real devices' ids aren't shaped 8-4-4-4-12.
63
+ const SIM_ID = /(^|,)id=[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}\b/i;
64
+ const simTest = argv => argv.some(a => a === 'test' || a === 'test-without-building') && (ownSim(argv) || argv.some(a => /Simulator/.test(a) || SIM_ID.test(a)));
65
+ const RULES = {
66
+ xcodebuild: { match: 'xcodebuild', res: argv => (simTest(argv) ? `${sim(argv)},xcode-build` : 'xcode-build'),
67
+ unless: ['-version', '-showsdks', '-list', '-showBuildSettings', '-showdestinations', '-showTestPlans', '-help', '-usage',
68
+ '-license', '-checkFirstLaunchStatus', '-runFirstLaunch', '-find-executable', '-find-library', '-showComponent'] },
69
+ simctl: { match: 'simctl', res: sim, reads: simctlRead },
70
+ 'swift-test': { match: 'swift test', res: 'test', unless: ['--help', '-h', '--list-tests'] },
71
+ playwright: { match: ['playwright test', 'pnpm playwright test', 'yarn playwright test'], res: 'playwright', unless: ['--help', '-h', '--list'] },
72
+ vitest: { match: ['vitest', 'pnpm vitest', 'yarn vitest'], res: 'test', unless: ['--version', '-v', '--help', '-h', 'list', 'init'] },
73
+ jest: { match: ['jest', 'pnpm jest', 'yarn jest'], res: 'test', unless: ['--version', '-v', '--help', '-h', '--listTests', '--showConfig'] },
74
+ 'npm-test': { match: ['npm test', 'npm t', 'npm run test*', 'npm run-script test*', 'pnpm test', 'pnpm t', 'pnpm run test*',
75
+ 'yarn test', 'yarn run test*', 'bun test', 'bun run test*'], res: 'test' },
76
+ 'node-test': { match: 'node', with: ['--test'], res: 'test' },
77
+ // A type check of a big app takes 1.5 GB: on 2026-10-22 six at once, outside
78
+ // dibs, put 9 GB into swap and took free disk to 1.4 GB. Not --watch, which
79
+ // never ends, and not the quick ones.
80
+ tsc: { match: ['tsc', 'vue-tsc', 'npm run typecheck*', 'npm run type-check*', 'pnpm typecheck*', 'pnpm run typecheck*', 'pnpm type-check*',
81
+ 'yarn typecheck*', 'yarn run typecheck*', 'bun run typecheck*'], res: 'test',
82
+ unless: ['--version', '-v', '--help', '-h', '--init', '--showConfig', '--watch', '-w', '--listFiles', '--listFilesOnly', '--all'] },
83
+ wrangler: { match: ['wrangler deploy', 'wrangler publish', 'wrangler pages deploy', 'wrangler versions deploy'], res: 'deploy', unless: ['--help', '-h', '--dry-run'] },
84
+ vercel: { match: ['vercel deploy', 'vercel --prod', 'vercel --yes', 'vercel -y', 'vercel $'], res: 'deploy', unless: ['--version', '-v', '--help', '-h'] },
85
+ 'deploy-script': { match: ['ship*.sh', 'deploy*.sh', 'npm run deploy*', 'pnpm run deploy*', 'yarn deploy', 'yarn run deploy*', 'bun run deploy*'], res: 'deploy' },
86
+ };
87
+
88
+ // Words that come before the command and stay before dibs.
89
+ const KEYWORDS = new Set(['then', 'do', 'else', 'elif', 'if', 'while', 'until', '!', 'time', 'command', 'exec']);
90
+ const ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/;
91
+ // DIBS_GUARD=off in front of a command, as a real assignment: in a quoted
92
+ // message or a file name it's only words.
93
+ const OFF = /^DIBS_GUARD=(0|off|false|no)$/;
94
+
95
+ // Commands that run another command: dibs goes in front of them, and the
96
+ // command they run is what gets matched. Each returns the index of that
97
+ // command, or null when the word isn't acting as a wrapper here.
98
+ const flags = (words, j, takesValue = []) => {
99
+ while (words[j]?.startsWith('-')) j += takesValue.includes(words[j]) ? 2 : 1;
100
+ return j;
101
+ };
102
+ const runner = (words, i) => { const j = flags(words, i + 1, ['-p', '--package']); return words[j] === '--' ? j + 1 : j; };
103
+ const PREFIX = {
104
+ env: (w, i) => { let j = flags(w, i + 1, ['-u', '--unset', '-C', '--chdir']); while (ASSIGN.test(w[j] || '')) j++; return j; },
105
+ nice: (w, i) => flags(w, i + 1, ['-n']),
106
+ caffeinate: (w, i) => flags(w, i + 1, ['-t', '-w']),
107
+ timeout: (w, i) => flags(w, i + 1, ['-s', '-k', '--signal', '--kill-after']) + 1,
108
+ gtimeout: (w, i) => PREFIX.timeout(w, i),
109
+ nohup: (w, i) => i + 1,
110
+ time: (w, i) => flags(w, i + 1, ['-o']), // /usr/bin/time; the shell's own time is a keyword
111
+ sudo: (w, i) => flags(w, i + 1, ['-u', '-g', '-C', '-D', '-h', '-p', '-U', '-r', '-t', '-T']),
112
+ xcrun: (w, i) => {
113
+ let j = i + 1;
114
+ while (['-sdk', '--sdk', '-toolchain', '--toolchain'].includes(w[j])) j += 2; // not --find: xcrun --find xcodebuild is a lookup
115
+ return ['xcodebuild', 'simctl'].includes(w[j]) ? j : null;
116
+ },
117
+ npx: runner,
118
+ bunx: runner,
119
+ bun: (w, i) => (w[i + 1] === 'x' ? runner(w, i + 1) : null),
120
+ npm: (w, i) => (w[i + 1] === 'exec' ? runner(w, i + 1) : null),
121
+ pnpm: (w, i) => (['exec', 'dlx'].includes(w[i + 1]) ? runner(w, i + 1) : null),
122
+ yarn: (w, i) => (['exec', 'dlx'].includes(w[i + 1]) ? runner(w, i + 1) : null),
123
+ // bash -x deploy.sh runs the script; -c and -s run text we can't see as a command.
124
+ bash: (w, i) => {
125
+ const j = flags(w, i + 1, ['-o', '+o', '-O', '+O']);
126
+ return w[j] && !w.slice(i + 1, j).some(f => /^-[a-zA-Z]*[cs]/.test(f)) ? j : null;
127
+ },
128
+ sh: (w, i) => PREFIX.bash(w, i),
129
+ zsh: (w, i) => PREFIX.bash(w, i),
130
+ };
131
+ // Package managers' own flags before the script name (npm --prefix web test).
132
+ const PM = new Set(['npm', 'pnpm', 'yarn', 'bun']);
133
+ const PM_VALUE = ['--prefix', '-C', '--cwd', '--dir', '--filter', '-F', '-w', '--workspace'];
134
+
135
+ const base = s => s.slice(s.lastIndexOf('/') + 1);
136
+
137
+ // The shell command split into simple commands, each a list of words with
138
+ // where they start. Quotes are removed; $(...), backticks and $VARS mark a word
139
+ // opaque; redirect targets are marked; heredoc bodies are skipped. Each list
140
+ // also says how many ( ) subshells it's in (depth), so a cd inside one ends
141
+ // with it, and whether its input is piped from the one before (pipe). Null when
142
+ // it can't be read (an open quote, an unterminated heredoc).
143
+ export function split(src) {
144
+ const segs = [], docs = [];
145
+ let seg = [], w = null, redir = false, depth = 0, pipe = false;
146
+ const word = i => (w ||= { text: '', start: i, quoted: false, opaque: false });
147
+ const end = () => {
148
+ if (!w) return;
149
+ // A group's brace ends the simple command before it. The word is dropped
150
+ // before cutting: cut() ends the current word first, and ending this one
151
+ // again called cut() again, without end (every { ...; } overflowed the stack
152
+ // until 0.0.178, and the hook let those commands through unguarded).
153
+ if (!w.quoted && (w.text === '{' || w.text === '}')) { w = null; cut(); return; }
154
+ w.redir = redir; redir = false;
155
+ seg.push(w); w = null;
156
+ };
157
+ const cut = () => { w && end(); if (seg.length) { segs.push(Object.assign(seg, { depth, pipe })); pipe = false; } seg = []; w = null; };
158
+ for (let i = 0; i < src.length; i++) {
159
+ const c = src[i], d = src[i + 1];
160
+ if (c === ' ' || c === '\t') end();
161
+ else if (c === '\n') {
162
+ cut();
163
+ if (docs.length) { i = bodies(src, i + 1, docs) - 1; if (i < 0) return null; docs.length = 0; }
164
+ }
165
+ else if (c === '#' && !w) { while (i + 1 < src.length && src[i + 1] !== '\n') i++; }
166
+ else if (c === '\\') { if (d !== '\n') { word(i).text += d ?? ''; w.quoted = true; } i++; }
167
+ else if (c === "'") {
168
+ const j = src.indexOf("'", i + 1);
169
+ if (j < 0) return null;
170
+ word(i).text += src.slice(i + 1, j); w.quoted = true; i = j;
171
+ }
172
+ else if (c === '"') {
173
+ word(i).quoted = true;
174
+ let j = i + 1;
175
+ for (; src[j] !== '"'; j++) {
176
+ if (j >= src.length) return null;
177
+ if (src[j] === '\\') w.text += src[++j];
178
+ else if (src[j] === '`' || (src[j] === '$' && src[j + 1] === '(')) {
179
+ const k = src[j] === '`' ? src.indexOf('`', j + 1) : close(src, j + 1);
180
+ if (k < 0) return null;
181
+ w.opaque = true; w.text += src.slice(j, k + 1); j = k;
182
+ }
183
+ else { if (src[j] === '$') w.opaque = true; w.text += src[j]; }
184
+ }
185
+ i = j;
186
+ }
187
+ else if (c === '`' || (c === '$' && d === '(') || ((c === '<' || c === '>') && d === '(')) {
188
+ const k = c === '`' ? src.indexOf('`', i + 1) : close(src, i + 1);
189
+ if (k < 0) return null;
190
+ word(i).opaque = true; w.text += src.slice(i, k + 1); i = k;
191
+ }
192
+ else if (c === '$') { word(i).opaque = true; w.text += c; }
193
+ else if (c === '(' || c === ')' || c === ';') { cut(); depth = Math.max(0, depth + (c === '(') - (c === ')')); }
194
+ else if (c === '|') { cut(); if (d === '|') i++; else { pipe = true; if (d === '&') i++; } }
195
+ else if (c === '&' && d !== '>') { cut(); if (d === '&') i++; }
196
+ else if (c === '<' || c === '>' || c === '&') {
197
+ if (w && /^\d+$/.test(w.text) && !w.quoted) w = null; // the fd in 2>&1
198
+ else end();
199
+ if (c === '<' && d === '<' && src[i + 2] !== '<') {
200
+ i += 2;
201
+ const dash = src[i] === '-';
202
+ if (dash) i++;
203
+ while (src[i] === ' ' || src[i] === '\t') i++;
204
+ let delim = '';
205
+ for (; i < src.length && !/[\s;&|<>()]/.test(src[i]); i++) if (!`'"\\`.includes(src[i])) delim += src[i];
206
+ i--;
207
+ docs.push({ delim, dash });
208
+ continue;
209
+ }
210
+ while ('<>&|'.includes(src[i + 1]) && src[i + 1] !== undefined) i++;
211
+ redir = true;
212
+ }
213
+ else word(i).text += c;
214
+ }
215
+ if (docs.length) return null;
216
+ cut();
217
+ return segs;
218
+ }
219
+
220
+ // Index of the ")" closing the "(" at i, or -1.
221
+ function close(src, i) {
222
+ for (let depth = 0; i < src.length; i++) {
223
+ const c = src[i];
224
+ if (c === '\\') i++;
225
+ else if (c === "'") { i = src.indexOf("'", i + 1); if (i < 0) return -1; }
226
+ else if (c === '(') depth++;
227
+ else if (c === ')' && --depth === 0) return i;
228
+ }
229
+ return -1;
230
+ }
231
+
232
+ // Where the line after the last heredoc body starts, or -1 if one never ends.
233
+ function bodies(src, pos, docs) {
234
+ for (const doc of docs) {
235
+ for (;;) {
236
+ if (pos > src.length) return -1;
237
+ let nl = src.indexOf('\n', pos);
238
+ if (nl < 0) nl = src.length;
239
+ const line = src.slice(pos, nl);
240
+ pos = nl + 1;
241
+ if ((doc.dash ? line.replace(/^\t+/, '') : line) === doc.delim) break;
242
+ }
243
+ }
244
+ return pos;
245
+ }
246
+
247
+ // One simple command: where dibs would go, and the words of what it runs.
248
+ // Null when it starts with something opaque or a form we don't follow.
249
+ function peel(seg) {
250
+ const words = seg.filter(w => !w.redir);
251
+ const t = words.map(w => w.text);
252
+ let i = 0, at = null;
253
+ for (;;) {
254
+ const w = words[i];
255
+ if (!w || w.opaque || (OFF.test(w.text) && at === null)) return null;
256
+ if (!w.quoted && KEYWORDS.has(w.text) && at === null) {
257
+ i++;
258
+ if (w.text === 'time') i = flags(t, i);
259
+ if (w.text === 'command' && t[i]?.startsWith('-')) return null; // command -v is a lookup
260
+ continue;
261
+ }
262
+ if (ASSIGN.test(w.text) && at === null) { i++; continue; }
263
+ at ??= w.start;
264
+ const next = PREFIX[w.quoted ? '' : base(w.text)]?.(t, i);
265
+ if (next == null) break;
266
+ // env DIBS_GUARD=off xcodebuild switches it off too
267
+ if (t.slice(i, next).some(a => OFF.test(a))) return null;
268
+ i = next;
269
+ }
270
+ let argv = t.slice(i);
271
+ if (PM.has(base(argv[0]))) {
272
+ argv = [argv[0], ...argv.slice(flags(argv, 1, PM_VALUE))];
273
+ if (argv[1] === 'workspace') argv = [argv[0], ...argv.slice(3)]; // yarn workspace web test
274
+ }
275
+ return { at, argv };
276
+ }
277
+
278
+ const globs = new Map();
279
+ function glob(p) {
280
+ if (!globs.has(p)) globs.set(p, new RegExp(`^${p.split('*').map(s => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`));
281
+ return globs.get(p);
282
+ }
283
+
284
+ // The arguments after a rule's words, or null if it doesn't match.
285
+ function after(pattern, argv) {
286
+ const pat = pattern.trim().split(/\s+/);
287
+ for (let k = 0; k < pat.length; k++) {
288
+ if (pat[k] === '$') return argv.length === k ? [] : null;
289
+ const word = k === 0 ? base(argv[0]) : argv[k];
290
+ if (word === undefined || !glob(pat[k]).test(word)) return null;
291
+ }
292
+ return argv.slice(pat.length);
293
+ }
294
+
295
+ // The resource a command needs, or null.
296
+ function resourceFor(argv, rules) {
297
+ for (const rule of Object.values(rules)) {
298
+ if (!rule || !rule.res) continue;
299
+ const rest = [].concat(rule.match).map(p => after(p, argv)).find(Boolean);
300
+ if (!rest) continue;
301
+ if (rule.unless?.some(u => rest.includes(u)) || rule.reads?.(rest)) continue;
302
+ if (rule.with && !rule.with.some(a => argv.includes(a))) continue;
303
+ return typeof rule.res === 'function' ? rule.res(argv) : String(rule.res);
304
+ }
305
+ return null;
306
+ }
307
+
308
+ // The rules after ~/.dibs/config.json's guard.rules: a name set to false
309
+ // switches a built-in off, anything else adds or replaces one.
310
+ export function rulesFrom(guardCfg) {
311
+ return { ...RULES, ...(guardCfg?.rules || {}) };
312
+ }
313
+
314
+ const quote = s => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
315
+
316
+ // What to do with a command: null to leave it alone, or the rewritten command
317
+ // and what was caught.
318
+ export function check(cmd, { rules = RULES, dibs = 'dibs' } = {}) {
319
+ if (typeof cmd !== 'string') return null;
320
+ const segs = split(cmd);
321
+ if (!segs) return null;
322
+ // dibs calls themselves are left alone, and what a `dibs hold` on this line
323
+ // takes covers the commands after it. Anything else heavy on the line, before
324
+ // or after a dibs call, still needs its turn.
325
+ const held = new Set();
326
+ const hits = [];
327
+ for (const c of segs.map(peel).filter(Boolean)) {
328
+ if (c.argv[0] === 'export' && c.argv.some(a => OFF.test(a))) break; // export DIBS_GUARD=off: the rest of the line
329
+ if (['dibs', 'dibs.mjs', 'dibs-guard.mjs'].includes(base(c.argv[0] || ''))) {
330
+ if (c.argv[1] === 'hold') for (const r of c.argv.slice(2).filter(a => !a.startsWith('-'))) resList(r).forEach(x => held.add(x));
331
+ continue;
332
+ }
333
+ const res = resourceFor(c.argv, rules);
334
+ if (res && !res.split(',').every(r => held.has(r))) hits.push({ at: c.at, res, what: c.argv.slice(0, 3).join(' ') });
335
+ }
336
+ if (!hits.length) return null;
337
+ // $SIM is only set inside the run, so a command that reads it goes to sh -c
338
+ // whole, under one lease for everything it needs.
339
+ if (/\$\{?SIM(_NAME)?\b/.test(cmd)) {
340
+ const res = [...new Set(hits.flatMap(h => h.res.split(',')))].join(',');
341
+ const why = `guard: ${hits[0].what}`.replace(/[^\w .:/=@,+-]/g, '').slice(0, 50).trim();
342
+ return { command: `${dibs} run ${res} -m ${quote(why)} -- sh -c ${quote(cmd)}`, hits };
343
+ }
344
+ let out = cmd;
345
+ for (const h of [...hits].sort((a, b) => b.at - a.at)) {
346
+ const why = `guard: ${h.what}`.replace(/[^\w .:/=@,+-]/g, '').slice(0, 50).trim();
347
+ out = `${out.slice(0, h.at)}${dibs} run ${h.res} -m ${quote(why)} -- ${out.slice(h.at)}`;
348
+ }
349
+ return { command: out, hits };
350
+ }
351
+
352
+ // The hook never stops a session over its own failure, but leaves one line
353
+ // here so the failure isn't invisible. Writing it may fail too; nothing to do then.
354
+ // Where in dibs it broke and on what kind of call, never the command itself
355
+ // (it can hold secrets): enough to find the bug, as `dibs alerts` reports it.
356
+ function logError(e, input) {
357
+ const at = String(e?.stack || '').split('\n').find(l => l.includes('/src/'))?.match(/\/(src\/[\w.]+:\d+)/)?.[1];
358
+ const on = input?.hook_event_name ? ` [${input.hook_event_name}${input.tool_name ? ` ${input.tool_name}` : ''}]` : '';
359
+ try { fs.appendFileSync(LOG, `${new Date().toISOString()} ${String(e?.message || e).split('\n')[0]}${at ? ` at ${at}` : ''}${on}\n`); } catch {}
360
+ }
361
+
362
+ function dibsConfig() {
363
+ try { return JSON.parse(fs.readFileSync(CONFIG, 'utf8')); }
364
+ catch (e) { if (e.code !== 'ENOENT') logError(`${CONFIG}: ${e.message}`); return {}; }
365
+ }
366
+ const guardConfig = () => dibsConfig().guard ?? {};
367
+
368
+ // Subagent spawns, starts and stops go to the subagent limit (src/agents.mjs),
369
+ // loaded only for those: a Bash call still pays for this module alone.
370
+ const AGENT_EVENT = input => ['Agent', 'Task'].includes(input?.tool_name) || ['SubagentStart', 'SubagentStop'].includes(input?.hook_event_name);
371
+
372
+ // `dibs` when it's on PATH, so the rewritten command reads the way agents
373
+ // write it; otherwise this copy's full path.
374
+ function dibsCommand() {
375
+ for (const dir of (process.env.PATH || '').split(path.delimiter))
376
+ if (dir && fs.existsSync(path.join(dir, 'dibs'))) return 'dibs';
377
+ return quote(path.join(ROOT, 'bin', 'dibs.mjs'));
378
+ }
379
+
380
+ // Rewrite only where "allow" approves nothing the session wouldn't have run
381
+ // anyway (bypassPermissions), unless guard.rewrite says always or never.
382
+ // Everywhere else, deny with the exact command, so the agent's retry goes
383
+ // through the normal permission checks.
384
+ // "guard": false in config.json (or guard.commands false) switches off only
385
+ // the heavy-command half; file leases stay enforced unless guard.files is false.
386
+ export function respond(input, guardCfg = {}, dibs = 'dibs') {
387
+ // Another session's file lease (src/files.mjs) turns a write away before anything else.
388
+ // So does a delete in another session's temp folder, whatever the config says: it's the person's rule.
389
+ const leased = tmpGuard(input, split) || (guardCfg?.files === false ? null : fileGuard(input, split));
390
+ if (leased || input?.tool_name !== 'Bash' || guardCfg === false || guardCfg?.commands === false) return leased;
391
+ const ti = input.tool_input || {};
392
+ const plan = check(ti.command, { rules: rulesFrom(guardCfg), dibs });
393
+ if (!plan) return null;
394
+ const mode = guardCfg.rewrite || 'bypass';
395
+ const what = [...new Set(plan.hits.map(h => h.what.split(' ')[0]))].join(', ');
396
+ if (mode === 'always' || (mode === 'bypass' && input.permission_mode === 'bypassPermissions')) {
397
+ return { hookSpecificOutput: {
398
+ hookEventName: 'PreToolUse',
399
+ permissionDecision: 'allow',
400
+ permissionDecisionReason: `dibs guard wrapped ${what} in dibs run`,
401
+ updatedInput: { ...ti, command: plan.command },
402
+ additionalContext: `dibs guard ran this through dibs because ${what} wasn't wrapped: ${plan.command}\n` +
403
+ 'Wrap builds, simulator use, test suites and deploys in dibs run yourself. If this call reaches its timeout while waiting in the queue, Claude Code moves it to the background and tells you when it ends: don\'t run it again.',
404
+ } };
405
+ }
406
+ return { hookSpecificOutput: {
407
+ hookEventName: 'PreToolUse',
408
+ permissionDecision: 'deny',
409
+ permissionDecisionReason: `dibs guard: ${what} has to take its turn through dibs, or it collides with other agents. Run this instead:\n ${plan.command}\n` +
410
+ 'If it really is a quick read that builds, boots, tests and deploys nothing, put DIBS_GUARD=off in front of it.',
411
+ } };
412
+ }
413
+
414
+ const STOP_EVENT = input => ['Stop', 'SubagentStop'].includes(input?.hook_event_name);
415
+ const START_EVENT = input => ['SessionStart', 'SubagentStart'].includes(input?.hook_event_name);
416
+
417
+ // Whether the person has a message waiting for the agent making this call
418
+ // (src/talk.mjs). With none queued anywhere the file doesn't exist.
419
+ function queuedFor(input) {
420
+ if (typeof input?.session_id !== 'string' || input.hook_event_name === 'SubagentStart') return false;
421
+ try { return (JSON.parse(fs.readFileSync(INBOX, 'utf8'))[input.session_id] || []).includes(input.agent_id || 'main'); }
422
+ catch { return false; }
423
+ }
424
+
425
+ // Whether a stopping subagent has a thread to mark ended. Most never talked,
426
+ // and talk.mjs loads most of dibs, so look for its id in the file first.
427
+ function talked(input) {
428
+ if (typeof input.agent_id !== 'string' || !input.agent_id) return false;
429
+ try { return fs.readFileSync(MESSAGES, 'utf8').includes(JSON.stringify(input.agent_id)); } catch { return false; }
430
+ }
431
+
432
+ // The hook itself: Claude Code's JSON on stdin, a decision on stdout. Any
433
+ // failure prints nothing, which leaves the command to the normal permission flow.
434
+ export async function hook() {
435
+ let out = null, input = null;
436
+ try {
437
+ input = JSON.parse(fs.readFileSync(0, 'utf8'));
438
+ if (AGENT_EVENT(input)) out = (await import('./agents.mjs')).agentHook(input, dibsConfig());
439
+ else if (!STOP_EVENT(input) && !START_EVENT(input)) out = respond(input, guardConfig(), dibsCommand());
440
+ } catch (e) { logError(e, input); }
441
+ // A new session, or a subagent's first start, hears the few rules that keep it out of trouble (src/primer.mjs).
442
+ try { if (START_EVENT(input)) out = (await import('./primer.mjs')).primer(input, out); } catch (e) { logError(e, input); }
443
+ try {
444
+ if (queuedFor(input)) out = (await import('./talk.mjs')).deliver(input, out);
445
+ else if (input?.hook_event_name === 'SubagentStop' && talked(input)) (await import('./talk.mjs')).finished(input);
446
+ } catch (e) { logError(e, input); }
447
+ if (out) process.stdout.write(JSON.stringify(out) + '\n');
448
+ }
449
+
450
+ const isGuard = h => h?.type === 'command' && /dibs-guard\.mjs['"]?$|\bdibs(\.mjs)?['"]? guard['"]?$/.test(String(h.command || '').trim());
451
+
452
+ function readSettings(file) {
453
+ if (!fs.existsSync(file)) return {};
454
+ const text = fs.readFileSync(file, 'utf8');
455
+ if (!text.trim()) return {};
456
+ try { return JSON.parse(text); } catch { throw new Error(`${file} isn't valid JSON; not touching it`); }
457
+ }
458
+
459
+ // Back up the old file once per change, then swap the new one in whole.
460
+ // Returns where the backup went, if there was a file to back up.
461
+ function writeSettings(file, s) {
462
+ const had = fs.existsSync(file);
463
+ const real = had ? fs.realpathSync(file) : file;
464
+ fs.mkdirSync(path.dirname(real), { recursive: true });
465
+ if (had) fs.copyFileSync(real, `${file}.dibs-backup`);
466
+ const tmp = `${real}.dibs-${process.pid}`;
467
+ fs.writeFileSync(tmp, JSON.stringify(s, null, 2) + '\n', { mode: had ? fs.statSync(real).mode & 0o777 : 0o600 });
468
+ fs.renameSync(tmp, real);
469
+ return had ? `${file}.dibs-backup` : null;
470
+ }
471
+
472
+ // Where the hook goes: Bash and the edit tools for the guard and file leases;
473
+ // the Agent tool (Task in older Claude Code) and subagent starts and stops for
474
+ // the subagent limit. No matcher on those two: agents.mjs sorts out which
475
+ // subagents count.
476
+ // Stop (no matcher: it takes none) hands the person's messages to an agent
477
+ // about to end its turn; SubagentStop does the same for subagents.
478
+ // SessionStart (no matcher: startup, resume, clear and compact all need it) tells a session the rules.
479
+ const ENTRIES = [['PreToolUse', 'Bash|Edit|Write|MultiEdit|NotebookEdit'], ['PreToolUse', 'Agent|Task'], ['SubagentStart', null], ['SubagentStop', null], ['Stop', null],
480
+ ['SessionStart', null]];
481
+ const EVENTS = [...new Set(ENTRIES.map(e => e[0]))];
482
+
483
+ // Take our hook out of every event, dropping groups and lists it leaves empty.
484
+ function strip(s) {
485
+ let found = false;
486
+ for (const ev of EVENTS) {
487
+ const groups = s.hooks?.[ev];
488
+ if (!Array.isArray(groups)) continue;
489
+ const kept = [];
490
+ for (const g of groups) {
491
+ const hs = Array.isArray(g?.hooks) ? g.hooks.filter(h => !isGuard(h)) : g?.hooks;
492
+ if (Array.isArray(g?.hooks) && hs.length !== g.hooks.length) found = true;
493
+ if (!Array.isArray(hs) || hs.length) kept.push(Array.isArray(g?.hooks) ? { ...g, hooks: hs } : g);
494
+ }
495
+ if (kept.length) s.hooks[ev] = kept;
496
+ else delete s.hooks[ev];
497
+ }
498
+ if (s.hooks && !Object.keys(s.hooks).length) delete s.hooks;
499
+ return found;
500
+ }
501
+
502
+ export const MATCHER = ENTRIES[0][1];
503
+
504
+ // Our groups in one event.
505
+ const ours = (s, ev = 'PreToolUse') => (s.hooks?.[ev] || []).filter(g => Array.isArray(g?.hooks) && g.hooks.some(isGuard));
506
+ // Every entry there with this command, and nothing else of ours: an older
507
+ // install (Bash alone, or no subagent events) is replaced, not added to.
508
+ const complete = (s, command) => EVENTS.every(ev => ours(s, ev).length === ENTRIES.filter(e => e[0] === ev).length)
509
+ && ENTRIES.every(([ev, matcher]) => ours(s, ev).some(g => (g.matcher ?? null) === matcher && g.hooks.some(h => isGuard(h) && h.command === command)));
510
+
511
+ export function installed(file = SETTINGS) {
512
+ return ours(readSettings(file)).flatMap(g => g.hooks).find(isGuard) || null;
513
+ }
514
+
515
+ export function install(file = SETTINGS, command = quote(HOOK_BIN)) {
516
+ const s = readSettings(file);
517
+ const had = installed(file);
518
+ if (complete(s, command)) return `already installed in ${file}`;
519
+ strip(s);
520
+ s.hooks ||= {};
521
+ for (const [ev, matcher] of ENTRIES)
522
+ (s.hooks[ev] ||= []).push({ ...(matcher ? { matcher } : {}), hooks: [{ type: 'command', command, timeout: 5 }] });
523
+ const backup = writeSettings(file, s);
524
+ return `${had ? 'updated' : 'installed'} in ${file}${backup ? ` (old file in ${backup})` : ''}`;
525
+ }
526
+
527
+ export function remove(file = SETTINGS) {
528
+ const s = readSettings(file);
529
+ if (!strip(s)) return null;
530
+ writeSettings(file, s);
531
+ return `removed from ${file} (old file in ${file}.dibs-backup)`;
532
+ }
533
+
534
+ const USAGE = `dibs guard: catch heavy commands an agent runs outside dibs, turn away edits to files another session leased, cap subagents running at once when you set a limit, and hand agents the person's messages (dibs tell) (a Claude Code hook)
535
+ dibs guard install [--settings file] add the hook to ~/.claude/settings.json (backup kept)
536
+ dibs guard remove [--settings file] take it out again
537
+ dibs guard status [--settings file] [--json] is it installed (exit 1 if not; --json always exits 0)
538
+ dibs guard check "<command>" what the hook would do with a command
539
+ The hook reads Claude Code's JSON on stdin: dibs guard < input.json`;
540
+
541
+ // What `dibs guard status --json` prints, for dibs web too.
542
+ export function guardJson(file = SETTINGS) {
543
+ const h = installed(file);
544
+ const s = readSettings(file);
545
+ const agents = dibsConfig().agents;
546
+ return { installed: !!h, file, command: h?.command ?? null, complete: !!h && complete(s, h.command),
547
+ matchers: EVENTS.flatMap(ev => ours(s, ev).map(g => ({ event: ev, matcher: g.matcher ?? null }))), rewrite: guardConfig().rewrite || 'bypass',
548
+ subagents: Number(agents?.slots) > 0 ? { slots: Number(agents.slots) } : null };
549
+ }
550
+
551
+ // dibs guard [install|remove|status|check]. With no verb and JSON piped in, be the hook.
552
+ export function guard(args) {
553
+ const reply = (msg, code = 0) => { (code ? process.stderr : process.stdout).write(`${msg}\n`); process.exitCode = code; };
554
+ const at = args.indexOf('--settings');
555
+ const file = at >= 0 ? args[at + 1] : SETTINGS;
556
+ if (at >= 0 && !file) return reply('--settings needs a path', 2);
557
+ const verb = args[0];
558
+ try {
559
+ if (!verb) return process.stdin.isTTY ? reply(USAGE) : hook();
560
+ if (verb === 'install') return reply(`dibs guard: ${install(file)}`);
561
+ if (verb === 'remove') { const r = remove(file); return r ? reply(`dibs guard: ${r}`) : reply(`dibs guard: not installed in ${file}`, 1); }
562
+ if (verb === 'status') {
563
+ const h = installed(file);
564
+ const mode = guardConfig().rewrite || 'bypass';
565
+ const agents = dibsConfig().agents;
566
+ // For the Mac app: the same facts as an object, exit 0 either way.
567
+ if (args.includes('--json')) return reply(JSON.stringify(guardJson(file), null, 1));
568
+ if (!h) return reply(`dibs guard is off: it isn't in ${file}. Turn it on: dibs guard install`, 1);
569
+ return reply([`dibs guard is on (in ${file}).`,
570
+ ` Heavy commands an agent runs outside dibs: ${guardConfig() === false || guardConfig().commands === false ? 'let through (switched off in config.json)' : mode === 'bypass' ? 'run through dibs in bypassPermissions sessions, turned away in others' : `run through dibs in "${mode}" sessions, turned away in others`}.`,
571
+ ` Edits to files another agent reserved: ${guardConfig().files === false ? 'let through (guard.files is false in config.json)' : 'turned away'}.`,
572
+ ' New sessions and subagents: told in a few lines how to use dibs. Messages from the person (dibs tell) and notices about their own jobs: handed over on their next tool call.',
573
+ ` Subagents: ${Number(agents?.slots) > 0 ? `at most ${agents.slots} at once across every session` : 'no limit (set agents.slots in config.json to add one)'}.`,
574
+ ...(complete(readSettings(file), h.command) ? [] : [' This is an older install without the file checks, the subagent limit, messages from the person or the new-session primer. Add them: dibs guard install']),
575
+ ` The hook: ${h.command}`].join('\n'));
576
+ }
577
+ if (verb === 'check') {
578
+ const plan = check(args.slice(1).join(' '), { rules: rulesFrom(guardConfig()) });
579
+ return reply(plan ? `${plan.hits.map(h => h.res).join(' + ')}: ${plan.command}` : 'leave alone');
580
+ }
581
+ return reply(USAGE, 2);
582
+ } catch (e) { return reply(`dibs guard: ${e.message}`, 1); }
583
+ }