@dibssoftware/dibs 0.0.180 → 0.0.195

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 (107) hide show
  1. package/CHANGELOG.md +111 -1
  2. package/README.md +10 -8
  3. package/bin/dibs.mjs +379 -74
  4. package/docs/agents.md +303 -0
  5. package/docs/council.md +88 -0
  6. package/docs/files.md +3 -3
  7. package/docs/guard.md +86 -11
  8. package/docs/json.md +211 -0
  9. package/docs/later.md +5 -5
  10. package/docs/machines.md +6 -6
  11. package/docs/questions.md +104 -3
  12. package/docs/reference.md +124 -30
  13. package/docs/relay.md +135 -11
  14. package/docs/releasing.md +7 -1
  15. package/docs/scheduling.md +28 -6
  16. package/docs/secrets.md +53 -0
  17. package/docs/simulators.md +3 -3
  18. package/docs/windows.md +3 -3
  19. package/package.json +1 -1
  20. package/skills/dibs/SKILL.md +79 -149
  21. package/src/about.mjs +341 -0
  22. package/src/acquire.mjs +113 -28
  23. package/src/after.mjs +127 -0
  24. package/src/agents.mjs +2 -1
  25. package/src/alerts.mjs +109 -48
  26. package/src/answers.mjs +2 -2
  27. package/src/board.mjs +21 -16
  28. package/src/broker.mjs +23 -7
  29. package/src/carry.mjs +287 -0
  30. package/src/codex.mjs +132 -0
  31. package/src/commands.mjs +254 -86
  32. package/src/config.mjs +85 -14
  33. package/src/connect.mjs +4 -2
  34. package/src/cool.mjs +28 -12
  35. package/src/council.mjs +482 -0
  36. package/src/cwd.mjs +9 -0
  37. package/src/decisions.mjs +250 -0
  38. package/src/declare.mjs +96 -0
  39. package/src/diskreport.mjs +306 -0
  40. package/src/diskuse.mjs +420 -0
  41. package/src/diskwarn.mjs +68 -13
  42. package/src/doctor.mjs +149 -0
  43. package/src/doors.mjs +547 -0
  44. package/src/durable.mjs +143 -0
  45. package/src/envs.mjs +372 -0
  46. package/src/events.mjs +7 -2
  47. package/src/files.mjs +121 -7
  48. package/src/guard.mjs +288 -105
  49. package/src/guardd.mjs +8 -1
  50. package/src/halt.mjs +63 -0
  51. package/src/handoffs.mjs +362 -0
  52. package/src/history.mjs +34 -4
  53. package/src/hogs.mjs +36 -8
  54. package/src/jobprogress.mjs +283 -0
  55. package/src/later.mjs +21 -10
  56. package/src/lock.mjs +51 -11
  57. package/src/measure.mjs +60 -14
  58. package/src/media.mjs +240 -0
  59. package/src/news.mjs +31 -0
  60. package/src/notes.mjs +49 -8
  61. package/src/notices.mjs +126 -43
  62. package/src/ondemand.mjs +25 -2
  63. package/src/outcome.mjs +163 -0
  64. package/src/overlap.mjs +2 -2
  65. package/src/override.mjs +149 -79
  66. package/src/owner.mjs +15 -2
  67. package/src/people.mjs +236 -0
  68. package/src/pickup.mjs +72 -0
  69. package/src/picture.mjs +321 -0
  70. package/src/plain.mjs +84 -18
  71. package/src/platform.mjs +29 -7
  72. package/src/preempt.mjs +123 -15
  73. package/src/primer.mjs +91 -20
  74. package/src/prints.mjs +99 -0
  75. package/src/proc.mjs +11 -1
  76. package/src/progress.mjs +49 -3
  77. package/src/proof.mjs +102 -0
  78. package/src/push.mjs +271 -0
  79. package/src/questions.mjs +328 -57
  80. package/src/quota.mjs +1 -1
  81. package/src/recap.mjs +205 -0
  82. package/src/relay.mjs +262 -26
  83. package/src/remote.mjs +23 -10
  84. package/src/reviewgate.mjs +268 -0
  85. package/src/reviews.mjs +377 -0
  86. package/src/route.mjs +263 -0
  87. package/src/rules.mjs +216 -0
  88. package/src/schedule.mjs +238 -44
  89. package/src/schema.mjs +62 -0
  90. package/src/scratch.mjs +2 -2
  91. package/src/serve.mjs +3 -2
  92. package/src/service.mjs +5 -1
  93. package/src/signed.mjs +97 -0
  94. package/src/simpool.mjs +46 -1
  95. package/src/spend.mjs +375 -0
  96. package/src/state.mjs +43 -17
  97. package/src/talk.mjs +1082 -134
  98. package/src/thin.sh +2 -0
  99. package/src/trail.mjs +290 -0
  100. package/src/trailnote.mjs +209 -0
  101. package/src/util.mjs +7 -0
  102. package/src/vault.mjs +435 -0
  103. package/src/vendors.mjs +327 -0
  104. package/src/version.mjs +1 -1
  105. package/src/web.mjs +354 -60
  106. package/src/work.mjs +487 -0
  107. package/src/worker.mjs +7 -1
package/src/guard.mjs CHANGED
@@ -8,7 +8,7 @@ import fs from 'node:fs';
8
8
  import os from 'node:os';
9
9
  import path from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
11
- import { tmpGuard, fileGuard, resList } from './files.mjs';
11
+ import { tmpGuard, fileGuard, resList, sharedNudge } 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');
@@ -24,13 +24,26 @@ const LOG = path.join(DIBS_HOME, 'guard.log');
24
24
  // Who has a message from the person waiting: { session_id: [agent ids] }, or
25
25
  // no file at all. src/talk.mjs keeps it; the hook only reads it.
26
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.
27
+ // dibs listen's list of who listens (src/talk.mjs), and the sessions kept going at a stop to start one.
28
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.
29
+ const REARMED = path.join(DIBS_HOME, 'rearm.json');
30
+ // Sessions remembered in REARMED: enough for every session a machine runs in a day or two.
31
31
  const REMIND_KEEP = 200;
