@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/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';
@@ -19,7 +19,7 @@ import { bold, dim, amber, columns, wrap, quoted } from './style.mjs';
19
19
  import { quotasNow, isQuota } from './quota.mjs';
20
20
  import { agentsNow } from './agents.mjs';
21
21
  import { forYou } from './questions.mjs';
22
- import { notesForYou } from './talk.mjs';
22
+ import { notesForYou, listeners } from './talk.mjs';
23
23
  import { remoteConf, shortHost } from './remote.mjs';
24
24
  import { sample, sized, grewLine, grewPlain, tellOverAsk } from './measure.mjs';
25
25
  import { clash, isFiles, short, takeAgent, callKey, sameAgent, fileKey, shellRes, projectKey } from './files.mjs';
@@ -28,11 +28,11 @@ import { laterBoard, laterLines, laterPlain } from './later.mjs';
28
28
  import { noticeScan, NOTICE_EVERY, twinOf } from './notices.mjs';
29
29
  import { answer, ISSUES } from './answers.mjs';
30
30
  import { event } from './events.mjs';
31
- import { scan as scanAlerts, alertLines } from './alerts.mjs';
31
+ import { scan as scanAlerts, alertLines, onBoard } from './alerts.mjs';
32
32
 
33
33
  const REQUESTS = path.join(HOME, 'requests.jsonl');
34
34
  // Exit codes dibs gives its own meaning (AGENTS.md).
35
- const DIBS_CODES = new Set([1, 2, 70, 74, 75, 76, 77, 127]);
35
+ const DIBS_CODES = new Set([1, 2, 3, 70, 74, 75, 76, 77, 127]);
36
36
  const json = x => console.log(JSON.stringify(x, null, 1));
37
37
 
38
38
  export function freePort() {
@@ -133,6 +133,7 @@ export async function run(o, cfg) {
133
133
  };
134
134
  const stopAll = sig => { stopTree(child.pid, sig); if (OS !== 'windows') for (const g of groups) stopTree(g, sig); };
135
135
  let finished = false, tracker = null, ran = null;
136
+ let took = null; // how long a run the quick lane let in really took
136
137
  const finish = code => {
137
138
  if (finished) return;
138
139
  finished = true;
@@ -152,7 +153,8 @@ export async function run(o, cfg) {
152
153
  + `${l.stopReason ? '' : ' Find out why before running it again: dibs history, or ask whoever stopped it.'}`);
153
154
  s.leases = s.leases.filter(x => x.id !== lease.id);
154
155
  // A failing run is often the one that ran out of memory: its size counts too.
155
- 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
+ if (l?.quick) took = now() - l.start - pausedFor(l);
156
158
  tellOverAsk(l);
157
159
  });
