@dibssoftware/dibs 0.0.178 → 0.0.180

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 (60) hide show
  1. package/CHANGELOG.md +40 -2
  2. package/README.md +49 -196
  3. package/bin/dibs-guard.mjs +10 -1
  4. package/bin/dibs.mjs +72 -31
  5. package/docs/benchmarks.md +1 -1
  6. package/docs/files.md +1 -1
  7. package/docs/guard.md +6 -0
  8. package/docs/machines.md +1 -1
  9. package/docs/questions.md +7 -3
  10. package/docs/reference.md +157 -0
  11. package/docs/relay.md +9 -7
  12. package/docs/releasing.md +11 -8
  13. package/docs/scheduling.md +6 -6
  14. package/docs/windows.md +14 -0
  15. package/package.json +2 -1
  16. package/skills/dibs/SKILL.md +104 -83
  17. package/src/acquire.mjs +102 -34
  18. package/src/agents.mjs +7 -22
  19. package/src/alerts.mjs +157 -57
  20. package/src/answers.mjs +2 -2
  21. package/src/board.mjs +3 -4
  22. package/src/broker.mjs +26 -11
  23. package/src/commands.mjs +39 -14
  24. package/src/config.mjs +27 -6
  25. package/src/cool.mjs +104 -9
  26. package/src/diskwarn.mjs +32 -35
  27. package/src/events.mjs +13 -2
  28. package/src/files.mjs +52 -67
  29. package/src/guard.mjs +52 -6
  30. package/src/guardd.mjs +97 -0
  31. package/src/guardw.mjs +19 -0
  32. package/src/hogs.mjs +18 -5
  33. package/src/later.mjs +20 -25
  34. package/src/lock.mjs +292 -0
  35. package/src/measure.mjs +9 -4
  36. package/src/news.mjs +101 -0
  37. package/src/notes.mjs +171 -0
  38. package/src/notices.mjs +52 -13
  39. package/src/ondemand.mjs +6 -3
  40. package/src/override.mjs +60 -14
  41. package/src/plain.mjs +7 -4
  42. package/src/platform.mjs +165 -35
  43. package/src/preempt.mjs +54 -6
  44. package/src/primer.mjs +43 -15
  45. package/src/proc.mjs +39 -8
  46. package/src/progress.mjs +33 -4
  47. package/src/questions.mjs +8 -22
  48. package/src/relay.mjs +10 -22
  49. package/src/remote.mjs +12 -8
  50. package/src/schedule.mjs +182 -44
  51. package/src/serve.mjs +22 -3
  52. package/src/service.mjs +4 -3
  53. package/src/state.mjs +139 -47
  54. package/src/stats.mjs +3 -2
  55. package/src/talk.mjs +335 -73
  56. package/src/trust.mjs +7 -1
  57. package/src/util.mjs +28 -2
  58. package/src/version.mjs +1 -1
  59. package/src/web.mjs +19 -27
  60. package/src/worker.mjs +2 -1
package/src/files.mjs CHANGED
@@ -6,9 +6,22 @@
6
6
  // but util.mjs, reads state.json without the lock (it's written by rename) and
7
7
  // spawns nothing unless another session's lease covers the path.
8
8
  import fs from 'node:fs';
9
- import os from 'node:os';
10
- import path from 'node:path';
9
+ import nodeOs from 'node:os';
10
+ import nodePath from 'node:path';
11
11
  import { execFileSync } from 'node:child_process';
12
+
13
+ // Every path in this file is written with /, Windows too (C:/Users/x/src/a.ts, as
14
+ // git writes them): lease keys, globs and the hook's comparisons all split on /.
15
+ // path and os here hand back paths that way; macOS and Linux are unchanged.
16
+ const WIN = process.platform === 'win32';
17
+ const slash = p => (WIN && typeof p === 'string' ? p.replace(/\\/g, '/') : p);
18
+ const path = !WIN ? nodePath : {
19
+ ...nodePath, sep: '/',
20
+ resolve: (...a) => slash(nodePath.resolve(...a)), join: (...a) => slash(nodePath.join(...a)), dirname: p => slash(nodePath.dirname(p)),
21
+ relative: (a, b) => slash(nodePath.relative(a, b)), normalize: p => slash(nodePath.normalize(p)),
22
+ };
23
+ const os = !WIN ? nodeOs : { ...nodeOs, homedir: () => slash(nodeOs.homedir()), tmpdir: () => slash(nodeOs.tmpdir()) };
24
+ const cwdNow = () => slash(process.cwd());
12
25
  import { dur, clock, fakeFull, callerPid } from './util.mjs';
13
26
 
14
27
  export const FILES = 'files:';
@@ -87,12 +100,11 @@ function guessedOthers(prefix, session) {
87
100
  return null;
88
101
  }
