@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/talk.mjs CHANGED
@@ -24,13 +24,18 @@ import { takeAgent, talkKey } from './files.mjs';
24
24
  import { asked, forYou } from './questions.mjs';
25
25
  import { named, minutes, lower } from './plain.mjs';
26
26
  import { bold, dim, columns } from './style.mjs';
27
- import { die, now, say as note, sleepSync, fakeFull } from './util.mjs';
27
+ import { underLock, commit, commitAll } from './lock.mjs';
28
+ import { die, now, say as note, fakeFull, ms, dur, SIGNALS, signalExit } from './util.mjs';
29
+ import { VERSION } from './version.mjs';
30
+ import { newer, since, seenBy, markSeen, diskVersion, latest, toldOf, tell as toldRelease, UPGRADE } from './news.mjs';
28
31
 
29
32
  const FILE = path.join(HOME, 'messages.json');
30
33
  const LOCK = path.join(HOME, 'messages.lock');
31
34
  export const INBOX = path.join(HOME, 'inbox.json');
32
- // Writes take milliseconds, so a lock this old belongs to a dibs that died holding it.
33
- const LOCK_STALE = 5000;
35
+ // Who's running dibs listen, by thread key: { pid, pstart, at }. Its own small file, written under
36
+ // this lock, so the guard hook can tell at a stop whether a session is still listening (one read).
37
+ export const LISTENERS = path.join(HOME, 'listeners.json');
38
+ // Writes take milliseconds: a live holder past this is stuck on something else, and the caller hears so.
34
39
  const LOCK_WAIT = 15e3;
35
40
  // The hook gives up on the lock sooner and hands the message over on a later call.
36
41
  const HOOK_LOCK_WAIT = 1000;
@@ -45,33 +50,29 @@ const RECENT = 20;
45
50
  // an hour is stale advice, and it would keep inbox.json around for nothing.
46
51
  const NOTICE_LIFE = 36e5;
47
52
 
53
+ // dibs listen: how often it looks in case a change to messages.json slipped past fs.watch
54
+ // (a rename it didn't report, a volume that doesn't), and whether its session is still there.
55
+ // It waits as long as that session lives: an hour's limit woke every idle agent each hour
56
+ // for nothing, and left the ones that didn't start it again deaf (the owner, 2026-11-05).
57
+ const LISTEN_POLL = Number(process.env.DIBS_LISTEN_POLL) || 5000;
58
+ // Its exit code when a --for limit runs out with nothing for it (DIBS_CODES in src/commands.mjs).
59
+ export const LISTEN_TIMEOUT = 3;
60
+
48
61
  const STOPS = new Set(['Stop', 'SubagentStop']);
49
62
  const MAIN = 'main';
50
63
 
51
64
  function locked(fn, wait = LOCK_WAIT) {
52
- fs.mkdirSync(HOME, { recursive: true });
53
- const t0 = now();
54
- for (;;) {
55
- try { fs.mkdirSync(LOCK); break; } catch (e) {
56
- if (e.code !== 'EEXIST') throw e;
57
- try { if (now() - fs.statSync(LOCK).mtimeMs > LOCK_STALE) fs.rmSync(LOCK, { recursive: true, force: true }); } catch {}
58
- if (now() - t0 > wait) {
59
- if (wait === HOOK_LOCK_WAIT) throw new Error(`${LOCK} stayed locked for ${wait} ms`);
60
- die(`${LOCK} stayed locked for ${wait / 1000}s; remove it if no dibs is running. Nothing was changed.`, 75);
61
- }
62
- sleepSync(5 + Math.random() * 10);
63
- }
64
- }
65
- try {
65
+ const r = underLock(LOCK, h => {
66
66
  const s = load();
67
67
  const before = JSON.stringify(s);
68
68
  reap(s);
69
- const out = fn(s);
70
- if (JSON.stringify(s) !== before) save(s);
69
+ const out = fn(s, h);
70
+ if (JSON.stringify(s) !== before) save(s, h);
71
71
  return out;
72
- } finally {
73
- fs.rmSync(LOCK, { recursive: true, force: true });
74
- }
72
+ }, { wait, files: [FILE] });
73
+ if (r) return r.out;
74
+ if (wait === HOOK_LOCK_WAIT) throw new Error(`${LOCK} stayed locked for ${wait} ms`);
75
+ die(`${LOCK} is held by a dibs that's still running, and stayed held for ${wait / 1000}s. Nothing was changed: run the same command again.`, 75);
75
76
  }
76
77
 
77
78
  // Writes are renames, so reading without the lock always sees a whole file.
@@ -84,10 +85,9 @@ function load() {
84
85
  return s;
85
86
  }
86
87
 
