@dibssoftware/dibs 0.0.179 → 0.0.181

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 (53) hide show
  1. package/CHANGELOG.md +31 -2
  2. package/README.md +4 -2
  3. package/bin/dibs-guard.mjs +10 -1
  4. package/bin/dibs.mjs +37 -10
  5. package/docs/benchmarks.md +1 -1
  6. package/docs/files.md +1 -1
  7. package/docs/guard.md +6 -0
  8. package/docs/questions.md +6 -2
  9. package/docs/reference.md +4 -4
  10. package/docs/relay.md +24 -9
  11. package/docs/releasing.md +4 -3
  12. package/docs/scheduling.md +4 -4
  13. package/docs/windows.md +14 -0
  14. package/package.json +1 -1
  15. package/skills/dibs/SKILL.md +6 -6
  16. package/src/acquire.mjs +93 -27
  17. package/src/agents.mjs +7 -22
  18. package/src/alerts.mjs +75 -29
  19. package/src/board.mjs +1 -2
  20. package/src/broker.mjs +26 -11
  21. package/src/commands.mjs +37 -14
  22. package/src/config.mjs +21 -4
  23. package/src/cool.mjs +105 -10
  24. package/src/diskwarn.mjs +4 -0
  25. package/src/events.mjs +10 -1
  26. package/src/files.mjs +52 -88
  27. package/src/guard.mjs +76 -30
  28. package/src/guardd.mjs +97 -0
  29. package/src/guardw.mjs +19 -0
  30. package/src/later.mjs +20 -25
  31. package/src/lock.mjs +308 -0
  32. package/src/measure.mjs +27 -7
  33. package/src/ondemand.mjs +5 -2
  34. package/src/override.mjs +39 -2
  35. package/src/plain.mjs +2 -2
  36. package/src/platform.mjs +175 -42
  37. package/src/preempt.mjs +51 -3
  38. package/src/primer.mjs +1 -1
  39. package/src/proc.mjs +45 -5
  40. package/src/questions.mjs +8 -22
  41. package/src/relay.mjs +137 -32
  42. package/src/remote.mjs +12 -8
  43. package/src/schedule.mjs +139 -26
  44. package/src/serve.mjs +16 -3
  45. package/src/service.mjs +9 -4
  46. package/src/state.mjs +139 -47
  47. package/src/stats.mjs +3 -2
  48. package/src/talk.mjs +169 -83
  49. package/src/trust.mjs +7 -1
  50. package/src/util.mjs +28 -2
  51. package/src/version.mjs +1 -1
  52. package/src/web.mjs +17 -26
  53. package/src/worker.mjs +2 -1
package/src/alerts.mjs CHANGED
@@ -7,43 +7,60 @@
7
7
  // list; the app turns a new one into a notification, at most one per cause
8
8
  // every 30 minutes.
9
9
  //
10
- // Six causes:
10
+ // Seven causes:
11
11
  // wait a job waiting far longer than usual, worst when a person waits on it
12
12
  // memory memory pressure or swap holding new jobs back, with what to close
13
13
  // idle a slot held by a job that has done nothing for a long time
14
14
  // ended jobs that failed, were stopped, or were lost on another machine
15
15
  // dibs dibs itself: a service down or restarting, a crash, the hook failing
16
16
  // disk free disk under the floor
17
+ // machine what only the person can fix on the machine: cores that stopped taking
18
+ // work, processes left running with their script gone (src/cool.mjs)
17
19
  //
18
20
  // alerts.json keeps the open ones, the resolved ones for a day, and what the
19
21
  // scan needs between runs: how far into the event log and the hook's log it
20
- // has read, recent waits per resource, and the services' start counts. Every
21
- // process that shows the board scans at most every SCAN_EVERY, and so does the
22
- // throttle watcher, so alerts keep up even when nobody looks.
22
+ // has read, recent waits per resource, and the services' start counts. The
23
+ // throttle watcher scans every SCAN_EVERY, so alerts keep up even when nobody
24
+ // looks; whatever shows the board scans too, every SCAN_EVERY without a
25
+ // watcher and every READER_EVERY with one.
23
26
  import fs from 'node:fs';
24
27
  import path from 'node:path';
25
- import { HOME, machine } from './config.mjs';
28
+ import { HOME, paths, machine } from './config.mjs';
26
29
  import { verdict } from './schedule.mjs';
27
30
  import { stuckFor, minutes, andList } from './plain.mjs';
28
- import { processes, memoryUse } from './platform.mjs';
31
+ import { processesNow, memoryUse } from './platform.mjs';
29
32
  import { treeOf } from './measure.mjs';
30
33
  import { withState, history } from './state.mjs';
31
- import { markIdle } from './acquire.mjs';
34
+ import { markIdle, tableFirst } from './acquire.mjs';
32
35
  import { sessionFiles } from './proc.mjs';
33
36
  import { EVENTS } from './events.mjs';
34
- import { serviceHealth } from './service.mjs';
37
+ import { serviceHealth, logName } from './service.mjs';
35
38
  import { hogHint } from './hogs.mjs';
39
+ import { underLock, heldBy } from './lock.mjs';
36
40
  import { now, bytes, clock, gb, die } from './util.mjs';
37
41
  import { dim, red, amber, wrap } from './style.mjs';
38
42
 
39
43
  export const FILE = path.join(HOME, 'alerts.json');
44
+ // The throttle watcher's notes on the machine (src/cool.mjs noteCpu).
45
+ export const CPU_FILE = path.join(HOME, 'cpu.json');
46
+ // Notes older than this are from a watcher that stopped: three of its passes.
47
+ const CPU_FRESH = 30e3;
40
48
  const LOCK = path.join(HOME, 'alerts.lock');
41
49
  const GUARD_LOG = path.join(HOME, 'guard.log');
