@dibssoftware/dibs 0.0.179 → 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 (53) hide show
  1. package/CHANGELOG.md +23 -2
  2. package/README.md +4 -2
  3. package/bin/dibs-guard.mjs +10 -1
  4. package/bin/dibs.mjs +28 -9
  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 +9 -7
  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 +5 -5
  16. package/src/acquire.mjs +91 -26
  17. package/src/agents.mjs +7 -22
  18. package/src/alerts.mjs +59 -21
  19. package/src/board.mjs +1 -2
  20. package/src/broker.mjs +26 -11
  21. package/src/commands.mjs +25 -9
  22. package/src/config.mjs +21 -4
  23. package/src/cool.mjs +104 -9
  24. package/src/diskwarn.mjs +4 -0
  25. package/src/events.mjs +10 -1
  26. package/src/files.mjs +49 -87
  27. package/src/guard.mjs +24 -8
  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 +292 -0
  32. package/src/measure.mjs +9 -4
  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 +165 -35
  37. package/src/preempt.mjs +51 -3
  38. package/src/primer.mjs +1 -1
  39. package/src/proc.mjs +35 -5
  40. package/src/questions.mjs +8 -22
  41. package/src/relay.mjs +10 -22
  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 +4 -3
  46. package/src/state.mjs +139 -47
  47. package/src/stats.mjs +3 -2
  48. package/src/talk.mjs +160 -77
  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 +15 -25
  53. package/src/worker.mjs +2 -1
package/src/commands.mjs CHANGED
@@ -7,8 +7,8 @@ import { resCfg, machine, HOME, paths, PACES, PACE_OVERLAP, paced, paceKnobs, ha
7
7
  import { logChange } from './owner.mjs';
8
8
  import { identity, isMine, tag } from './proc.mjs';
9
9
  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';
10
+ import { withState, withStateIfRoom, history, record, peakOf, peek, KEEP_PLACE } from './state.mjs';
11
+ import { acquire, markIdle, tableFirst, idleFor, describeLease, commandKey, holdUntil, outerLease, defaultMaxWait, HOLD_CAP } from './acquire.mjs';
12
12
  import { rank, rankParts, byRank, forecast, verdict, remaining, used, sum, lent, pausedFor, overLoad, loadWhy, loadAhead, holdingOf, swapping, swapWhy, diskSqueeze, BACKGROUND, roomFor } from './schedule.mjs';
13
13
  import { noticeHandler } from './preempt.mjs';
14
14
  import { checkout, checkin, jobSize } from './simpool.mjs';
@@ -153,7 +153,7 @@ export async function run(o, cfg) {
153
153
  + `${l.stopReason ? '' : ' Find out why before running it again: dibs history, or ask whoever stopped it.'}`);
154
154
  s.leases = s.leases.filter(x => x.id !== lease.id);
155
155
  // 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);
156
+ if (l && (code === 0 || l.peak?.mem)) record(l.key, now() - l.start - pausedFor(l), l.who, peakOf(l), code !== 0);
157
157
  if (l?.quick) took = now() - l.start - pausedFor(l);
158
158
  tellOverAsk(l);
159
159
  });