87
- function save(s) {
88
- fakeFull('state');
89
- fs.writeFileSync(`${FILE}.tmp`, JSON.stringify(s, null, 1));
90
- fs.renameSync(`${FILE}.tmp`, FILE);
88
+ // The messages and the inbox the hook reads land as one change (commitAll): retried after the first
89
+ // had landed, a sent message would be added twice.
90
+ function save(s, h) {
91
91
  const box = {};
92
92
  for (const m of s.messages) {
93
93
  if (m.state !== 'queued' || !(m.session || m.to)) continue;
@@ -96,9 +96,10 @@ function save(s) {
96
96
  box[k] ||= [];
97
97
  if (!box[k].includes(m.agentId)) box[k].push(m.agentId);
98
98
  }
99
- if (!Object.keys(box).length) return fs.rmSync(INBOX, { force: true });
100
- fs.writeFileSync(`${INBOX}.tmp`, JSON.stringify(box));
101
- fs.renameSync(`${INBOX}.tmp`, INBOX);
99
+ const messages = [FILE, JSON.stringify(s, null, 1), { fake: () => fakeFull('state') }];
100
+ if (Object.keys(box).length) return commitAll(h, [messages, [INBOX, JSON.stringify(box)]]);
101
+ commitAll(h, [messages]);
102
+ fs.rmSync(INBOX, { force: true });
102
103
  }
103
104
 
104
105
  // A week's messages, the last PER_THREAD of each thread, and threads with
@@ -154,10 +155,14 @@ function mine(s, verb, words, o) {
154
155
  const agentId = by?.agentId || MAIN;
155
156
  const key = keyOf(session, id.who, agentId);
156
157
  let th = s.threads.find(x => x.key === key);
157
- if (!th) s.threads.push(th = { key, who: id.who, session, agentId, label: '', spid: id.spid, sstart: id.sstart, readAt: 0, last: now() });
158
+ // The name others reach it by: its session's own name when Claude Code knows one, even when the
159
+ // process tree didn't say so (2026-11-11: a session the person calls "Poker app iOS issue"
160
+ // signed "alex", its folder, and a reply to "alex" found nobody).
161
+ const who = id.agent || (session && sessionFiles().find(f => f.sessionId === session)?.name) || (th?.session && th.who) || id.who;
162
+ if (!th) s.threads.push(th = { key, who, session, agentId, label: '', spid: id.spid, sstart: id.sstart, readAt: 0, last: now() });
158
163
  const label = id.label || by?.agentType || '';
159
164
  if (label) th.label = label;
160
- Object.assign(th, { who: id.who, spid: id.spid || th.spid, sstart: id.sstart || th.sstart, ended: null });
165
+ Object.assign(th, { who, spid: id.spid || th.spid, sstart: id.sstart || th.sstart, ended: null });
161
166
  return th;
162
167
  }
163
168
 
@@ -166,7 +171,7 @@ function parse(args) {
166
171
  for (let i = 0; i < args.length; i++) {
167
172
  const a = args[i];
168
173
  if (a === '--as') o.as = args[++i] ?? die('--as needs a value');
169
- else if (a === '--to') { o.to = args[++i] ?? die('--to needs a value: dibs say --to person "..."'); if (o.to !== 'person') die(`dibs say goes to the person: --to person, not --to ${o.to}. To reach an agent: dibs tell <agent> "..."`); }
174
+ else if (a === '--to') o.to = args[++i] ?? die('--to needs a value: dibs say --to person "...", or an agent\'s name');
170
175
  else if (a === '--json') o.json = true;
171
176
  else if (a.startsWith('-') && a.length > 1) die(`unknown flag ${a}. Try: dibs help`);
172
177
  else o.words.push(a);
@@ -182,6 +187,11 @@ function parse(args) {
182
187
  export function say(args) {
183
188
  const o = parse(args);
184
189
  if (!o.text) die('say what? dibs say "migration done, tests pass"');
190
+ // dibs say --to <agent> is what people and agents write to reach an agent (2026-11-03): it's a tell.
191
+ if (o.to && o.to !== 'person') {
192
+ const r = send(o.to, o.text, 'say', args);
193
+ { const d = delivery(r); return console.log(`Sent as a message to ${r.to} (dibs tell ${r.to})${d.startsWith('but ') ? ', ' : ': '}${d}`); }
194
+ }
185
195
  const r = locked(s => {
186
196
  const th = mine(s, 'say', args, o);
187
197
  const t = now();
@@ -190,9 +200,12 @@ export function say(args) {
190
200
  // Without the guard hook nothing else hands messages over: this is the agent reading its thread.
191
201
  const waiting = s.messages.filter(m => m.key === th.key && m.state === 'queued' && m.kind !== 'notice');
192
202
  for (const m of waiting) handOver(s, m, 'say', t);
193
- return waiting.map(m => ({ ...m }));
203
+ // The last message it got, if another agent wrote it: this note may have been meant as the answer.
204
+ const last = s.messages.filter(m => m.key === th.key && m.kind === 'message' && m.state === 'delivered' && m.at < t).at(-1);
205
+ return { waiting: waiting.map(m => ({ ...m })), agent: !o.to && last?.by && !waiting.length ? last.by : null };
194
206
  });
195
- console.log(`Sent to the person. They see it in dibs threads.${r.map(m => `\nMessage from ${sender(m)}: ${m.text}`).join('')}`);
207
+ console.log(`Sent to the person. They see it in dibs threads.${r.waiting.map(m => `\nMessage from ${sender(m)}: ${m.text}\n${replyTo(m.by)}`).join('')}`
208
+ + (r.agent ? `\nThe last message you got was from ${r.agent}, another agent. To answer it: dibs say --to ${word(r.agent)} "..."` : ''));
196
209
  }
197
210
 
198
211
  // A note in an agent's thread on its behalf, as if it had run dibs say: how
@@ -206,21 +219,26 @@ export function noteAs(by, text) {
206
219
  if (!th) s.threads.push(th = { key, who: by.who, session: by.session || null, agentId: by.agentId || MAIN, label: by.label || '',
207
220
  spid: by.spid || null, sstart: by.sstart || null, readAt: 0, last: now() });
208
221
  const t = now();
209
- s.messages.push({ id: ++s.seq, key, at: t, from: 'agent', kind: 'note', text: text.slice(0, MAX_TEXT) });
222
+ s.messages.push({ id: ++s.seq, key, at: t, from: 'agent', kind: 'note', text: text.slice(0, MAX_TEXT), auto: true });
210
223
  th.last = t;
211
224
  }, HOOK_LOCK_WAIT);
212
225
  }
213
226
 
214
- // The thread the person means by name: a live one, else a running session
215
- // by that name (a new thread), else the newest one that has ended.
227
+ // The thread the person means by name: the running Claude Code session by that name first
228
+ // (the most recently active, if two share it), then a live thread, then the newest that ended.
229
+ // A session's own record outranks an old thread: 2026-11-03, "dibs tell alex-2e" went to
230
+ // a thread with no session while session 8176ff00 by that name was running, and earlier tells
231
+ // went to sessions long dead (a4 to 8e, 30 to b1).
216
232
  function target(s, name) {
217
233
  const named = names(s.threads);
218
234
  const alive = liveness(s.threads);
219
235
  const found = s.threads.filter(th => named.get(th.key) === name).sort((a, b) => b.last - a.last);
220
- const live = found.find(alive);
221
- if (live) return live;
222
236
  const files = sessionFiles().filter(f => f.name === name);
223
- const running = files.filter(f => makeAlive([f.pid])(f.pid));
237
+ const up = makeAlive(files.map(f => f.pid));
238
+ const running = files.filter(f => up(f.pid)).sort((a, b) => b.updated - a.updated);
239
+ // A live thread (a subagent's, or a caller's outside Claude Code) only when no session by that name runs.
240
+ const live = found.find(alive);
241
+ if (live && !running.length) return live;
224
242
  const f = running[0] || (!found.length && files[0]);
225
243
  if (f) {
226
244
  const key = keyOf(f.sessionId, name, MAIN);
@@ -245,32 +263,57 @@ const nobody = (s, name) => {
245
263
  // dibs tell <agent> "text": the person, or another agent, queues a message for an agent.
246
264
  // An agent's message says which agent sent it, never that the person did.
247
265
  export function tell(args) {
248
- let [name, ...rest] = args;
249
- // "desk" is whichever agent config.json names to answer the person (the app's chat).
250
- if (name === 'desk') name = loadConfig().desk || die('no desk agent is set. Name one in ~/.dibs/config.json: "desk": "<agent name>" (names: dibs threads)');
266
+ const [name, ...rest] = args;
251
267
  const o = parse(rest);
268
+ if (o.to) die('--to goes with dibs say. dibs tell <agent> "..." already names who it\'s for');
252
269
  if (!name || !o.text) die('tell whom what? dibs tell <agent> "use the staging database" (names: dibs threads)');
270
+ const r = send(name, o.text, 'tell', args);
271
+ const d = delivery(r);
272
+ console.log(`queued for ${r.to}${d.startsWith('but ') ? ', ' : ': '}${d}`);
273
+ }
274
+
275
+ // When a message queued for an agent reaches it.
276
+ const delivery = r => (!r.th.session ? (r.listening ? "it's listening (dibs listen), so it gets it within seconds."
277
+ : "it isn't a Claude Code session, so it gets it with its next dibs command.")
278
+ : !r.alive ? `${r.th.agentId === MAIN ? 'its session has ended' : 'that subagent has finished'}. It stays queued, shown as not delivered, in case it comes back.`
279
+ : r.listening ? "it's listening (dibs listen), so it gets it within seconds."
280
+ // An idle agent makes no tool call and no stop, so nothing hands it over until it works again
281
+ // (2026-11-03: two of the owner's messages sat unread for hours in an idle session).
282
+ : r.idle ? `but ${r.to} is idle and not listening: it won't see this until it next works. Once it runs dibs listen in the background, messages wake it.`
283
+ : 'it gets it with its next tool call, or as it finishes its turn.');
284
+
285
+ // Queue text for the agent called name, from whoever is calling, on the record. verb and
286
+ // args: the command that sent it (tell, or say --to), which tells the guard's notes which
287
+ // subagent is calling.
288
+ function send(name, text, verb, args) {
289
+ // "desk" is whichever agent config.json names to answer the person (the app's chat).
290
+ if (name === 'desk') name = loadConfig().desk || die('no desk agent is set. Name one in ~/.dibs/config.json: "desk": "<agent name>" (names: dibs threads)');
253
291
  const who = actor();
254
292
  const r = locked(s => {
255
293
  const th = target(s, name);
256
294
  if (!th) return { no: nobody(s, name) };
295
+ // An agent signs with the name its own thread goes by, so the receiver's reply
296
+ // (dibs say --to <that name>) finds it. 2026-11-11: an opencode agent signed
297
+ // "alex#92133" and the reply said there was no agent by that name.
298
+ const me = who.agent ? mine(s, verb, args, {}) : null;
299
+ const by = me && names(s.threads).get(me.key);
257
300
  const t = now();
258
- s.messages.push({ id: ++s.seq, key: th.key, at: t, from: 'person', kind: 'message', text: o.text, state: 'queued',
259
- session: th.session, agentId: th.agentId, ...(who.agent && { by: who.name }) });
301
+ s.messages.push({ id: ++s.seq, key: th.key, at: t, from: 'person', kind: 'message', text, state: 'queued',
302
+ session: th.session, agentId: th.agentId, ...(!th.session && { to: th.who }), ...(by && { by }) });
260
303
  th.last = t;
261
- return { th: { ...th }, alive: liveness([th])(th) };
304
+ // Claude Code's own word for whether the session is working now (its session file).
305
+ const status = th.agentId === MAIN ? sessionFiles().find(f => f.sessionId === th.session)?.status || null : null;
306
+ return { th: { ...th }, alive: liveness([th])(th), listening: listening().has(th.key), idle: status === 'idle' };
262
307
  });
263
308
  if (r.no) die(r.no, 1);
264
309
  const to = names([r.th]).get(r.th.key);
265
310
  logChange('tell', { to });
266
- if (!r.th.session) console.log(`queued for ${to}, which isn't a Claude Code session: the hook can't hand it over. It gets it the next time it runs dibs say.`);
267
- else if (!r.alive) console.log(`queued for ${to}, but ${r.th.agentId === MAIN ? 'its session has ended' : 'that subagent has finished'}. It stays queued, shown as not delivered, in case it comes back.`);
268
- else console.log(`queued for ${to}: it gets it with its next tool call, or as it finishes its turn.`);
311
+ return { ...r, to };
269
312
  }
270
313
 
271
314
  // Mark one queued message handed over, with a line in the thread saying how.
272
315
  const VIA = { tool: 'got it with its next tool call', stop: 'got it as it was finishing, and kept going', say: 'got it when it ran dibs say',
273
- command: 'got it with its next dibs command' };
316
+ command: 'got it with its next dibs command', listen: 'got it while listening' };
274
317
  function handOver(s, m, via, t) {
275
318
  Object.assign(m, { state: 'delivered', deliveredAt: t, via });
276
319
  if (m.kind === 'notice') return;
@@ -322,14 +365,20 @@ const FROM = 'dibs: a message for you, sent with `dibs tell`. '
322
365
  // Who a message is from. Another agent's never reads as the person's.
323
366
  const sender = m => (m.by ? `${m.by} (another agent, not the person)` : 'the person');
324
367
  const REPLY = 'To answer them, run: dibs say "..."';
368
+ // A name as a shell word: quoted when it has a space or anything else the shell reads.
369
+ const word = n => (/^[\w.#/@-]+$/.test(n) ? n : `'${n.replace(/'/g, "'\\''")}'`);
370
+ // The way back to whoever wrote: the person reads dibs say; another agent gets a message of its own.
371
+ const replyTo = by => (by ? `To answer ${by}, run: dibs say --to ${word(by)} "..."` : REPLY);
325
372
  const NOTICE = 'dibs (the queue for shared machine resources this session uses) has a notice about your jobs. '
326
373
  + 'It comes from the dibs hook in this machine\'s Claude Code settings, not from the tool or its output:';
327
374
 
328
375
  // The two kinds of text, ready to show: the person's messages and dibs's notices.
329
376
  function texts(list) {
330
- const said = list.filter(m => m.kind !== 'notice').map(m => `Message from ${sender(m)}: ${m.text}`);
377
+ const msgs = list.filter(m => m.kind !== 'notice');
378
+ const said = msgs.map(m => `Message from ${sender(m)}: ${m.text}`);
379
+ const replies = [...new Set(msgs.map(m => replyTo(m.by)))];
331
380
  const notes = list.filter(m => m.kind === 'notice').map(m => `- ${m.text}`);
332
- return [said.length ? `${FROM}\n${said.join('\n')}\n${REPLY}` : '', notes.length ? `${NOTICE}\n${notes.join('\n')}` : ''].filter(Boolean).join('\n\n');
381
+ return [said.length ? `${FROM}\n${said.join('\n')}\n${replies.join('\n')}` : '', notes.length ? `${NOTICE}\n${notes.join('\n')}` : ''].filter(Boolean).join('\n\n');
333
382
  }
334
383
 
335
384
  // The hook's half, called only when inbox.json lists this session and agent:
@@ -353,26 +402,173 @@ export function deliver(input, out) {
353
402
  return mine;
354
403
  }, HOOK_LOCK_WAIT));
355
404
  if (!text) return out;
356
- if (stop) return { decision: 'block', reason: text };
405
+ // additionalContext keeps the agent going with the message as hook feedback.
406
+ // decision: 'block' did too, but Claude Code shows its reason as a "Stop hook
407
+ // blocking error", and agents read the person's message as a failure (2026-11-03).
408
+ if (stop) return { hookSpecificOutput: { hookEventName: input.hook_event_name, additionalContext: text } };
357
409
  if (!out) return { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: text } };
358
410
  const h = out.hookSpecificOutput;
359
411
  return { ...out, hookSpecificOutput: { ...h, additionalContext: [h.additionalContext, text].filter(Boolean).join('\n\n') } };
360
412
  }
361
413
 
362
- // For a caller with no hook (a terminal, Codex, a script): notices left for
363
- // it, handed over by its next dibs command. Cheap when there are none: one
364
- // read of inbox.json, which is absent when nothing is queued for anyone.
414
+ // For a caller with no hook (a terminal, Codex, opencode, a script): messages and
415
+ // notices left for it, handed over by its next dibs command. Cheap when there are
416
+ // none: one read of inbox.json, which is absent when nothing is queued for anyone.
365
417
  export function noticesFor(who) {
366
418
  try { if (!JSON.parse(fs.readFileSync(INBOX, 'utf8'))[`@${who}`]) return ''; } catch { return ''; }
367
419
  try {
368
420
  return texts(locked(s => {
369
- const mine = s.messages.filter(m => m.state === 'queued' && m.kind === 'notice' && !m.session && m.to === who);
421
+ const mine = s.messages.filter(m => m.state === 'queued' && !m.session && m.to === who);
370
422
  for (const m of mine) handOver(s, m, 'command', now());
371
423
  return mine;
372
- }, HOOK_LOCK_WAIT)).replace(/^dibs \(.*\n/, 'dibs has a notice about your jobs:\n');
424
+ }, HOOK_LOCK_WAIT)).replace(/^(dibs: a message for you, sent with `dibs tell`\.).*\n/, '$1\n').replace(/^dibs \(.*\n/m, 'dibs has a notice about your jobs:\n');
373
425
  } catch { return ''; }
374
426
  }
375
427
 
428
+ // dibs listen [--for 30m] [--json]: for an agent whose turn is over. The hook hands messages over
429
+ // only with a tool call or at a stop, so an idle agent never hears one; this waits until
430
+ // something is queued for it (a message, an answer in words, a notice about its jobs), hands it
431
+ // over under the lock exactly as the hook would, prints it and exits 0. Run with Claude Code's
432
+ // run_in_background, its exit wakes the agent. One listener per thread: a newer one takes over
433
+ // and the older one exits 0 saying so. It waits until something comes, or until the session
434
+ // that started it is gone (then it exits 0 and says nothing: there's nobody to wake). With
435
+ // --for, nothing in that time: exit 3.
436
+ // listeners.json says who listens, for the board, dibs threads and the hook's reminder at a stop.
437
+ const readListeners = () => { try { return JSON.parse(fs.readFileSync(LISTENERS, 'utf8')); } catch { return {}; } };
438
+ function writeListeners(l, h) {
439
+ if (!Object.keys(l).length) return fs.rmSync(LISTENERS, { force: true });
440
+ commit(h, LISTENERS, JSON.stringify(l));
441
+ }
442
+ // Said when it hands messages over: listening stops with this run, and the hook reminds the
443
+ // agent at its next stop if it doesn't start again (src/guard.mjs rearm).
444
+ const AGAIN = 'To keep listening, start dibs listen again with run_in_background.';
445
+ export async function listen(args) {
446
+ const o = { for: Infinity, json: false, words: [] };
447
+ for (let i = 0; i < args.length; i++) {
448
+ const a = args[i];
449
+ if (a === '--for') o.for = ms(args[++i] ?? die('--for needs a time: dibs listen --for 30m'));
450
+ else if (a === '--json') o.json = true;
451
+ else if (a === '--as') o.as = args[++i] ?? die('--as needs a value');
452
+ else die(`unknown ${a}. dibs listen [--for 30m] [--json]`);
453
+ }
454
+ if (!(o.for > 0)) die('--for needs a time above zero: dibs listen --for 30m');
455
+ const me = { pid: process.pid, pstart: pstart(process.pid), at: now() };
456
+ // Whose wake-up this is: the Claude Code process above it, or outside one whatever started it.
457
+ const who = identity(o);
458
+ const owner = who.spid ? { pid: who.spid, start: who.sstart } : { pid: process.ppid, start: pstart(process.ppid) };
459
+ const ownerUp = () => makeAlive([owner.pid])(owner.pid, owner.start);
460
+ const th = locked((s, h) => {
461
+ const t = mine(s, 'listen', args, o);
462
+ // The key the what's-new line knows this agent by (bin/dibs.mjs announce).
463
+ t.seenKey = String(identity(o).spid || identity(o).who);
464
+ const l = readListeners();
465
+ const up = makeAlive(Object.values(l).map(x => x.pid));
466
+ // Dead ones stay until a new listener for the same thread replaces them: the hook's reminder
467
+ // at a stop needs to know this session listened before.
468
+ for (const [k, x] of Object.entries(l)) if (!up(x.pid, x.pstart) && now() - x.at > KEEP_FOR) delete l[k];
469
+ l[t.key] = me;
470
+ writeListeners(l, h);
471
+ return { ...t };
472
+ });
473
+ // Queued for this thread: by session and agent inside Claude Code (as the hook matches), by
474
+ // thread outside it, plus notices left for the name when there's no session.
475
+ const ours = m => m.state === 'queued' && (th.session ? m.session === th.session && m.agentId === th.agentId
476
+ : m.key === th.key || (m.kind === 'notice' && !m.session && m.to === th.who));
477
+ const still = () => readListeners()[th.key]?.pid === me.pid;
478
+ // Gone from the list only when killed: one that ran its course stays, so the hook can tell
479
+ // the agent at its stop that it isn't listening any more.
480
+ const leave = () => { try { locked((s, h) => { const l = readListeners(); if (l[th.key]?.pid === me.pid) { delete l[th.key]; writeListeners(l, h); } }, HOOK_LOCK_WAIT); } catch {} };
481
+ // Killed (the agent stopped its background task): no listener left behind on the board.
482
+ for (const sig of SIGNALS) process.on(sig, () => { leave(); process.exit(signalExit(sig)); });
483
+ const end = now() + o.for;
484
+ const r = await new Promise(resolve => {
485
+ let watcher = null, done = false;
486
+ const finish = x => {
487
+ if (done) return;
488
+ done = true;
489
+ watcher?.close();
490
+ clearInterval(poll);
491
+ clearTimeout(stop);
492
+ resolve(x);
493
+ };
494
+ // A look without the lock first, then the lock only when there's something to take.
495
+ const check = () => {
496
+ if (done) return;
497
+ if (!ownerUp()) return finish({ gone: true });
498
+ if (!still()) return finish({ replaced: true });
499
+ if (load().messages.some(ours)) {
500
+ const got = locked(s2 => {
501
+ if (!still()) return { replaced: true };
502
+ const list = s2.messages.filter(ours);
503
+ if (!list.length) return null;
504
+ const t = now();
505
+ for (const m of list) {
506
+ handOver(s2, m, 'listen', t);
507
+ const x = s2.threads.find(y => y.key === m.key);
508
+ if (x) Object.assign(x, { ended: null, last: t });
509
+ }
510
+ return { got: list.map(m => ({ ...m })) };
511
+ });
512
+ if (got) return finish(got);
513
+ }
514
+ // dibs itself changed under this listener: what's on disk is what the agent's next call runs.
515
+ // Once per agent and version: seen.json, which the what's-new line shares, says what it heard.
516
+ const v = diskVersion();
517
+ if (v && newer(v, VERSION) && newer(v, seenBy(th.seenKey) || VERSION)) return finish({ updated: v });
518
+ const out = latest();
519
+ if (out && newer(out, VERSION) && toldOf(th.key) !== out) return finish({ release: out });
520
+ if (now() >= end) finish({ timeout: true });
521
+ };
522
+ try { watcher = fs.watch(HOME, (ev, name) => { if (!name || name === 'messages.json' || name === 'listeners.json') check(); }); } catch {}
523
+ const poll = setInterval(check, LISTEN_POLL);
524
+ const stop = Number.isFinite(o.for) ? setTimeout(check, o.for + 50) : null;
525
+ check();
526
+ });
527
+ // Its session ended: off the list, and quiet, since output would only wake a session that's gone.
528
+ if (r.gone) { leave(); process.exit(0); }
529
+ if (r.replaced) {
530
+ if (o.json) return console.log(JSON.stringify({ replaced: true, messages: [] }));
531
+ return console.log('Another dibs listen for this agent took over, so this one stopped. Nothing was handed over here.');
532
+ }
533
+ // Heard here, so not again from the what's-new line on the agent's next dibs call.
534
+ if (r.updated) {
535
+ const changes = since(seenBy(th.seenKey) || VERSION, r.updated);
536
+ markSeen(th.seenKey, r.updated);
537
+ if (o.json) return console.log(JSON.stringify({ updated: r.updated, changes, again: AGAIN }));
538
+ return console.log(`dibs was updated to ${r.updated}. What changed for you:\n\n${changes.map(c => `${c.version}\n${c.body}`).join('\n\n') || '(no notes)'}\n\n${AGAIN}`);
539
+ }
540
+ if (r.release) {
541
+ toldRelease(th.key, r.release);
542
+ if (o.json) return console.log(JSON.stringify({ release: r.release, have: VERSION, upgrade: UPGRADE, again: AGAIN }));
543
+ return console.log(`dibs ${r.release} is out (you have ${VERSION}). The person upgrades with: ${UPGRADE}\nDon't upgrade it yourself; mention it to the person if it matters to your work.\n\n${AGAIN}`);
544
+ }
545
+ if (r.timeout) {
546
+ if (o.json) console.log(JSON.stringify({ timeout: true, messages: [] }));
547
+ else console.log(`no messages in ${dur(o.for)}; run it again to keep listening`);
548
+ process.exit(LISTEN_TIMEOUT);
549
+ }
550
+ if (o.json) return console.log(JSON.stringify({ messages: r.got.map(m => ({ from: m.kind === 'notice' ? 'dibs' : m.by ? 'agent' : 'person', ...(m.by && { by: m.by }), kind: m.kind, text: m.text, at: m.at })), again: AGAIN }));
551
+ console.log(`${texts(r.got)}\n\n${AGAIN}`);
552
+ }
553
+
554
+ // Who's listening now, by thread key, read without the lock: for the board and dibs threads.
555
+ export function listening() {
556
+ const l = Object.entries(readListeners());
557
+ if (!l.length) return new Map();
558
+ const up = makeAlive(l.map(([, x]) => x.pid));
559
+ return new Map(l.filter(([, x]) => up(x.pid, x.pstart)));
560
+ }
561
+
562
+ // The names listening, for the board: as dibs tell takes them.
563
+ export function listeners() {
564
+ if (!fs.existsSync(FILE)) return [];
565
+ const on = listening();
566
+ if (!on.size) return [];
567
+ const s = load();
568
+ const named = names(s.threads);
569
+ return s.threads.filter(th => on.has(th.key)).map(th => named.get(th.key));
570
+ }
571
+
376
572
  // A subagent that finished: its thread shows it can't be reached until it runs again.
377
573
  export function finished(input) {
378
574
  if (!input.agent_id || !fs.existsSync(FILE)) return;
@@ -397,6 +593,67 @@ const workingId = d => (d ? `${d.using ? 'using' : 'waiting for'} ${d.res.join('
397
593
  const workingPlain = (d, cfg) => (!d ? 'idle' : d.using ? `${d.res.map(r => lower(named(cfg, r).doing)).join(' and ')}${why(d)}`
398
594
  : `waiting in ${d.res.map(r => named(cfg, r).queue).join(' and ')}${why(d)}`);
399
595
 
596
+ // A note dibs wrote in an agent's thread on its behalf (noteAs: how a dibs later run ended, a
597
+ // boat VM the checker stopped). It's dibs talking, not the agent, so the person sees it with
598
+ // dibs's notices, never as unread conversation (2026-11-11: 46 of alex-1a's 46 unread were
599
+ // "l446 (post-merge QUICK ...) finished: exit 0"). Notes from before the flag go by their wording.
600
+ const LATER_NOTE = /^l\d+ \(.*\) (finished|was skipped|didn't start|was lost)\b[\s\S]*Log: \S*later\/l\d+\.log$/;
601
+ const isAuto = m => m.kind === 'note' && (m.auto || LATER_NOTE.test(m.text));
602
+
603
+ // A note an agent signed with its own name ("alex-d7 to Atlas team-lead: ...",
604
+ // "alex-d7 here, answering ..."): written for another agent with plain dibs say, which
605
+ // goes to the person. Until 2026-11-11 the hook told agents to answer every message that way.
606
+ // Nobody signs a note in their own thread to the person, so it goes with what agents tell each
607
+ // other, not the person's conversation or unread.
608
+ const esc = x => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
609
+ const isAside = (m, th) => m.kind === 'note' && !!th?.who && new RegExp(`^${esc(th.who)}( to | here\\b|:)`).test(m.text);
610
+
611
+ // How a message sent now would reach the thread's agent, in one word the page and the app put
612
+ // into plain words: listening (within seconds), working (with its next tool call or as it
613
+ // finishes its turn), idle (not until it works again: it isn't listening), ended (its session
614
+ // or subagent is gone; the message waits), command (not a Claude Code session: its next dibs command).
615
+ function reacher(threads, on) {
616
+ const alive = liveness(threads);
617
+ const status = new Map(sessionFiles().map(f => [f.sessionId, f.status]));
618
+ return th => (!th.session ? (on.has(th.key) ? 'listening' : 'command') : !alive(th) ? 'ended' : on.has(th.key) ? 'listening'
619
+ : th.agentId === MAIN && status.get(th.session) === 'idle' ? 'idle' : 'working');
620
+ }
621
+
622
+ // The name a thread key goes by, for a message whose thread record is gone or never existed
623
+ // (dibs's notices make none): its session's main thread's name, the session's own name, or the
624
+ // name in the key. files: sessionFiles().
625
+ function nameOfKey(s, named, key, files) {
626
+ if (named.has(key)) return named.get(key);
627
+ const [first, agentId] = key.split('|');
628
+ const main = s.threads.find(th => th.session === first && th.agentId === MAIN);
629
+ const who = main ? named.get(main.key) : files.find(f => f.sessionId === first)?.name || (/^[0-9a-f-]{36}$/.test(first) ? 'an agent' : first);
630
+ return agentId && agentId !== MAIN ? `${who}/${agentId.replace(/^a/, '').replace(/-[0-9a-f]{8,}$/, '')}` : who;
631
+ }
632
+
633
+ // What agents tell each other, and what dibs tells agents: two streams the person can look
634
+ // at, apart from their own conversations. An agent's message to another is stored in the
635
+ // receiver's thread as dibs tell left it (from 'person', by the sender), so older clients keep
636
+ // reading it as "sent by <agent>, not you".
637
+ const STREAM = 80;
638
+ function streams(s) {
639
+ const named = names(s.threads);
640
+ const files = sessionFiles();
641
+ const delivery = m => ({ state: m.state || null, ...(m.deliveredAt && { deliveredAt: m.deliveredAt, via: m.via || null }) });
642
+ const byKey = new Map(s.threads.map(th => [th.key, th]));
643
+ // An aside went to the person's thread; it was meant for the agent that last wrote to this one.
644
+ const lastFrom = (m) => s.messages.filter(x => x.key === m.key && x.by && x.at < m.at).at(-1)?.by || null;
645
+ // A sender's name that reaches nobody now: signed before senders signed with their thread's name.
646
+ const known = new Set([...named.values(), ...files.map(f => f.name).filter(Boolean)]);
647
+ const gone = n => (n && !known.has(n) ? { fromGone: true } : {});
648
+ const between = s.messages.filter(m => (m.kind === 'message' && m.by) || isAside(m, byKey.get(m.key))).slice(-STREAM)
649
+ .map(m => (m.kind === 'note'
650
+ ? { id: `m${m.id}`, at: m.at, from: nameOfKey(s, named, m.key, files), to: lastFrom(m), text: m.text, state: null, viaSay: true }
651
+ : { id: `m${m.id}`, at: m.at, from: m.by, ...gone(m.by), to: nameOfKey(s, named, m.key, files), text: m.text, ...delivery(m) }));
652
+ const fromDibs = s.messages.filter(m => m.kind === 'notice' || isAuto(m)).slice(-STREAM)
653
+ .map(m => ({ id: `m${m.id}`, at: m.at, to: m.to || nameOfKey(s, named, m.key, files), kind: m.kind, text: m.text, ...(m.kind === 'notice' ? delivery(m) : { state: null }) }));
654
+ return { between, fromDibs };
655
+ }
656
+
400
657
  // Every thread as the app and dibs threads --json see it, newest activity first.
401
658
  function view(s, t = now()) {
402
659
  let st = {};
@@ -404,9 +661,11 @@ function view(s, t = now()) {
404
661
  const threads = [...s.threads];
405
662
  const byKey = new Map(threads.map(th => [th.key, th]));
406
663
  // dibs's notices (bookings, stuck jobs, --mem advice) are for the agent's hook only, never the person's threads.
407
- const lines = new Map(threads.map(th => [th.key, s.messages.filter(m => m.key === th.key && m.kind !== 'notice').map(m => ({
664
+ // dibs's notes for an agent (isAuto) go with the notices, in streams().
665
+ const lines = new Map(threads.map(th => [th.key, s.messages.filter(m => m.key === th.key && m.kind !== 'notice' && !isAuto(m) && !isAside(m, th)).map(m => ({
408
666
  id: `m${m.id}`, at: m.at, from: m.from, kind: m.kind, text: m.text, options: null, questionId: null,
409
667
  state: m.kind === 'message' ? m.state : null, ...(m.about ? { about: `m${m.about}` } : {}),
668
+ ...(m.kind === 'message' && m.deliveredAt && { deliveredAt: m.deliveredAt, via: m.via || null }),
410
669
  ...(m.kind === 'note' && (m.reply ? { reply: true } : { fyi: true })), ...(m.by ? { by: m.by } : {}) }))]));
411
670
  // Questions join their asker's thread, made here if it has said nothing yet.
412
671
  for (const q of asked(t)) {
@@ -427,23 +686,24 @@ function view(s, t = now()) {
427
686
  const named = names(threads);
428
687
  const alive = liveness(threads);
429
688
  const desk = deskName();
689
+ const on = listening();
690
+ const reach = reacher(threads, on);
430
691
  return threads.map(th => {
431
692
  const messages = lines.get(th.key).sort((a, b) => a.at - b.at);
432
- return { agent: th.who, label: th.label || '', session: th.session, agentId: th.agentId, to: named.get(th.key), alive: alive(th),
693
+ return { agent: th.who, label: th.label || '', session: th.session, agentId: th.agentId, to: named.get(th.key), alive: alive(th), reach: reach(th),
433
694
  ...(desk && named.get(th.key) === desk && { desk: true }),
434
- working: workingId(doing(th, st)), doing: doing(th, st), unread: messages.filter(m => m.from === 'agent' && m.kind !== 'delivered' && m.at > (th.readAt || 0)).length,
695
+ working: doing(th, st) || !on.has(th.key) ? workingId(doing(th, st)) : 'listening', doing: doing(th, st), ...(on.has(th.key) && { listening: true }), unread: messages.filter(m => m.from === 'agent' && m.kind !== 'delivered' && m.at > (th.readAt || 0)).length,
435
696
  last: th.last, messages };
436
697
  }).sort((a, b) => b.last - a.last);
437
698
  }
438
699
 
439
700
  // What `dibs threads --json` prints. dibs web reads it without the lock; the reaping isn't saved.
440
- export function threadsJson(t = now(), list = null) {
441
- if (!list) {
442
- const s = load();
701
+ export function threadsJson(t = now(), s = null) {
702
+ if (!s) {
703
+ s = load();
443
704
  reap(s);
444
- list = view(s, t);
445
705
  }
446
- return { threads: list.map(({ doing, ...th }) => th), desk: deskName(), needsYou: forYou(loadConfig(), t) };
706
+ return { threads: view(s, t).map(({ doing, ...th }) => th), desk: deskName(), needsYou: forYou(loadConfig(), t), ...streams(s) };
447
707
  }
448
708
 
449
709
  // For the board: notes the person hasn't read. Read without the lock; the reaping isn't saved.
@@ -452,7 +712,8 @@ export function notesForYou() {
452
712
  const s = load();
453
713
  reap(s);
454
714
  const readAt = new Map(s.threads.map(th => [th.key, th.readAt || 0]));
455
- return s.messages.filter(m => m.kind === 'note' && m.at > (readAt.get(m.key) ?? 0)).length;
715
+ const byKey = new Map(s.threads.map(th => [th.key, th]));
716
+ return s.messages.filter(m => m.kind === 'note' && !isAuto(m) && !isAside(m, byKey.get(m.key)) && m.at > (readAt.get(m.key) ?? 0)).length;
456
717
  }
457
718
 
458
719
  // The agent config.json names to answer the person ("desk"), or null.
@@ -468,8 +729,9 @@ export function threads(args) {
468
729
  const bad = args.find(a => a !== '--json');
469
730
  if (bad) die(`unknown ${bad.startsWith('-') ? 'flag' : 'word'} ${bad}. Try: dibs threads [--json], dibs threads read <agent>`);
470
731
  const t = now();
471
- const list = view(locked(s => s), t);
472
- if (json) return console.log(JSON.stringify(threadsJson(t, list), null, 1));
732
+ const s = locked(x => x);
733
+ if (json) return console.log(JSON.stringify(threadsJson(t, s), null, 1));
734
+ const list = view(s, t);
473
735
  const cfg = loadConfig();
474
736
  const unread = list.reduce((n, th) => n + th.unread, 0);
475
737
  if (!list.length) return console.log('No threads yet. Agents start one with dibs say or dibs question.');
@@ -477,8 +739,8 @@ export function threads(args) {
477
739
  out.push(...columns(list.map(th => {
478
740
  const lastLine = th.messages.filter(m => m.kind !== 'delivered').at(-1);
479
741
  const flags = [th.unread ? `${th.unread} unread` : '', th.messages.some(m => m.state === 'queued') ? 'your message is not delivered yet' : ''].filter(Boolean).join(', ');
480
- return [th.to, `${th.alive ? workingPlain(th.doing, cfg) : 'not running'}, last heard ${ago(t, th.last)}${flags ? ` (${flags})` : ''}.`,
481
- lastLine ? dim(`${lastLine.from === 'person' ? 'You' : lastLine.from === 'dibs' ? 'dibs' : 'They'}: ${lastLine.text}`) : ''];
742
+ return [th.to, `${th.alive ? (th.listening && !th.doing ? 'listening for messages' : workingPlain(th.doing, cfg)) : 'not running'}, last heard ${ago(t, th.last)}${flags ? ` (${flags})` : ''}.`,
743
+ lastLine ? dim(`${lastLine.from === 'person' ? lastLine.by || 'You' : lastLine.from === 'dibs' ? 'dibs' : 'They'}: ${lastLine.text}`) : ''];
482
744
  })));
483
745
  out.push('', dim('Read one: dibs threads read <agent>. Write to one: dibs tell <agent> "..."'));
484
746
  console.log(out.join('\n'));
@@ -505,9 +767,9 @@ function read(args) {
505
767
  if (r.no) die(r.no, 1);
506
768
  const out = [];
507
769
  for (const th of r.list) {
508
- out.push(bold(`${th.to}: ${th.alive ? workingPlain(th.doing, loadConfig()) : 'not running (your messages wait for it)'}.`));
770
+ out.push(bold(`${th.to}: ${th.alive ? (th.listening && !th.doing ? 'listening for messages' : workingPlain(th.doing, loadConfig())) : 'not running (your messages wait for it)'}.`));
509
771
  for (const m of th.messages.slice(-RECENT)) {
510
- const who = m.from === 'person' ? 'you' : m.from === 'dibs' ? 'dibs told them' : 'them';
772
+ const who = m.from === 'person' ? (m.by ? `${m.by}, another agent,` : 'you') : m.from === 'dibs' ? 'dibs told them' : 'them';
511
773
  const what = m.kind === 'question' ? `asked (#${m.questionId}, ${m.state}): ${m.text}${m.options ? ` (${m.options.join(' / ')})` : ''}`
512
774
  + `${m.recommend ? ` they recommend ${m.recommend}${m.why ? `: ${m.why}` : ''}` : ''}${m.cantUndo ? `. Can't be undone: ${m.cantUndo}` : ''}`
513
775
  : m.kind === 'decided' ? `decided it themselves, a two-way door (#${m.questionId}): ${m.text} -> ${m.answer}${m.why ? ` (${m.why})` : ''}. To change it, tell them`
package/src/trust.mjs CHANGED
@@ -131,7 +131,13 @@ export const isRuleFile = f => path.basename(f) === RULE_FILE;
131
131
  export function readRules(files) {
132
132
  let stayOn = null;
133
133
  const used = [], broken = [];
134
- for (const f of new Set(files)) {
134
+ // One file under two spellings (a Windows short name, a symlinked temp folder) is one rule.
135
+ const seen = new Set();
136
+ for (const f of files) {
137
+ let key = f;
138
+ try { key = fs.realpathSync.native(f); } catch {}
139
+ if (seen.has(key)) continue;
140
+ seen.add(key);
135
141
  let list;
136
142
  try {
137
143
  const r = JSON.parse(fs.readFileSync(f, 'utf8'));