42
50
  const MIN = 6e4, HOUR = 36e5, DAY = 864e5;
51
+ // Stuck cores for this long, not a passing spike, before the person is told to restart.
52
+ const STUCK_AFTER = 5 * MIN;
43
53
 
44
54
  // Reads are cheap but not free (a verdict per waiter, the tail of two logs);
45
55
  // the app polls every 2 s, so a scan stands for this long.
46
56
  const SCAN_EVERY = 15e3;
57
+ // While the throttle watcher runs it scans every SCAN_EVERY, and a board, the page or the app
58
+ // scan only when nobody has for this long. A scan reads launchd once per service and top for
59
+ // memory: on 2026-11-11 that made every fifteenth-second board 2 s instead of 0.8. With no
60
+ // watcher, they scan every SCAN_EVERY as before.
61
+ const READER_EVERY = 60e3;
62
+ // A liveness hint only (kill 0, no ps): a reused pid costs alerts up to a minute's lag.
63
+ const watching = () => { try { process.kill(Number(fs.readFileSync(path.join(HOME, 'cool.pid'), 'utf8')), 0); return true; } catch (e) { return e.code === 'EPERM'; } };
47
64
  // A wait is long past this, or past WAIT_TIMES its usual wait, whichever is later.
48
65
  const WAIT_FLOOR = 10 * MIN;
49
66
  const WAIT_TIMES = 3;
@@ -103,13 +120,9 @@ function save(st) {
103
120
  }
104
121
 
105
122
  // One scan at a time. Whoever finds the lock taken shows what the file already
106
- // says; a lock left by a process that died is broken after 30 s.
123
+ // says; a lock left by a process that died is taken over at once (src/lock.mjs).
107
124
  function locked(fn) {
108
- try { fs.mkdirSync(LOCK); } catch (e) {
109
- if (e.code !== 'EEXIST') return null;
110
- try { if (now() - fs.statSync(LOCK).mtimeMs < 30e3) return null; fs.rmSync(LOCK, { recursive: true, force: true }); fs.mkdirSync(LOCK); } catch { return null; }
111
- }
112
- try { return fn(); } finally { fs.rmSync(LOCK, { recursive: true, force: true }); }
125
+ return underLock(LOCK, () => fn(), { wait: 0 })?.out ?? null;
113
126
  }
114
127
 
115
128
  // The lines a log gained since the offset last read. A file shorter than the
@@ -153,7 +166,8 @@ function readEvents(st, t) {
153
166
  const x = { at: e.at, id: e.id, who: e.who, res: e.res, cmd: e.cmd, purpose: e.purpose, key: e.key, code: e.code, prio: e.prio, due: e.due };
154
167
  if (by || STOPPED.has(e.code)) st.ended.push({ kind: 'stopped', ...x, by: by || null });
155
168
  else if (e.code != null && e.code !== 0) st.ended.push({ kind: 'failed', ...x });
156
- } else if (e.kind === 'lost' || e.kind === 'crash') st.ended.push({ kind: e.kind, at: e.at, who: e.who, cmd: e.cmd, code: e.code, why: e.why, verb: e.verb });
169
+ } else if (e.kind === 'lockstuck') st.ended.push({ kind: e.kind, at: e.at, key: e.key, pid: e.pid, cmd: e.cmd, held: e.held });
170
+ else if (e.kind === 'lost' || e.kind === 'crash') st.ended.push({ kind: e.kind, at: e.at, who: e.who, cmd: e.cmd, code: e.code, why: e.why, verb: e.verb });
157
171
  }
158
172
  st.ended = st.ended.filter(x => t - x.at < EVENT_KEEP);
159
173
  }
@@ -196,33 +210,35 @@ export function memoryUsers(s, procs, use) {
196
210
  const bytes = use.get(p.pid);
197
211
  if (!bytes) continue;
198
212
  const l = owner.get(p.pid);
199
- const name = l ? `dibs job #${l.id} (${l.who})` : appOf(p, sessions);
200
- const g = groups.get(name) || { name, bytes: 0, n: 0, dibs: !!l, ...(l && { id: l.id }) };
213
+ const [name, cmd] = l ? [`dibs job #${l.id} (${l.who})`] : appOf(p, sessions);
214
+ const g = groups.get(name) || { name, bytes: 0, n: 0, dibs: !!l, ...(l && { id: l.id }), ...(cmd && { cmd: true }) };
201
215
  g.bytes += bytes; g.n++;
202
216
  groups.set(name, g);
203
217
  }
204
218
  return [...groups.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5);
205
219
  }
206
220
 