@@ -223,7 +223,7 @@ function requeue(s, l, cfg) {
223
223
  const t = now();
224
224
  s.leases = s.leases.filter(x => x !== l);
225
225
  // 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);
226
+ if (l.peak?.mem) record(l.key, t - l.start - pausedFor(l), l.who, peakOf(l), true);
227
227
  const res = l.res;
228
228
  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
229
  // Booked at what it really used, up to all the memory dibs shares out (usual keeps the rest).
@@ -248,6 +248,9 @@ function runAgain(o, lease, again) {
248
248
  say(again.why === 'over'
249
249
  ? `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
250
  + ` 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.`
251
+ : again.why === 'memory'
252
+ ? `stopped #${lease.id}: it was paused for memory pressure, which stayed critical, and a paused job's memory only goes to swap.`
253
+ + ` 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
254
  : `stopped #${lease.id}: it sat paused for low disk while its memory went to swap and filled the disk.`
252
255
  + ` 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
256
  const args = process.argv.slice(2);
@@ -430,7 +433,7 @@ export function when(o, cfg) {
430
433
  const key = `${res.join(',')}|${o.cmd ? commandKey(o.cmd) : 'hold'}`;
431
434
  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
435
  ...sized(jobSize(cfg, res, o), hist, key, cfg), key };
433
- const s = withState(s => { markIdle(s); return s; });
436
+ const s = marked();
434
437
  probe.holding = holdingOf(s, probe, cfg, t);
435
438
  const v = verdict(s, probe, cfg, hist, t);
436
439
  const at = v.ok ? t : forecast(s, cfg, hist, t, probe).get(-1);
@@ -461,7 +464,7 @@ export function why(o, cfg) {
461
464
  const id = caller(o);
462
465
  const hist = history();
463
466
  const t = now();
464
- const s = withState(s => { markIdle(s); return s; });
467
+ const s = marked();
465
468
  const mine = s.queue.filter(q => q.pid && ours(q, id));
466
469
  if (!mine.length) {
467
470
  const holds = s.leases.filter(l => ours(l, id));
@@ -530,14 +533,14 @@ export function who(o, cfg) {
530
533
  if (!o.res.length) return status(o, cfg);
531
534
  const hist = history();
532
535
  const t = now();
533
- const s = withState(s => { markIdle(s); return s; });
536
+ const s = marked();
534
537
  const order = s.queue.filter(q => q.pid).sort(byRank(hist, t));
535
538
  const rows = [];
536
539
  for (const r of o.res) {
537
540
  // A file lease is held by whoever holds any path overlapping it.
538
541
  // One holder with two overlapping file leases is still one holder.
539
542
  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);
543
+ 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
544
  const n = named(cfg, r);
542
545
  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
546
  const hold = isFiles(r) ? '' : machineHold(s, cfg);
@@ -650,6 +653,9 @@ export function pace(args) {
650
653
  // The bar is lower than dibs throttle's (50%): this only reports, it doesn't act.
651
654
  const BUSY_CPU = 40; // % of a core
652
655
  function untracked(s) {
656
+ // Windows reads CPU per process by sampling twice a second apart (platform.mjs): 1.8 s a call
657
+ // on a CI runner, too much for every look at the board, for a line that's only informative.
658
+ if (OS === 'windows') return [];
653
659
  const ours = new Set(s.leases.flatMap(l => [l.pgid, ...(l.groups || [])]).filter(Boolean));
654
660
  const groups = new Map();
655
661
  for (const p of processes()) {
@@ -701,9 +707,19 @@ export function boardJson(s, cfg, { hist = history(), m = machine(), t = now(),
701
707
  };
702
708
  }
703
709
 
710
+ // The state with idle runs marked.
711
+ function marked() {
712
+ tableFirst();
713
+ return withState(s => { markIdle(s); return s; });
714
+ }
715
+
716
+ // Plain dibs never hangs: behind a holder that won't let go of the state lock, the board shows the
717
+ // state as last written, and the alert that says who dibs is stuck behind.
718
+ const BOARD_WAIT = 2000;
704
719
  export async function status(o, cfg) {
705
720
  const hist = history();
706
- const s = withState(s => { markIdle(s); return s; });
721
+ tableFirst();
722
+ const s = withState(s => { markIdle(s); return s; }, BOARD_WAIT) ?? peek();
707
723
  const m = machine();
708
724
  const t = now();
709
725
  // 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
  }
package/src/cool.mjs CHANGED
@@ -11,15 +11,16 @@ import path from 'node:path';
11
11
  import { HOME, machine, loadConfig } from './config.mjs';
12
12
  import { withState, history, peek } from './state.mjs';
13
13
  import { singleInstance } from './proc.mjs';
14
- import { processes, lower, memPressure, isDibs } from './platform.mjs';
14
+ import { processes, lower, memPressure, isDibs, runtimes } from './platform.mjs';
15
15
  import { hogsOnce, hogHint } from './hogs.mjs';
16
- import { pressureStep, pressurePause, pressureResume, diskStep, diskPause, diskPausesPerPass, diskLine, diskCritical, adoptPauses, diskRequeue, measured } from './preempt.mjs';
16
+ import { pressureStep, pressurePause, pressureRequeue, pressureResume, diskStep, diskPause, diskPausesPerPass, diskLine, diskCritical, adoptPauses, diskRequeue, measured, hardStop, hardResume, HARD_STOP, HARD_RESUME } from './preempt.mjs';
17
+ import { inversions, lift } from './override.mjs';
17
18
  import { swapGrowing } from './schedule.mjs';
18
19
  import { event } from './events.mjs';
19
20
  import { notify } from './talk.mjs';
20
21
  import { watchBroker } from './broker.mjs';
21
22
  import { progressScan } from './notices.mjs';
22
- import { scan as scanAlerts } from './alerts.mjs';
23
+ import { scan as scanAlerts, CPU_FILE } from './alerts.mjs';
23
24
  import { say, sleep, now, noSpace, gb } from './util.mjs';
24
25
 
25
26
  const PIDFILE = path.join(HOME, 'cool.pid');
@@ -33,11 +34,46 @@ const SAMPLE_EVERY = 60e3;
33
34
 
34
35
  const toolName = args => path.basename(args.split(/\s+/)[0]).replace(/\.exe$/i, '');
35
36
 
37
+ // Cores that stopped taking work. On 2026-11-10 this Mac's 4 performance cores did:
38
+ // load went from 127 to 400 while top read a flat 40% idle, and only a restart
39
+ // fixed it. Load that high counts work that's ready to run, so with that much of
40
+ // the CPU idle the work isn't being run, and moving hot processes to background
41
+ // priority (off the performance cores) only made it worse. Past STUCK_LOAD per
42
+ // core with STUCK_IDLE or more of the CPU idle, the watcher lowers nothing, and
43
+ // after STUCK_AFTER of it (src/alerts.mjs) the person is told to restart.
44
+ const STUCK_LOAD = 5;
45
+ const STUCK_IDLE = 0.25;
46
+ export function coresStuck(m) {
47
+ if (!(m?.cores > 0) || m.busy == null || !(m.load >= STUCK_LOAD * m.cores)) return false;
48
+ return 1 - m.busy / m.cores >= STUCK_IDLE;
49
+ }
50
+
51
+ // Processes left behind: build and test tools outside dibs that have run for
52
+ // ORPHAN_AGE and whose script is gone. On 2026-11-10 two node testfast.mjs from a
53
+ // deleted scratchpad had run 23 hours at 17 CPU-hours each, kept hot and moved to
54
+ // background priority over and over. They're named in an alert; nothing is killed.
55
+ const ORPHAN_AGE = 3 * 36e5;
56
+ const ORPHAN_EVERY = 6e4; // a ps over the hot ones, once a minute
57
+ const SCRIPT = /\.(c|m)?[jt]sx?$|\.py$|\.rb$/;
58
+ // The script a tool runs, when its command line names one by its full path.
59
+ export function scriptOf(args) {
60
+ return args.split(/\s+/).slice(1).find(a => a.startsWith('/') && SCRIPT.test(a)) || null;
61
+ }
62
+ export function orphans(procs, leased, ages, gone = f => !fs.existsSync(f)) {
63
+ const out = [];
64
+ for (const p of procs) {
65
+ if (leased.has(p.pgid) || !TOOLS.test(toolName(p.args)) || isDibs(p)) continue;
66
+ const script = scriptOf(p.args), r = ages.get(p.pid);
67
+ if (script && r && r.age >= ORPHAN_AGE && gone(script)) out.push({ pid: p.pid, name: toolName(p.args), script, age: r.age, cpu: r.cpu });
68
+ }
69
+ return out;
70
+ }
71
+
36
72
  // One pass. A process must be hot on two passes in a row, so short bursts are
37
73
  // left alone. Returns the processes it moved.
38
- function throttleOnce(cfg, seen = new Map()) {
39
- const load = machine().load;
40
- const leased = new Set(withState(s => s.leases.flatMap(l => [l.pgid, ...(l.groups || [])]).filter(Boolean)));
74
+ function throttleOnce(cfg, seen = new Map(), leased = leasedGroups()) {
75
+ const m = machine(), load = m.load;
76
+ const stuck = coresStuck(m);
41
77
  const moved = [];
42
78
  const next = new Map();
43
79
  for (const p of processes()) {
@@ -45,7 +81,7 @@ function throttleOnce(cfg, seen = new Map()) {
45
81
  if (p.cpu < HOT || p.pid === process.pid || leased.has(p.pgid) || !TOOLS.test(toolName(p.args)) || isDibs(p)) continue;
46
82
  const prev = seen.get(p.pid);
47
83
  if (prev === 'done') { next.set(p.pid, 'done'); continue; }
48
- if (prev && load > cfg.coolLoad && lower(p.pid)) {
84
+ if (prev && load > cfg.coolLoad && !stuck && lower(p.pid)) {
49
85
  moved.push({ ...p, name: toolName(p.args) });
50
86
  next.set(p.pid, 'done');
51
87
  fs.appendFileSync(LOG, `${new Date().toISOString()} load ${load.toFixed(1)}: background ${toolName(p.args)} ${p.pid} (${p.cpu}% cpu)\n`);
@@ -56,12 +92,33 @@ function throttleOnce(cfg, seen = new Map()) {
56
92
  return moved;
57
93
  }
58
94
 
95
+ const leasedGroups = () => new Set(withState(s => s.leases.flatMap(l => [l.pgid, ...(l.groups || [])]).filter(Boolean)));
96
+
97
+ // What the watcher saw that only a person can fix, for src/alerts.mjs: since when
98
+ // the cores have looked stuck, and the orphans. Every pass, with when, so a
99
+ // watcher that stopped leaves no alert standing.
100
+ function noteCpu(note) {
101
+ try { fs.writeFileSync(`${CPU_FILE}.${process.pid}`, JSON.stringify({ at: now(), ...note })); fs.renameSync(`${CPU_FILE}.${process.pid}`, CPU_FILE); } catch {}
102
+ }
103
+
59
104
  // One memory pressure reading. Under sustained critical pressure, pause the
60
105
  // next idle or low lease; once it's been normal for a while, resume one.
61
106
  // Returns { act, leases } when it did something.
62
107
  export function pressureOnce(cfg, track, read = memPressure) {
63
108
  const act = pressureStep(track, read());
64
109
  if (!act) return null;
110
+ if (act === 'pause') {
111
+ const l = withState(s => pressureRequeue(s, cfg, now(), history()));
112
+ if (l) {
113
+ const used = measured(l) || l.mem;
114
+ fs.appendFileSync(LOG, `${new Date().toISOString()} memory pressure still critical with jobs paused: stopped ${l.who} ${l.res.join(',')} (${l.prio || 'normal'}), using ${gb(used)}, to run again at the front of its line: ${l.cmd.slice(0, 60)}\n`);
115
+ event({ kind: 'requeue', id: l.id, res: l.res, who: l.who, agent: l.agent, prio: l.prio || 'normal', why: 'memory', mem: used, booked: l.mem });
116
+ notify(l, `requeue:#${l.id}`, `your job #${l.id} (${l.purpose ? `"${l.purpose}", ` : ''}${l.cmd.slice(0, 60)}) was paused for memory pressure, and pausing frees no memory`
117
+ + ` (a stopped job's memory goes to swap), so with the pressure still critical dibs stopped it. Its dibs run put it back at the front of its line and runs it again`
118
+ + ` from the start once there's room. Don't run it again yourself, and don't end it: the same tool call carries on.`);
119
+ return { act: 'requeue', leases: [l] };
120
+ }
121
+ }
65
122
  const ls = withState(s => (act === 'pause' ? [pressurePause(s, cfg, now(), history())].filter(Boolean) : pressureResume(s)));
