@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/platform.mjs CHANGED
@@ -12,33 +12,56 @@ export const OS = process.platform === 'win32' ? 'windows' : process.platform ==
12
12
  const WIN = OS === 'windows';
13
13
 
14
14
  // Output of a command, or null when it couldn't run at all (spawn failed under
15
- // memory pressure, killed by a signal). Callers must not read null as "nothing".
16
- function tryRun(cmd, args) {
17
- try { return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true }); }
15
+ // memory pressure, killed by a signal, or no answer in RUN_LIMIT). Callers must not read null as "nothing".
16
+ // Some of these run under the state lock (killLease reaping a dead job), where a ps that never
17
+ // returns would stop every dibs command: no process-table read gets longer than this.
18
+ const RUN_LIMIT = 15e3;
19
+ function tryRun(cmd, args, timeout = RUN_LIMIT) {
20
+ try { return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, timeout }); }
18
21
  catch (e) { return typeof e.status === 'number' ? e.stdout || '' : null; } // ps exits 1 when any pid is gone
19
22
  }
20
23
  const run = (cmd, args) => tryRun(cmd, args) ?? '';
21
- const ps = script => tryRun('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]);
24
+ // A PowerShell that stalls (rebuilding its module cache, say) is "can't tell", not a hung dibs.
25
+ const ps = script => tryRun('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], 30e3);
22
26
 
23
27
  // pid -> start time string. Comparing start times keeps a recycled pid from
24
28
  // passing as a live holder. null when the process table couldn't be read.
25
29
  // The highest pid each system hands out (macOS's PID_MAX, Linux's PID_MAX_LIMIT).
26
30
  // ps refuses a list with anything past it and prints nothing for the rest.
27
31
  const PID_MAX = OS === 'macos' ? 99999 : OS === 'linux' ? 4194304 : Infinity;
32
+ const START_TTL = 30e3, winStarts = new Map();
33
+ const exists = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
28
34
  export function starts(pids) {
29
35
  const out = new Map();
30
36
  // One bad number in the state file mustn't make every holder look dead.
31
37
  pids = [...new Set(pids.filter(p => Number.isInteger(p) && p > 0 && p <= PID_MAX))];
32
38
  if (!pids.length) return out;
33
39
  if (WIN) {
34
- const txt = ps(`Get-CimInstance Win32_Process -Filter "${pids.map(p => `ProcessId=${p}`).join(' OR ')}" | ForEach-Object { "$($_.ProcessId) $($_.CreationDate.ToFileTimeUtc())" }`);
40
+ // A start time read in the last START_TTL stands while kill 0 (cheap here)
41
+ // finds the pid alive at every look, and is dropped the first time it doesn't.
42
+ // Each read is a PowerShell, about 0.4 s of CPU: a dozen waiters polling
43
+ // each read fresh kept a CI runner's cores busy and true took 40 s to run.
44
+ // A new process (dibs stop, cancel) starts with nothing kept, so reads fresh.
45
+ const now = Date.now(), need = [];
46
+ for (const pid of pids) {
47
+ const c = winStarts.get(pid);
48
+ if (!c || now - c.at >= START_TTL) need.push(pid);
49
+ else if (exists(pid)) out.set(pid, c.start);
50
+ else winStarts.delete(pid);
51
+ }
52
+ if (!need.length) return out;
53
+ // Get-Process, not a CIM query: 0.3 s against 0.5 s on a CI runner, paid by every dibs call that reads the state.
54
+ const txt = ps(`Get-Process -Id ${need.join(',')} -ErrorAction SilentlyContinue | ForEach-Object { "$($_.Id) $($_.StartTime.ToFileTimeUtc())" }`);
35
55
  if (txt == null) return null;
36
- for (const line of txt.split(/\r?\n/)) { const m = line.trim().match(/^(\d+)\s+(\d+)$/); if (m) out.set(Number(m[1]), m[2]); }
56
+ for (const line of txt.split(/\r?\n/)) {
57
+ const m = line.trim().match(/^(\d+)\s+(\d+)$/);
58
+ if (m) { out.set(Number(m[1]), m[2]); winStarts.set(Number(m[1]), { start: m[2], at: now }); }
59
+ }
37
60
  return out;
38
61
  }
39
62
  // ps exits 1 with no output when every pid is gone, and also when it refuses
40
63
  // the list (it says why on stderr). The second is "can't tell", not "all dead".
41
- const r = spawnSync('ps', ['-o', 'pid=,lstart=', '-p', pids.join(',')], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
64
+ const r = spawnSync('ps', ['-o', 'pid=,lstart=', '-p', pids.join(',')], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: RUN_LIMIT });
42
65
  if (r.status == null || (r.status !== 0 && !r.stdout && r.stderr.trim())) return null;
43
66
  const txt = r.stdout;
44
67
  for (const line of txt.split('\n')) {
@@ -48,11 +71,42 @@ export function starts(pids) {
48
71
  return out;
49
72
  }
50
73
 
74
+ // How long each process has run and the CPU time it has used, in ms, from one ps.
75
+ // Empty on Windows. ps writes both as [[dd-]hh:]mm:ss, CPU time with hundredths.
76
+ export function duration(text) {
77
+ const m = String(text).trim().match(/^(?:(\d+)-)?([\d:]+)(?:\.(\d+))?$/);
78
+ if (!m) return null;
79
+ const parts = m[2].split(':').map(Number).reverse();
80
+ const secs = (parts[0] || 0) + (parts[1] || 0) * 60 + (parts[2] || 0) * 3600 + Number(m[1] || 0) * 86400;
81
+ return secs * 1000 + (m[3] ? Number(`0.${m[3]}`) * 1000 : 0);
82
+ }
83
+ export function runtimes(pids) {
84
+ const out = new Map();
85
+ pids = [...new Set(pids.filter(p => Number.isInteger(p) && p > 0 && p <= PID_MAX))];
86
+ if (WIN || !pids.length) return out;
87
+ for (const line of run('ps', ['-o', 'pid=,etime=,time=', '-p', pids.join(',')]).split('\n')) {
88
+ const [pid, age, cpu] = line.trim().split(/\s+/);
89
+ const a = duration(age), c = duration(cpu);
90
+ if (pid && a != null && c != null) out.set(Number(pid), { age: a, cpu: c });
91
+ }
92
+ return out;
93
+ }
94
+
51
95
  // Parent pid and executable name, for walking up to the owning agent.
96
+ // On Windows each PowerShell CIM read costs about half a second, and a walk up
97
+ // to the agent is a dozen levels: one read of the whole table answers them all.
98
+ let parentCache = null;
52
99
  export function parent(pid) {
53
100
  if (WIN) {
54
- const m = (ps(`$p = Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; "$($p.ParentProcessId) $($p.Name)"`) ?? '').trim().match(/^(\d+)\s+(.*)$/);
55
- return m ? { ppid: Number(m[1]), name: m[2].replace(/\.exe$/i, '') } : null;
101
+ if (!parentCache || Date.now() - parentCache.at > 5000) {
102
+ const table = new Map();
103
+ for (const l of (ps('Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,Name | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId) $($_.Name)" }') ?? '').split(/\r?\n/)) {
104
+ const m = l.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);
105
+ if (m) table.set(Number(m[1]), { ppid: Number(m[2]), name: m[3].replace(/\.exe$/i, '') });
106
+ }
107
+ parentCache = { at: Date.now(), table };
108
+ }
109
+ return parentCache.table.get(Number(pid)) ?? null;
56
110
  }
57
111
  const m = run('ps', ['-o', 'ppid=,comm=', '-p', String(pid)]).trim().match(/^(\d+)\s+(.*)$/);
58
112
  if (!m) return null;
@@ -94,6 +148,13 @@ const DIBS_PROC = /^\S*\bnode\s+(?:-\S+\s+)*\S*(?:\/bin\/dibs|\/dibs\.mjs)(?:\s|
94
148
  export const isDibs = p => DIBS_PROC.test(p.args);
95
149
  export const dibsMem = (procs = processes()) => procs.reduce((a, p) => a + (isDibs(p) ? p.rss || 0 : 0), 0);
96
150
 
151
+ // The process table as it is now, not as the last 5 seconds' cache had it: for joining with another
152
+ // reading by pid, where a pid that ended meanwhile would carry its name onto nothing.
153
+ export function processesNow() {
154
+ procCache = null;
155
+ return processes();
156
+ }
157
+
97
158
  // Every process group that has a process in it right now.
98
159
  export function liveGroups() {
99
160
  procCache = null;
@@ -125,9 +186,9 @@ export function descendants(pid) {
125
186
  // smaps_rollup, which splits shared pages between the processes sharing them.
126
187
  // Windows: null. DIBS_FAKE_FOOTPRINT names a JSON file of { pid: bytes } for tests.
127
188
  const UNITS = { B: 1, K: 1024, M: 1024 ** 2, G: 1024 ** 3, T: 1024 ** 4 };
128
- // Every process's memory, the way Activity Monitor's Memory column adds it up
129
- // on macOS: top's MEM plus CMPRS, what it holds in RAM plus what the system
130
- // squeezed of it. For telling the person what to close (src/alerts.mjs), so
189
+ // Every process's memory, the way Activity Monitor's Memory column shows it on
190
+ // macOS: its physical footprint, top's MEM, which already counts what the system
191
+ // compressed of it. For telling the person what to close (src/alerts.mjs), so
131
192
  // all processes, not only dibs's. Linux: resident memory. DIBS_FAKE_MEMORY,
132
193
  // a JSON file of { pid: bytes }, stands in for tests.
133
194
  export function memoryUse() {
@@ -135,12 +196,17 @@ export function memoryUse() {
135
196
  try { return new Map(Object.entries(JSON.parse(fs.readFileSync(process.env.DIBS_FAKE_MEMORY, 'utf8'))).map(([p, b]) => [Number(p), b])); } catch { return new Map(); }
136
197
  }
137
198
  if (OS !== 'macos') return new Map(processes().map(p => [p.pid, p.rss || 0]));
138
- const txt = tryRun('top', ['-l', '1', '-o', 'mem', '-stats', 'pid,mem,cmprs']);
199
+ return topMemory(tryRun('top', ['-l', '1', '-o', 'mem', '-stats', 'pid,mem']));
200
+ }
201
+ // top's MEM by pid. MEM is the footprint, compressed pages included: adding CMPRS on top counted
202
+ // those twice, and under swap, when this is read, most of a process can be compressed. On
203
+ // 2026-11-05 a WebKit page read 813 MB in MEM and 805 MB in CMPRS, and footprint -p said 813 MB.
204
+ export function topMemory(txt) {
139
205
  const out = new Map();
140
206
  const size = x => { const m = x?.match(/^([\d.]+)([BKMGT])[+-]?$/); return m ? Number(m[1]) * UNITS[m[2]] : 0; };
141
207
  for (const line of (txt || '').split('\n')) {
142
208
  const f = line.trim().split(/\s+/);
143
- if (f.length === 3 && /^\d+$/.test(f[0])) out.set(Number(f[0]), size(f[1]) + size(f[2]));
209
+ if (f.length >= 2 && /^\d+$/.test(f[0])) out.set(Number(f[0]), size(f[1]));
144
210
  }
145
211
  return out;
146
212
  }
@@ -203,18 +269,28 @@ const winQuote = a => (/^[\w@%+=:,./\\-]+$/.test(a) ? a : `"${a.replace(/(\\*)"/
203
269
  // process group first, so a caller killed in between leaves nothing untracked.
204
270
  // If the caller dies before go(), the pipe closes and the command never starts.
205
271
  const GATE = 'IFS= read -r _ <&3 || exit 125; exec 3<&-; exec "$@"';
272
+ // A command line as the system can start it: on Windows a .cmd or .bat (npm's shims,
273
+ // boat's) runs only through cmd.exe. Spawn it with windowsVerbatimArguments when cmd[0] is cmd.exe.
274
+ export function runnable(argv, env = process.env) {
275
+ return WIN && /\.(cmd|bat)$/i.test(which(argv[0], env) || '') ? ['cmd.exe', '/d', '/s', '/c', `"${argv.map(winQuote).join(' ')}"`] : argv;
276
+ }
277
+
278
+ // Windows has no exec, so its gate is a small Node that waits the same way, then
279
+ // runs the command and passes on its exit code. Stopping the gate's tree (taskkill /T)
280
+ // stops the command with it.
281
+ const WIN_GATE = "const fs=require('fs');let n=0;try{n=fs.readSync(3,Buffer.alloc(3),0,3,null)}catch{}if(!n)process.exit(125);fs.closeSync(3);"
282
+ + "const[c,...a]=JSON.parse(process.argv[1]);const r=require('child_process').spawnSync(c,a,{stdio:'inherit',windowsVerbatimArguments:c==='cmd.exe'});"
283
+ + "if(r.error){process.stderr.write(r.error.message+'\\n');process.exit(127)}process.exit(r.status??1)";
206
284
  export function launch(argv, { env, background = false, gate = false }) {
207
- let cmd = argv;
208
- if (WIN && /\.(cmd|bat)$/i.test(which(argv[0], env) || '')) cmd = ['cmd.exe', '/d', '/s', '/c', `"${argv.map(winQuote).join(' ')}"`];
209
- const gated = gate && !WIN;
210
- if (gated) cmd = ['/bin/sh', '-c', GATE, 'dibs', ...cmd];
211
- const child = spawn(cmd[0], cmd.slice(1), { stdio: gated ? ['inherit', 'inherit', 'inherit', 'pipe'] : 'inherit',
285
+ let cmd = runnable(argv, env);
286
+ if (gate) cmd = WIN ? [process.execPath, '-e', WIN_GATE, JSON.stringify(cmd)] : ['/bin/sh', '-c', GATE, 'dibs', ...cmd];
287
+ const child = spawn(cmd[0], cmd.slice(1), { stdio: gate ? ['inherit', 'inherit', 'inherit', 'pipe'] : 'inherit',
212
288
  detached: !WIN, env, windowsHide: false, windowsVerbatimArguments: cmd[0] === 'cmd.exe' });
213
289
  // Lowered from outside, as the throttle watcher does, so dibs boost can raise it again: on macOS
214
290
  // a process started under `taskpolicy -b` keeps background QoS whatever `taskpolicy -B -p` says.
215
291
  // Its children inherit it. Gated, the command doesn't start until it's lowered.
216
292
  if (background && child.pid) lower(child.pid);
217
- child.go = () => { if (gated) child.stdio[3].end('go\n'); };
293
+ child.go = () => { if (gate) child.stdio[3].end('go\n'); };
218
294
  return child;
219
295
  }
220
296
 
@@ -287,20 +363,46 @@ export function raise(pid) {
287
363
  export function freeDisk(dir) {
288
364
  try { const st = fs.statfsSync(dir); return st.bavail * st.bsize; } catch { return null; }
289
365
  }
366
+ // The volume's whole size: a job that needs more can never start there, however long it waits.
367
+ export function diskSize(dir) {
368
+ try { const st = fs.statfsSync(dir); return st.blocks * st.bsize; } catch { return null; }
369
+ }
290
370
 
291
371
  // Free disk where dibs lives, swap in use, % of memory free, 1-minute load.
292
372
  // Windows has no load average, so CPU busy % across all cores stands in for it.
293
- export function pressure(dir) {
294
- const diskFree = freeDisk(OS === 'macos' ? '/System/Volumes/Data' : dir);
373
+ // The CPU's busy and total time so far, summed over every core (ms).
374
+ export function cpuTicks() {
375
+ let busy = 0, total = 0;
376
+ for (const { times: c } of os.cpus()) { busy += c.user + c.nice + c.sys + c.irq; total += c.user + c.nice + c.sys + c.irq + c.idle; }
377
+ return { busy, total };
378
+ }
379
+ // Cores in use from two cpuTicks readings this far apart: closer is noise,
380
+ // further is an average that hides what's happening now.
381
+ const BUSY_GAP_MIN = 1000, BUSY_GAP_MAX = 60e3;
382
+ export function busyBetween(prev, ticks, gap, cores) {
383
+ const dt = ticks.total - (prev?.total ?? NaN);
384
+ if (!(gap >= BUSY_GAP_MIN && gap <= BUSY_GAP_MAX && dt > 0)) return null;
385
+ return Math.max(0, (ticks.busy - prev.busy) / dt) * cores;
386
+ }
387
+
388
+ // prev: an earlier reading's { at, ticks }, from which the cores in use come
389
+ // without ps (src/config.mjs machine keeps the last one).
390
+ export function pressure(dir, prev = null) {
391
+ const vol = OS === 'macos' ? '/System/Volumes/Data' : dir;
392
+ const diskFree = freeDisk(vol), diskTotal = diskSize(vol);
295
393
  let swapUsed = 0, swapFiles = null, memFree = Math.round(100 * os.freemem() / os.totalmem()), memAvail = null;
394
+ let vmPressure;
296
395
  if (OS === 'macos') {
297
- const sw = run('sysctl', ['-n', 'vm.swapusage']).match(/used = ([\d.]+)M/);
396
+ // One sysctl for all three: under heavy load each spawn costs 100 to 300 ms.
397
+ const [usage = '', level = '', vmLevel = ''] = run('sysctl', ['-n', 'vm.swapusage', 'kern.memorystatus_level', MEM_PRESSURE]).split('\n');
398
+ const sw = usage.match(/used = ([\d.]+)M/);
298
399
  if (sw) swapUsed = parseFloat(sw[1]) * 1024 ** 2;
299
400
  // The swap files' total size, which is what swap takes from the disk: macOS adds them a gigabyte at a time, ahead of what's used.
300
- const tot = run('sysctl', ['-n', 'vm.swapusage']).match(/total = ([\d.]+)M/);
401
+ const tot = usage.match(/total = ([\d.]+)M/);
301
402
  if (tot) swapFiles = parseFloat(tot[1]) * 1024 ** 2;
302
- const lvl = Number(run('sysctl', ['-n', 'kern.memorystatus_level']));
403
+ const lvl = Number(level);
303
404
  if (lvl) memFree = lvl; // counts reclaimable cache as free, unlike os.freemem
405
+ vmPressure = PRESSURE_LEVEL[Number(vmLevel)] ?? null;
304
406
  memAvail = vmAvail(run('vm_stat', []));
305
407
  } else if (OS === 'linux') {
306
408
  try {
@@ -311,22 +413,39 @@ export function pressure(dir) {
311
413
  swapUsed = (mi.SwapTotal || 0) - (mi.SwapFree || 0);
312
414
  } catch {}
313
415
  }
314
- let load = os.loadavg()[0];
315
- if (WIN) {
316
- const pct = Number(ps('(Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average'));
317
- load = (pct || 0) / 100 * os.cpus().length;
318
- }
416
+ // Windows has no load average: the cores' busy share over a short window stands in, times
417
+ // the core count. Read from os.cpus() in-process: the CIM processor query it replaces took
418
+ // 1.5 s on a CI runner, and every dibs call reads the machine.
419
+ const load = WIN ? cpuBusy() * os.cpus().length : os.loadavg()[0];
319
420
  // Cores actually in use. The load average also counts processes waiting on
320
421
  // disk, so heavy swapping can read 20 on a machine that's nearly idle.
321
422
  // Just the CPU column (13 ms) unless the full table is fresh anyway: the full one,
322
423
  // with every command line, took 60 ms of each dibs run's start on a busy Mac.
424
+ // The CPU's own counters since the last reading cost nothing; ps -Ao pcpu took
425
+ // 0.1 to 1.8 s on 2026-11-11, at load 30 with a thousand processes.
323
426
  let busy = null;
427
+ const ticks = cpuTicks(), cores = os.cpus().length;
324
428
  if (!WIN) {
325
- const cpus = procCache && Date.now() - procCache.at < 5000 ? procCache.list.map(p => p.cpu || 0)
326
- : run('ps', ['-Ao', 'pcpu=']).split('\n').map(Number).filter(x => !isNaN(x));
327
- if (cpus.length) busy = cpus.reduce((a, c) => a + c, 0) / 100;
429
+ busy = busyBetween(prev?.ticks, ticks, Date.now() - prev?.at, cores);
430
+ if (busy == null) {
431
+ const cpus = procCache && Date.now() - procCache.at < 5000 ? procCache.list.map(p => p.cpu || 0)
432
+ : run('ps', ['-Ao', 'pcpu=']).split('\n').map(Number).filter(x => !isNaN(x));
433
+ if (cpus.length) busy = cpus.reduce((a, c) => a + c, 0) / 100;
434
+ }
328
435
  }
329
- return { diskFree, swapUsed, ...(swapFiles != null && { swapFiles }), memFree, memAvail, load, busy, cores: os.cpus().length, os: OS };
436
+ return { diskFree, ...(diskTotal != null && { diskTotal }), swapUsed, ...(swapFiles != null && { swapFiles }), memFree, memAvail, load, busy, cores, os: OS, ticks,
437
+ vmPressure: vmPressure === undefined ? memPressure() : vmPressure };
438
+ }
439
+
440
+ // Share of all cores busy over CPU_WINDOW ms (0 to 1), from two os.cpus() readings.
441
+ const CPU_WINDOW = 100;
442
+ function cpuBusy() {
443
+ const total = () => os.cpus().reduce((a, c) => { const t = c.times; a.busy += t.user + t.nice + t.sys + t.irq; a.all += t.user + t.nice + t.sys + t.irq + t.idle; return a; }, { busy: 0, all: 0 });
444
+ const a = total();
445
+ const until = Date.now() + CPU_WINDOW;
446
+ while (Date.now() < until) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, until - Date.now());
447
+ const b = total();
448
+ return b.all > a.all ? Math.min(1, Math.max(0, (b.busy - a.busy) / (b.all - a.all))) : 0;
330
449
  }
331
450
 
332
451
  // Memory a new job can take without anything going to swap, from vm_stat: pages
@@ -343,8 +462,19 @@ export function vmAvail(text) {
343
462
  // Memory pressure: 0 normal, 1 warning, 2 critical (swapping hard), or null
344
463
  // when the OS doesn't say. One sysctl on macOS; PSI on Linux, where a tenth of
345
464
  // the last 10s fully stalled on memory counts as critical. Windows: null.
465
+ // When the machine last woke from sleep (dark wakes and Power Nap included), or null:
466
+ // macOS's kern.waketime, which reads 0 until the first sleep after boot. DIBS_FAKE_WAKETIME
467
+ // (ms since 1970) stands in for it in tests.
468
+ export function wokeAt() {
469
+ if (process.env.DIBS_FAKE_WAKETIME) return Number(process.env.DIBS_FAKE_WAKETIME) || null;
470
+ if (OS !== 'macos') return null;
471
+ const m = run('sysctl', ['-n', 'kern.waketime']).match(/sec = (\d+), usec = (\d+)/);
472
+ return m && Number(m[1]) ? Number(m[1]) * 1000 + Math.floor(Number(m[2]) / 1000) : null;
473
+ }
474
+ const MEM_PRESSURE = 'kern.memorystatus_vm_pressure_level';
475
+ const PRESSURE_LEVEL = { 1: 0, 2: 1, 4: 2 };
346
476
  export function memPressure() {
347
- if (OS === 'macos') return { 1: 0, 2: 1, 4: 2 }[Number(run('sysctl', ['-n', 'kern.memorystatus_vm_pressure_level']))] ?? null;
477
+ if (OS === 'macos') return PRESSURE_LEVEL[Number(run('sysctl', ['-n', MEM_PRESSURE]))] ?? null;
348
478
  if (OS !== 'linux') return null;
349
479
  try {
350
480
  const t = fs.readFileSync('/proc/pressure/memory', 'utf8');
package/src/preempt.mjs CHANGED
@@ -302,6 +302,32 @@ export function diskStep(track, m, cfg) {
302
302
  return null;
303
303
  }
304
304
 
305
+ // The hard stop: under HARD_STOP free, a full disk is seconds away and fails every job on the
306
+ // machine, so the dibs run writing fastest is paused whatever its priority or resource (a deploy
307
+ // included, which pausing may time out: that's the lesser harm), one a pass, never the last one
308
+ // running. They resume once
309
+ // there's HARD_RESUME. Writing fastest: the biggest share of the disk's last fall (src/measure.mjs
310
+ // ateLast), then of its fall per minute run.
311
+ export const HARD_STOP = 1024 ** 3, HARD_RESUME = 2 * 1024 ** 3;
312
+ const writing = (l, t) => [l.ateLast || 0, (l.ate || 0) / Math.max(1, t - l.start)];
313
+ export function hardStop(s, t = now(), m = {}) {
314
+ if (m.diskFree == null || m.diskFree >= HARD_STOP || OS === 'windows') return null;
315
+ // Never the last one running: dibs doesn't pause every job (heal would resume one at once).
316
+ if (running(s).length < 2) return null;
317
+ const l = s.leases.filter(x => x.kind === 'run' && x.pgid && !x.pausedAt)
318
+ .sort((a, b) => { const [x, y] = [writing(a, t), writing(b, t)]; return y[0] - x[0] || y[1] - x[1]; })[0];
319
+ if (!l) return null;
320
+ (l.pauses ||= []).push({ watcher: process.pid, wstart: pstart(process.pid), at: t, disk: true, hard: true });
321
+ sync(l);
322
+ return { ...l };
323
+ }
324
+ export function hardResume(s, m = {}) {
325
+ if (m.diskFree == null || m.diskFree < HARD_RESUME) return [];
326
+ const ls = s.leases.filter(l => l.pauses?.some(p => p.hard));
327
+ for (const l of ls) { l.pauses = l.pauses.filter(p => !p.hard); sync(l); }
328
+ return ls.map(l => ({ ...l }));
329
+ }
330
+
305
331
  // Pause the next lease while free disk is low and filling: one on top of a full
306
332
  // resource first, then idle, low and normal work, newest first (the newest is
307
333
  // likeliest to be the one growing). Urgent and high work, holds, and resources
@@ -350,8 +376,13 @@ export function diskRequeue(s, cfg, t = now(), hist = []) {
350
376
  && x.res.every(r => resCfg(cfg, r).rerun === true) && !nearlyDone(x, hist, t))
351
377
  .sort((a, b) => (measured(b) || b.mem || 0) - (measured(a) || a.mem || 0))[0];
352
378
  if (!l) return null;
353
- l.requeue = { at: t, why: why(l) };
354
- // Killed where it stands: SIGKILL ends a stopped process too. Its dibs run sees it end.
379
+ return stopToRequeue(l, why(l), t);
380
+ }
381
+
382
+ // Killed where it stands: SIGKILL ends a stopped process too. Its dibs run sees it end and
383
+ // puts it back in line (src/commands.mjs requeue).
384
+ function stopToRequeue(l, why, t) {
385
+ l.requeue = { at: t, why };
355
386
  if (ours(l)) {
356
387
  const groups = [...new Set([l.pgid, ...(l.stopped || []), ...(l.groups || [])].filter(Boolean))];
357
388
  queued.push(() => { for (const g of groups) stopTree(g, 'SIGKILL'); });
@@ -359,6 +390,22 @@ export function diskRequeue(s, cfg, t = now(), hist = []) {
359
390
  return { ...l };
360
391
  }
361
392
 
393
+ // Memory pressure still critical with a job already paused for it: a stopped job keeps every
394
+ // byte it had, and under pressure those go to swap, so pausing more only moves memory to the
395
+ // disk. On 2026-11-10 at 23:48 swap reached 13.7 GB with jobs paused, and the Mac froze. One
396
+ // paused job is stopped instead, the lowest priority first, then the most memory, and its dibs
397
+ // run puts it back at the front of its line, to run again from the start once there's room.
398
+ // Same limits as diskRequeue: jobs dibs can run again (rerun, requeuable), not nearly done, not
399
+ // paused by a person or agent. Returns it, or null when none can go (then the watcher pauses one more).
400
+ const LOWEST = { idle: 0, low: 1, normal: 2 };
401
+ const memPaused = l => !!l.pauses?.some(p => p.watcher && !p.disk);
402
+ export function pressureRequeue(s, cfg, t = now(), hist = []) {
403
+ const l = s.leases.filter(x => memPaused(x) && x.kind === 'run' && x.requeuable && !x.requeue && !x.pauses?.some(p => p.owner)
404
+ && x.res.every(r => resCfg(cfg, r).rerun === true) && !nearlyDone(x, hist, t))
405
+ .sort((a, b) => (LOWEST[a.prio || 'normal'] ?? 3) - (LOWEST[b.prio || 'normal'] ?? 3) || (measured(b) || b.mem || 0) - (measured(a) || a.mem || 0))[0];
406
+ return l ? stopToRequeue(l, 'memory', t) : null;
407
+ }
408
+
362
409
  // Pause the next lease under memory pressure: a job running on top of a full
363
410
  // resource first, newest first (src/overlap.mjs), since it's the extra load;
364
411
  // then the one furthest over the memory it asked for (it's why the books are
@@ -379,7 +426,8 @@ export function pressurePause(s, cfg, t = now(), hist = []) {
379
426
  // memory. With all = true, every one (the watcher is stopping); 'memory', every
380
427
  // memory pause and no disk ones. Returns what it resumed.
381
428
  export function pressureResume(s, all = false, disk = false) {
382
- const ours = p => p.watcher && (all === 'memory' ? !p.disk : all || !!p.disk === disk);
429
+ // A hard stop's pause lifts only at HARD_RESUME (hardResume), or when the watcher hands over.
430
+ const ours = p => p.watcher && !(p.hard && all !== true) && (all === 'memory' ? !p.disk : all || !!p.disk === disk);
383
431
  const ls = s.leases.filter(l => l.pauses?.some(ours)).sort((a, b) => !!a.alongside - !!b.alongside || (a.alongside ? a.start - b.start : 0)
384
432
  || (a.prio === 'idle') - (b.prio === 'idle') || a.mem - b.mem);
385
433
  const out = all ? ls : ls.slice(0, 1);
@@ -421,13 +469,13 @@ export function noticeHandler(read) {
421
469
  const by = pausedBy(l);
422
470
  const why = l.pauses.find(x => x.owner)?.reason;
423
471
  say(by ? `${by === 'owner' ? 'the owner (the person at this machine)' : by} paused your job (dibs pause ${l.id})${why ? `: "${why}"` : ''}. It keeps its lease and its place; dibs resume ${l.id} continues it.`
424
- + ' Timeouts inside it may fire on resume.'
472
+ + ' Its processes were stopped (SIGSTOP) and continue where they were when it resumes. Anything waiting on a server meanwhile (an HTTP request, an upload) may have timed out on the far side: check its output for timeouts.'
425
473
  : p
426
474
  ? `paused your job for ${p.who} (${p.prio}${p.purpose ? `: "${p.purpose}"` : ''}), who needed ${p.res.join(', ')}.`
427
- + ` It keeps its lease and its place, and resumes when their job ends. Timeouts inside it may fire on resume.`
475
+ + ' It keeps its lease and its place, and resumes when their job ends.' + ' Its processes were stopped (SIGSTOP) and continue where they were when it resumes. Anything waiting on a server meanwhile (an HTTP request, an upload) may have timed out on the far side: check its output for timeouts.'
428
476
  : l.pauses?.some(x => x.disk)
429
477
  ? `paused your job: free disk is low and ${l.pauses.some(x => x.swap) ? 'swap is still growing on it' : 'still falling'}. It keeps its lease and its place, and resumes once there's room again.`
430
- + ' If it stays paused, free some disk space. Timeouts inside it may fire on resume.'
478
+ + ' If it stays paused, free some disk space.' + ' Its processes were stopped (SIGSTOP) and continue where they were when it resumes. Anything waiting on a server meanwhile (an HTTP request, an upload) may have timed out on the far side: check its output for timeouts.'
431
479
  : l.alongside ? pausedLine()
432
480
  : `paused your ${l.prio} job: the machine is short on memory. It keeps its lease and resumes when memory pressure eases.`);
433
481
  } else if (!l.pausedAt && since) {
package/src/primer.mjs CHANGED
@@ -6,6 +6,7 @@
6
6
  import fs from 'node:fs';
7
7
  import os from 'node:os';
8
8
  import path from 'node:path';
9
+ import { fileURLToPath } from 'node:url';
9
10
 
10
11
  const DIBS_HOME = process.env.DIBS_HOME || path.join(os.homedir(), '.dibs');
11
12
  const BUILT_IN = ['sim', 'sim-own', 'xcode-build', 'test', 'playwright', 'deploy', 'heavy'];
@@ -17,23 +18,50 @@ function resources() {
17
18
  return [...new Set([...BUILT_IN, ...extra])].join(', ');
18
19
  }
19
20
 
20
- export function primerText() {
21
+ // The rules every agent gets first, and nothing else: what to wrap and how, what
22
+ // needs no dibs, staying reachable, the two exit codes agents hit, and when to ask
23
+ // the person. One source: the session primer below, and the top of
24
+ // skills/dibs/SKILL.md and docs/reference.md's "Tell your agents", which writeRules()
25
+ // fills from it (test/rules.test.mjs checks they match). The rest is reference,
26
+ // under the skill's "When you need it": agents that got every rule up front
27
+ // skimmed them all (feedback, 2026-11-03).
28
+ export function rules(res = resources(), more = 'is in dibs.md beside dibs (the dibs skill) and in `dibs help`') {
21
29
  return [
22
- 'dibs runs on this machine: agents take turns through it on the simulator, builds, tests, browser runs and deploys.',
23
- `- Wrap those: dibs run <resource> -m "why" -- <command> (resources: ${resources()}). Across several tool calls: dibs hold sim --for 20m -m "why", `
24
- + 'keep wrapping each command (no wait under your hold), dibs release sim. Reads, edits and small commands need nothing.',
25
- '- Waiting is normal. A call moved to the background is still waiting: don\'t run it again. '
26
- + 'A memory, swap or disk wait protects the machine: keep waiting. Never lower --mem or raise -p for it.',
27
- '- Post progress as often as you commit: dibs progress "what you did or found" --task <name> --eta 30m, then --blocked or --done. The person reads it live.',
28
- '- Decide two-way doors yourself. Ask the person only what can\'t be undone: dibs question "..." --recommend X -m why --one-way "what is lost", '
29
- + 'keep working, then the same command plus --wait reads the answer. "Message from the person:" lines are theirs.',
30
- '- You may boost, pause or stop any job (--owner <session> if not yours); dibs logs who. A job "stopped by" someone was ended on purpose: find out why first.',
31
- '- Exit codes: 75 never ran (outside Claude Code; rerun within 2 min), 74 no disk, 76 lost before it started (send again), 77 lost after (check first), 70 dibs crashed. '
32
- + 'Quote file globs: dibs hold \'files:src/auth/**\'.',
33
- '- More: the dibs skill, dibs help. Something wrong with dibs: dibs ask "...".',
34
- ].join('\n');
30
+ 'dibs runs on this machine. Agents take turns through it on the simulator, Xcode builds, test suites, browser runs and deploys.',
31
+ `- Wrap those: \`dibs run <resource> -m "why" -- <command>\` (resources: ${res}). Two at once: \`dibs run sim,xcode-build -- ...\`.`,
32
+ '- No dibs for reads, edits, small commands, or long jobs that mostly wait on the network and use little CPU, memory or disk (crawlers, pollers, HTTP checks). The hook leaves those alone too.',
33
+ '- Start `dibs listen` with run_in_background now, and again each time it exits: it wakes you when the person or dibs has something for you.',
34
+ '- Waiting is normal. A call moved to the background is still waiting: don\'t run it again. A wait on memory, swap or disk protects the machine: keep waiting, and never lower `--mem` or raise `-p` to get past it.',
35
+ '- Exit 75: it gave up waiting and your command never ran; run the same command again. Exit 74: it can\'t fit on this disk, or its wait limit ran out; low disk just means a wait.',
36
+ '- Decide what you can undo yourself. Ask the person only before something you can\'t undo (`dibs question ... --one-way`). Lines starting "Message from the person:" are theirs: act on them.',
37
+ '- Post progress as you work: `dibs progress "what you did or found" --task <name> --eta 30m`, then `--done`.',
38
+ `- The rest (holding across tool calls, file leases, other machines, every exit code, overriding jobs, questions) ${more}.`,
39
+ ];
35
40
  }
36
41
 
42
+ // A subagent ends with its task, so it isn't told to keep a listener running.
43
+ export const primerText = ({ subagent = false } = {}) => rules().filter(l => !(subagent && l.includes('dibs listen'))).join('\n');
44
+
45
+ // The rules as the skill and docs/reference.md carry them, between their markers, with the
46
+ // built-in resources (a machine's config adds its own; the primer names those).
47
+ const MARK = /<!-- dibs:rules:start -->[\s\S]*?<!-- dibs:rules:end -->/;
48
+ const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
49
+ export const DOCS = {
50
+ 'skills/dibs/SKILL.md': () => rules(BUILT_IN.join(', '), 'is below, under "When you need it", and in `dibs help`'),
51
+ // A block to paste, fenced, for anyone who doesn't let dibs init write the note.
52
+ 'docs/reference.md': () => ['```markdown', '## dibs', ...rules(BUILT_IN.join(', '), 'is in the dibs skill and in `dibs help`'), '```'],
53
+ };
54
+ export const marked = lines => `<!-- dibs:rules:start -->\n${lines.join('\n')}\n<!-- dibs:rules:end -->`;
55
+ export function writeRules(root = ROOT) {
56
+ for (const [f, make] of Object.entries(DOCS)) {
57
+ const file = path.join(root, f);
58
+ const text = fs.readFileSync(file, 'utf8');
59
+ if (!MARK.test(text)) throw new Error(`${f} has no <!-- dibs:rules:start --> ... <!-- dibs:rules:end --> to fill`);
60
+ fs.writeFileSync(file, text.replace(MARK, marked(make())));
61
+ }
62
+ }
63
+
64
+
37
65
  // Each subagent hears it once: SubagentStart also fires every time an agent
38
66
  // team teammate takes a new message. A short list of ids it was told, newest last.
39
67
  const TOLD = path.join(DIBS_HOME, 'primed.json');
@@ -57,5 +85,5 @@ function firstTime(agentId) {
57
85
  export function primer(input, out) {
58
86
  const event = input.hook_event_name;
59
87
  if (event === 'SubagentStart' && (typeof input.agent_id !== 'string' || !firstTime(input.agent_id))) return out;
60
- return { ...out, hookSpecificOutput: { hookEventName: event, additionalContext: primerText() } };
88
+ return { ...out, hookSpecificOutput: { hookEventName: event, additionalContext: primerText({ subagent: event === 'SubagentStart' }) } };
61
89
  }
package/src/proc.mjs CHANGED
@@ -17,14 +17,19 @@ export const pstart = pid => starts([pid])?.get(pid) || null;
17
17
  // 30 to 50 ms each time on a busy Mac. A pid can only be reused after its
18
18
  // process is gone, which kill(0) sees.
19
19
  const STARTS_FOR = 10e3;
20
- const known = new Map(); // pid -> { start, at }
20
+ const known = new Map(); // pid -> { pid, start, at }
21
+ const KNOWN_MAX = 1000; // a long-lived broker or service sees thousands of pids a day
22
+ // A pid found gone is remembered as gone (start null) for as long: that process
23
+ // can't come back, and a new one given its number isn't the holder recorded.
21
24
  const answers = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
25
+ const still = (k, t) => k && t - k.at < STARTS_FOR && (k.start == null || answers(k.pid));
22
26
  export function makeAlive(pids) {
23
27
  const t = Date.now();
24
- const need = pids.filter(p => p && !(known.has(p) && t - known.get(p).at < STARTS_FOR && answers(p)));
28
+ const need = pids.filter(p => p && !still(known.get(p), t));
25
29
  const st = need.length ? starts(need) : new Map();
26
30
  if (!st) return pid => !!pid;
27
- for (const p of need) if (st.has(p)) known.set(p, { start: st.get(p), at: t }); else known.delete(p);
31
+ for (const p of need) known.set(p, { pid: p, start: st.has(p) ? st.get(p) : null, at: t });
32
+ if (known.size > KNOWN_MAX) for (const [p, k] of known) if (t - k.at >= STARTS_FOR) known.delete(p);
28
33
  const startOf = pid => (st.has(pid) ? st.get(pid) : known.get(pid)?.start);
29
34
  return (pid, started) => !!pid && startOf(pid) != null && (!started || startOf(pid) === started);
30
35
  }
@@ -43,7 +48,7 @@ function session() {
43
48
  if (!p) break;
44
49
  if (AGENTS.test(p.name)) {
45
50
  let name = null;
46
- try { name = JSON.parse(fs.readFileSync(path.join(SESSIONS, `${pid}.json`), 'utf8')).name || null; } catch {}
51
+ try { name = sessionFile(path.join(SESSIONS, `${pid}.json`)).name || null; } catch {}
47
52
  cached = { pid, name, app: p.name.toLowerCase(), start: pstart(pid) };
48
53
  break;
49
54
  }
@@ -61,16 +66,42 @@ export function identity(o = {}) {
61
66
  return { who, agent, label, spid: se?.pid || null, sstart: se?.start || null };
62
67
  }
63
68
 
64
- // Claude Code's own record of each session it runs: { pid, sessionId, name }.
65
- // The person addresses an agent by the name; hooks know it by sessionId.
69
+ // One session's record. Claude Code has left one with a stray } after the object (2026-11-10,
70
+ // 43095.json), and a strict parse dropped that session from the board and its messages: the
71
+ // object it starts with is the record.
72
+ export function sessionFile(file) {
73
+ const text = fs.readFileSync(file, 'utf8');
74
+ try { return JSON.parse(text); } catch (e) {
75
+ const end = objectEnd(text);
76
+ if (end < 0) throw e;
77
+ return JSON.parse(text.slice(0, end));
78
+ }
79
+ }
80
+
81
+ // Where the JSON object a text starts with ends, counting braces outside strings; -1 if it doesn't.
82
+ function objectEnd(text) {
83
+ let depth = 0, str = false;
84
+ for (let i = text.indexOf('{'); i >= 0 && i < text.length; i++) {
85
+ const c = text[i];
86
+ if (str) { if (c === '\\') i++; else if (c === '"') str = false; continue; }
87
+ if (c === '"') str = true;
88
+ else if (c === '{') depth++;
89
+ else if (c === '}' && --depth === 0) return i + 1;
90
+ }
91
+ return -1;
92
+ }
93
+
94
+ // Claude Code's own record of each session it runs: { pid, sessionId, name, status, updated }.
95
+ // The person addresses an agent by the name; hooks know it by sessionId. status is Claude
96
+ // Code's word for what it's doing ("busy", "idle", "shell"), or null from an older one.
66
97
  export function sessionFiles() {
67
98
  let names = [];
68
99
  try { names = fs.readdirSync(SESSIONS).filter(n => /^\d+\.json$/.test(n)); } catch { return []; }
69
100
  const out = [];
70
101
  for (const n of names) {
71
102
  try {
72
- const x = JSON.parse(fs.readFileSync(path.join(SESSIONS, n), 'utf8'));
73
- if (x.pid && x.sessionId) out.push({ pid: x.pid, sessionId: x.sessionId, name: x.name || null });
103
+ const x = sessionFile(path.join(SESSIONS, n));
104
+ if (x.pid && x.sessionId) out.push({ pid: x.pid, sessionId: x.sessionId, name: x.name || null, status: typeof x.status === 'string' ? x.status : null, updated: x.statusUpdatedAt || x.updatedAt || 0 });
74
105
  } catch {}
75
106
  }
76
107
  return out;