89
102
 
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
103
+ // dibs remembers which agent first wrote into each folder at the top of a
104
+ // session's scratchpad (scratch/<session>/<folder> in DIBS_HOME, made with wx so
105
+ // the first one wins without a lock), so the disk watcher can tell whose it is
106
+ // (src/hogs.mjs). It never decides who may delete: every agent of a session may
107
+ // delete anything in its own scratchpad short of all of it.
96
108
  const makersDir = session => path.join(dibsHome(), 'scratch', session);
97
109
  const agentOf = input => input.agent_id || 'main';
98
110
 
@@ -110,47 +122,21 @@ export function maker(session, name) {
110
122
  try { return JSON.parse(fs.readFileSync(path.join(makersDir(session), encodeURIComponent(name)), 'utf8')); } catch { return null; }
111
123
  }
112
124
 
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
125
  // 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.
126
+ // the whole of what every agent of the session shares, or null when it's fine.
132
127
  function ownDelete(p, t, input) {
133
128
  const at = inSession(p);
134
129
  if (!at) return null;
135
130
  const [folder, rest] = at, pad = path.join(folder, 'scratchpad');
136
131
  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.';
132
+ + 'Delete the folders in it you are done with instead. If it really must all go, have the person delete it.';
138
133
  if (!rest.length) return whole("your session's temp folder");
139
134
  if (!overlap(path.join(folder, rest[0]), pad)) return null;
140
135
  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
- }
136
+ // A glob of only wildcards at the top (scratchpad/*, scratchpad/.*) is the whole scratchpad by another name.
137
+ if (rest.length === 2 && /^[*?.]+$/.test(rest[1])) return whole("your session's scratchpad");
138
+ // Anything under it is the session's own, whoever of the session made it and however
139
+ // old: 2e had to ask a teammate to delete 850 MB of browser profiles at 4.9 GB free (2026-11-04).
154
140
  return null;
155
141
  }
156
142
 
@@ -158,10 +144,9 @@ function ownDelete(p, t, input) {
158
144
  // A program can make a scratchpad folder dibs doesn't see it write
159
145
  // (xcodebuild -derivedDataPath scratchpad/dd made fix-app's 0.5 GB of derived
160
146
  // 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.
147
+ // anywhere in a command counts as made by whoever ran it.
163
148
  function noteMakers(input, split, written) {
164
- const made = new Set(), named = new Set(), gone = new Set();
149
+ const made = new Set(), gone = new Set();
165
150
  const top = p => {
166
151
  const at = inSession(real(p));
167
152
  return at && at[1][0] === 'scratchpad' && at[1].length >= 2 && !GLOB.test(at[1][1]) && path.basename(at[0]) === input.session_id
@@ -176,12 +161,10 @@ function noteMakers(input, split, written) {
176
161
  }
177
162
  for (const p of namedPaths(input, split)) {
178
163
  const f = top(p);
179
- if (!f) continue;
180
- named.add(f[0]);
181
- if (!fs.existsSync(f[1])) made.add(f[0]);
164
+ if (f && !fs.existsSync(f[1])) made.add(f[0]);
182
165
  }
183
- for (const n of gone) { made.delete(n); named.delete(n); }
184
- if (!made.size && !named.size && !gone.size) return;
166
+ for (const n of gone) made.delete(n);
167
+ if (!made.size && !gone.size) return;
185
168
  // Best effort: a full disk or a race costs only a record, never the call.
186
169
  try {
187
170
  const dir = makersDir(input.session_id);
@@ -195,19 +178,16 @@ function noteMakers(input, split, written) {
195
178
  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
179
  catch {}
197
180
  }
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
181
  if (fresh) pruneMakers();
201
182
  } catch {}
202
183
  }
203
- const namedBy = (session, name, agent) => fs.existsSync(path.join(makersDir(session), `${encodeURIComponent(name)}@${encodeURIComponent(agent)}`));
204
184
 
205
185
  // Every word of a Bash command that could be a path in this session's folder,
206
186
  // absolute: arguments anywhere (after dibs run's --, too), and --out=<path> values.
207
187
  function namedPaths(input, split) {
208
188
  const cmd = input.tool_name === 'Bash' && input.tool_input?.command;
209
189
  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);
190
+ return namedIn(cmd, typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow(), input.session_id, split, 0);
211
191
  }
212
192
  // A script handed to a shell with -c is read the same way, from the folder the shell starts in:
213
193
  // dibs run xcode-build -- sh -c '... -derivedDataPath <scratchpad>/dd-test' made 177 MB on
@@ -252,7 +232,7 @@ function mkdirs(input, split) {
252
232
  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
233
  if (!segs) return [];
254
234
  const out = [];
255
- for (const { name, args, dir } of commands(segs, typeof input.cwd === 'string' ? input.cwd : process.cwd()))
235
+ for (const { name, args, dir } of commands(segs, typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow()))
256
236
  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
237
  return out;
258
238
  }
@@ -299,7 +279,7 @@ function real(abs) {
299
279
  let k = segs.findIndex(s => GLOB.test(s));
300
280
  if (k < 0) k = segs.length;
301
281
  for (let i = k; i > 1; i--) {
302
- try { return [fs.realpathSync.native(segs.slice(0, i).join('/')), ...segs.slice(i)].join('/'); } catch {}
282
+ try { return [slash(fs.realpathSync.native(segs.slice(0, i).join('/'))), ...segs.slice(i)].join('/'); } catch {}
303
283
  }
304
284
  return abs;
305
285
  }
@@ -355,12 +335,12 @@ function mainOf(dir) {
355
335
  if (path.basename(path.dirname(gitdir)) !== 'worktrees') return null;
356
336
  common = path.dirname(path.dirname(gitdir));
357
337
  }
358
- if (path.basename(common) === '.git') return fs.realpathSync(path.dirname(common));
338
+ if (path.basename(common) === '.git') return slash(fs.realpathSync(path.dirname(common)));
359
339
  // A submodule's own worktrees: its checkout is core.worktree. A bare repo has none, so the repo itself stands in.
360
340
  let config = '';
361
341
  try { config = fs.readFileSync(path.join(common, 'config'), 'utf8'); } catch {}
362
342
  const w = /^\s*worktree\s*=\s*(.+?)\s*$/m.exec(config);
363
- return fs.realpathSync(w ? path.resolve(common, w[1]) : common);
343
+ return slash(fs.realpathSync(w ? path.resolve(common, w[1]) : common));
364
344
  } catch { return null; }