66
123
  for (const l of ls)
67
124
  fs.appendFileSync(LOG, `${new Date().toISOString()} memory pressure ${act === 'pause' ? 'critical: paused' : 'eased: resumed'} ${l.who} ${l.res.join(',')} (${l.prio || 'normal'}${l.alongside ? ', on top' : ''}): ${l.cmd.slice(0, 60)}\n`);
@@ -73,6 +130,7 @@ export function pressureOnce(cfg, track, read = memPressure) {
73
130
  // again, resume one a minute.
74
131
  // Returns { act, leases } when it did something.
75
132
  export function diskOnce(cfg, track, m = machine()) {
133
+ const hard = hardOnce(m);
76
134
  const act = diskStep(track, m, cfg);
77
135
  if (!act) return null;
78
136
  // Swap still growing with jobs already paused: their memory is what's going to swap.
@@ -108,6 +166,27 @@ export function diskOnce(cfg, track, m = machine()) {
108
166
  return ls.length ? { act, leases: ls } : null;
109
167
  }
110
168
 
169
+ // The hard stop (src/preempt.mjs hardStop), said loudly: the board's alert for the person
170
+ // (src/alerts.mjs), a line in the log, and a notice to the job's own session.
171
+ function hardOnce(m) {
172
+ const r = withState(s => ({ resumed: hardResume(s, m), paused: hardStop(s, now(), m) }));
173
+ const free = gb(m.diskFree ?? 0).replace(/G$/, ' GB');
174
+ for (const l of r.resumed) {
175
+ fs.appendFileSync(LOG, `${new Date().toISOString()} disk back to ${free}: resumed ${l.who} ${l.res.join(',')} (${l.prio || 'normal'}): ${l.cmd.slice(0, 60)}\n`);
176
+ event({ kind: 'resume', id: l.id, res: l.res, who: l.who, why: 'hard stop over', diskFree: m.diskFree });
177
+ notify(l, `hardresume:#${l.id}:${now()}`, `your job #${l.id} (${l.cmd.slice(0, 60)}) is running again: free disk is back to ${free}.`);
178
+ }
179
+ const l = r.paused;
180
+ if (l) {
181
+ fs.appendFileSync(LOG, `${new Date().toISOString()} disk at ${free}, under ${gb(HARD_STOP)}: hard stop, paused ${l.who} ${l.res.join(',')} (${l.prio || 'normal'}), writing fastest: ${l.cmd.slice(0, 60)}\n`);
182
+ event({ kind: 'pause', id: l.id, res: l.res, who: l.who, prio: l.prio || 'normal', why: 'hard stop', diskFree: m.diskFree });
183
+ notify(l, `hardstop:#${l.id}:${l.pausedAt}`, `your job #${l.id} (${l.purpose ? `"${l.purpose}", ` : ''}${l.cmd.slice(0, 60)}) is paused: free disk is down to ${free}, `
184
+ + `under the ${gb(HARD_STOP).replace(/G$/, ' GB')} where every job on the machine is about to fail, and it was writing the most. It resumes once there's ${gb(HARD_RESUME).replace(/G$/, ' GB')}. `
185
+ + "Free what you can of your own now: build output, scratch folders and merged worktrees your session made. Don't end the job or run it again.");
186
+ }
187
+ return r;
188
+ }
189
+
111
190
  export async function throttle(o, cfg) {
112
191
  if (!o.watch) {
113
192
  const seen = new Map();
@@ -122,7 +201,7 @@ export async function throttle(o, cfg) {
122
201
  say(`throttling: when load is over ${cfg.coolLoad}, build and test processes outside dibs go to background priority.`
123
202
  + ` Under heavy memory pressure, idle and low dibs jobs pause until it eases; when swap fills the disk, jobs below high pause until there's room. Log: ${LOG}`);
124
203
  const seen = new Map(), track = { high: 0, low: 0, diskOk: 0, diskStill: 0 };
125
- let sampled = 0, nudged = 0;
204
+ let sampled = 0, nudged = 0, stuckSince = null, found = [], looked = 0;
126
205
  // Disk pauses stay while the disk is still critical: the next watcher adopts them (src/preempt.mjs settle).
127
206
  const stop = () => {
128
207
  try { withState(s => pressureResume(s, diskCritical(machine(), cfg) ? 'memory' : true)); } catch {}
@@ -143,7 +222,23 @@ export async function throttle(o, cfg) {
143
222
  // First, without the lock: a broker stuck while holding it would hold up this pass too.
144
223
  const fixed = watchBroker();
145
224
  if (fixed) fs.appendFileSync(LOG, `${new Date().toISOString()} ${fixed}\n`);
146
- try { throttleOnce(cfg, seen); pressureOnce(cfg, track); diskOnce(cfg, track); } catch (e) { if (!noSpace(e)) throw e; }
225
+ try {
226
+ const leased = leasedGroups();
227
+ throttleOnce(cfg, seen, leased);
228
+ const m = machine(), stuck = coresStuck(m);
229
+ if (stuck !== (stuckSince != null)) fs.appendFileSync(LOG, `${new Date().toISOString()} load ${m.load.toFixed(0)} with ${Math.round(100 * (1 - m.busy / m.cores))}% of the CPU idle: `
230
+ + `${stuck ? 'cores look stuck, lowering nothing until it passes' : 'the cores are taking work again'}\n`);
231
+ stuckSince = stuck ? stuckSince ?? now() : null;
232
+ if (now() - looked >= ORPHAN_EVERY) {
233
+ looked = now();
234
+ const hot = processes().filter(p => p.cpu >= HOT && p.pid !== process.pid);
235
+ found = orphans(hot, leased, runtimes(hot.map(p => p.pid)));
236
+ }
237
+ noteCpu({ stuckSince, ...(stuck && { load: Math.round(m.load), idle: Math.round(100 * (1 - m.busy / m.cores)), cores: m.cores, swapping: m.vmPressure >= 1 || swapGrowing(m) }), orphans: found });
238
+ pressureOnce(cfg, track); diskOnce(cfg, track);
239
+ } catch (e) { if (!noSpace(e)) throw e; }
240
+ // A lift whose waiter went away without leaving (kill -9) drops back here (src/override.mjs inversions).
241
+ try { lift(withState(s => inversions(s, cfg))); } catch (e) { if (!noSpace(e)) throw e; }
147
242
  // Not awaited: measuring a full temp folder can take a minute, and this loop keeps the machine's pace meanwhile.
148
243
  hogsOnce(cfg, machine());
149
244
  // Alerts open and close even while nobody looks at the board (src/alerts.mjs); the scan itself keeps its pace.
package/src/diskwarn.mjs CHANGED
@@ -16,6 +16,7 @@ import { freeDisk, OS } from './platform.mjs';
16
16
  import { event } from './events.mjs';
17
17
  import { gb, bytes, now } from './util.mjs';
18
18
  import { makeAlive } from './proc.mjs';
19
+ import { withState } from './state.mjs';
19
20
 
20
21
  const GB = b => gb(b).replace(/G$/, ' GB');
21
22
  const SAY_FREED = 0.1 * 1024 ** 3; // less than shows as 0.0 GB: not worth a line
@@ -84,6 +85,9 @@ export async function clean(t = now(), where = HOME) {
84
85
  done.push({ label: st.label, freed: Math.max(0, by) });
85
86
  }
86
87
  const freed = done.reduce((a, d) => a + d.freed, 0);
88
+ // The room this freed hides what running jobs wrote meanwhile, so their runs don't count
89
+ // toward being small (src/schedule.mjs tinyDisk).
90
+ try { withState(s => { for (const l of s.leases) if (l.kind === 'run') l.cleaned = true; }); } catch {}
87
91
  try {
88
92
  fs.appendFileSync(LOG, `${new Date(t).toISOString()} disk low: dibs cleared ${done.map(d => d.label).join(', ')}, freeing ${GB(freed)}\n`);
89
93
  event({ kind: 'clean', freed, steps: done });
package/src/events.mjs CHANGED
@@ -7,7 +7,7 @@
7
7
  // run: an error is written once per process to dibs.log and dropped.
8
8
  import fs from 'node:fs';
9
9
  import path from 'node:path';
10
- import { HOME } from './config.mjs';
10
+ import { HOME, paths } from './config.mjs';
11
11
  import { now } from './util.mjs';
12
12
 
13
13
  export const EVENTS = path.join(HOME, 'events.jsonl');
@@ -33,7 +33,16 @@ export function event(e) {
33
33
 
34
34
  // Move the current file aside once it's past half of either limit. Called
35
35
  // under the state lock, so two processes never rotate at once.
36
+ // Run times (src/state.mjs record) rotate the same way, at RUNS_ROTATE: about 15,000
37
+ // runs, a month here. Learned sizes need only the newest 1000, read across both files.
38
+ const RUNS_ROTATE = 2 * 1024 ** 2;
39
+ function rotateRuns() {
40
+ try { if (fs.statSync(paths.history).size >= RUNS_ROTATE) fs.renameSync(paths.history, paths.historyOlder); }
41
+ catch (e) { if (e.code !== 'ENOENT') complain(e); }
42
+ }
43
+
36
44
  export function rotate(t = now()) {
45
+ rotateRuns();
37
46
  try {
38
47
  const st = fs.statSync(EVENTS);
39
48
  if (st.size < KEEP_BYTES / 2 && t - firstAt() < KEEP_MS / 2) return;