158
160
  } catch (e) {
@@ -163,6 +165,9 @@ export async function run(o, cfg) {
163
165
  else say(`dibs hit a bug recording that this job ended (${e.message}). Your command's exit code comes back anyway, and the next dibs command cleans up. Report it: dibs ask "..."`);
164
166
  }
165
167
  if (again) return runAgain(o, lease, again);
168
+ // Over the quick lane's limit: its next runs wait their turn until one comes in under (src/schedule.mjs quickPass).
169
+ const under = cfg.quickUnder == null ? null : ms(cfg.quickUnder);
170
+ if (took != null && under != null && took >= under) say(`this took ${dur(took)}, over the ${dur(under)} the quick lane is for, so its next runs wait their turn until one finishes in under ${dur(under)}.`);
166
171
  // A failing command's code can look like one of dibs's own (75, 74, 127), so say whose it is.
167
172
  if (code && code < 128) say(`${path.basename(o.cmd[0])} exited with code ${code}${DIBS_CODES.has(code) ? ". That's your command's code, not dibs's" : ''}.`);
168
173
  // One line that says it all, for an agent that has lost the output above (a compacted context).
@@ -218,7 +223,7 @@ function requeue(s, l, cfg) {
218
223
  const t = now();
219
224
  s.leases = s.leases.filter(x => x !== l);
220
225
  // What it really used goes into the history, so every later run of the command is planned at it too.
221
- 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);
222
227
  const res = l.res;
223
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;
224
229
  // Booked at what it really used, up to all the memory dibs shares out (usual keeps the rest).
@@ -243,6 +248,9 @@ function runAgain(o, lease, again) {
243
248
  say(again.why === 'over'
244
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},`
245
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.`
246
254
  : `stopped #${lease.id}: it sat paused for low disk while its memory went to swap and filled the disk.`
247
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.`);
248
256
  const args = process.argv.slice(2);
@@ -425,7 +433,7 @@ export function when(o, cfg) {
425
433
  const key = `${res.join(',')}|${o.cmd ? commandKey(o.cmd) : 'hold'}`;
426
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,
427
435
  ...sized(jobSize(cfg, res, o), hist, key, cfg), key };
428
- const s = withState(s => { markIdle(s); return s; });
436
+ const s = marked();
429
437
  probe.holding = holdingOf(s, probe, cfg, t);
430
438
  const v = verdict(s, probe, cfg, hist, t);
431
439
  const at = v.ok ? t : forecast(s, cfg, hist, t, probe).get(-1);
@@ -456,7 +464,7 @@ export function why(o, cfg) {
456
464
  const id = caller(o);
457
465
  const hist = history();
458
466
  const t = now();
459
- const s = withState(s => { markIdle(s); return s; });
467
+ const s = marked();
460
468
  const mine = s.queue.filter(q => q.pid && ours(q, id));
461
469
  if (!mine.length) {
462
470
  const holds = s.leases.filter(l => ours(l, id));
@@ -525,14 +533,14 @@ export function who(o, cfg) {
525
533
  if (!o.res.length) return status(o, cfg);
526
534
  const hist = history();
527
535
  const t = now();
528
- const s = withState(s => { markIdle(s); return s; });
536
+ const s = marked();
529
537
  const order = s.queue.filter(q => q.pid).sort(byRank(hist, t));
530
538
  const rows = [];
531
539
  for (const r of o.res) {
532
540
  // A file lease is held by whoever holds any path overlapping it.
533
541
  // One holder with two overlapping file leases is still one holder.
534
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);
535
- 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
536
544
  const n = named(cfg, r);
537
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`;
538
546
  const hold = isFiles(r) ? '' : machineHold(s, cfg);
@@ -645,6 +653,9 @@ export function pace(args) {
645
653
  // The bar is lower than dibs throttle's (50%): this only reports, it doesn't act.
646
654
  const BUSY_CPU = 40; // % of a core
647
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 [];
648
659
  const ours = new Set(s.leases.flatMap(l => [l.pgid, ...(l.groups || [])]).filter(Boolean));
649
660
  const groups = new Map();
650
661
  for (const p of processes()) {
@@ -686,6 +697,8 @@ export function boardJson(s, cfg, { hist = history(), m = machine(), t = now(),
686
697
  agents: agentsNow(cfg),
687
698
  questions: forYou(cfg, t),
688
699
  notes: notesForYou(),
700
+ // Agents waiting on dibs listen for a message: dibs tell reaches them within seconds.
701
+ listening: listeners(),
689
702
  caps: s.caps || {},
690
703
  later: laterBoard(t),
691
704
  // What's wrong, each with its fix (src/alerts.mjs): open ones, then those resolved lately.
@@ -694,9 +707,19 @@ export function boardJson(s, cfg, { hist = history(), m = machine(), t = now(),
694
707
  };
695
708
  }
696
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;
697
719
  export async function status(o, cfg) {
698
720
  const hist = history();
699
- const s = withState(s => { markIdle(s); return s; });
721
+ tableFirst();
722
+ const s = withState(s => { markIdle(s); return s; }, BOARD_WAIT) ?? peek();
700
723
  const m = machine();
701
724
  const t = now();
702
725
  // A broken remote.json still leaves this machine's board worth showing.
@@ -713,7 +736,7 @@ export async function status(o, cfg) {
713
736
  const out = [`${others ? `${rc.name} (this one) ` : ''}${cfg.pace ? `pace ${cfg.pace}, ` : ''}${handedOut(b)} `
714
737
  + `machine: ${m.memFree}% memory free, disk ${m.diskFree == null ? 'unknown' : `${gb(m.diskFree)} free`}, swap ${gb(m.swapUsed)}, load ${m.load.toFixed(1)}`
715
738
  + `${cfg.maxLoad != null ? ` (ceiling ${cfg.maxLoad})` : ''}`];
716
- out.unshift(...alertLines(scanAlerts({ s, cfg, hist, m, t }), t));
739
+ out.unshift(...alertLines(scanAlerts({ s, cfg, hist, m, t }).filter(a => onBoard(a, t)), t));
717
740
  const asks = forYou(cfg, t), notes = notesForYou();
718
741
  const plural = (n, w) => `${n} ${w}${n > 1 ? 's' : ''}`;
719
742
  if (asks || notes) out.unshift(`${[asks && plural(asks, 'question'), notes && plural(notes, 'note')].filter(Boolean).join(' and ')} for you: dibs ${notes ? 'threads' : 'questions'}`);
@@ -742,7 +765,7 @@ function plainStatus(s, cfg, hist, m, t, rc, away, broken, me) {
742
765
  const agent = !!me.agent;
743
766
  const out = [bold(headline(p))];
744
767
  // What's wrong comes before anything else, so it can't be missed.
745
- const alerted = alertLines(scanAlerts({ s, cfg, hist, m, t }), t);
768
+ const alerted = alertLines(scanAlerts({ s, cfg, hist, m, t }).filter(a => onBoard(a, t)), t);
746
769
  if (alerted.length) out.push('', ...alerted, '');
747
770
  // An agent reading the board wants its own place first.
748
771
  if (agent) {
@@ -757,6 +780,8 @@ function plainStatus(s, cfg, hist, m, t, rc, away, broken, me) {
757
780
  const count = (n, w) => `${n} ${w}${n > 1 ? 's' : ''}`;
758
781
  if (asks && !notes) out.push(amber(`${count(asks, 'question')} ${asks > 1 ? 'are' : 'is'} waiting for your answer: dibs questions`));
759
782
  else if (notes) out.push(amber(`${[asks && count(asks, 'question'), count(notes, 'note')].filter(Boolean).join(' and ')} ${asks + notes > 1 ? 'are' : 'is'} waiting for you: dibs threads`));
783
+ const ears = listeners();
784
+ if (ears.length) out.push(dim(`Listening for messages (dibs tell reaches them within seconds): ${ears.join(', ')}`));
760
785
  const { busy, free } = lineParts(p);
761
786
  out.push('', ...columns([...busy.map(b => [b.label, b.now, b.next]), ...(free.length ? [['Free', dim(freeText(p, free))]] : [])]));
762
787
 
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)
@@ -27,6 +28,7 @@ export const DEFAULT_CONFIG = {
27
28
  minFreeMem: 15, // jobs of 2G+ wait while the OS reports less than this % of memory free
28
29
  minDisk: '5G', // nothing starts below this much free disk
29
30
  starveAfter: '3m', // after this long at the head of the line, nobody jumps it
31
+ quickUnder: '15s', // a command that runs under this goes in the quick lane: it starts at once (src/schedule.mjs quickPass)
30
32
  roomyMemFree: 35, // with at least this % of memory free...
31
33
  roomyLoad: 0.6, // ...and load under this share of the cores, the memory and CPU budgets don't apply
32
34
  coolLoad: 8, // `dibs throttle` acts when the 1-minute load average is above this
@@ -75,8 +77,9 @@ export const DEFAULT_CONFIG = {
75
77
  test: { slots: 3, mem: '2G', cpu: 3, pausable: true, rerun: true },
76
78
  // One deploy at a time per project, up to across at once (exclusiveBy: src/schedule.mjs roomFor):
77
79
  // two projects' deploys don't touch each other, and a 6-second web deploy waited behind another
78
- // project's TestFlight upload (2026-11-03). slots is per project, so a config's slots: 1 reads so too.
79
- deploy: { slots: 1, mem: '0.5G', cpu: 1, pausable: false, exclusive: true, exclusiveBy: 'repo', across: 3 },
80
+ // project's TestFlight upload (2026-11-03). slots is per project, so a config's slots: 1 reads so too. A quick deploy of
81
+ // another project may go past across (quickAlongside).
82
+ deploy: { slots: 1, mem: '0.5G', cpu: 1, pausable: false, exclusive: true, exclusiveBy: 'repo', across: 3, quickAlongside: 'other-repo' },
80
83
  heavy: { slots: 1, mem: '4G', cpu: 4, disk: '10G', pausable: true, rerun: true },
81
84
  },
82
85
  // A name dibs doesn't know is often someone's lock ("one migration at a time"), so it never overlaps.
@@ -109,7 +112,9 @@ export function loadConfig() {
109
112
  if (v.onReleaseTimeout != null) ms(v.onReleaseTimeout);
110
113
  if (v.exclusiveBy != null && v.exclusiveBy !== 'repo') die(`resources.${k}.exclusiveBy in ${paths.config} is "repo" (one at a time per project), or null`);
111
114
  if (v.across != null && !(Number.isInteger(v.across) && v.across > 0)) die(`resources.${k}.across in ${paths.config} is how many projects may use it at once, a whole number above 0`);
115
+ if (v.quickAlongside != null && v.quickAlongside !== 'other-repo') die(`resources.${k}.quickAlongside in ${paths.config} is "other-repo" (a quick job of another repo starts beside this one's jobs), or null`);
112
116
  }
117
+ if (merged.quickUnder != null && !(ms(merged.quickUnder) >= 0)) die(`quickUnder in ${paths.config} is a duration like 15s, or null for no quick lane`);
113
118
  merged.profiles = checkProfiles(c.profiles, merged.resources);
114
119
  if (c.pace) Object.assign(merged, paced(c).knobs);
115
120
  // The person's own word wins; else the pace's; else one job per slot.
@@ -300,21 +305,37 @@ export const swapGrowth = (used, t = now()) => trends(used, null, t).swapGrowth;
300
305
 
301
306
  // Free disk and how fast it falls, swap and how fast it grows, memory
302
307
  // pressure, OS-reported free memory and load. Cached for 3s because waiters
303
- // 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
304
312
  // swapGrowth, diskDrain, drainMs, swapRecent and drainRecent; otherwise they
305
313
  // come from the readings file, with the fake swapUsed and diskFree.
306
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
+ }
307
325
  export function machine() {
308
326
  if (process.env.DIBS_FAKE_MACHINE) {
309
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'));
310
330
  // A fake that gives the 5-minute totals but not the recent ones is still moving.
311
331
  if (m.swapGrowth != null && m.diskDrain != null) return { drainMs: SWAP_WINDOW, swapRecent: m.swapGrowth, drainRecent: m.diskDrain, ...m };
312
332
  const t = trends(m.swapUsed, m.diskFree, m.at);
313
333
  return { ...m, swapGrowth: m.swapGrowth ?? t.swapGrowth, diskDrain: m.diskDrain ?? t.diskDrain, drainMs: m.drainMs ?? t.drainMs,
314
334
  swapRecent: m.swapRecent ?? (m.swapGrowth != null ? m.swapGrowth : t.swapRecent), drainRecent: m.drainRecent ?? (m.diskDrain != null ? m.diskDrain : t.drainRecent) };
315
335
  }
316
- if (cache && now() - cache.at < 3000) return cache;
336
+ if (fresh(cache)) return cache;
317
337
  // dibsMem, the full process table, only when swap is in question (schedule.mjs swapNotOurs).
318
- const m = { at: now(), ...pressure(HOME), vmPressure: memPressure() };
338
+ let m = lastReading();
339
+ if (!fresh(m)) shareReading(m = { at: now(), ...pressure(HOME, m) });
319
340
  return (cache = { ...m, ...trends(m.swapUsed, m.diskFree, m.at) });
320
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
@@ -1,10 +1,12 @@
1
1
  // Before the disk runs out: under twice the floor, dibs clears caches that
2
- // rebuild themselves, and tells every active session how much is free, what's
3
- // growing and whose folder holds the most, at most every WARN_EVERY, again at
4
- // once when it drops under the floor. Under the floor, each agent with a job
5
- // running hears to save its work now, and each with a job waiting hears that
6
- // it waits for disk. On 2026-10-20 the Mac hit 210 MB free: writes failed,
7
- // Bash died for every session, and jobs sat silently on "free disk".
2
+ // rebuild themselves, and tells the sessions with something of their own to
3
+ // free (a big scratch folder, or running jobs that wrote a lot) how much is
4
+ // free and what to do. Each hears once per band: under twice the floor, then
5
+ // under the floor. On 2026-10-20 the Mac hit 210 MB free: writes failed, Bash
6
+ // died for every session, and jobs sat silently on "free disk". On 2026-11-03
7
+ // the warnings had gone to every session, 13 of them as the disk fell from 8.2
8
+ // to 4.7 GB, mostly to agents with nothing to free; the person sees the whole
9
+ // machine in dibs alerts.
8
10
  import fs from 'node:fs';
9
11
  import os from 'node:os';
10
12
  import path from 'node:path';
@@ -14,11 +16,15 @@ import { freeDisk, OS } from './platform.mjs';
14
16
  import { event } from './events.mjs';
15
17
  import { gb, bytes, now } from './util.mjs';
16
18
  import { makeAlive } from './proc.mjs';
19
+ import { withState } from './state.mjs';
17
20
 
18
21
  const GB = b => gb(b).replace(/G$/, ' GB');
19
22
  const SAY_FREED = 0.1 * 1024 ** 3; // less than shows as 0.0 GB: not worth a line
20
23
  const LOG = path.join(HOME, 'cool.log');
21
- export const WARN_EVERY = 15 * 6e4;
24
+ // Running jobs that wrote this much (src/measure.mjs, a run's share of the disk's fall) have something to free.
25
+ const ATE_MIN = 1024 ** 3;
26
+ // The bands a session hears about once each, worst last.
27
+ const BANDS = ['low', 'critical'];
22
28
  // Clearing caches again sooner than this frees little: they refill slowly.
23
29
  const CLEAN_EVERY = 30 * 6e4;
24
30
  const STEP_TIMEOUT = 2 * 6e4;
@@ -79,6 +85,9 @@ export async function clean(t = now(), where = HOME) {
79
85
  done.push({ label: st.label, freed: Math.max(0, by) });
80
86
  }
81
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 {}
82
91
  try {
83
92
  fs.appendFileSync(LOG, `${new Date(t).toISOString()} disk low: dibs cleared ${done.map(d => d.label).join(', ')}, freeing ${GB(freed)}\n`);
84
93
  event({ kind: 'clean', freed, steps: done });
@@ -87,17 +96,17 @@ export async function clean(t = now(), where = HOME) {
87
96
  }
88
97
  export const cleanDue = (was, t, critical) => !(t - (was?.cleaned?.at || 0) < (critical && !was?.cleanedCritical ? 0 : CLEAN_EVERY));
89
98
 
90
- // The sessions to tell: those with a job running or waiting, and those whose
91
- // thread with dibs moved in the last hour. Their jobs, for the note.
92
- function sessions(s, t) {
99
+ // The sessions to tell: those with something of their own to free, a scratch
100
+ // folder hogs.mjs found over its line (was.folders) or running jobs that ate
101
+ // ATE_MIN of disk. Their jobs, for the note.
102
+ function sessions(s, was) {
93
103
  const out = new Map();
94
- const add = (session, who, agentId) => { if (session && !out.has(session)) out.set(session, { session, who, agentId: agentId || null, running: [], waiting: [] }); return out.get(session); };
95
- for (const l of s.leases || []) if (l.kind === 'run' && l.sessionId) add(l.sessionId, l.who, l.agentId).running.push(l);
96
- for (const q of s.queue || []) if (q.pid && q.sessionId) add(q.sessionId, q.who, q.agentId).waiting.push(q);
97
- try {
98
- for (const th of JSON.parse(fs.readFileSync(path.join(HOME, 'messages.json'), 'utf8')).threads || [])
99
- if (th.session && t - (th.last || 0) < 36e5) add(th.session, th.who, th.agentId);
100
- } catch {}
104
+ const add = (session, who, agentId) => { if (session && !out.has(session)) out.set(session, { session, who, agentId: agentId || null, running: [], waiting: [], growing: false }); return out.get(session); };
105
+ // Growing: its folder grew since the last reading (hogs.mjs), or its jobs are writing.
106
+ for (const h of was?.folders || []) add(h.session, h.who, h.agentId).growing ||= !!was.grew?.includes(`session ${h.session}'s scratch folder`);
107
+ for (const l of s.leases || []) if (l.kind === 'run' && l.sessionId && (l.ate || 0) >= ATE_MIN) add(l.sessionId, l.who, l.agentId).growing = true;
108
+ for (const l of s.leases || []) if (l.kind === 'run' && out.has(l.sessionId)) out.get(l.sessionId).running.push(l);
109
+ for (const q of s.queue || []) if (q.pid && out.has(q.sessionId)) out.get(q.sessionId).waiting.push(q);
101
110
  return [...out.values()];
102
111
  }
103
112
  const job = x => `#${x.id}${x.purpose ? ` ("${x.purpose}")` : ''}`;
@@ -113,21 +122,11 @@ export function noteText(x, m, floor, hint, cleaned) {
113
122
  if (critical && x.running.length) lines.push(`Your running dibs ${x.running.length === 1 ? 'job' : 'jobs'} ${x.running.map(job).join(', ')} may fail writing: save what it has done if you can`);
114
123
  // Over the floor a waiter is held by something else, not the disk.
115
124
  if (critical && x.waiting.length) lines.push(`Your waiting ${x.waiting.length === 1 ? 'job' : 'jobs'} ${x.waiting.map(job).join(', ')} won't start until there's room`);
116
- lines.push('Free what you can of your own: build output, scratch folders and merged worktrees your session made (only exact paths you made; others of your session may still use the rest)');
125
+ // Files holding still were there before the disk got low: telling their session to free them each time taught agents to skip the note (e4, 2026-11-03).
126
+ if (x.growing) lines.push('Free what you can of your own: build output, scratch folders and merged worktrees your session made (only exact paths you made; others of your session may still use the rest)');
117
127
  return lines.join('. ') + '.';
118
128
  }
119
129
 
120
- // Whether a session hears again. Under the floor: every WARN_EVERY, and at once on
121
- // dropping under it. Over it: only once free disk has fallen DROP_AGAIN since its last
122
- // note, or something grows fast (hogs.mjs writer): a note every 15 minutes at a steady
123
- // 9.2 GB taught agents to skip it.
124
- const DROP_AGAIN = 1024 ** 3;
125
- function again(last, level, m, was, t) {
126
- if (level === 'critical') return last.level !== 'critical' || t - last.at >= WARN_EVERY;
127
- if (t - last.at < WARN_EVERY) return false;
128
- return last.free == null || last.free - m.diskFree >= DROP_AGAIN || !!(was?.writer && t - was.readAt < WARN_EVERY);
129
- }
130
-
131
130
  // Whether the throttle watcher (src/cool.mjs) is down: its pidfile names no live process.
132
131
  export function watcherDown() {
133
132
  let pid = 0;
@@ -136,7 +135,7 @@ export function watcherDown() {
136
135
  }
137
136
 
138
137
  // One pass, from hogs.mjs under twice the floor: clear caches when due, then tell
139
- // each active session, once per WARN_EVERY and level. Returns what to keep in hogs.json.
138
+ // each session with something to free, once per band. Returns what to keep in hogs.json.
140
139
  export async function warnOnce(cfg, m, was, hint, t = now()) {
141
140
  const floor = bytes(cfg.minDisk);
142
141
  if (m.diskFree == null || m.diskFree >= 2 * floor) return {};
@@ -148,14 +147,12 @@ export async function warnOnce(cfg, m, was, hint, t = now()) {
148
147
  try { s = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
149
148
  const { notify } = await import('./talk.mjs');
150
149
  const level = critical ? 'critical' : 'low';
151
- // Each session's last note, so it hears again only WARN_EVERY later, or at once when it turns critical.
150
+ // The worst band each session has heard about; hogs.mjs clears it once there's room again.
152
151
  const warned = { ...(was?.warned || {}) };
153
- for (const x of sessions(s, t)) {
154
- const last = warned[x.session];
155
- if (last && !again(last, level, m, was, t)) continue;
152
+ for (const x of sessions(s, was)) {
153
+ if (BANDS.indexOf(warned[x.session]?.level) >= BANDS.indexOf(level)) continue;
156
154
  if (notify({ sessionId: x.session, who: x.who, agentId: x.agentId }, `disk:${level}:${t}`, noteText(x, m, floor, hint, cleaned))) warned[x.session] = { at: t, level, free: m.diskFree };
157
155
  }
158
- for (const [k, w] of Object.entries(warned)) if (t - w.at > 4 * WARN_EVERY) delete warned[k];
159
156
  // Kept only when it changed: on a nearly full disk, every write counts.
160
157
  return JSON.stringify(warned) === JSON.stringify(was?.warned || {}) ? keep : { ...keep, warned };
161
158
  }
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;
@@ -85,7 +94,9 @@ export function logChanges(before, paused, s) {
85
94
  const pausedMs = (l.pausedMs || 0) + (paused.get(l.id) ? t - paused.get(l.id) : 0);
86
95
  // What it was, so a failure can be named and a later success of the same command can close it (src/alerts.mjs).
87
96
  out.push({ at: t, kind: 'end', ...fields(l), code: l.code ?? null, ms: t - l.start, paused: pausedMs,
88
- ...(l.kind === 'run' && { key: l.key, cmd: String(l.cmd || '').slice(0, 120), ...(l.purpose && { purpose: String(l.purpose).slice(0, 120) }) }) });
97
+ ...(l.kind === 'run' && { key: l.key, cmd: String(l.cmd || '').slice(0, 120), ...(l.purpose && { purpose: String(l.purpose).slice(0, 120) }),
98
+ // A deadline (--by) makes its failure the person's business; an override's by is a name, not that.
99
+ ...(typeof l.by === 'number' && { due: l.by }) }) });
89
100
  }
90
101
  if (!out.length) return;
91
102
  rotate(t);