365
345
  }
366
346
 
@@ -383,10 +363,10 @@ export const fileKey = r => (isFiles(r) ? FILES + canon(r.slice(FILES.length)) :
383
363
 
384
364
  // ' in another copy of this repo (wt-trust)' when lease l was taken from a
385
365
  // different worktree of the repo cwd is in, else ''.
386
- export function elsewhere(l, cwd = process.cwd()) {
366
+ export function elsewhere(l, cwd = cwdNow()) {
387
367
  try {
388
368
  if (typeof l?.cwd !== 'string') return '';
389
- const mine = worktreeOf(real(path.resolve(cwd))), theirs = worktreeOf(real(l.cwd));
369
+ const mine = worktreeOf(real(path.resolve(cwd))), theirs = worktreeOf(real(path.resolve(l.cwd)));
390
370
  if (!mine || !theirs || mine[1] !== theirs[1] || mine[0] === theirs[0]) return '';
391
371
  return ` in another copy of this repo (${path.basename(theirs[0])})`;
392
372
  } catch { return ''; }
@@ -435,7 +415,7 @@ function braces(r) {
435
415
  return parts.flatMap(p => braces(r.slice(0, open) + p + r.slice(close + 1))).slice(0, BRACES);
436
416
  }
437
417
 
438
- export function fileRes(r, cwd = process.cwd()) {
418
+ export function fileRes(r, cwd = cwdNow()) {
439
419
  if (!isFiles(r)) return r;
440
420
  const p = r.slice(FILES.length).trim();
441
421
  if (!p) return null;
@@ -443,7 +423,7 @@ export function fileRes(r, cwd = process.cwd()) {
443
423
  }
444
424
 
445
425
  // 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()) {
426
+ export function short(r, cwd = cwdNow()) {
447
427
  if (!isFiles(r)) return r;
448
428
  const p = r.slice(FILES.length);
449
429
  const root = gitRoot(cwd) && real(gitRoot(cwd));
@@ -482,7 +462,7 @@ function walk(a, i, b, j) {
482
462
  // Unsure counts as yes. Both are keyed by the main worktree first (canon), so
483
463
  // a lease an older dibs stored under a worktree's own path still counts.
484
464
  export function overlap(a, b) {
485
- const segs = p => folded(canon(p.replace(FILES, ''))).split('/').filter(Boolean);
465
+ const segs = p => folded(canon(slash(p.replace(FILES, '')))).split('/').filter(Boolean);
486
466
  return walk(segs(a), 0, segs(b), 0);
487
467
  }
488
468
 
@@ -514,7 +494,11 @@ let above = null;
514
494
  function ancestors() {
515
495
  if (above) return above;
516
496
  const up = new Map();
517
- for (const line of execFileSync('ps', ['-A', '-o', 'pid=,ppid='], { encoding: 'utf8', timeout: 2000 }).trim().split('\n')) {
497
+ // Windows has no ps: one CIM read of the table, about a second, once per hook.
498
+ const table = WIN
499
+ ? execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', 'Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }'], { encoding: 'utf8', timeout: 10000, windowsHide: true })
500
+ : execFileSync('ps', ['-A', '-o', 'pid=,ppid='], { encoding: 'utf8', timeout: 2000 });
501
+ for (const line of table.trim().split(/\r?\n/)) {
518
502
  const [pid, ppid] = line.trim().split(/\s+/).map(Number);
519
503
  up.set(pid, ppid);
520
504
  }
@@ -947,12 +931,13 @@ const READ_VERBS = new Set(['status', 'why', 'mine', 'who', 'when', 'yield']);
947
931
  const ACT_VERBS = new Set(['boost', 'pause', 'resume', 'stop']);
948
932
  const ALIASES = { done: 'release', renew: 'hold', ls: 'status', board: 'status' };
949
933
  // 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
934
+ // dibs later tells that thread how the job ended (src/later.mjs), and a dibs
935
+ // progress task belongs to the subagent that posts it (src/progress.mjs). Their
951
936
  // note is keyed by the words, so subagents saying "done" at once each get
952
937
  // their own. A word the hook can't read ($VAR) matches any one word.
953
938
  // Every other call is keyed the same way, by all its words, so two subagents
954
939
  // running `dibs run sim -- ...` at once each claim their own note.
955
- const TALK_VERBS = new Set(['say', 'question', 'later']);
940
+ const TALK_VERBS = new Set(['say', 'question', 'later', 'progress', 'listen']);
956
941
  export const talkKey = (verb, words) => `${verb}|${words.join('\0')}`;
957
942
  // A word the hook can't read ("files:$R/a.ts", $(...)) stands for any one word.
958
943
  const WILD = '\u0001';
@@ -996,7 +981,7 @@ export function dibsCalls(cmd, split, cwd) {
996
981
 
997
982
  function noteAgent(input, split) {
998
983
  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());
984
+ const calls = dibsCalls(input.tool_input?.command, split, typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow());
1000
985
  if (!calls.length) return;
1001
986
  // Only a nicety (naming the subagent): a full disk must not cost the lease check after it.
1002
987
  try {
@@ -1057,7 +1042,7 @@ export const shellRes = rs => {
1057
1042
  // The paths a tool call would write, absolute.
1058
1043
  function targets(input, split, guesses = false) {
1059
1044
  const ti = input.tool_input || {};
1060
- const cwd = typeof input.cwd === 'string' ? input.cwd : process.cwd();
1045
+ const cwd = typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow();
1061
1046
  if (input.tool_name === 'Bash') return bashWrites(ti.command, split, cwd, guesses);
1062
1047
  const p = ti.file_path ?? ti.notebook_path;
1063
1048
  return typeof p === 'string' && p ? [{ path: path.resolve(cwd, expand(p)), why: input.tool_name }] : [];
@@ -1071,7 +1056,7 @@ export function fileGuard(input, split) {
1071
1056
  noteAgent(input, split);
1072
1057
  const live = leases();
1073
1058
  if (!live.length) return null;
1074
- const cwd = typeof input.cwd === 'string' ? input.cwd : process.cwd();
1059
+ const cwd = typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow();
1075
1060
  const t = Date.now();
1076
1061
  for (const target of targets(input, split)) {
1077
1062
  if (target.guess != null) continue;
package/src/guard.mjs CHANGED
@@ -12,6 +12,10 @@ import { tmpGuard, fileGuard, resList } from './files.mjs';
12
12
 
13
13
  const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
14
14
  const HOOK_BIN = path.join(ROOT, 'bin', 'dibs-guard.mjs');
15
+ // Claude Code runs hooks and Bash commands through Git Bash on Windows, where a
16
+ // .mjs doesn't run by name: there node runs it, from a path written with /.
17
+ const WIN = process.platform === 'win32';
18
+ const viaNode = file => (WIN ? `node ${quote(file.replace(/\\/g, '/'))}` : quote(file));
15
19
  // The same folder as config.mjs's HOME, worked out here because the hook loads no other module.
16
20
  const DIBS_HOME = process.env.DIBS_HOME || path.join(os.homedir(), '.dibs');
17
21
  const CONFIG = path.join(DIBS_HOME, 'config.json');
@@ -20,6 +24,11 @@ const LOG = path.join(DIBS_HOME, 'guard.log');
20
24
  // Who has a message from the person waiting: { session_id: [agent ids] }, or
21
25
  // no file at all. src/talk.mjs keeps it; the hook only reads it.
22
26
  const INBOX = path.join(DIBS_HOME, 'inbox.json');
27
+ // dibs listen's list of who listens (src/talk.mjs), and the listeners already reminded about.
28
+ const LISTENERS = path.join(DIBS_HOME, 'listeners.json');
29
+ const REMINDED = path.join(DIBS_HOME, 'listen-reminded.json');
30
+ // Sessions remembered in REMINDED: enough for every session a machine runs in a day or two.
31
+ const REMIND_KEEP = 200;
23
32
  // The threads themselves, which the hook only searches for a subagent's id.
24
33
  const MESSAGES = path.join(DIBS_HOME, 'messages.json');
25
34
  const SETTINGS = process.env.DIBS_CLAUDE_SETTINGS || path.join(os.homedir(), '.claude', 'settings.json');
@@ -311,7 +320,8 @@ export function rulesFrom(guardCfg) {
311
320
  return { ...RULES, ...(guardCfg?.rules || {}) };
312
321
  }
313
322
 
314
- const quote = s => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
323
+ // A ~ inside a word stays as typed (Windows short names: C:/Users/RUNNER~1); only a leading one expands.
324
+ const quote = s => (/^[\w@%+=:,./-][\w@%+=:,./~-]*$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
315
325
 
316
326
  // What to do with a command: null to leave it alone, or the rewritten command
317
327
  // and what was caught.
@@ -354,6 +364,8 @@ export function check(cmd, { rules = RULES, dibs = 'dibs' } = {}) {
354
364
  // Where in dibs it broke and on what kind of call, never the command itself
355
365
  // (it can hold secrets): enough to find the bug, as `dibs alerts` reports it.
356
366
  function logError(e, input) {
367
+ // A full disk is no bug in dibs: the call goes through, and the board already says the disk is full.
368
+ if (e?.code === 'ENOSPC' || e?.code === 'EDQUOT') return;
357
369
  const at = String(e?.stack || '').split('\n').find(l => l.includes('/src/'))?.match(/\/(src\/[\w.]+:\d+)/)?.[1];
358
370
  const on = input?.hook_event_name ? ` [${input.hook_event_name}${input.tool_name ? ` ${input.tool_name}` : ''}]` : '';
359
371
  try { fs.appendFileSync(LOG, `${new Date().toISOString()} ${String(e?.message || e).split('\n')[0]}${at ? ` at ${at}` : ''}${on}\n`); } catch {}
@@ -374,7 +386,7 @@ const AGENT_EVENT = input => ['Agent', 'Task'].includes(input?.tool_name) || ['S
374
386
  function dibsCommand() {
375
387
  for (const dir of (process.env.PATH || '').split(path.delimiter))
376
388
  if (dir && fs.existsSync(path.join(dir, 'dibs'))) return 'dibs';
377
- return quote(path.join(ROOT, 'bin', 'dibs.mjs'));
389
+ return viaNode(path.join(ROOT, 'bin', 'dibs.mjs'));
378
390
  }
379
391
 
380
392
  // Rewrite only where "allow" approves nothing the session wouldn't have run
@@ -429,12 +441,43 @@ function talked(input) {
429
441
  try { return fs.readFileSync(MESSAGES, 'utf8').includes(JSON.stringify(input.agent_id)); } catch { return false; }
430
442
  }
431
443
 
444
+ // A main agent ending its turn after its dibs listen ended (it handed messages over, ran out of
445
+ // time or was killed) is kept going once, for that listener, to start it again: without one, a
446
+ // message sent while it waits sits until its next tool call. Only a session that listened
447
+ // before; one that never did hears about it at its start (src/primer.mjs). One read, and one
448
+ // small write when it reminds.
449
+ function rearm(input) {
450
+ if (input?.hook_event_name !== 'Stop' || input.stop_hook_active || typeof input.session_id !== 'string') return null;
451
+ let l;
452
+ try { l = JSON.parse(fs.readFileSync(LISTENERS, 'utf8'))[`${input.session_id}|main`]; } catch { return null; }
453
+ if (!Number.isInteger(l?.pid)) return null;
454
+ try { process.kill(l.pid, 0); return null; } catch (e) { if (e.code !== 'ESRCH') return null; }
455
+ let told = {};
456
+ try { told = JSON.parse(fs.readFileSync(REMINDED, 'utf8')); } catch {}
457
+ if (told[input.session_id] === l.pid) return null;
458
+ delete told[input.session_id];
459
+ told[input.session_id] = l.pid;
460
+ const keys = Object.keys(told);
461
+ for (const k of keys.slice(0, Math.max(0, keys.length - REMIND_KEEP))) delete told[k];
462
+ fs.writeFileSync(`${REMINDED}.${process.pid}`, JSON.stringify(told));
463
+ fs.renameSync(`${REMINDED}.${process.pid}`, REMINDED);
464
+ return { decision: 'block', reason: 'dibs: re-arm: your dibs listen has ended. Start it again with run_in_background (dibs listen) before you end your turn, so a message sent while you wait wakes you. dibs reminds you once each time it ends.' };
465
+ }
466
+
432
467
  // The hook itself: Claude Code's JSON on stdin, a decision on stdout. Any
433
468
  // failure prints nothing, which leaves the command to the normal permission flow.
434
469
  export async function hook() {
435
- let out = null, input = null;
470
+ let input;
471
+ try { input = JSON.parse(fs.readFileSync(0, 'utf8')); } catch (e) { return logError(e, null); }
472
+ const out = await decide(input);
473
+ if (out) process.stdout.write(JSON.stringify(out) + '\n');
474
+ }
475
+
476
+ // What the hook answers for one event, or null to say nothing. The resident
477
+ // guard (src/guardd.mjs) runs this too, in a fresh worker per call.
478
+ export async function decide(input) {
479
+ let out = null;
436
480
  try {
437
- input = JSON.parse(fs.readFileSync(0, 'utf8'));
438
481
  if (AGENT_EVENT(input)) out = (await import('./agents.mjs')).agentHook(input, dibsConfig());
439
482
  else if (!STOP_EVENT(input) && !START_EVENT(input)) out = respond(input, guardConfig(), dibsCommand());
440
483
  } catch (e) { logError(e, input); }
@@ -444,7 +487,8 @@ export async function hook() {
444
487
  if (queuedFor(input)) out = (await import('./talk.mjs')).deliver(input, out);
445
488
  else if (input?.hook_event_name === 'SubagentStop' && talked(input)) (await import('./talk.mjs')).finished(input);
446
489
  } catch (e) { logError(e, input); }
447
- if (out) process.stdout.write(JSON.stringify(out) + '\n');
490
+ try { if (!out) out = rearm(input); } catch (e) { logError(e, input); }
491
+ return out;
448
492
  }
449
493
 
450
494
  const isGuard = h => h?.type === 'command' && /dibs-guard\.mjs['"]?$|\bdibs(\.mjs)?['"]? guard['"]?$/.test(String(h.command || '').trim());
@@ -512,7 +556,7 @@ export function installed(file = SETTINGS) {
512
556
  return ours(readSettings(file)).flatMap(g => g.hooks).find(isGuard) || null;
513
557
  }
514
558
 
515
- export function install(file = SETTINGS, command = quote(HOOK_BIN)) {
559
+ export function install(file = SETTINGS, command = viaNode(HOOK_BIN)) {
516
560
  const s = readSettings(file);
517
561
  const had = installed(file);
518
562
  if (complete(s, command)) return `already installed in ${file}`;
@@ -536,6 +580,7 @@ const USAGE = `dibs guard: catch heavy commands an agent runs outside dibs, turn
536
580
  dibs guard remove [--settings file] take it out again
537
581
  dibs guard status [--settings file] [--json] is it installed (exit 1 if not; --json always exits 0)
538
582
  dibs guard check "<command>" what the hook would do with a command
583
+ dibs guard serve answer the hook from one running process (dibs service install guard keeps it up)
539
584
  The hook reads Claude Code's JSON on stdin: dibs guard < input.json`;
540
585
 
541
586
  // What `dibs guard status --json` prints, for dibs web too.
@@ -557,6 +602,7 @@ export function guard(args) {
557
602
  const verb = args[0];
558
603
  try {
559
604
  if (!verb) return process.stdin.isTTY ? reply(USAGE) : hook();
605
+ if (verb === 'serve') return import('./guardd.mjs').then(m => m.serveGuard());
560
606
  if (verb === 'install') return reply(`dibs guard: ${install(file)}`);
561
607
  if (verb === 'remove') { const r = remove(file); return r ? reply(`dibs guard: ${r}`) : reply(`dibs guard: not installed in ${file}`, 1); }
562
608
  if (verb === 'status') {
package/src/guardd.mjs ADDED
@@ -0,0 +1,97 @@
1
+ // dibs guard serve: the resident guard. The Claude Code hook runs on every
2
+ // tool call, about 30,000 a day here, and starting Node for each was nearly
3
+ // all of its time (100 to 400 ms on a busy Mac, against 3 to 20 ms of the
4
+ // hook's own work). bin/dibs-guard.mjs is also a small sh script that sends
5
+ // the call down GUARD_SOCK when this is running, and starts Node as before
6
+ // when it isn't, or when it doesn't answer.
7
+ //
8
+ // Each call runs in a worker thread loaded before the call comes, with the
9
+ // hook's own environment and parent pid (src/guardw.mjs), and the worker ends
10
+ // with it, so a call here is the same as a call in its own Node.
11
+ //
12
+ // On the socket, an HTTP POST from the client (curl): its parent pid, its
13
+ // folder, its environment (env -0), an empty field, the hook's JSON, each
14
+ // ending in a NUL. Back: "ok", then the hook's answer on the next line if it
15
+ // has one. Anything but "ok" and the client runs the hook itself.
16
+ import fs from 'node:fs';
17
+ import http from 'node:http';
18
+ import path from 'node:path';
19
+ import { Worker } from 'node:worker_threads';
20
+ import { fileURLToPath } from 'node:url';
21
+ import { HOME } from './config.mjs';
22
+ import { singleInstance } from './proc.mjs';
23
+ import { log } from './util.mjs';
24
+
25
+ export const GUARD_SOCK = path.join(HOME, 'guard.sock');
26
+ const PIDFILE = path.join(HOME, 'guard.pid');
27
+ const WORKER = path.join(path.dirname(fileURLToPath(import.meta.url)), 'guardw.mjs');
28
+ // Workers kept loaded and waiting: calls come in bursts when several agents work
29
+ // at once, and one takes 20 to 45 ms to load on a busy Mac.
30
+ const READY = 2;
31
+ // A call that takes longer is answered with nothing (allow), as a failing hook
32
+ // is, inside the client's 2 s: the subagent ledger's lock gives up at 1 s. A
33
+ // client that gets no answer then starts Node, which must still fit in Claude
34
+ // Code's 5 s hook timeout.
35
+ const CALL_LIMIT = 1500;
36
+ // No hook input comes near this; a client sending more is cut off.
37
+ const MAX_FRAME = 8 * 1024 ** 2;
38
+
39
+ // The fields of a whole frame, or null while more is still to come.
40
+ export function frame(buf) {
41
+ const parts = buf.toString('utf8').split('\0');
42
+ const end = parts.indexOf('', 2); // the empty field after the environment
43
+ // Complete once the JSON after it has its own NUL: parts then ends with ''.
44
+ if (end < 0 || parts.length < end + 3) return null;
45
+ const env = {};
46
+ for (const kv of parts.slice(2, end)) { const i = kv.indexOf('='); if (i > 0) env[kv.slice(0, i)] = kv.slice(i + 1); }
47
+ return { ppid: Number(parts[0]) || null, cwd: parts[1], env, input: parts[end + 1] };
48
+ }
49
+
50
+ export async function serveGuard() {
51
+ await singleInstance(PIDFILE, 'a resident guard is already running here');
52
+ const ready = [], waiting = [];
53
+ const warm = () => {
54
+ const w = new Worker(WORKER, { execArgv: [] });
55
+ w.once('message', () => { const next = waiting.shift(); next ? next(w) : ready.push(w); });
56
+ w.once('error', e => log(`a guard worker failed to load: ${e.message}`));
57
+ };
58
+ const take = () => new Promise(r => { warm(); const w = ready.shift(); w ? r(w) : waiting.push(r); });
59
+ for (let i = 0; i < READY; i++) warm();
60
+
61
+ function call(f) {
62
+ let input;
63
+ try { input = JSON.parse(f.input); } catch { return null; } // the hook says nothing for input it can't read
64
+ return new Promise(resolve => {
65
+ let w = null, over = false;
66
+ const done = out => { if (over) return; over = true; clearTimeout(timer); w?.terminate(); resolve(out); };
67
+ const timer = setTimeout(() => { log(`a hook call took over ${CALL_LIMIT} ms and was let through: ${input?.hook_event_name} ${input?.tool_name || ''}`); done(null); }, CALL_LIMIT);
68
+ take().then(got => {
69
+ if (over) return got.terminate();
70
+ w = got;
71
+ w.once('message', m => done(m.out ?? null));
72
+ w.once('exit', () => done(null));
73
+ w.postMessage({ input, env: f.env, ppid: f.ppid });
74
+ });
75
+ });
76
+ }
77
+
78
+ try { fs.unlinkSync(GUARD_SOCK); } catch {}
79
+ // HTTP over the socket, because curl is the client every Mac and Linux box has
80
+ // that waits for an answer: macOS nc hangs up as soon as its input ends.
81
+ const server = http.createServer((req, res) => {
82
+ const chunks = [];
83
+ let size = 0;
84
+ req.on('data', d => { size += d.length; if (size > MAX_FRAME) req.destroy(); else chunks.push(d); });
85
+ req.on('end', async () => {
86
+ const f = frame(Buffer.concat(chunks));
87
+ const out = f ? await call(f) : null;
88
+ res.end(f ? `ok\n${out ? `${JSON.stringify(out)}\n` : ''}` : 'bad frame\n');
89
+ });
90
+ });
91
+ server.listen(GUARD_SOCK, () => {
92
+ fs.chmodSync(GUARD_SOCK, 0o600);
93
+ log(`answering the Claude Code hook on ${GUARD_SOCK}`);
94
+ });
95
+ const stop = () => { server.close(); try { fs.unlinkSync(GUARD_SOCK); } catch {} try { fs.rmSync(PIDFILE); } catch {} process.exit(0); };
96
+ process.on('SIGINT', stop); process.on('SIGTERM', stop);
97
+ }
package/src/guardw.mjs ADDED
@@ -0,0 +1,19 @@
1
+ // One hook call in the resident guard (src/guardd.mjs): a worker thread that
2
+ // loads the hook's modules before its call comes, answers that one call as
3
+ // the hook process would, and ends. A fresh worker per call keeps every call
4
+ // as fresh as its own Node process was: the modules keep caches (the pool's
5
+ // simulators, the processes above the hook) that are only right for one call.
6
+ import { parentPort } from 'node:worker_threads';
7
+ import { decide } from './guard.mjs';
8
+ import { setCaller } from './util.mjs';
9
+
10
+ parentPort.once('message', async ({ input, env, ppid }) => {
11
+ // The hook's own environment and parent, as the client saw them.
12
+ for (const k of Object.keys(process.env)) delete process.env[k];
13
+ Object.assign(process.env, env);
14
+ setCaller(ppid);
15
+ let out = null;
16
+ try { out = await decide(input); } catch {}
17
+ parentPort.postMessage({ out });
18
+ });
19
+ parentPort.postMessage({ ready: true });
package/src/hogs.mjs CHANGED
@@ -118,6 +118,12 @@ function short(cfg, m, s) {
118
118
  return m.diskFree < floor || (s.queue || []).some(q => q.pid && q.disk && m.diskFree < q.disk);
119
119
  }
120
120
 
121
+ // The session folders over HOG_MIN, biggest first, with whose they are.
122
+ function bigFolders(folders, size) {
123
+ return Object.entries(size).filter(([p, b]) => folders.includes(p) && b >= HOG_MIN()).sort((a, b) => b[1] - a[1]).slice(0, TOP)
124
+ .map(([folder, b]) => ({ folder, session: path.basename(folder), bytes: b, what: contents(path.join(folder, 'scratchpad')) || contents(folder), ...ownerOf(folder, path.basename(folder), size) }));
125
+ }
126
+
121
127
  // One pass, from the throttle watcher: measure on a new drop (and every
122
128
  // REMEASURE while it lasts), and leave the biggest folders' agents a notice
123
129
  // once per drop. Never throws.
@@ -136,12 +142,17 @@ export async function hogsOnce(cfg, m, t = now()) {
136
142
  write(was = { ...was, cleaned: await clean(t), cleanedCritical: critical });
137
143
  }
138
144
  if (!short(cfg, m, s)) {
139
- if (was?.under && m.diskFree >= floor + OVER) write({ ...was, under: false, endedAt: t });
145
+ // Room again (twice the floor): a later fall is news to each session, band by band (src/diskwarn.mjs).
146
+ const room = m.diskFree != null && m.diskFree >= 2 * floor;
147
+ if (was?.under && m.diskFree >= floor + OVER) { const { warned, ...rest } = was; write({ ...(room ? rest : was), under: false, endedAt: t }); }
148
+ else if (was?.warned && room) { const { warned, ...rest } = was; write(rest); }
140
149
  else if (m.diskFree != null && m.diskFree < 2 * floor) {
141
150
  let x = was || {};
142
151
  if (!(t - (was?.readAt || 0) < REMEASURE)) {
143
152
  const folders = sessionFolders();
144
- write(x = { ...x, under: false, ...readings(folders, await sizes([...folders, ...Object.values(places())]), m, was, t) });
153
+ const size = await sizes([...folders, ...Object.values(places())]);
154
+ // The folders big enough to be worth freeing: their sessions are the ones told.
155
+ write(x = { ...x, under: false, folders: bigFolders(folders, size), ...readings(folders, size, m, was, t) });
145
156
  }
146
157
  const keep = await warnOnce(cfg, m, x, hintOf(x), t);
147
158
  if (Object.keys(keep).length) write({ ...x, ...keep });
@@ -157,8 +168,7 @@ export async function hogsOnce(cfg, m, t = now()) {
157
168
  }
158
169
  const folders = sessionFolders();
159
170
  const size = await sizes([...folders, ...Object.values(places())]);
160
- const big = Object.entries(size).filter(([p, b]) => folders.includes(p) && b >= HOG_MIN()).sort((a, b) => b[1] - a[1]).slice(0, TOP)
161
- .map(([folder, b]) => ({ folder, session: path.basename(folder), bytes: b, what: contents(path.join(folder, 'scratchpad')) || contents(folder), ...ownerOf(folder, path.basename(folder), size) }));
171
+ const big = bigFolders(folders, size);
162
172
  const waiting = (s.queue || []).filter(q => q.pid).length;
163
173
  const x = { ...(was?.cleaned && { cleaned: was.cleaned, cleanedCritical: was.cleanedCritical }), ...(was?.warned && { warned: was.warned }), under: true, drop, at: t, free: m.diskFree, floor, waiting, folders: big, ...readings(folders, size, m, was, t) };
164
174
  write(x);
@@ -183,13 +193,16 @@ function readings(folders, size, m, was, t) {
183
193
  for (const [label, p] of Object.entries(places())) if (size[p] != null) now[label] = size[p];
184
194
  if (m.swapUsed != null) now.swap = m.swapUsed;
185
195
  let writer = null;
196
+ // Every folder that grew, not only the fastest: a session whose files hold still has nothing new to free (src/diskwarn.mjs).
197
+ const grew = [];
186
198
  if (was?.readings && t - was.readAt <= 3 * REMEASURE) {
187
199
  for (const [label, b] of Object.entries(now)) {
188
200
  const by = b - (was.readings[label] ?? b);
201
+ if (by >= GROW_MIN) grew.push(label);
189
202
  if (by >= GROW_MIN && (!writer || by > writer.by)) writer = { label, by, ms: t - was.readAt };
190
203
  }
191
204
  }
192
- return { readings: now, readAt: t, writer };
205
+ return { readings: now, readAt: t, writer, grew };
193
206
  }
194
207
 
195
208
  // For a disk wait: what's growing and the biggest folder and whose it is, as words to add, or ''.