221
+ // [name, true when it's named by its command]: one of those may be many separate processes.
207
222
  function appOf(p, sessions) {
208
223
  const a = p.args || '';
209
- if (/\blaunchd_sim\b|\/CoreSimulator\/Devices\/|\.simruntime\//.test(a)) return 'the iOS Simulator';
210
- if (/com\.apple\.WebKit\.(WebContent|GPU|Networking)/.test(a)) return 'Safari and other web pages';
224
+ if (/\blaunchd_sim\b|\/CoreSimulator\/Devices\/|\.simruntime\//.test(a)) return ['the iOS Simulator'];
225
+ if (/com\.apple\.WebKit\.(WebContent|GPU|Networking)/.test(a)) return ['Safari and other web pages'];
211
226
  if (/(^|\/)claude(\s|$)/.test(a)) {
212
227
  const x = sessions.get(p.pid);
213
- return x?.name ? `Claude Code session ${x.name}` : `Claude Code (pid ${p.pid})`;
228
+ return [x?.name ? `Claude Code session ${x.name}` : `Claude Code (pid ${p.pid})`];
214
229
  }
215
230
  const app = a.match(/\/([^/]+)\.app\//);
216
- if (app) return app[1];
231
+ if (app) return [app[1]];
217
232
  // A script under an interpreter is the script: "node" alone says nothing about which.
218
233
  const [cmd, ...args] = a.split(/\s+/);
219
234
  const name = path.basename(cmd || `pid ${p.pid}`);
220
235
  const script = INTERPRETERS.test(name) && args.find(x => !x.startsWith('-'));
221
- return script ? `${name} ${path.basename(script)}` : name;
236
+ return [script ? `${name} ${path.basename(script)}` : name, true];
222
237
  }
223
238
 
224
239
  const INTERPRETERS = /^(node|bun|deno|python3?(\.\d+)?|ruby|perl)$/;
225
- const sized = g => `${g.name} (${gb(g.bytes).replace(/G$/, ' GB')}${g.n > 1 && g.name.startsWith('Safari') ? `, ${g.n} pages` : ''})`;
240
+ // A command's count when it's more than one: 25 short-lived curls (2026-11-05) read as one big curl otherwise.
241
+ const sized = g => `${g.name} (${gb(g.bytes).replace(/G$/, ' GB')}${g.n > 1 && g.name.startsWith('Safari') ? `, ${g.n} pages` : g.n > 1 && g.cmd ? `, ${g.n} processes` : ''})`;
226
242
 
227
243
  // Every alert the state calls for now: { id, cause, level, title, fix, after?, at? }.
228
244
  // level: urgent (a person is held up or dibs is broken), warn, or note.
@@ -297,6 +313,13 @@ export function detect({ s, cfg, hist, m, t, st, users }) {
297
313
  out.push({ id: `lost:${x.at}`, cause: 'ended', level: 'urgent', at: x.at, who: x.who,
298
314
  title: `${x.who}'s job was lost${x.code === 77 ? ' after it started' : ' before it started'} at ${stamp(x.at, t)}: ${x.why || x.cmd}`,
299
315
  fix: x.code === 77 ? 'It may have run. Check what it changed before running it again.' : 'It never ran, so it\'s safe to run again.' });
316
+ } else if (x.kind === 'lockstuck') {
317
+ // Open while that same holder still has the lock; it closes the moment it lets go.
318
+ const now = heldBy(paths.lock);
319
+ if (now?.key !== x.key) continue;
320
+ out.push({ id: `lockstuck:${x.key}`, cause: 'dibs', level: 'urgent', at: x.at - x.held,
321
+ title: `dibs is stuck behind pid ${x.pid}${x.cmd ? ` (${x.cmd.slice(0, 80)})` : ''}: it has held the state lock for ${minutes(now.held)}, and every dibs command waits for it`,
322
+ fix: `If pid ${x.pid} is hung, end it and everyone goes on at once: kill ${x.pid}` });
300
323
  } else if (x.kind === 'crash') {
301
324
  out.push({ id: `crash:${x.at}`, cause: 'dibs', level: 'urgent', at: x.at, who: x.who,
302
325
  title: `dibs crashed at ${stamp(x.at, t)} running dibs ${x.verb || ''} for ${x.who}`,
@@ -315,13 +338,13 @@ export function detect({ s, cfg, hist, m, t, st, users }) {
315
338
  if (!h.running)
316
339
  out.push({ id: `service:${k}`, cause: 'dibs', level: 'urgent',
317
340
  title: `dibs's ${k} service isn't running${h.exit ? ` (it last exited with code ${h.exit})` : ''}: ${h.what}`,
318
- fix: `Start it again: dibs service install ${k}. Why it stopped is in ~/.dibs/${k}.log.` });
341
+ fix: `Start it again: dibs service install ${k}. Why it stopped is in ~/.dibs/${logName(k)}.` });
319
342
  for (const k of new Set((st.restarts || []).map(r => r.k))) {
320
343
  const rs = st.restarts.filter(r => r.k === k);
321
344
  const last = rs[rs.length - 1];
322
345
  out.push({ id: `restart:${k}`, cause: 'dibs', level: 'warn', at: rs[0].at,
323
346
  title: `dibs's ${k} service crashed (exit ${last.exit}) and launchd started it again${rs.length > 1 ? `, ${rs.length} times in the last hour` : ''}, last at ${stamp(last.at, t)}`,
324
- fix: `Look in ~/.dibs/${k}.log for why, and report it: dibs ask "the ${k} service keeps exiting with ${last.exit}"` });
347
+ fix: `Look in ~/.dibs/${logName(k)} for why, and report it: dibs ask "the ${k} service keeps exiting with ${last.exit}"` });
325
348
  }
326
349
  if (st.hook?.length) {
327
350
  const last = st.hook[st.hook.length - 1];
@@ -330,11 +353,31 @@ export function detect({ s, cfg, hist, m, t, st, users }) {
330
353
  fix: `Those tool calls ran without dibs's checks. Report it: dibs ask "hook: ${last.msg.slice(0, 60)}"` });
331
354
  }
332
355
 
356
+ // The hard stop (src/preempt.mjs hardStop): a job paused under 1 GB free, whatever it was.
357
+ for (const l of s.leases.filter(x => x.pauses?.some(p => p.hard)))
358
+ out.push({ id: `hardstop:#${l.id}`, cause: 'disk', level: 'urgent', job: l.id, who: l.who, at: l.pausedAt,
359
+ title: `Free disk fell under 1 GB, so dibs paused ${job(l)}, the job writing the most. It resumes once 2 GB is free`,
360
+ fix: diskFix() });
361
+
362
+ // The machine itself, from the throttle watcher.
363
+ let cpu = null;
364
+ try { cpu = JSON.parse(fs.readFileSync(CPU_FILE, 'utf8')); } catch {}
365
+ if (cpu && t - cpu.at < CPU_FRESH) {
366
+ if (cpu.stuckSince && !cpu.swapping)
367
+ out.push({ id: 'cores', cause: 'machine', level: 'urgent', after: STUCK_AFTER, at: cpu.stuckSince,
368
+ title: `The load is ${cpu.load} on ${cpu.cores} cores while ${cpu.idle}% of the CPU sits idle: work is ready to run and some cores have stopped taking it`,
369
+ fix: 'Restart the Mac. On 2026-11-10 nothing else brought its cores back. Until then dibs moves nothing to background priority.' });
370
+ for (const o of cpu.orphans || [])
371
+ out.push({ id: `orphan:${o.pid}`, cause: 'machine', level: 'warn',
372
+ title: `${o.name} ${o.pid} has run ${Math.round(o.age / HOUR)} hours outside dibs, using ${Math.round(o.cpu / HOUR)} CPU-hours, and its script ${o.script} is gone`,
373
+ fix: `Likely left behind by a session that ended. dibs leaves it running; if nobody needs it, end it: kill ${o.pid}` });
374
+ }
375
+
333
376
  // Disk under the floor: nothing new starts.
334
377
  const floor = bytes(cfg.minDisk || '0');
335
378
  if (floor && m.diskFree != null && m.diskFree < floor)
336
379
  out.push({ id: 'disk', cause: 'disk', level: 'urgent',
337
- title: `Free disk is ${gb(m.diskFree).replace(/G$/, ' GB')}, under the ${gb(floor).replace(/G$/, ' GB')} dibs keeps free, so no new job starts`,
380
+ title: `Free disk is ${gb(m.diskFree).replace(/G$/, ' GB')}, under the ${gb(floor).replace(/G$/, ' GB')} dibs keeps free, so only jobs that write next to nothing start; the rest wait for room`,
338
381
  fix: diskFix() });
339
382
  return out;
340
383
  }
@@ -403,10 +446,10 @@ export function merge(st, found, t) {
403
446
  // Read what's new and bring alerts.json up to date, unless another process
404
447
  // did within SCAN_EVERY. Returns the list to show. Never throws: the board,
405
448
  // the watcher and the page call it, and none of them may fail over an alert.
406
- export function scan({ s, cfg, hist, m = machine(), t = now(), force = false } = {}) {
449
+ export function scan({ s, cfg, hist, m = machine(), t = now(), force = false, watcher = false } = {}) {
407
450
  try {
408
451
  const was = load();
409
- if (!force && was.at && t - was.at < SCAN_EVERY) return shown(was, t);
452
+ if (!force && was.at && t - was.at < (watcher || !watching() ? SCAN_EVERY : READER_EVERY)) return shown(was, t);
410
453
  const st = locked(() => {
411
454
  const st = load();
412
455
  // Alerts made by older rules aren't resolved, only no longer said that way: start the open list over.
@@ -418,7 +461,9 @@ export function scan({ s, cfg, hist, m = machine(), t = now(), force = false } =
418
461
  let found = detect({ s, cfg, hist, m, t, st, users });
419
462
  // The machine-wide reading only once memory is what holds jobs back.
420
463
  if (!users && found.some(a => a.want === 'users')) {
421
- users = memoryUsers(s, processes(), memoryUse());
464
+ // Memory first, then the process table it's named from: both as they are now.
465
+ const use = memoryUse();
466
+ users = memoryUsers(s, processesNow(), use);
422
467
  st.top = { at: t, list: users };
423
468
  found = detect({ s, cfg, hist, m, t, st, users });
424
469
  }
@@ -485,6 +530,7 @@ export function alerts(args, cfg) {
485
530
  : `No open alert matches ${which}. dibs alerts lists them.`);
486
531
  }
487
532
  const t = now();
533
+ tableFirst();
488
534
  const s = withState(s => { markIdle(s); return s; });
489
535
  let list = scan({ s, cfg, hist: history(), t, force: true });
490
536
  if (args.includes('--all')) list = shown(load(), t, true);
package/src/board.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  // joined to a coordinator, on every other machine too.
3
3
  import { resCfg } from './config.mjs';
4
4
  import { tag, isMine } from './proc.mjs';
5
- import { idleFor } from './acquire.mjs';
5
+ import { idleFor, UNPOLLED } from './acquire.mjs';
6
6
  import { forecast, byRank, remaining, used, overBy, verdict, memUsed, cpuUsed, shownFree, swapGrowing, diskSqueeze, BREAKER_LINE, QUICK_LINE } from './schedule.mjs';
7
7
  import { grewLine, cappedLine } from './measure.mjs';
8
8
  import { pauseLabel } from './preempt.mjs';
@@ -29,7 +29,6 @@ const blockedBy = v => { const r = waitReason(v); return r && !/^(behind|held by
29
29
  // line and the machine, then a shared rate limit), or, when nothing does, that
30
30
  // nobody has decided for it lately. On 2026-10-20 two test runs showed no
31
31
  // reason at all and didn't start, with free slots and memory.
32
- const UNPOLLED = 3 * 6e4; // a waiter's dibs decides every few seconds, and notes it once a minute (acquire.mjs POLLED_EVERY)
33
32
  function waitingOn(s, q, cfg, hist, t) {
34
33
  const v = verdict(s, q, cfg, hist, t);
35
34
  if (!v.ok) return blockedBy(v);
package/src/broker.mjs CHANGED
@@ -11,12 +11,14 @@ import net from 'node:net';
11
11
  import path from 'node:path';
12
12
  import { spawn, spawnSync } from 'node:child_process';
13
13
  import { fileURLToPath } from 'node:url';
14
- import { HOME, paths, loadConfig } from './config.mjs';
14
+ import { HOME, paths, loadConfig, machine } from './config.mjs';
15
15
  import { pstart, makeAlive } from './proc.mjs';
16
16
  import { processes } from './platform.mjs';
17
17
  import { withState, history, kick, quiet, KEEP_PLACE } from './state.mjs';
18
+ import { sweepLock } from './lock.mjs';
18
19
  import { decide, step, waiter, full, markIdle, saidText, abandon, POLL } from './acquire.mjs';
19
20
  import { byRank } from './schedule.mjs';
21
+ import { inversions, lift } from './override.mjs';
20
22
  import { noticeScan } from './notices.mjs';
21
23
  import { event } from './events.mjs';
22
24
  import { now, noSpace, sleepSync, signalExit, notifyLine, LEAN } from './util.mjs';
@@ -186,17 +188,19 @@ function keepFor(q, shell) {
186
188
  // up on the broker (why is keep: the place stays for its in-process retry).
187
189
  // id 0: interrupted before it knew its id; its place is the one under its pid.
188
190
  export function leaveLine(id, shell, why) {
189
- withState(s => {
191
+ // A low job lifted for this waiter alone goes back down as it leaves (src/override.mjs inversions).
192
+ lift(withState(s => {
190
193
  // Its place by id when it knows it, else by its pid. A place kept with nobody on it (for its own
191
194
  // retry in Node, or taken for gone) is its too: interrupted, it gives that up as well.
192
195
  const q = s.queue.find(x => (id ? x.id === id && (x.pid === shell || (why !== 'keep' && !x.pid)) : x.pid === shell)
193
196
  || (why !== 'keep' && x.keptFor === shell));
194
- if (!q) return;
195
- if (why === 'keep') return keepFor(q, shell);
197
+ if (!q) return [];
198
+ if (why === 'keep') { keepFor(q, shell); return []; }
196
199
  s.queue = s.queue.filter(x => x !== q);
197
200
  if (q.wake?.notify) notified(q, signalExit(why));
198
201
  if (q.wake) event({ kind: 'left', id: q.id, res: q.res, who: q.who, prio: q.prio || 'normal', type: q.kind, ms: now() - q.enq, why });
199
- });
202
+ return inversions(s, loadConfig());
203
+ }));
200
204
  }
201
205
 
202
206
  // --notify's line for a thin wait that ended before its command started (src/commands.mjs notifyOnExit).
@@ -260,7 +264,7 @@ export function broker() {
260
264
  const ctl = new net.Socket({ fd: fs.openSync(paths.ctl, O_RDWR | O_NONBLOCK), readable: true, writable: false });
261
265
  const code = fs.readFileSync(path.join(SRC, 'version.mjs'), 'utf8');
262
266
  const waits = new Map(); // queue id -> its wait (src/acquire.mjs waiter), with its FIFO as out
263
- let cfg = loadConfig(), hist = history(), histAt = 0, beat = 0, idleSince = now(), pending = false, forced = false, pruned = 0, seen = '', full = 0;
267
+ let cfg = loadConfig(), hist = history(), histAt = 0, beat = 0, idleSince = now(), pending = false, forced = false, pruned = 0, seen = '', fullAt = 0;
264
268
 
265
269
  const exit = () => {
266
270
  for (const w of waits.values()) w.out.close();
@@ -284,18 +288,25 @@ export function broker() {
284
288
  pending = forced = false;
285
289
  const t = now();
286
290
  // A release changed the code: the waiters' shells start the new one.
287
- try { if (fs.readFileSync(path.join(SRC, 'version.mjs'), 'utf8') !== code) return leave(true); } catch {}
291
+ // Said in the log, so a waiter's "broker gone, starting another" that follows reads as a release, not a crash.
292
+ try {
293
+ if (fs.readFileSync(path.join(SRC, 'version.mjs'), 'utf8') !== code) {
294
+ event({ kind: 'thin', why: 'a new version of dibs: the broker hands its waiters to a new one', pid: me.pid, waiting: waits.size });
295
+ return leave(true);
296
+ }
297
+ } catch {}
288
298
  if (t - pruned > PRUNE_EVERY) { pruned = t; prune(); }
289
299
  // With nobody to wait for, the lock is taken only to keep the beat fresh.
290
300
  let quietNow = false, text = '';
291
301
  try { text = fs.readFileSync(paths.state, 'utf8'); quietNow = !waits.size && !thinWaiters(JSON.parse(text)).length; } catch {}
292
- if (!quietNow && !kicked && text === seen && t - full < QUIET_POLL && [...waits.values()].every(w => running(w.me.pid))) return;
302
+ if (!quietNow && !kicked && text === seen && t - fullAt < QUIET_POLL && [...waits.values()].every(w => running(w.me.pid))) return;
293
303
  if (quietNow) {
294
304
  if (t - idleSince > IDLE_EXIT) return leave(false);
295
305
  if (t - beat > BEAT) withState(s => { if (s.broker?.pid === me.pid || !s.broker) s.broker = { ...me, beat: (beat = t) }; });
296
306
  return;
297
307
  }
298
- processes(); // read the process table before taking the lock, not while holding it
308
+ processes(); // read the process table and the machine before taking the lock, not while holding it
309
+ machine();
299
310
  noticeScan();
300
311
  try { cfg = loadConfig(); } catch {}
301
312
  try { const m = fs.statSync(paths.history).mtimeMs; if (m !== histAt) { histAt = m; hist = history(); } } catch {}
@@ -347,7 +358,7 @@ export function broker() {
347
358
  }
348
359
  }
349
360
  done();
350
- idleSince = full = now();
361
+ idleSince = fullAt = now();
351
362
  try { seen = fs.readFileSync(paths.state, 'utf8'); } catch {}
352
363
  };
353
364
  const done = () => { for (const [id, w] of waits) if (w.out.done) waits.delete(id); };
@@ -358,8 +369,12 @@ export function broker() {
358
369
  tick();
359
370
  }
360
371
 
361
- // FIFOs of shells that are gone. Only in ~/.dibs/w, the folder dibs made for them.
372
+ // FIFOs of shells that are gone. Only in ~/.dibs/w, the folder dibs made for them. And what writers
373
+ // killed mid-change left beside the state and message locks (src/lock.mjs sweepLock): a claim
374
+ // sweeps too, but only after a death it sees, and the broker is always around while anyone waits.
362
375
  function prune() {
376
+ sweepLock(paths.lock, [paths.state]);
377
+ sweepLock(path.join(HOME, 'messages.lock'), [path.join(HOME, 'messages.json'), path.join(HOME, 'inbox.json'), path.join(HOME, 'listeners.json')]);
363
378
  let names = [];
364
379
  try { names = fs.readdirSync(WAKE); } catch { return; }
365
380
  for (const n of names) {
package/src/commands.mjs CHANGED
@@ -3,12 +3,13 @@ import fs from 'node:fs';
3
3
  import net from 'node:net';
4
4
  import path from 'node:path';
5
5
  import { spawn } from 'node:child_process';
6
+ import { fileURLToPath } from 'node:url';
6
7
  import { resCfg, machine, HOME, paths, PACES, PACE_OVERLAP, paced, paceKnobs, hardware, writePace, loadConfig } from './config.mjs';
7
8
  import { logChange } from './owner.mjs';
8
- import { identity, isMine, tag } from './proc.mjs';
9
+ import { identity, isMine, tag, makeAlive } from './proc.mjs';
9
10
  import { launch, stopTree, processes, descendants, which, starts, scoped, watchdog, OS } from './platform.mjs';
10
- import { withState, withStateIfRoom, history, record, KEEP_PLACE } from './state.mjs';
11
- import { acquire, markIdle, idleFor, describeLease, commandKey, holdUntil, outerLease, defaultMaxWait, HOLD_CAP } from './acquire.mjs';
11
+ import { withState, withStateIfRoom, history, record, peakOf, peek, pidsOf, KEEP_PLACE } from './state.mjs';
12
+ import { acquire, markIdle, tableFirst, idleFor, describeLease, commandKey, holdUntil, outerLease, defaultMaxWait, HOLD_CAP } from './acquire.mjs';
12
13
  import { rank, rankParts, byRank, forecast, verdict, remaining, used, sum, lent, pausedFor, overLoad, loadWhy, loadAhead, holdingOf, swapping, swapWhy, diskSqueeze, BACKGROUND, roomFor } from './schedule.mjs';
13
14
  import { noticeHandler } from './preempt.mjs';
14
15
  import { checkout, checkin, jobSize } from './simpool.mjs';
@@ -19,7 +20,7 @@ import { bold, dim, amber, columns, wrap, quoted } from './style.mjs';
19
20
  import { quotasNow, isQuota } from './quota.mjs';
20
21
  import { agentsNow } from './agents.mjs';
21
22
  import { forYou } from './questions.mjs';
22
- import { notesForYou, listeners } from './talk.mjs';
23
+ import { notesForYou, listeners, listenerPids } from './talk.mjs';
23
24
  import { remoteConf, shortHost } from './remote.mjs';
24
25
  import { sample, sized, grewLine, grewPlain, tellOverAsk } from './measure.mjs';
25
26
  import { clash, isFiles, short, takeAgent, callKey, sameAgent, fileKey, shellRes, projectKey } from './files.mjs';
@@ -153,7 +154,7 @@ export async function run(o, cfg) {
153
154
  + `${l.stopReason ? '' : ' Find out why before running it again: dibs history, or ask whoever stopped it.'}`);
154
155
  s.leases = s.leases.filter(x => x.id !== lease.id);
155
156
  // A failing run is often the one that ran out of memory: its size counts too.
156
- if (l && (code === 0 || l.peak?.mem)) record(l.key, now() - l.start - pausedFor(l), l.who, l.peak, code !== 0);
157
+ if (l && (code === 0 || l.peak?.mem)) record(l.key, now() - l.start - pausedFor(l), l.who, peakOf(l), code !== 0);
157
158
  if (l?.quick) took = now() - l.start - pausedFor(l);
158
159
  tellOverAsk(l);
159
160
  });
@@ -186,8 +187,11 @@ export async function run(o, cfg) {
186
187
  // Low and idle work can be paused for urgent work (src/preempt.mjs); say so when it happens.
187
188
  // Notices about this job and others go to their agents while it runs (src/notices.mjs).
188
189
  setInterval(noticeScan, NOTICE_EVERY).unref();
190
+ // Windows has no SIGUSR2: there each tick of this run reads its own lease (a plain read, no lock)
191
+ // and says the same things, a few seconds later at most.
189
192
  const notify = OS !== 'windows';
190
- if (notify) process.on('SIGUSR2', noticeHandler(() => withStateIfRoom(s => s.leases.find(x => x.id === lease.id))));
193
+ const heard = noticeHandler(() => (notify ? withStateIfRoom(s => s.leases.find(x => x.id === lease.id)) : peek().leases?.find(x => x.id === lease.id)));
194
+ if (notify) process.on('SIGUSR2', heard);
191
195
  // The command starts only once its group is on record, so a wrapper killed
192
196
  // at any point has its job reaped with it, or the job never starts.
193
197
  // The gate shell execs the command, so its start time is the command's.
@@ -207,7 +211,7 @@ export async function run(o, cfg) {
207
211
  if (child.pid) wd.add(child.pid);
208
212
  if (child.pid && !pgstart) withStateIfRoom(note({ pgstart: starts([child.pid])?.get(child.pid) ?? null }));
209
213
  // Each tick also measures every lease on the machine, when it's this run's turn (src/measure.mjs).
210
- tracker = setInterval(() => { track(); sample(); }, 3000);
214
+ tracker = setInterval(() => { track(); sample(); if (!notify) heard(); }, 3000);
211
215
  tracker.unref();
212
216
  child.on('error', e => { say(`couldn't start ${o.cmd[0]}: ${e.message}`); finish(127); });
213
217
  // No last track(): once the child has exited, its process groups are found by the
@@ -223,7 +227,7 @@ function requeue(s, l, cfg) {
223
227
  const t = now();
224
228
  s.leases = s.leases.filter(x => x !== l);
225
229
  // What it really used goes into the history, so every later run of the command is planned at it too.
226
- if (l.peak?.mem) record(l.key, t - l.start - pausedFor(l), l.who, l.peak, true);
230
+ if (l.peak?.mem) record(l.key, t - l.start - pausedFor(l), l.who, peakOf(l), true);
227
231
  const res = l.res;
228
232
  const front = Math.min(l.start - (l.waited || 0), ...s.queue.filter(q => q.res.some(r => res.includes(r))).map(q => q.enq)) - 1;
229
233
  // Booked at what it really used, up to all the memory dibs shares out (usual keeps the rest).
@@ -242,12 +246,15 @@ function requeue(s, l, cfg) {
242
246
  // Run the same dibs run again, as this same process where Node allows it
243
247
  // (process.execve keeps the pid the agent's tool call is waiting on), so it
244
248
  // waits in line like any other and picks up the place requeue() kept.
245
- const BIN = path.join(path.dirname(new URL(import.meta.url).pathname), '..', 'bin', 'dibs.mjs');
249
+ const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'dibs.mjs');
246
250
  let handedOn = false;
247
251
  function runAgain(o, lease, again) {
248
252
  say(again.why === 'over'
249
253
  ? `stopped #${lease.id}: it was using far more memory than it booked while swap filled the disk. It's back at the front of the line as #${again.id},`
250
254
  + ` booked at ${gb(again.mem)}, and runs again from the start once that much memory is really free. Nothing for you to do: this call carries on.`
255
+ : again.why === 'memory'
256
+ ? `stopped #${lease.id}: it was paused for memory pressure, which stayed critical, and a paused job's memory only goes to swap.`
257
+ + ` It's back at the front of the line as #${again.id} and runs again from the start when there's room. Nothing for you to do: this call carries on.`
251
258
  : `stopped #${lease.id}: it sat paused for low disk while its memory went to swap and filled the disk.`
252
259
  + ` It's back at the front of the line as #${again.id} and runs again from the start when there's room. Nothing for you to do: this call carries on.`);
253
260
  const args = process.argv.slice(2);
@@ -430,7 +437,7 @@ export function when(o, cfg) {
430
437
  const key = `${res.join(',')}|${o.cmd ? commandKey(o.cmd) : 'hold'}`;
431
438
  const probe = { id: -1, res, enq: t, pid: 1, who: id.who, agent: id.agent, spid: id.spid, prio: o.prio, by: o.by, est: o.est, declared: o.mem != null,
432
439
  ...sized(jobSize(cfg, res, o), hist, key, cfg), key };
433
- const s = withState(s => { markIdle(s); return s; });
440
+ const s = marked();
434
441
  probe.holding = holdingOf(s, probe, cfg, t);
435
442
  const v = verdict(s, probe, cfg, hist, t);
436
443
  const at = v.ok ? t : forecast(s, cfg, hist, t, probe).get(-1);
@@ -461,7 +468,7 @@ export function why(o, cfg) {
461
468
  const id = caller(o);
462
469
  const hist = history();
463
470
  const t = now();
464
- const s = withState(s => { markIdle(s); return s; });
471
+ const s = marked();
465
472
  const mine = s.queue.filter(q => q.pid && ours(q, id));
466
473
  if (!mine.length) {
467
474
  const holds = s.leases.filter(l => ours(l, id));
@@ -530,14 +537,14 @@ export function who(o, cfg) {
530
537
  if (!o.res.length) return status(o, cfg);
531
538
  const hist = history();
532
539
  const t = now();
533
- const s = withState(s => { markIdle(s); return s; });
540
+ const s = marked();
534
541
  const order = s.queue.filter(q => q.pid).sort(byRank(hist, t));
535
542
  const rows = [];
536
543
  for (const r of o.res) {
537
544
  // A file lease is held by whoever holds any path overlapping it.
538
545
  // One holder with two overlapping file leases is still one holder.
539
546
  const held = s.leases.filter(l => l.res.some(x => clash(x, r))).filter((l, i, all) => all.findIndex(x => x.who === l.who) === i);
540
- const next = order.filter(q => q.res.some(x => clash(x, r))).map(q => q.who);
547
+ const next = order.filter(q => q.res.some(x => clash(x, r))).map(q => `${q.who} (#${q.id})`); // the id, for dibs why, boost or stop
541
548
  const n = named(cfg, r);
542
549
  const room = isFiles(r) ? 'nobody has these files or any that overlap them' : `${resCfg(cfg, r).slots - used(s, r)} of ${resCfg(cfg, r).slots} free`;
543
550
  const hold = isFiles(r) ? '' : machineHold(s, cfg);
@@ -650,6 +657,9 @@ export function pace(args) {
650
657
  // The bar is lower than dibs throttle's (50%): this only reports, it doesn't act.
651
658
  const BUSY_CPU = 40; // % of a core
652
659
  function untracked(s) {
660
+ // Windows reads CPU per process by sampling twice a second apart (platform.mjs): 1.8 s a call
661
+ // on a CI runner, too much for every look at the board, for a line that's only informative.
662
+ if (OS === 'windows') return [];
653
663
  const ours = new Set(s.leases.flatMap(l => [l.pgid, ...(l.groups || [])]).filter(Boolean));
654
664
  const groups = new Map();
655
665
  for (const p of processes()) {
@@ -701,9 +711,22 @@ export function boardJson(s, cfg, { hist = history(), m = machine(), t = now(),
701
711
  };
702
712
  }
703
713
 
714
+ // The state with idle runs marked.
715
+ function marked() {
716
+ tableFirst();
717
+ return withState(s => { markIdle(s); return s; });
718
+ }
719
+
720
+ // Plain dibs never hangs: behind a holder that won't let go of the state lock, the board shows the
721
+ // state as last written, and the alert that says who dibs is stuck behind.
722
+ const BOARD_WAIT = 2000;
704
723
  export async function status(o, cfg) {
705
724
  const hist = history();
706
- const s = withState(s => { markIdle(s); return s; });
725
+ // One ps for the start times of the state's pids and the listeners' (src/proc.mjs keeps
726
+ // them 10 s): the state lock's own read and the board's line of listeners took one each.
727
+ try { makeAlive([...pidsOf(peek()), ...listenerPids()]); } catch {}
728
+ tableFirst();
729
+ const s = withState(s => { markIdle(s); return s; }, BOARD_WAIT) ?? peek();
707
730
  const m = machine();
708
731
  const t = now();
709
732
  // A broken remote.json still leaves this machine's board worth showing.
package/src/config.mjs CHANGED
@@ -2,7 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
- import { pressure, memPressure, dibsMem } from './platform.mjs';
5
+ import { pressure, dibsMem } from './platform.mjs';
6
6
  import { isFiles, FILES_COST } from './files.mjs';
7
7
  import { die, ms, now, bytes } from './util.mjs';
8
8
 
@@ -11,6 +11,7 @@ export const paths = {
11
11
  state: path.join(HOME, 'state.json'),
12
12
  lock: path.join(HOME, 'lock'),
13
13
  history: path.join(HOME, 'history.jsonl'),
14
+ historyOlder: path.join(HOME, 'history.1.jsonl'), // the one before, kept by rotate() in src/events.mjs
14
15
  config: path.join(HOME, 'config.json'),
15
16
  seen: path.join(HOME, 'seen.json'),
16
17
  ctl: path.join(HOME, 'ctl'), // the broker's control FIFO (src/broker.mjs)
@@ -304,21 +305,37 @@ export const swapGrowth = (used, t = now()) => trends(used, null, t).swapGrowth;
304
305
 
305
306
  // Free disk and how fast it falls, swap and how fast it grows, memory
306
307
  // pressure, OS-reported free memory and load. Cached for 3s because waiters
307
- // poll and each reading costs a process spawn. DIBS_FAKE_MACHINE may give
308
+ // poll and each reading costs process spawns. The cache is shared through
309
+ // MACHINE_FILE: on 2026-11-11 a dozen waiters each took their own reading,
310
+ // three spawns of 100 ms to 1.8 s apiece on a Mac at load 30, most of them
311
+ // while holding the state lock. DIBS_FAKE_MACHINE may give
308
312
  // swapGrowth, diskDrain, drainMs, swapRecent and drainRecent; otherwise they
309
313
  // come from the readings file, with the fake swapUsed and diskFree.
310
314
  let cache = null;
315
+ const MACHINE_FILE = path.join(HOME, 'machine.json');
316
+ const MACHINE_FRESH = 3000;
317
+ const fresh = m => Number.isFinite(m?.at) && now() - m.at < MACHINE_FRESH && m.at <= now();
318
+ function lastReading() {
319
+ try { return JSON.parse(fs.readFileSync(MACHINE_FILE, 'utf8')); } catch { return null; }
320
+ }
321
+ function shareReading(m) {
322
+ const tmp = `${MACHINE_FILE}.${process.pid}`;
323
+ try { fs.writeFileSync(tmp, JSON.stringify(m)); fs.renameSync(tmp, MACHINE_FILE); } catch { try { fs.rmSync(tmp, { force: true }); } catch {} }
324
+ }
311
325
  export function machine() {
312
326
  if (process.env.DIBS_FAKE_MACHINE) {
313
327
  const m = { at: now(), load: 0, cores: 8, dibsMem: 0, ...JSON.parse(process.env.DIBS_FAKE_MACHINE) };
328
+ // DIBS_FAKE_DISK names a file holding the free disk in bytes, read at each call, so a test can free disk under a waiter.
329
+ if (process.env.DIBS_FAKE_DISK) m.diskFree = Number(fs.readFileSync(process.env.DIBS_FAKE_DISK, 'utf8'));
314
330
  // A fake that gives the 5-minute totals but not the recent ones is still moving.
315
331
  if (m.swapGrowth != null && m.diskDrain != null) return { drainMs: SWAP_WINDOW, swapRecent: m.swapGrowth, drainRecent: m.diskDrain, ...m };
316
332
  const t = trends(m.swapUsed, m.diskFree, m.at);
317
333
  return { ...m, swapGrowth: m.swapGrowth ?? t.swapGrowth, diskDrain: m.diskDrain ?? t.diskDrain, drainMs: m.drainMs ?? t.drainMs,
318
334
  swapRecent: m.swapRecent ?? (m.swapGrowth != null ? m.swapGrowth : t.swapRecent), drainRecent: m.drainRecent ?? (m.diskDrain != null ? m.diskDrain : t.drainRecent) };
319
335
  }
320
- if (cache && now() - cache.at < 3000) return cache;
336
+ if (fresh(cache)) return cache;
321
337
  // dibsMem, the full process table, only when swap is in question (schedule.mjs swapNotOurs).
322
- const m = { at: now(), ...pressure(HOME), vmPressure: memPressure() };
338
+ let m = lastReading();
339
+ if (!fresh(m)) shareReading(m = { at: now(), ...pressure(HOME, m) });
323
340
  return (cache = { ...m, ...trends(m.swapUsed, m.diskFree, m.at) });
324
341
  }