32
+ // Stops in a row a session is kept going with no listener starting in between. A listen that
33
+ // can't start (dibs broken, no background tasks here) would otherwise wake the agent, fail, and
34
+ // keep it going again at every stop, for ever; after this many it's left alone until one starts.
35
+ const REARM_MAX = 3;
36
+ // A Bash background task running dibs listen, however dibs was named: dibs, ~/bin/dibs, dibs.mjs.
37
+ const LISTEN_CMD = /(^|[\s;&|(/'"])dibs(\.mjs)?['"]?\s+listen\b/;
32
38
  // The threads themselves, which the hook only searches for a subagent's id.
33
39
  const MESSAGES = path.join(DIBS_HOME, 'messages.json');
40
+ // Fingerprints of stored secrets (src/prints.mjs). Absent when none is stored, and then the hook loads nothing more.
41
+ const PRINTS = path.join(DIBS_HOME, 'prints.json');
42
+ // Who has heard the rest of the rules (src/primer.mjs firstUse): read on a dibs call, and
43
+ // primer.mjs loaded only when this session and agent isn't in it yet.
44
+ const FIRST_USE = path.join(DIBS_HOME, 'firstuse.json');
45
+ // A Bash command that calls dibs, however it was named: dibs, ~/bin/dibs, dibs.mjs.
46
+ const DIBS_CALL = /(^|[\s;&|(/'"])dibs(\.mjs)?['"]?(\s|$)/;
34
47
  const SETTINGS = process.env.DIBS_CLAUDE_SETTINGS || path.join(os.homedir(), '.claude', 'settings.json');
35
48
 
36
49
  // What counts as heavy: the command's first words, once env, npx, time, cd and
@@ -323,8 +336,13 @@ export function rulesFrom(guardCfg) {
323
336
  // A ~ inside a word stays as typed (Windows short names: C:/Users/RUNNER~1); only a leading one expands.
324
337
  const quote = s => (/^[\w@%+=:,./-][\w@%+=:,./~-]*$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
325
338
 
326
- // What to do with a command: null to leave it alone, or the rewritten command
327
- // and what was caught.
339
+ // Where the agent's own words go in the line the hook hands back. dibs run takes
340
+ // only plain words a person can follow (src/declare.mjs), which the hook can't
341
+ // make up, and refuses this placeholder if it's sent as it is.
342
+ export const ASK = '<what this does and why, in plain words>';
343
+
344
+ // What to do with a command: null to leave it alone, or the command to run
345
+ // instead and what was caught.
328
346
  export function check(cmd, { rules = RULES, dibs = 'dibs' } = {}) {
329
347
  if (typeof cmd !== 'string') return null;
330
348
  const segs = split(cmd);
@@ -348,14 +366,10 @@ export function check(cmd, { rules = RULES, dibs = 'dibs' } = {}) {
348
366
  // whole, under one lease for everything it needs.
349
367
  if (/\$\{?SIM(_NAME)?\b/.test(cmd)) {
350
368
  const res = [...new Set(hits.flatMap(h => h.res.split(',')))].join(',');
351
- const why = `guard: ${hits[0].what}`.replace(/[^\w .:/=@,+-]/g, '').slice(0, 50).trim();
352
- return { command: `${dibs} run ${res} -m ${quote(why)} -- sh -c ${quote(cmd)}`, hits };
369
+ return { command: `${dibs} run ${res} -m ${quote(ASK)} -- sh -c ${quote(cmd)}`, hits };
353
370
  }
354
371
  let out = cmd;
355
- for (const h of [...hits].sort((a, b) => b.at - a.at)) {
356
- const why = `guard: ${h.what}`.replace(/[^\w .:/=@,+-]/g, '').slice(0, 50).trim();
357
- out = `${out.slice(0, h.at)}${dibs} run ${h.res} -m ${quote(why)} -- ${out.slice(h.at)}`;
358
- }
372
+ for (const h of [...hits].sort((a, b) => b.at - a.at)) out = `${out.slice(0, h.at)}${dibs} run ${h.res} -m ${quote(ASK)} -- ${out.slice(h.at)}`;
359
373
  return { command: out, hits };
360
374
  }
361
375
 
@@ -363,7 +377,7 @@ export function check(cmd, { rules = RULES, dibs = 'dibs' } = {}) {
363
377
  // here so the failure isn't invisible. Writing it may fail too; nothing to do then.
364
378
  // Where in dibs it broke and on what kind of call, never the command itself
365
379
  // (it can hold secrets): enough to find the bug, as `dibs alerts` reports it.
366
- function logError(e, input) {
380
+ export function logError(e, input) {
367
381
  // A full disk is no bug in dibs: the call goes through, and the board already says the disk is full.
368
382
  if (e?.code === 'ENOSPC' || e?.code === 'EDQUOT') return;
369
383
  const at = String(e?.stack || '').split('\n').find(l => l.includes('/src/'))?.match(/\/(src\/[\w.]+:\d+)/)?.[1];
@@ -371,58 +385,91 @@ function logError(e, input) {
371
385
  try { fs.appendFileSync(LOG, `${new Date().toISOString()} ${String(e?.message || e).split('\n')[0]}${at ? ` at ${at}` : ''}${on}\n`); } catch {}
372
386
  }
373
387
 
374
- function dibsConfig() {
388
+ export function dibsConfig() {
375
389
  try { return JSON.parse(fs.readFileSync(CONFIG, 'utf8')); }
376
390
  catch (e) { if (e.code !== 'ENOENT') logError(`${CONFIG}: ${e.message}`); return {}; }
377
391
  }
378
- const guardConfig = () => dibsConfig().guard ?? {};
392
+ export const guardConfig = () => dibsConfig().guard ?? {};
379
393
 
380
394
  // Subagent spawns, starts and stops go to the subagent limit (src/agents.mjs),
381
395
  // loaded only for those: a Bash call still pays for this module alone.
382
396
  const AGENT_EVENT = input => ['Agent', 'Task'].includes(input?.tool_name) || ['SubagentStart', 'SubagentStop'].includes(input?.hook_event_name);
383
397
 
398
+ // A Bash command that may be a milestone for the trail (src/trailnote.mjs, loaded only for these):
399
+ // a commit, push, merge or tag, a GitHub release or pull request, an upload to App Store Connect,
400
+ // a publish. Loose on purpose: a near miss costs one small module, a miss costs the person a line.
401
+ const TRAIL_HINT = /\bgit\b[^\n;|&]*\b(commit|push|merge|tag)\b|\bgh\s+(release|pr)\s|-exportArchive|\baltool\b|\basc\s+(builds\s+upload|publish)\b|\bfastlane\b|\beas\s+submit\b|\b(npm|pnpm|yarn)\b[^\n;|&]*\bpublish\b/;
402
+ // A Bash command that may merge or push: the review gate (src/reviewgate.mjs, loaded only for these)
403
+ // checks whether the project asks for an approving review first. Loose on purpose: a near miss costs
404
+ // one small module and a few file reads, a miss lets an unreviewed change into main.
405
+ const MERGE_HINT = /\bgit\b[^\n;|&]*\b(merge|push)\b|\bgh\b[^\n;|&]*\bpr\s+merge\b/;
406
+ // A Bash command that may be a one-way door (src/doors.mjs, loaded only for these, and only when the
407
+ // person turned dibs doors on). Loose on purpose: a near miss costs one small module.
408
+ export const DOOR_HINT = /\bpush\b|deploy|publish|promote|altool|\basc\b|-exportArchive|fastlane|\beas\b|upload|\brm\b|drop|truncate|delete|reset|restore|destroy|\bbuy\b|purchase|register|--live|\brelease\b/i;
409
+
384
410
  // `dibs` when it's on PATH, so the rewritten command reads the way agents
385
411
  // write it; otherwise this copy's full path.
386
- function dibsCommand() {
412
+ export function dibsCommand() {
387
413
  for (const dir of (process.env.PATH || '').split(path.delimiter))
388
414
  if (dir && fs.existsSync(path.join(dir, 'dibs'))) return 'dibs';
389
415
  return viaNode(path.join(ROOT, 'bin', 'dibs.mjs'));
390
416
  }
391
417
 
392
- // Rewrite only where "allow" approves nothing the session wouldn't have run
393
- // anyway (bypassPermissions), unless guard.rewrite says always or never.
394
- // Everywhere else, deny with the exact command, so the agent's retry goes
395
- // through the normal permission checks.
418
+ // A heavy command outside dibs is turned away with the dibs run line to send
419
+ // instead. Before 0.0.191 a bypassPermissions session's command was rewritten
420
+ // and let through, labelled "guard: <its command>"; now every run says in plain
421
+ // words what it does (src/declare.mjs), and only the agent knows that, so the
422
+ // hook never runs anything for it. A denial is an ordinary answer: the agent
423
+ // sends the line again with its own words, through the normal permission checks.
424
+ // guard.rewrite in config.json is no longer read.
396
425
  // "guard": false in config.json (or guard.commands false) switches off only
397
426
  // the heavy-command half; file leases stay enforced unless guard.files is false.
398
427
  export function respond(input, guardCfg = {}, dibs = 'dibs') {
428
+ // Codex (and OpenCode) edit through one patch: each file it touches is checked as a Write.
429
+ if (input?.tool_name === 'apply_patch') {
430
+ for (const file of patchFiles(input.tool_input?.command)) {
431
+ const r = respond({ ...input, tool_name: 'Write', tool_input: { file_path: file } }, guardCfg, dibs);
432
+ if (r) return r;
433
+ }
434
+ return null;
435
+ }
399
436
  // Another session's file lease (src/files.mjs) turns a write away before anything else.
400
437
  // So does a delete in another session's temp folder, whatever the config says: it's the person's rule.
401
438
  const leased = tmpGuard(input, split) || (guardCfg?.files === false ? null : fileGuard(input, split));
402
439
  if (leased || input?.tool_name !== 'Bash' || guardCfg === false || guardCfg?.commands === false) return leased;
403
- const ti = input.tool_input || {};
404
- const plan = check(ti.command, { rules: rulesFrom(guardCfg), dibs });
440
+ const plan = check(input.tool_input?.command, { rules: rulesFrom(guardCfg), dibs });
405
441
  if (!plan) return null;
406
- const mode = guardCfg.rewrite || 'bypass';
407
442
  const what = [...new Set(plan.hits.map(h => h.what.split(' ')[0]))].join(', ');
408
- if (mode === 'always' || (mode === 'bypass' && input.permission_mode === 'bypassPermissions')) {
409
- return { hookSpecificOutput: {
410
- hookEventName: 'PreToolUse',
411
- permissionDecision: 'allow',
412
- permissionDecisionReason: `dibs guard wrapped ${what} in dibs run`,
413
- updatedInput: { ...ti, command: plan.command },
414
- additionalContext: `dibs guard ran this through dibs because ${what} wasn't wrapped: ${plan.command}\n` +
415
- '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.',
416
- } };
417
- }
418
443
  return { hookSpecificOutput: {
419
444
  hookEventName: 'PreToolUse',
420
445
  permissionDecision: 'deny',
421
- permissionDecisionReason: `dibs guard: ${what} has to take its turn through dibs, or it collides with other agents. Run this instead:\n ${plan.command}\n` +
422
- 'If it really is a quick read that builds, boots, tests and deploys nothing, put DIBS_GUARD=off in front of it.',
446
+ permissionDecisionReason: `dibs guard: ${what} has to take its turn through dibs, or it collides with other agents. Run it through dibs, with -m in your own plain words`
447
+ + ` saying what it does and why (the person reads them; "run the login tests after fixing the redirect", not "npm test"):\n ${plan.command}\n`
448
+ + 'If it really is a quick read that builds, boots, tests and deploys nothing, put DIBS_GUARD=off in front of it.',
423
449
  } };
424
450
  }
425
451
 
452
+ // The files a patch in Codex's apply_patch format adds, changes, deletes or moves to.
453
+ const PATCH_FILE = /^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)$/;
454
+ export function patchFiles(text) {
455
+ if (typeof text !== 'string') return [];
456
+ return text.split(/\r?\n/).map(l => l.match(PATCH_FILE)?.[1].trim()).filter(Boolean);
457
+ }
458
+
459
+ // Which agent tool sent the call. Codex sends Claude Code's format (its calls carry
460
+ // turn_id, and it edits with apply_patch); Gemini CLI, Cursor and the OpenCode plugin
461
+ // are told apart by their own event names and fields (src/vendors.mjs reads them).
462
+ export function vendorOf(input, env = process.env) {
463
+ const ev = input?.hook_event_name;
464
+ if (typeof ev !== 'string') return 'claude';
465
+ if (ev.startsWith('opencode.')) return 'opencode';
466
+ if ('cursor_version' in input || /^[a-z]/.test(ev)) return 'cursor';
467
+ if (ev === 'BeforeTool' || ev === 'AfterTool' || (ev === 'SessionStart' && (env.GEMINI_SESSION_ID || 'timestamp' in input))) return 'gemini';
468
+ // Codex's SessionStart has no turn_id; its transcript is a rollout-*.jsonl (Codex 0.167.1, captured).
469
+ if ('turn_id' in input || input.tool_name === 'apply_patch' || /[\\/]rollout-[^\\/]*\.jsonl$/.test(String(input.transcript_path || ''))) return 'codex';
470
+ return 'claude';
471
+ }
472
+
426
473
  const STOP_EVENT = input => ['Stop', 'SubagentStop'].includes(input?.hook_event_name);
427
474
  const START_EVENT = input => ['SessionStart', 'SubagentStart'].includes(input?.hook_event_name);
428
475
 
@@ -441,27 +488,62 @@ function talked(input) {
441
488
  try { return fs.readFileSync(MESSAGES, 'utf8').includes(JSON.stringify(input.agent_id)); } catch { return false; }
442
489
  }
443
490
 
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; }
491
+ // A main agent ending its turn with no dibs listen running is kept going to start one, so it
492
+ // never has to remember: a message sent while it waits wakes it. Claude Code (2.1.3xx) lists the
493
+ // session's running background tasks at a stop, which says it outright; older versions don't,
494
+ // so then listeners.json does. Never for a subagent or teammate (agent_id: Stop is the main
495
+ // thread's, but a stray one costs nothing to skip), never on the continuation a stop hook caused
496
+ // (stop_hook_active: at most once a turn), never for Codex (turn_id) or the SDK and -p (their
497
+ // background tasks die with the run), and at most REARM_MAX stops in a row with no listener
498
+ // starting in between. Claude Code fires no Stop for an interrupt or a session that's ending.
499
+ // Returns the line to keep the agent going with, or null.
500
+ function rearm(input, env = process.env) {
501
+ if (input?.hook_event_name !== 'Stop' || input.stop_hook_active || input.agent_id || 'turn_id' in input) return null;
502
+ const sid = input.session_id;
503
+ if (typeof sid !== 'string' || !sid) return null;
504
+ if (/^sdk-/.test(env.CLAUDE_CODE_ENTRYPOINT || '') || /^(1|true|yes|on)$/i.test(env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS || '')) return null;
505
+ let l = null;
506
+ try { l = JSON.parse(fs.readFileSync(LISTENERS, 'utf8'))[`${sid}|main`] || null; } catch {}
507
+ const listed = Array.isArray(input.background_tasks);
508
+ if (listed && input.background_tasks.some(t => LISTEN_CMD.test(String(t?.command || '')))) return null;
509
+ // A dibs listen --stream may run under a monitor, which the list of background tasks needn't name.
510
+ if ((!listed || l?.stream) && Number.isInteger(l?.pid)) {
511
+ try { process.kill(l.pid, 0); return null; } catch (e) { if (e.code !== 'ESRCH') return null; }
512
+ }
455
513
  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;
514
+ try { told = JSON.parse(fs.readFileSync(REARMED, 'utf8')); } catch {}
515
+ const last = told[sid];
516
+ // A listener that started since the last time counts the stops from zero again.
517
+ const n = last && !(l?.at > last.at) ? last.n : 0;
518
+ if (n >= REARM_MAX) return null;
519
+ delete told[sid];
520
+ told[sid] = { n: n + 1, at: Date.now() };
460
521
  const keys = Object.keys(told);
461
522
  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.' };
523
+ fs.mkdirSync(DIBS_HOME, { recursive: true });
524
+ fs.writeFileSync(`${REARMED}.${process.pid}`, JSON.stringify(told));
525
+ fs.renameSync(`${REARMED}.${process.pid}`, REARMED);
526
+ return 'dibs: no dibs listen is running for you, so a message sent while you wait can\'t wake you. ' +
527
+ 'Before you end your turn, start it with the Bash tool and run_in_background: dibs listen';
528
+ }
529
+
530
+ // The re-arm line added to a stop's answer: alone, or after the messages handed over at that stop.
531
+ // additionalContext keeps the agent going without the "blocking error" a decision: 'block' shows.
532
+ function withRearm(input, out) {
533
+ const line = rearm(input);
534
+ if (!line) return out;
535
+ const prev = out?.hookSpecificOutput?.additionalContext;
536
+ return { ...out, hookSpecificOutput: { ...out?.hookSpecificOutput, hookEventName: 'Stop', additionalContext: [prev, line].filter(Boolean).join('\n\n') } };
537
+ }
538
+
539
+ // Whether this Bash call is the session's first use of dibs that hasn't been told the rest of
540
+ // the rules yet: a dibs command, or a heavy command the guard turned away. Claude Code only:
541
+ // the other tools hear every rule at their start (src/vendors.mjs).
542
+ function firstUse(input, out) {
543
+ if (input?.tool_name !== 'Bash' || typeof input.session_id !== 'string' || !input.session_id) return false;
544
+ const turned = /has to take its turn through dibs/.test(out?.hookSpecificOutput?.permissionDecisionReason || '');
545
+ if (!turned && !DIBS_CALL.test(String(input.tool_input?.command || ''))) return false;
546
+ try { return !JSON.parse(fs.readFileSync(FIRST_USE, 'utf8')).includes(`${input.session_id}|${input.agent_id || 'main'}`); } catch { return true; }
465
547
  }
466
548
 
467
549
  // The hook itself: Claude Code's JSON on stdin, a decision on stdout. Any
@@ -473,13 +555,62 @@ export async function hook() {
473
555
  if (out) process.stdout.write(JSON.stringify(out) + '\n');
474
556
  }
475
557
 
558
+ // A command or an edit that holds a stored secret's value would leave it in the transcript, the
559
+ // shell history or a file. Turned away with the way to use it unseen (src/vault.mjs).
560
+ const WRITES = { Bash: ti => [ti.command], Write: ti => [ti.content], Edit: ti => [ti.new_string], MultiEdit: ti => (ti.edits || []).map(e => e?.new_string),
561
+ NotebookEdit: ti => [ti.new_source] };
562
+ async function secretGuard(input) {
563
+ const texts = WRITES[input?.tool_name];
564
+ if (!texts || !fs.existsSync(PRINTS)) return null;
565
+ const { find } = await import('./prints.mjs');
566
+ const names = [...new Set(texts(input.tool_input || {}).filter(t => typeof t === 'string').flatMap(t => find(t).map(h => h.name)))];
567
+ if (!names.length) return null;
568
+ const n = names[0];
569
+ const why = input.tool_name === 'Bash'
570
+ ? `this command has the value of the secret ${names.join(', ')} in it, so it would sit in your transcript and the shell's history. Use it without seeing it:\n dibs secret run ${names.join(',')} -- <the command, reading $${n}>`
571
+ : `this edit writes the value of the secret ${names.join(', ')} into ${input.tool_input?.file_path || input.tool_input?.notebook_path || 'a file'}. Read it at run time instead (dibs secret run ${n} -- <command reading $${n}>), or ask the person where it belongs.`;
572
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: `dibs guard: ${why}` } };
573
+ }
574
+
476
575
  // What the hook answers for one event, or null to say nothing. The resident
477
576
  // guard (src/guardd.mjs) runs this too, in a fresh worker per call.
478
577
  export async function decide(input) {
578
+ const vendor = vendorOf(input);
579
+ // Gemini CLI, Cursor and OpenCode: the same rules, read from and answered in their own formats.
580
+ if (vendor !== 'claude' && vendor !== 'codex') {
581
+ try { return await (await import('./vendors.mjs')).decideFor(vendor, input); } catch (e) { logError(e, input); return null; }
582
+ }
479
583
  let out = null;
584
+ // config.json, read once for the whole call.
585
+ let cfg = null;
586
+ const conf = () => (cfg ??= dibsConfig());
587
+ const gcfg = () => conf().guard ?? {};
480
588
  try {
481
- if (AGENT_EVENT(input)) out = (await import('./agents.mjs')).agentHook(input, dibsConfig());
482
- else if (!STOP_EVENT(input) && !START_EVENT(input)) out = respond(input, guardConfig(), dibsCommand());
589
+ if (AGENT_EVENT(input)) out = (await import('./agents.mjs')).agentHook(input, conf());
590
+ else if (!STOP_EVENT(input) && !START_EVENT(input)) out = (await secretGuard(input)) || respond(input, gcfg(), dibsCommand());
591
+ } catch (e) { logError(e, input); }
592
+ const cmd = input?.tool_name === 'Bash' ? input.tool_input?.command || '' : '';
593
+ const denied = () => out?.hookSpecificOutput?.permissionDecision === 'deny';
594
+ // A merge into main, or a push to it, with no approving review, where the project asks for one, is turned away
595
+ // before it runs. A call already turned away stays as it is.
596
+ try {
597
+ if (cmd && MERGE_HINT.test(cmd) && !denied() && gcfg().reviews !== false) out = (await import('./reviewgate.mjs')).gate(input, split) || out;
598
+ } catch (e) { logError(e, input); }
599
+ // A command that can't be undone waits for the person's yes, when they turned dibs doors on. Last of
600
+ // the checks, so a once-only yes is used up only by a command that goes ahead.
601
+ try {
602
+ if (cmd && conf().doors?.on === true && DOOR_HINT.test(cmd) && !denied()) out = (await import('./doors.mjs')).gate(input, split, conf(), { vendor }) || out;
603
+ } catch (e) { logError(e, input); }
604
+ // What may be a milestone goes on the trail, unless the guard turned the command away: then it never runs.
605
+ try {
606
+ if (cmd && TRAIL_HINT.test(cmd) && !denied() && gcfg().trail !== false) (await import('./trailnote.mjs')).note(input, split);
607
+ } catch (e) { logError(e, input); }
608
+ // A command that writes or deletes in a folder another agent wrote into lately hears who (src/files.mjs).
609
+ try {
610
+ if (out?.hookSpecificOutput?.permissionDecision !== 'deny' && guardConfig()?.files !== false) {
611
+ const nudge = sharedNudge(input, split);
612
+ if (nudge) out = { ...out, hookSpecificOutput: { hookEventName: 'PreToolUse', ...out?.hookSpecificOutput, additionalContext: [out?.hookSpecificOutput?.additionalContext, nudge].filter(Boolean).join('\n\n') } };
613
+ }
483
614
  } catch (e) { logError(e, input); }
484
615
  // A new session, or a subagent's first start, hears the few rules that keep it out of trouble (src/primer.mjs).
485
616
  try { if (START_EVENT(input)) out = (await import('./primer.mjs')).primer(input, out); } catch (e) { logError(e, input); }
@@ -487,13 +618,18 @@ export async function decide(input) {
487
618
  if (queuedFor(input)) out = (await import('./talk.mjs')).deliver(input, out);
488
619
  else if (input?.hook_event_name === 'SubagentStop' && talked(input)) (await import('./talk.mjs')).finished(input);
489
620
  } catch (e) { logError(e, input); }
490
- try { if (!out) out = rearm(input); } catch (e) { logError(e, input); }
621
+ // The first dibs call of a session (or a subagent) hears the rules it didn't need at its start.
622
+ try { if (vendor === 'claude' && firstUse(input, out)) out = (await import('./primer.mjs')).firstUse(input, out); } catch (e) { logError(e, input); }
623
+ try { out = withRearm(input, out); } catch (e) { logError(e, input); }
624
+ // A Codex session isn't one Claude Code knows, so its messages wait under its name, as for a terminal's.
625
+ try { if (vendor === 'codex') out = await (await import('./vendors.mjs')).codexAnswer(input, out); } catch (e) { logError(e, input); }
491
626
  return out;
492
627
  }
493
628
 
494
- const isGuard = h => h?.type === 'command' && /dibs-guard\.mjs['"]?$|\bdibs(\.mjs)?['"]? guard['"]?$/.test(String(h.command || '').trim());
629
+ // Cursor's hooks.json leaves type out; it means a command there.
630
+ const isGuard = h => (h?.type ?? 'command') === 'command' && /dibs-guard\.mjs['"]?$|\bdibs(\.mjs)?['"]? guard['"]?$/.test(String(h?.command || '').trim());
495
631
 
496
- function readSettings(file) {
632
+ export function readSettings(file) {
497
633
  if (!fs.existsSync(file)) return {};
498
634
  const text = fs.readFileSync(file, 'utf8');
499
635
  if (!text.trim()) return {};
@@ -502,7 +638,7 @@ function readSettings(file) {
502
638
 
503
639
  // Back up the old file once per change, then swap the new one in whole.
504
640
  // Returns where the backup went, if there was a file to back up.
505
- function writeSettings(file, s) {
641
+ export function writeSettings(file, s) {
506
642
  const had = fs.existsSync(file);
507
643
  const real = had ? fs.realpathSync(file) : file;
508
644
  fs.mkdirSync(path.dirname(real), { recursive: true });
@@ -522,16 +658,23 @@ function writeSettings(file, s) {
522
658
  // SessionStart (no matcher: startup, resume, clear and compact all need it) tells a session the rules.
523
659
  const ENTRIES = [['PreToolUse', 'Bash|Edit|Write|MultiEdit|NotebookEdit'], ['PreToolUse', 'Agent|Task'], ['SubagentStart', null], ['SubagentStop', null], ['Stop', null],
524
660
  ['SessionStart', null]];
525
- const EVENTS = [...new Set(ENTRIES.map(e => e[0]))];
661
+
662
+ // A tool's hook file: its events and matchers, one handler, and whether its groups
663
+ // hold a list of handlers (Claude Code, Codex, Gemini CLI) or are the handler (Cursor).
664
+ // src/vendors.mjs has the others.
665
+ export const CLAUDE = { name: 'Claude Code', entries: ENTRIES, handler: command => ({ type: 'command', command, timeout: 5 }) };
666
+ const events = t => [...new Set(t.entries.map(e => e[0]))];
667
+ const handlers = (t, g) => (t.flat ? [g].filter(isGuard) : Array.isArray(g?.hooks) ? g.hooks.filter(isGuard) : []);
526
668
 
527
669
  // Take our hook out of every event, dropping groups and lists it leaves empty.
528
- function strip(s) {
670
+ function strip(s, t = CLAUDE) {
529
671
  let found = false;
530
- for (const ev of EVENTS) {
672
+ for (const ev of events(t)) {
531
673
  const groups = s.hooks?.[ev];
532
674
  if (!Array.isArray(groups)) continue;
533
675
  const kept = [];
534
676
  for (const g of groups) {
677
+ if (t.flat) { if (isGuard(g)) found = true; else kept.push(g); continue; }
535
678
  const hs = Array.isArray(g?.hooks) ? g.hooks.filter(h => !isGuard(h)) : g?.hooks;
536
679
  if (Array.isArray(g?.hooks) && hs.length !== g.hooks.length) found = true;
537
680
  if (!Array.isArray(hs) || hs.length) kept.push(Array.isArray(g?.hooks) ? { ...g, hooks: hs } : g);
@@ -546,84 +689,124 @@ function strip(s) {
546
689
  export const MATCHER = ENTRIES[0][1];
547
690
 
548
691
  // Our groups in one event.
549
- const ours = (s, ev = 'PreToolUse') => (s.hooks?.[ev] || []).filter(g => Array.isArray(g?.hooks) && g.hooks.some(isGuard));
692
+ const ours = (s, ev, t = CLAUDE) => (Array.isArray(s.hooks?.[ev]) ? s.hooks[ev] : []).filter(g => handlers(t, g).length);
550
693
  // Every entry there with this command, and nothing else of ours: an older
551
694
  // install (Bash alone, or no subagent events) is replaced, not added to.
552
- const complete = (s, command) => EVENTS.every(ev => ours(s, ev).length === ENTRIES.filter(e => e[0] === ev).length)
553
- && ENTRIES.every(([ev, matcher]) => ours(s, ev).some(g => (g.matcher ?? null) === matcher && g.hooks.some(h => isGuard(h) && h.command === command)));
695
+ const complete = (s, command, t = CLAUDE) => events(t).every(ev => ours(s, ev, t).length === t.entries.filter(e => e[0] === ev).length)
696
+ && t.entries.every(([ev, matcher]) => ours(s, ev, t).some(g => (g.matcher ?? null) === matcher && handlers(t, g).some(h => h.command === command)));
554
697
 
555
- export function installed(file = SETTINGS) {
556
- return ours(readSettings(file)).flatMap(g => g.hooks).find(isGuard) || null;
698
+ export function installed(file = SETTINGS, t = CLAUDE) {
699
+ return ours(readSettings(file), t.entries[0][0], t).flatMap(g => handlers(t, g))[0] || null;
557
700
  }
558
701
 
559
- export function install(file = SETTINGS, command = viaNode(HOOK_BIN)) {
702
+ export const HOOK_COMMAND = viaNode(HOOK_BIN);
703
+
704
+ export function install(file = SETTINGS, command = HOOK_COMMAND, t = CLAUDE) {
560
705
  const s = readSettings(file);
561
- const had = installed(file);
562
- if (complete(s, command)) return `already installed in ${file}`;
563
- strip(s);
706
+ const had = installed(file, t);
707
+ if (complete(s, command, t)) return `already installed in ${file}`;
708
+ strip(s, t);
709
+ Object.assign(s, { ...t.top, ...s });
564
710
  s.hooks ||= {};
565
- for (const [ev, matcher] of ENTRIES)
566
- (s.hooks[ev] ||= []).push({ ...(matcher ? { matcher } : {}), hooks: [{ type: 'command', command, timeout: 5 }] });
711
+ for (const [ev, matcher] of t.entries) {
712
+ const m = matcher ? { matcher } : {};
713
+ (s.hooks[ev] ||= []).push(t.flat ? { ...m, ...t.handler(command) } : { ...m, hooks: [t.handler(command)] });
714
+ }
567
715
  const backup = writeSettings(file, s);
568
716
  return `${had ? 'updated' : 'installed'} in ${file}${backup ? ` (old file in ${backup})` : ''}`;
569
717
  }
570
718
 
571
- export function remove(file = SETTINGS) {
719
+ export function remove(file = SETTINGS, t = CLAUDE) {
572
720
  const s = readSettings(file);
573
- if (!strip(s)) return null;
721
+ if (!strip(s, t)) return null;
574
722
  writeSettings(file, s);
575
723
  return `removed from ${file} (old file in ${file}.dibs-backup)`;
576
724
  }
577
725
 
578
- 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)
579
- dibs guard install [--settings file] add the hook to ~/.claude/settings.json (backup kept)
580
- dibs guard remove [--settings file] take it out again
581
- dibs guard status [--settings file] [--json] is it installed (exit 1 if not; --json always exits 0)
726
+ // Whether the hook in file is this version's whole set of entries.
727
+ export const isComplete = (file, t = CLAUDE) => { const h = installed(file, t); return !!h && complete(readSettings(file), h.command, t); };
728
+
729
+ 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 hook for Claude Code, Codex, Gemini CLI and Cursor, and a plugin for OpenCode
730
+ dibs guard install [--for tools] [--settings file] add the hook to ~/.claude/settings.json (backup kept)
731
+ --for codex,gemini,cursor,opencode (and claude): each tool's own hooks file instead, or OpenCode's plugins folder
732
+ dibs guard remove [--for tools] [--settings file] take it out again
733
+ dibs guard status [--for tools] [--settings file] [--json] which tools it covers (exit 1 if none; --json always exits 0)
582
734
  dibs guard check "<command>" what the hook would do with a command
583
735
  dibs guard serve answer the hook from one running process (dibs service install guard keeps it up)
584
- The hook reads Claude Code's JSON on stdin: dibs guard < input.json`;
736
+ The hook reads Claude Code's JSON on stdin (or Codex's, Gemini CLI's, Cursor's): dibs guard < input.json`;
585
737
 
586
- // What `dibs guard status --json` prints, for dibs web too.
587
- export function guardJson(file = SETTINGS) {
738
+ // What `dibs guard status --json` prints, for dibs web too. tools: the other agent tools, when asked for.
739
+ export function guardJson(file = SETTINGS, tools = null) {
588
740
  const h = installed(file);
589
741
  const s = readSettings(file);
590
742
  const agents = dibsConfig().agents;
591
743
  return { installed: !!h, file, command: h?.command ?? null, complete: !!h && complete(s, h.command),
592
- matchers: EVENTS.flatMap(ev => ours(s, ev).map(g => ({ event: ev, matcher: g.matcher ?? null }))), rewrite: guardConfig().rewrite || 'bypass',
593
- subagents: Number(agents?.slots) > 0 ? { slots: Number(agents.slots) } : null };
744
+ matchers: events(CLAUDE).flatMap(ev => ours(s, ev).map(g => ({ event: ev, matcher: g.matcher ?? null }))),
745
+ // Always never since 0.0.191 (respond): kept because the Mac app reads it.
746
+ rewrite: 'never',
747
+ subagents: Number(agents?.slots) > 0 ? { slots: Number(agents.slots) } : null, ...(tools && { tools }) };
594
748
  }
595
749
 
750
+ // The Claude Code half of dibs guard status.
751
+ function claudeStatus(file, h) {
752
+ const agents = dibsConfig().agents;
753
+ if (!h) return `dibs guard is off: it isn't in ${file}. Turn it on: dibs guard install`;
754
+ return [`dibs guard is on (in ${file}).`,
755
+ ` Heavy commands an agent runs outside dibs: ${guardConfig() === false || guardConfig().commands === false ? 'let through (switched off in config.json)' : 'turned away, with the dibs run line to send instead'}.`,
756
+ ` Edits to files another agent reserved: ${guardConfig().files === false ? 'let through (guard.files is false in config.json)' : 'turned away'}.`,
757
+ ' 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.',
758
+ ` Merges into main and pushes to it in a repo whose .dibs.json says "reviewBeforeMerge": ${guardConfig().reviews === false ? 'let through (guard.reviews is false in config.json)' : 'turned away until another agent approves that commit (dibs review)'}.`,
759
+ ` 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)'}.`,
760
+ ...(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']),
761
+ ` The hook: ${h.command}`].join('\n');
762
+ }
763
+
764
+ // One line for each other tool.
765
+ const toolLine = st => (st.installed
766
+ ? `${st.name}: on (in ${st.file}).${st.complete ? '' : ` An older install: dibs guard install --for ${st.tool}.`}${st.note ? ` ${st.note}.` : ''}`
767
+ : st.viaClaude ? `${st.name}: on through the Claude Code hook (cursor-agent runs the hooks in Claude Code's settings.json too). ${st.note}.`
768
+ : `${st.name}: off. Turn it on: dibs guard install --for ${st.tool}`);
769
+
596
770
  // dibs guard [install|remove|status|check]. With no verb and JSON piped in, be the hook.
597
- export function guard(args) {
771
+ export async function guard(args) {
598
772
  const reply = (msg, code = 0) => { (code ? process.stderr : process.stdout).write(`${msg}\n`); process.exitCode = code; };
599
773
  const at = args.indexOf('--settings');
600
- const file = at >= 0 ? args[at + 1] : SETTINGS;
601
- if (at >= 0 && !file) return reply('--settings needs a path', 2);
774
+ const given = at >= 0 ? args[at + 1] : null;
775
+ if (at >= 0 && !given) return reply('--settings needs a path', 2);
776
+ const fi = args.indexOf('--for');
777
+ const tools = fi >= 0 ? String(args[fi + 1] || '').split(',').filter(Boolean) : null;
602
778
  const verb = args[0];
603
779
  try {
604
780
  if (!verb) return process.stdin.isTTY ? reply(USAGE) : hook();
605
781
  if (verb === 'serve') return import('./guardd.mjs').then(m => m.serveGuard());
606
- if (verb === 'install') return reply(`dibs guard: ${install(file)}`);
607
- if (verb === 'remove') { const r = remove(file); return r ? reply(`dibs guard: ${r}`) : reply(`dibs guard: not installed in ${file}`, 1); }
608
- if (verb === 'status') {
609
- const h = installed(file);
610
- const mode = guardConfig().rewrite || 'bypass';
611
- const agents = dibsConfig().agents;
612
- // For the Mac app: the same facts as an object, exit 0 either way.
613
- if (args.includes('--json')) return reply(JSON.stringify(guardJson(file), null, 1));
614
- if (!h) return reply(`dibs guard is off: it isn't in ${file}. Turn it on: dibs guard install`, 1);
615
- return reply([`dibs guard is on (in ${file}).`,
616
- ` 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`}.`,
617
- ` Edits to files another agent reserved: ${guardConfig().files === false ? 'let through (guard.files is false in config.json)' : 'turned away'}.`,
618
- ' 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.',
619
- ` 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)'}.`,
620
- ...(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']),
621
- ` The hook: ${h.command}`].join('\n'));
622
- }
623
782
  if (verb === 'check') {
624
783
  const plan = check(args.slice(1).join(' '), { rules: rulesFrom(guardConfig()) });
625
784
  return reply(plan ? `${plan.hits.map(h => h.res).join(' + ')}: ${plan.command}` : 'leave alone');
626
785
  }
627
- return reply(USAGE, 2);
786
+ if (!['install', 'remove', 'status'].includes(verb)) return reply(USAGE, 2);
787
+ const v = await import('./vendors.mjs');
788
+ const known = ['claude', ...v.NAMES];
789
+ if (tools && (!tools.length || tools.some(x => !known.includes(x)))) return reply(`--for takes ${known.join(', ')}, or several with commas`, 2);
790
+ if (given && tools?.length > 1) return reply('--settings names one file: give --for one tool with it', 2);
791
+ const only = tools || ['claude'];
792
+ // --settings names Claude Code's file, or the one tool --for names.
793
+ const fileOf = x => (given && (tools ? tools[0] === x : x === 'claude') ? given : x === 'claude' ? SETTINGS : v.TOOLS[x].file());
794
+ if (verb === 'install') return reply(only.map(x => `dibs guard${x === 'claude' ? '' : ` for ${v.TOOLS[x].name}`}: ${x === 'claude' ? install(fileOf(x)) : v.installFor(x, fileOf(x))}`
795
+ + (v.TOOLS[x]?.note ? `. ${v.TOOLS[x].note}` : '')).join('\n'));
796
+ if (verb === 'remove') {
797
+ const done = only.map(x => [x, x === 'claude' ? remove(fileOf(x)) : v.removeFor(x, fileOf(x))]);
798
+ const lines = done.map(([x, r]) => `dibs guard${x === 'claude' ? '' : ` for ${v.TOOLS[x].name}`}: ${r || `not installed in ${fileOf(x)}`}`);
799
+ return reply(lines.join('\n'), done.every(([, r]) => r) ? 0 : 1);
800
+ }
801
+ // status: Claude Code first, as before, then each other tool; with --for, only those.
802
+ const shown = tools || known;
803
+ const others = shown.filter(x => x !== 'claude').map(x => v.statusFor(x, fileOf(x)));
804
+ const file = fileOf('claude');
805
+ const h = installed(file);
806
+ if (args.includes('--json')) return reply(JSON.stringify(guardJson(file, others), null, 1));
807
+ const lines = [...(shown.includes('claude') ? [claudeStatus(file, h)] : []), ...others.map(st => (tools ? '' : ' ') + toolLine(st))];
808
+ if (!tools && others.length) lines.splice(1, 0, 'Other agent tools:');
809
+ const any = (shown.includes('claude') && h) || others.some(st => st.installed || st.viaClaude);
810
+ return reply(lines.join('\n'), any ? 0 : 1);
628
811
  } catch (e) { return reply(`dibs guard: ${e.message}`, 1); }
629
812
  }
package/src/guardd.mjs CHANGED
@@ -33,6 +33,9 @@ const READY = 2;
33
33
  // client that gets no answer then starts Node, which must still fit in Claude
34
34
  // Code's 5 s hook timeout.
35
35
  const CALL_LIMIT = 1500;
36
+ // Slots in the list of running workers that src/lock.mjs reads to tell a sibling's lock from a dead
37
+ // one's. Two wait loaded, and each call holds one for at most CALL_LIMIT: more than enough.
38
+ const THREAD_SLOTS = 64;
36
39
  // No hook input comes near this; a client sending more is cut off.
37
40
  const MAX_FRAME = 8 * 1024 ** 2;
38
41
 
@@ -50,8 +53,12 @@ export function frame(buf) {
50
53
  export async function serveGuard() {
51
54
  await singleInstance(PIDFILE, 'a resident guard is already running here');
52
55
  const ready = [], waiting = [];
56
+ const threads = new Int32Array(new SharedArrayBuffer(4 * THREAD_SLOTS));
53
57
  const warm = () => {
54
- const w = new Worker(WORKER, { execArgv: [] });
58
+ const w = new Worker(WORKER, { execArgv: [], workerData: { threads } });
59
+ const slot = threads.indexOf(0);
60
+ if (slot >= 0) Atomics.store(threads, slot, w.threadId);
61
+ w.once('exit', () => { if (slot >= 0) Atomics.store(threads, slot, 0); });
55
62
  w.once('message', () => { const next = waiting.shift(); next ? next(w) : ready.push(w); });
56
63
  w.once('error', e => log(`a guard worker failed to load: ${e.message}`));
57
64
  };