@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.
- package/CHANGELOG.md +23 -2
- package/README.md +4 -2
- package/bin/dibs-guard.mjs +10 -1
- package/bin/dibs.mjs +28 -9
- package/docs/benchmarks.md +1 -1
- package/docs/files.md +1 -1
- package/docs/guard.md +6 -0
- package/docs/questions.md +6 -2
- package/docs/reference.md +4 -4
- package/docs/relay.md +9 -7
- package/docs/releasing.md +4 -3
- package/docs/scheduling.md +4 -4
- package/docs/windows.md +14 -0
- package/package.json +1 -1
- package/skills/dibs/SKILL.md +5 -5
- package/src/acquire.mjs +91 -26
- package/src/agents.mjs +7 -22
- package/src/alerts.mjs +59 -21
- package/src/board.mjs +1 -2
- package/src/broker.mjs +26 -11
- package/src/commands.mjs +25 -9
- package/src/config.mjs +21 -4
- package/src/cool.mjs +104 -9
- package/src/diskwarn.mjs +4 -0
- package/src/events.mjs +10 -1
- package/src/files.mjs +49 -87
- package/src/guard.mjs +24 -8
- package/src/guardd.mjs +97 -0
- package/src/guardw.mjs +19 -0
- package/src/later.mjs +20 -25
- package/src/lock.mjs +292 -0
- package/src/measure.mjs +9 -4
- package/src/ondemand.mjs +5 -2
- package/src/override.mjs +39 -2
- package/src/plain.mjs +2 -2
- package/src/platform.mjs +165 -35
- package/src/preempt.mjs +51 -3
- package/src/primer.mjs +1 -1
- package/src/proc.mjs +35 -5
- package/src/questions.mjs +8 -22
- package/src/relay.mjs +10 -22
- package/src/remote.mjs +12 -8
- package/src/schedule.mjs +139 -26
- package/src/serve.mjs +16 -3
- package/src/service.mjs +4 -3
- package/src/state.mjs +139 -47
- package/src/stats.mjs +3 -2
- package/src/talk.mjs +160 -77
- package/src/trust.mjs +7 -1
- package/src/util.mjs +28 -2
- package/src/version.mjs +1 -1
- package/src/web.mjs +15 -25
- package/src/worker.mjs +2 -1
package/src/acquire.mjs
CHANGED
|
@@ -5,17 +5,17 @@ import { spawn } from 'node:child_process';
|
|
|
5
5
|
import { resCfg, machine, paths, HOME, loadConfig } from './config.mjs';
|
|
6
6
|
import { identity, pstart, tag } from './proc.mjs';
|
|
7
7
|
import { processes, parent, OS } from './platform.mjs';
|
|
8
|
-
import { withState, history, KEEP_PLACE } from './state.mjs';
|
|
8
|
+
import { withState, peek, history, setLockDeadline, KEEP_PLACE } from './state.mjs';
|
|
9
9
|
import { preempt } from './preempt.mjs';
|
|
10
10
|
import { isFiles, short, shellRes, projectKey } from './files.mjs';
|
|
11
11
|
import { jobSize } from './simpool.mjs';
|
|
12
12
|
import { sized, grewLine, grewPlain, treeOf } from './measure.mjs';
|
|
13
13
|
import { isQuota, quotaProblem, quotaBlock, takeQuota } from './quota.mjs';
|
|
14
|
-
import { capWaiter } from './override.mjs';
|
|
14
|
+
import { capWaiter, inversions, lift } from './override.mjs';
|
|
15
15
|
import { verdict, forecast, expected, remaining, byRank, holdingOf, PRIORITY_SHIFT, PRIORITIES, NEEDS_REASON, used, overBy, STALL, neverFits, explicitAsk, capToMachine, quickPass } from './schedule.mjs';
|
|
16
16
|
import { event } from './events.mjs';
|
|
17
17
|
import { startLine } from './overlap.mjs';
|
|
18
|
-
import { dur, clock, die, say, sleep, now, ms, gb, SIGNALS, signalExit, KEY_SPLIT, noSpace, OFF_LIMITS, callerPid } from './util.mjs';
|
|
18
|
+
import { dur, clock, die, say, sleep, now, ms, gb, SIGNALS, signalExit, KEY_SPLIT, noSpace, OFF_LIMITS, callerPid, POLLED_EVERY, UNPOLLED, GHOST_AFTER } from './util.mjs';
|
|
19
19
|
import { plainBoard, startPhrase, askFirst, named, andList, lower, ordinal, moves, stuckFor, STUCK_AFTER } from './plain.mjs';
|
|
20
20
|
import { quoted, wrap, width } from './style.mjs';
|
|
21
21
|
import { noticeScan } from './notices.mjs';
|
|
@@ -73,14 +73,16 @@ export const defaultMaxWait = () =>
|
|
|
73
73
|
backgroundable() ? Infinity : process.env.DIBS_MAX_WAIT ? ms(process.env.DIBS_MAX_WAIT) : DEFAULT_MAX_WAIT;
|
|
74
74
|
|
|
75
75
|
// Said once, when the wait starts, so nobody has to guess what happens at the end of it.
|
|
76
|
-
function waitTerms(w) {
|
|
76
|
+
function waitTerms(w, disk) {
|
|
77
77
|
if (w.maxWait === Infinity)
|
|
78
78
|
return !w.info.waitSet
|
|
79
79
|
? "No time limit. If this tool call times out, Claude Code moves it to the background and tells you when it ends: don't run it again, or it runs twice."
|
|
80
80
|
: 'No time limit (--wait).';
|
|
81
|
-
return `Gives up at ${clock(w.started + w.maxWait)} if it's still waiting (exit 75: your command won't have run). To wait as long as it takes, add --wait.`;
|
|
81
|
+
return `Gives up at ${clock(w.started + w.maxWait)} if it's still waiting (exit ${disk ? 74 : 75}: your command won't have run). To wait as long as it takes, add --wait.`;
|
|
82
82
|
}
|
|
83
83
|
|
|
84
|
+
const GB = x => gb(x).replace(/G$/, ' GB');
|
|
85
|
+
|
|
84
86
|
// The command as the agent typed it, to paste back.
|
|
85
87
|
const again = () => `dibs ${quoted(process.argv.slice(2))}`;
|
|
86
88
|
|
|
@@ -89,6 +91,12 @@ const again = () => `dibs ${quoted(process.argv.slice(2))}`;
|
|
|
89
91
|
// Every process group the run spans counts: a test runner's workers split off
|
|
90
92
|
// into groups of their own, and a run whose own group sleeps while they work isn't idle.
|
|
91
93
|
// A simulator the run is using counts too (src/measure.mjs treeOf): its work runs there.
|
|
94
|
+
// The process table markIdle reads, read before taking the lock when a run may need it:
|
|
95
|
+
// at load 30, ps -A took 0.6 to 4 s, and under the lock every other dibs waited that long too.
|
|
96
|
+
export function tableFirst() {
|
|
97
|
+
if (peek().leases.some(l => l.kind === 'run' && l.pgid && !l.pausedAt)) processes();
|
|
98
|
+
}
|
|
99
|
+
|
|
92
100
|
export function markIdle(s, procs) {
|
|
93
101
|
const runs = s.leases.filter(l => l.kind === 'run' && l.pgid && !l.pausedAt); // a paused job is quiet on purpose
|
|
94
102
|
if (!runs.length) return;
|
|
@@ -238,11 +246,13 @@ const left = (w, why) => { if (w.blocked) note(w, 'left', { ms: now() - w.me.enq
|
|
|
238
246
|
// state read drops it once this process is gone.
|
|
239
247
|
function leave(w, keep) {
|
|
240
248
|
try {
|
|
241
|
-
|
|
249
|
+
// A low job lifted for this waiter alone goes back down as it leaves (src/override.mjs inversions).
|
|
250
|
+
lift(withState(s => {
|
|
242
251
|
const q = s.queue.find(x => x.id === w.me.id);
|
|
243
252
|
if (keep && q) Object.assign(q, { pid: null, keepUntil: now() + KEEP_PLACE });
|
|
244
253
|
else s.queue = s.queue.filter(x => x.id !== w.me.id);
|
|
245
|
-
|
|
254
|
+
return inversions(s, w.cfg);
|
|
255
|
+
}));
|
|
246
256
|
} catch (e) { if (!noSpace(e)) throw e; }
|
|
247
257
|
}
|
|
248
258
|
|
|
@@ -288,7 +298,7 @@ async function saved(w, fn) {
|
|
|
288
298
|
// Its size again from what its command has used, as dibs learns now: on
|
|
289
299
|
// 2026-10-20 nine browser runs sized when one run had read 15 GB still waited,
|
|
290
300
|
// two hours on, for the whole budget the new rule no longer planned.
|
|
291
|
-
|
|
301
|
+
export { UNPOLLED }; // src/board.mjs reads it from here
|
|
292
302
|
function resize(cur, w) {
|
|
293
303
|
if (cur.sent) return;
|
|
294
304
|
const base = { mem: cur.asked ?? cur.mem, cpu: cur.cpu, disk: cur.disk };
|
|
@@ -298,9 +308,37 @@ function resize(cur, w) {
|
|
|
298
308
|
if (n.usual != null) cur.usual = n.usual; else delete cur.usual;
|
|
299
309
|
Object.assign(w.info.size, { mem: n.mem, usual: n.usual });
|
|
300
310
|
}
|
|
311
|
+
// Adds the time since the rule last changed to the rule that held it then, and
|
|
312
|
+
// notes the new one. Kept on the queue entry, not in the waiter's memory: #17303
|
|
313
|
+
// waited 10h22m on 2026-11-01 and its start event named 64 minutes of it, since
|
|
314
|
+
// each of four new brokers began the count again. Written only when the rule
|
|
315
|
+
// changes, so a poll that changes nothing still leaves the state file alone. A
|
|
316
|
+
// stretch nobody decided for it (no broker, a waiter stopped) is 'unpolled',
|
|
317
|
+
// from the last time its dibs looked, so every second it waited has a name.
|
|
318
|
+
function heldFor(cur, rule, looked) {
|
|
319
|
+
const t = now(), held = { ...cur.held };
|
|
320
|
+
let from = cur.heldAt ?? cur.enq;
|
|
321
|
+
const add = (k, ms) => { if (k && ms > 0) held[k] = (held[k] || 0) + ms; };
|
|
322
|
+
const gap = looked != null && t - looked > UNPOLLED;
|
|
323
|
+
if (gap) { add(cur.heldRule ?? rule, looked - from); add('unpolled', t - Math.max(looked, from)); from = t; }
|
|
324
|
+
if (!gap && rule === cur.heldRule && cur.heldAt != null) return;
|
|
325
|
+
add(cur.heldRule ?? rule, t - from);
|
|
326
|
+
if (Object.keys(held).length) cur.held = held;
|
|
327
|
+
if (rule) cur.heldRule = rule; else delete cur.heldRule;
|
|
328
|
+
cur.heldAt = t;
|
|
329
|
+
}
|
|
301
330
|
export function decide(s, w) {
|
|
331
|
+
const r = judge(s, w);
|
|
332
|
+
const moves = inversions(s, w.cfg);
|
|
333
|
+
if (moves.length) r.lift = moves;
|
|
334
|
+
return r;
|
|
335
|
+
}
|
|
336
|
+
function judge(s, w) {
|
|
302
337
|
const { me, cfg, hist, info } = w;
|
|
303
|
-
const cur = s.queue.find(x => x.id === me.id)
|
|
338
|
+
const cur = s.queue.find(x => x.id === me.id);
|
|
339
|
+
// No place, no turn: one taken out of line (stopped, or left unlooked-at, src/state.mjs reap)
|
|
340
|
+
// stays out. Running on from this copy of it, a waiter would start with nobody's place.
|
|
341
|
+
if (!cur) { const x = s.stopped?.[me.id]; return x ? { stopped: true, by: x.by, reason: x.reason } : { gone: true }; }
|
|
304
342
|
if (cur.ownerStop) { s.queue = s.queue.filter(x => x.id !== me.id); return { stopped: true, by: cur.stopBy, reason: cur.stopReason }; }
|
|
305
343
|
// Kept current here, so it lapses when the hold ages out or ends.
|
|
306
344
|
const holding = holdingOf(s, cur, cfg);
|
|
@@ -308,6 +346,7 @@ export function decide(s, w) {
|
|
|
308
346
|
resize(cur, w);
|
|
309
347
|
// When its dibs last looked, so the board can tell a waiter that could start from one nobody
|
|
310
348
|
// is deciding for. Once a minute at most: a poll that changes nothing leaves the state file alone.
|
|
349
|
+
const looked = cur.polledAt;
|
|
311
350
|
if (!(now() - (cur.polledAt || 0) < POLLED_EVERY)) cur.polledAt = now();
|
|
312
351
|
// Kept on the entry, so other waiters rank it at the front too (src/schedule.mjs quickPass).
|
|
313
352
|
if (quickPass(cur, hist, cfg)) cur.quickPass = true; else delete cur.quickPass;
|
|
@@ -316,12 +355,8 @@ export function decide(s, w) {
|
|
|
316
355
|
if (!v.ok && v.rule === 'slot' && !cur.quickPass) v = quotaBlock(s, cur, cfg, hist) || preempt(s, cur, cfg, hist) || v;
|
|
317
356
|
if (v.ok) v = quotaBlock(s, cur, cfg, hist) || v;
|
|
318
357
|
// What held it and for how long, for its start event: on 2026-10-24 a 2-second test waited
|
|
319
|
-
// 3 minutes with 11 GB of disk free, and the log said only that it waited.
|
|
320
|
-
|
|
321
|
-
const t = now();
|
|
322
|
-
if (w.heldRule) w.heldBy = { ...w.heldBy, [w.heldRule]: (w.heldBy?.[w.heldRule] || 0) + t - w.heldAt };
|
|
323
|
-
w.heldRule = v.ok ? null : v.rule || 'other';
|
|
324
|
-
w.heldAt = t;
|
|
358
|
+
// 3 minutes with 11 GB of disk free, and the log said only that it waited.
|
|
359
|
+
heldFor(cur, v.ok ? null : v.rule || 'other', looked);
|
|
325
360
|
// For the stall breaker (schedule.mjs): whether the machine, not the line, holds this one back.
|
|
326
361
|
if (!v.ok && v.machine) cur.machineHeld = true; else delete cur.machineHeld;
|
|
327
362
|
// When the load ceiling alone started holding it: after LOAD_STARVE it starts anyway (schedule.mjs).
|
|
@@ -347,7 +382,7 @@ export function decide(s, w) {
|
|
|
347
382
|
// Sitting on one resource while waiting for another wastes it for everyone.
|
|
348
383
|
// A file lease doesn't count: it keeps edits off files while you work, and a job waiting for a test slot doesn't change that.
|
|
349
384
|
const sitting = s.leases.filter(l => l.kind === 'hold' && me.spid && l.pid === me.spid && !l.res.some(x => me.res.includes(x)) && !l.res.every(isFiles));
|
|
350
|
-
return { v, line: waitLine(s, cur, v, cfg, hist, w.talk.told),
|
|
385
|
+
return { v, line: waitLine(s, cur, v, cfg, hist, w.talk.told), sitting, holding: cur.holding };
|
|
351
386
|
}
|
|
352
387
|
s.queue = s.queue.filter(x => x.id !== me.id);
|
|
353
388
|
takeQuota(s, cur, cfg);
|
|
@@ -355,7 +390,7 @@ export function decide(s, w) {
|
|
|
355
390
|
purpose: cur.purpose, cmd: me.cmd, key: me.key, est: info.est, prio: cur.prio, by: cur.by,
|
|
356
391
|
cwd: info.cwd, ppid: info.ppid, start: now(), waited: now() - cur.enq, agentId: info.agentId, sessionId: info.sessionId,
|
|
357
392
|
owner: cur.owner, askedPrio: cur.askedPrio };
|
|
358
|
-
if (
|
|
393
|
+
if (cur.held) lease.held = Object.fromEntries(Object.entries(cur.held).map(([k, x]) => [k, Math.round(x)]));
|
|
359
394
|
if (v.covered.length) lease.covered = v.covered;
|
|
360
395
|
if (v.alongside) lease.alongside = v.alongside;
|
|
361
396
|
if (v.trial) lease.trial = true;
|
|
@@ -381,11 +416,20 @@ export function decide(s, w) {
|
|
|
381
416
|
// through w.out (exit 74, 75, or the owner's stop).
|
|
382
417
|
export function step(r, w) {
|
|
383
418
|
const { me, cfg, out } = w;
|
|
419
|
+
if (r.lift) {
|
|
420
|
+
lift(r.lift);
|
|
421
|
+
for (const m of r.lift) if (!m.bg && m.for === me.id) out.say(`lifted #${m.id} (${m.who}'s low-priority job on ${m.res.join(',')}) off background priority, so you aren't stuck behind it while the machine is busy. It goes back down once nobody waits on it.`);
|
|
422
|
+
}
|
|
384
423
|
if (r.stopped) {
|
|
385
424
|
left(w, 'owner stop');
|
|
386
425
|
return out.die(`stopped by ${r.by || 'the owner (the person at this machine)'} on purpose (dibs stop)${r.reason ? `: "${r.reason}"` : ''}. This was taken out of line and your command did not run.`
|
|
387
426
|
+ `${r.reason ? '' : ' Find out why before trying again: dibs history, or ask whoever stopped it.'}`, signalExit('SIGTERM'));
|
|
388
427
|
}
|
|
428
|
+
if (r.gone) {
|
|
429
|
+
left(w, 'place gone');
|
|
430
|
+
return out.die(`#${me.id} is no longer in line: it was taken out, or nothing had looked at it for ${dur(GHOST_AFTER)}.`
|
|
431
|
+
+ ` Your command did NOT run (exit 75). Run it again to get back in line:\n ${w.info.again}`, 75);
|
|
432
|
+
}
|
|
389
433
|
if (r.never) {
|
|
390
434
|
left(w, 'never fits');
|
|
391
435
|
const text = neverText(r.never, me, cfg, null);
|
|
@@ -416,16 +460,25 @@ export function step(r, w) {
|
|
|
416
460
|
out.say(`you're keeping ${andList(kept.map(x => named(cfg, x).the))} reserved while you wait, so nobody else can use it.`
|
|
417
461
|
+ ` Give it back (dibs release ${kept[0]}) or ask for everything at once: dibs run ${[...new Set([...kept, ...me.res])].join(',')} -- <command>`);
|
|
418
462
|
}
|
|
419
|
-
//
|
|
420
|
-
|
|
421
|
-
|
|
463
|
+
// Low disk is waited out, like memory: a person or a job ending frees space, and the run
|
|
464
|
+
// starts the moment there's room, checked again at every poll. Until 0.0.179 a run with
|
|
465
|
+
// nothing else running was refused at once (exit 74): on 2026-11-02 a TestFlight ship
|
|
466
|
+
// waited 10 hours, then its inner dibs hold sim was refused with 6.7 GB free, and a
|
|
467
|
+
// scheduled job died the same way. Only a run that needs more than the whole disk is.
|
|
468
|
+
const total = r.v.disk && machine().diskTotal;
|
|
469
|
+
if (total && r.v.need > total) {
|
|
470
|
+
left(w, 'never fits the disk');
|
|
422
471
|
leave(w, false);
|
|
423
|
-
return out.die(`not enough
|
|
424
|
-
+ ` Your command did NOT run (exit 74).
|
|
472
|
+
return out.die(`not enough disk, ever: it needs ${GB(r.v.need)} free and the whole disk is ${GB(total)}.`
|
|
473
|
+
+ ` Your command did NOT run (exit 74). If this run needs less, pass --disk with what it really needs:\n ${w.info.again}`, 74);
|
|
425
474
|
}
|
|
426
475
|
if (now() - w.started >= w.maxWait) {
|
|
427
476
|
note(w, 'timeout', { ms: now() - me.enq });
|
|
428
477
|
leave(w, w.maxWait > 0);
|
|
478
|
+
// Outside Claude Code the wait has a limit; ended by the disk, it says so (exit 74).
|
|
479
|
+
if (r.v.disk)
|
|
480
|
+
return out.die(`${w.maxWait ? `gave up after ${dur(now() - w.started)} in the queue: ` : ''}not enough free disk: ${GB(r.v.free)} free, it needs ${GB(r.v.need)}${r.v.floorWhy ? `: ${r.v.floorWhy}` : ''}.`
|
|
481
|
+
+ ` Your command did NOT run (exit 74). Free some space${r.v.floorWhy ? '' : ", or pass --disk with what this job really needs if that's less"}, then run it again${w.maxWait ? `, or add --wait to wait until there's room` : ''}:\n ${w.info.again}\n ${OFF_LIMITS}`, 74);
|
|
429
482
|
if (!w.maxWait)
|
|
430
483
|
return out.die(`not free yet. ${r.line.why} --no-wait doesn't wait, so your command did NOT run (exit 75).`
|
|
431
484
|
+ ` See when it frees up: dibs when ${shellRes(me.res.map(x => short(x)))}`, 75);
|
|
@@ -457,7 +510,7 @@ export function step(r, w) {
|
|
|
457
510
|
// every MOVE_EVERY), or now and then.
|
|
458
511
|
const l = r.line;
|
|
459
512
|
const what = w.talk.step(l);
|
|
460
|
-
if (what === 'full') out.said(`queued for ${andList(me.res.map(x => named(cfg, x).the))}.${me.kind === 'hold' ? ' dibs hold waits for its turn like dibs run, then returns.' : ''}`, l.head, l.why, l.ask, w.maxWait > 0 ? waitTerms(w) : '');
|
|
513
|
+
if (what === 'full') out.said(`queued for ${andList(me.res.map(x => named(cfg, x).the))}.${me.kind === 'hold' ? ' dibs hold waits for its turn like dibs run, then returns.' : ''}`, l.head, l.why, l.ask, w.maxWait > 0 ? waitTerms(w, r.v.disk) : '');
|
|
461
514
|
else if (what === 'change') out.said(`still queued (${dur(now() - w.started)}). ${l.head}`, l.why);
|
|
462
515
|
else if (what === 'moved') out.say(`still queued (${dur(now() - w.started)}). You ${l.moved}`);
|
|
463
516
|
else if (what === 'repeat') out.say(`still queued (${dur(now() - w.started)}). ${l.head}`);
|
|
@@ -611,6 +664,7 @@ export async function acquire(o, kind, cfg) {
|
|
|
611
664
|
if (machine().diskFree == null) say("couldn't read free disk space, so the disk check is off for this request.");
|
|
612
665
|
|
|
613
666
|
const started = now();
|
|
667
|
+
if (maxWait !== Infinity) setLockDeadline(started + maxWait);
|
|
614
668
|
const w = waiter({ started, maxWait, waitSet: o.maxWait != null, for: o.for, est: o.est, agentId: o.agentId, sessionId: process.env.CLAUDE_CODE_SESSION_ID,
|
|
615
669
|
cwd: process.cwd(), ppid: callerPid(), sstart: id.sstart, size: { mem, cpu, asked, askedCpu, usual }, again: again(), path: o.thin?.fifo,
|
|
616
670
|
notify: o.notify ? path.resolve(o.notify) : undefined, follow: process.env.DIBS_REMOTE_JOB ? { pid: callerPid(), pstart: pstart(callerPid()) } : undefined }, cfg, hist, stderrOut);
|
|
@@ -621,9 +675,16 @@ export async function acquire(o, kind, cfg) {
|
|
|
621
675
|
const hold = sig => { early ||= sig; if (w.full) process.exit(signalExit(sig)); };
|
|
622
676
|
for (const sig of SIGNALS) process.on(sig, hold);
|
|
623
677
|
w.me = await saved(w, s => {
|
|
624
|
-
//
|
|
625
|
-
|
|
626
|
-
|
|
678
|
+
// Its own place first: this process, by pid and start time, getting in line again (a thin waiter's
|
|
679
|
+
// shell become Node keeps both). Then one kept for it, then one a timed-out wait left for this command.
|
|
680
|
+
// Never a live waiter's place, nor one kept for another process: on 2026-11-04 pid 97301 had #19783
|
|
681
|
+
// and #19784 for one command, and #19783, which nothing decided for any more, held heavy for 21 h.
|
|
682
|
+
const me = x => myStart && x.pid === pid && x.pstart === myStart;
|
|
683
|
+
let q = s.queue.find(x => x.ticket === ticket && me(x))
|
|
684
|
+
|| s.queue.find(x => x.ticket === ticket && !x.pid && x.keptFor === pid)
|
|
685
|
+
|| s.queue.find(x => x.ticket === ticket && !x.pid && !x.keptFor);
|
|
686
|
+
// Stamped as looked-at now: a place picked up is decided for again from here on.
|
|
687
|
+
if (q) { Object.assign(q, { pid, pstart: myStart, keepUntil: null, polledAt: now() }); delete q.wake; delete q.keptFor; }
|
|
627
688
|
else {
|
|
628
689
|
q = { id: ++s.seq, ticket, res, mem, cpu, disk, asked, askedCpu, usual, pid, pstart: myStart, enq: now(), polledAt: now(),
|
|
629
690
|
who: id.who, agent: id.agent, label: id.label, spid: id.spid, purpose: o.purpose || '', cmd, key, kind,
|
|
@@ -635,6 +696,8 @@ export async function acquire(o, kind, cfg) {
|
|
|
635
696
|
if (sent) q.sent = true; // placed here by the coordinator for its size (neverFits)
|
|
636
697
|
s.queue.push(q);
|
|
637
698
|
}
|
|
699
|
+
// A process waits for one thing: any other place under it was left behind, and only holds others back.
|
|
700
|
+
s.queue = s.queue.filter(x => x === q || !(me(x) || (!x.pid && x.keptFor === pid)));
|
|
638
701
|
// Without -m, a wait for the rest of what a ship needs says what the ship is for.
|
|
639
702
|
if (!q.purpose) q.purpose = holdingOf(s, q, cfg)?.purpose || '';
|
|
640
703
|
if (o.prio && !q.owner) q.prio = o.prio; // a place picked up again keeps the owner's word on it
|
|
@@ -673,6 +736,7 @@ export async function acquire(o, kind, cfg) {
|
|
|
673
736
|
processes(); // read the process table before taking the lock, not while holding it
|
|
674
737
|
noticeScan(); // a waiter is who notices a job ahead of it is stuck: tell that job's agent (src/notices.mjs)
|
|
675
738
|
}
|
|
739
|
+
machine(); // and the machine's readings, which decide() needs: a fresh one is up to 3 spawns
|
|
676
740
|
// A budget changed while this waits counts, as it does for the broker's waiters.
|
|
677
741
|
const at = configAt();
|
|
678
742
|
if (at !== cfgAt) { cfgAt = at; w.cfg = freshConfig() || w.cfg; }
|
|
@@ -686,6 +750,7 @@ export async function acquire(o, kind, cfg) {
|
|
|
686
750
|
const to = await loadShipTarget(me, cfg, w.info.cwd, { temp: MEMORY_HELD.has(x.ship) });
|
|
687
751
|
if (to) return shipTo(w, to, bail, x.ship);
|
|
688
752
|
} else if (x) {
|
|
753
|
+
setLockDeadline(null); // it runs now: its changes to the state wait as long as they must
|
|
689
754
|
for (const sig of SIGNALS) process.removeListener(sig, bail);
|
|
690
755
|
if (o.thin) o.thin.go(x.lease);
|
|
691
756
|
return x.lease;
|
package/src/agents.mjs
CHANGED
|
@@ -13,7 +13,8 @@ import fs from 'node:fs';
|
|
|
13
13
|
import path from 'node:path';
|
|
14
14
|
import { HOME } from './config.mjs';
|
|
15
15
|
import { identity, makeAlive } from './proc.mjs';
|
|
16
|
-
import {
|
|
16
|
+
import { underLock, commit } from './lock.mjs';
|
|
17
|
+
import { now, fakeFull } from './util.mjs';
|
|
17
18
|
|
|
18
19
|
const FILE = path.join(HOME, 'agents.json');
|
|
19
20
|
const LOCK = path.join(HOME, 'agents.lock');
|
|
@@ -30,8 +31,6 @@ const PENDING_FOR = 2 * 6e4;
|
|
|
30
31
|
const QUIET_FOR = 60 * 6e4;
|
|
31
32
|
// The hook gives up on the lock after this and lets the spawn through.
|
|
32
33
|
const LOCK_WAIT = 1000;
|
|
33
|
-
// A lock this old belongs to a hook that died holding it.
|
|
34
|
-
const LOCK_STALE = 5000;
|
|
35
34
|
|
|
36
35
|
// The Agent tool was called Task in older Claude Code.
|
|
37
36
|
const SPAWN_TOOLS = new Set(['Agent', 'Task']);
|
|
@@ -40,31 +39,17 @@ const SPAWN_TOOLS = new Set(['Agent', 'Task']);
|
|
|
40
39
|
export const agentSlots = cfg => (Number(cfg?.agents?.slots) > 0 ? Number(cfg.agents.slots) : null);
|
|
41
40
|
|
|
42
41
|
function locked(fn) {
|
|
43
|
-
|
|
44
|
-
const t0 = now();
|
|
45
|
-
for (;;) {
|
|
46
|
-
try { fs.mkdirSync(LOCK); break; } catch (e) {
|
|
47
|
-
if (e.code !== 'EEXIST') throw e;
|
|
48
|
-
try { if (now() - fs.statSync(LOCK).mtimeMs > LOCK_STALE) fs.rmSync(LOCK, { recursive: true, force: true }); } catch {}
|
|
49
|
-
if (now() - t0 > LOCK_WAIT) throw new Error(`${LOCK} stayed locked for ${LOCK_WAIT} ms`);
|
|
50
|
-
sleepSync(5 + Math.random() * 10);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
try {
|
|
42
|
+
const r = underLock(LOCK, h => {
|
|
54
43
|
let list = [];
|
|
55
44
|
try { list = JSON.parse(fs.readFileSync(FILE, 'utf8')).agents || []; } catch (e) { if (e.code !== 'ENOENT' && !(e instanceof SyntaxError)) throw e; }
|
|
56
45
|
const before = JSON.stringify(list);
|
|
57
46
|
list = reap(list);
|
|
58
47
|
const out = fn(list);
|
|
59
|
-
if (JSON.stringify(list) !== before) {
|
|
60
|
-
fakeFull('state');
|
|
61
|
-
fs.writeFileSync(`${FILE}.tmp`, JSON.stringify({ agents: list }, null, 1));
|
|
62
|
-
fs.renameSync(`${FILE}.tmp`, FILE);
|
|
63
|
-
}
|
|
48
|
+
if (JSON.stringify(list) !== before) commit(h, FILE, JSON.stringify({ agents: list }, null, 1), { fake: () => fakeFull('state') });
|
|
64
49
|
return out;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
|
|
50
|
+
}, { wait: LOCK_WAIT, files: [FILE] });
|
|
51
|
+
if (!r) throw new Error(`${LOCK} stayed locked for ${LOCK_WAIT} ms`);
|
|
52
|
+
return r.out;
|
|
68
53
|
}
|
|
69
54
|
|
|
70
55
|
// Drop kept slots nobody took, subagents of a session that has exited, and
|
package/src/alerts.mjs
CHANGED
|
@@ -7,13 +7,15 @@
|
|
|
7
7
|
// list; the app turns a new one into a notification, at most one per cause
|
|
8
8
|
// every 30 minutes.
|
|
9
9
|
//
|
|
10
|
-
//
|
|
10
|
+
// Seven causes:
|
|
11
11
|
// wait a job waiting far longer than usual, worst when a person waits on it
|
|
12
12
|
// memory memory pressure or swap holding new jobs back, with what to close
|
|
13
13
|
// idle a slot held by a job that has done nothing for a long time
|
|
14
14
|
// ended jobs that failed, were stopped, or were lost on another machine
|
|
15
15
|
// dibs dibs itself: a service down or restarting, a crash, the hook failing
|
|
16
16
|
// disk free disk under the floor
|
|
17
|
+
// machine what only the person can fix on the machine: cores that stopped taking
|
|
18
|
+
// work, processes left running with their script gone (src/cool.mjs)
|
|
17
19
|
//
|
|
18
20
|
// alerts.json keeps the open ones, the resolved ones for a day, and what the
|
|
19
21
|
// scan needs between runs: how far into the event log and the hook's log it
|
|
@@ -22,24 +24,31 @@
|
|
|
22
24
|
// throttle watcher, so alerts keep up even when nobody looks.
|
|
23
25
|
import fs from 'node:fs';
|
|
24
26
|
import path from 'node:path';
|
|
25
|
-
import { HOME, machine } from './config.mjs';
|
|
27
|
+
import { HOME, paths, machine } from './config.mjs';
|
|
26
28
|
import { verdict } from './schedule.mjs';
|
|
27
29
|
import { stuckFor, minutes, andList } from './plain.mjs';
|
|
28
|
-
import {
|
|
30
|
+
import { processesNow, memoryUse } from './platform.mjs';
|
|
29
31
|
import { treeOf } from './measure.mjs';
|
|
30
32
|
import { withState, history } from './state.mjs';
|
|
31
|
-
import { markIdle } from './acquire.mjs';
|
|
33
|
+
import { markIdle, tableFirst } from './acquire.mjs';
|
|
32
34
|
import { sessionFiles } from './proc.mjs';
|
|
33
35
|
import { EVENTS } from './events.mjs';
|
|
34
36
|
import { serviceHealth } from './service.mjs';
|
|
35
37
|
import { hogHint } from './hogs.mjs';
|
|
38
|
+
import { underLock, heldBy } from './lock.mjs';
|
|
36
39
|
import { now, bytes, clock, gb, die } from './util.mjs';
|
|
37
40
|
import { dim, red, amber, wrap } from './style.mjs';
|
|
38
41
|
|
|
39
42
|
export const FILE = path.join(HOME, 'alerts.json');
|
|
43
|
+
// The throttle watcher's notes on the machine (src/cool.mjs noteCpu).
|
|
44
|
+
export const CPU_FILE = path.join(HOME, 'cpu.json');
|
|
45
|
+
// Notes older than this are from a watcher that stopped: three of its passes.
|
|
46
|
+
const CPU_FRESH = 30e3;
|
|
40
47
|
const LOCK = path.join(HOME, 'alerts.lock');
|
|
41
48
|
const GUARD_LOG = path.join(HOME, 'guard.log');
|
|
42
49
|
const MIN = 6e4, HOUR = 36e5, DAY = 864e5;
|
|
50
|
+
// Stuck cores for this long, not a passing spike, before the person is told to restart.
|
|
51
|
+
const STUCK_AFTER = 5 * MIN;
|
|
43
52
|
|
|
44
53
|
// Reads are cheap but not free (a verdict per waiter, the tail of two logs);
|
|
45
54
|
// the app polls every 2 s, so a scan stands for this long.
|
|
@@ -103,13 +112,9 @@ function save(st) {
|
|
|
103
112
|
}
|
|
104
113
|
|
|
105
114
|
// One scan at a time. Whoever finds the lock taken shows what the file already
|
|
106
|
-
// says; a lock left by a process that died is
|
|
115
|
+
// says; a lock left by a process that died is taken over at once (src/lock.mjs).
|
|
107
116
|
function locked(fn) {
|
|
108
|
-
|
|
109
|
-
if (e.code !== 'EEXIST') return null;
|
|
110
|
-
try { if (now() - fs.statSync(LOCK).mtimeMs < 30e3) return null; fs.rmSync(LOCK, { recursive: true, force: true }); fs.mkdirSync(LOCK); } catch { return null; }
|
|
111
|
-
}
|
|
112
|
-
try { return fn(); } finally { fs.rmSync(LOCK, { recursive: true, force: true }); }
|
|
117
|
+
return underLock(LOCK, () => fn(), { wait: 0 })?.out ?? null;
|
|
113
118
|
}
|
|
114
119
|
|
|
115
120
|
// The lines a log gained since the offset last read. A file shorter than the
|
|
@@ -153,7 +158,8 @@ function readEvents(st, t) {
|
|
|
153
158
|
const x = { at: e.at, id: e.id, who: e.who, res: e.res, cmd: e.cmd, purpose: e.purpose, key: e.key, code: e.code, prio: e.prio, due: e.due };
|
|
154
159
|
if (by || STOPPED.has(e.code)) st.ended.push({ kind: 'stopped', ...x, by: by || null });
|
|
155
160
|
else if (e.code != null && e.code !== 0) st.ended.push({ kind: 'failed', ...x });
|
|
156
|
-
} else if (e.kind === '
|
|
161
|
+
} else if (e.kind === 'lockstuck') st.ended.push({ kind: e.kind, at: e.at, key: e.key, pid: e.pid, cmd: e.cmd, held: e.held });
|
|
162
|
+
else if (e.kind === 'lost' || e.kind === 'crash') st.ended.push({ kind: e.kind, at: e.at, who: e.who, cmd: e.cmd, code: e.code, why: e.why, verb: e.verb });
|
|
157
163
|
}
|
|
158
164
|
st.ended = st.ended.filter(x => t - x.at < EVENT_KEEP);
|
|
159
165
|
}
|
|
@@ -196,33 +202,35 @@ export function memoryUsers(s, procs, use) {
|
|
|
196
202
|
const bytes = use.get(p.pid);
|
|
197
203
|
if (!bytes) continue;
|
|
198
204
|
const l = owner.get(p.pid);
|
|
199
|
-
const name = l ? `dibs job #${l.id} (${l.who})` : appOf(p, sessions);
|
|
200
|
-
const g = groups.get(name) || { name, bytes: 0, n: 0, dibs: !!l, ...(l && { id: l.id }) };
|
|
205
|
+
const [name, cmd] = l ? [`dibs job #${l.id} (${l.who})`] : appOf(p, sessions);
|
|
206
|
+
const g = groups.get(name) || { name, bytes: 0, n: 0, dibs: !!l, ...(l && { id: l.id }), ...(cmd && { cmd: true }) };
|
|
201
207
|
g.bytes += bytes; g.n++;
|
|
202
208
|
groups.set(name, g);
|
|
203
209
|
}
|
|
204
210
|
return [...groups.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5);
|
|
205
211
|
}
|
|
206
212
|
|
|
213
|
+
// [name, true when it's named by its command]: one of those may be many separate processes.
|
|
207
214
|
function appOf(p, sessions) {
|
|
208
215
|
const a = p.args || '';
|
|
209
|
-
if (/\blaunchd_sim\b|\/CoreSimulator\/Devices\/|\.simruntime\//.test(a)) return 'the iOS Simulator';
|
|
210
|
-
if (/com\.apple\.WebKit\.(WebContent|GPU|Networking)/.test(a)) return 'Safari and other web pages';
|
|
216
|
+
if (/\blaunchd_sim\b|\/CoreSimulator\/Devices\/|\.simruntime\//.test(a)) return ['the iOS Simulator'];
|
|
217
|
+
if (/com\.apple\.WebKit\.(WebContent|GPU|Networking)/.test(a)) return ['Safari and other web pages'];
|
|
211
218
|
if (/(^|\/)claude(\s|$)/.test(a)) {
|
|
212
219
|
const x = sessions.get(p.pid);
|
|
213
|
-
return x?.name ? `Claude Code session ${x.name}` : `Claude Code (pid ${p.pid})
|
|
220
|
+
return [x?.name ? `Claude Code session ${x.name}` : `Claude Code (pid ${p.pid})`];
|
|
214
221
|
}
|
|
215
222
|
const app = a.match(/\/([^/]+)\.app\//);
|
|
216
|
-
if (app) return app[1];
|
|
223
|
+
if (app) return [app[1]];
|
|
217
224
|
// A script under an interpreter is the script: "node" alone says nothing about which.
|
|
218
225
|
const [cmd, ...args] = a.split(/\s+/);
|
|
219
226
|
const name = path.basename(cmd || `pid ${p.pid}`);
|
|
220
227
|
const script = INTERPRETERS.test(name) && args.find(x => !x.startsWith('-'));
|
|
221
|
-
return script ? `${name} ${path.basename(script)}` : name;
|
|
228
|
+
return [script ? `${name} ${path.basename(script)}` : name, true];
|
|
222
229
|
}
|
|
223
230
|
|
|
224
231
|
const INTERPRETERS = /^(node|bun|deno|python3?(\.\d+)?|ruby|perl)$/;
|
|
225
|
-
|
|
232
|
+
// A command's count when it's more than one: 25 short-lived curls (2026-11-05) read as one big curl otherwise.
|
|
233
|
+
const sized = g => `${g.name} (${gb(g.bytes).replace(/G$/, ' GB')}${g.n > 1 && g.name.startsWith('Safari') ? `, ${g.n} pages` : g.n > 1 && g.cmd ? `, ${g.n} processes` : ''})`;
|
|
226
234
|
|
|
227
235
|
// Every alert the state calls for now: { id, cause, level, title, fix, after?, at? }.
|
|
228
236
|
// level: urgent (a person is held up or dibs is broken), warn, or note.
|
|
@@ -297,6 +305,13 @@ export function detect({ s, cfg, hist, m, t, st, users }) {
|
|
|
297
305
|
out.push({ id: `lost:${x.at}`, cause: 'ended', level: 'urgent', at: x.at, who: x.who,
|
|
298
306
|
title: `${x.who}'s job was lost${x.code === 77 ? ' after it started' : ' before it started'} at ${stamp(x.at, t)}: ${x.why || x.cmd}`,
|
|
299
307
|
fix: x.code === 77 ? 'It may have run. Check what it changed before running it again.' : 'It never ran, so it\'s safe to run again.' });
|
|
308
|
+
} else if (x.kind === 'lockstuck') {
|
|
309
|
+
// Open while that same holder still has the lock; it closes the moment it lets go.
|
|
310
|
+
const now = heldBy(paths.lock);
|
|
311
|
+
if (now?.key !== x.key) continue;
|
|
312
|
+
out.push({ id: `lockstuck:${x.key}`, cause: 'dibs', level: 'urgent', at: x.at - x.held,
|
|
313
|
+
title: `dibs is stuck behind pid ${x.pid}${x.cmd ? ` (${x.cmd.slice(0, 80)})` : ''}: it has held the state lock for ${minutes(now.held)}, and every dibs command waits for it`,
|
|
314
|
+
fix: `If pid ${x.pid} is hung, end it and everyone goes on at once: kill ${x.pid}` });
|
|
300
315
|
} else if (x.kind === 'crash') {
|
|
301
316
|
out.push({ id: `crash:${x.at}`, cause: 'dibs', level: 'urgent', at: x.at, who: x.who,
|
|
302
317
|
title: `dibs crashed at ${stamp(x.at, t)} running dibs ${x.verb || ''} for ${x.who}`,
|
|
@@ -330,11 +345,31 @@ export function detect({ s, cfg, hist, m, t, st, users }) {
|
|
|
330
345
|
fix: `Those tool calls ran without dibs's checks. Report it: dibs ask "hook: ${last.msg.slice(0, 60)}"` });
|
|
331
346
|
}
|
|
332
347
|
|
|
348
|
+
// The hard stop (src/preempt.mjs hardStop): a job paused under 1 GB free, whatever it was.
|
|
349
|
+
for (const l of s.leases.filter(x => x.pauses?.some(p => p.hard)))
|
|
350
|
+
out.push({ id: `hardstop:#${l.id}`, cause: 'disk', level: 'urgent', job: l.id, who: l.who, at: l.pausedAt,
|
|
351
|
+
title: `Free disk fell under 1 GB, so dibs paused ${job(l)}, the job writing the most. It resumes once 2 GB is free`,
|
|
352
|
+
fix: diskFix() });
|
|
353
|
+
|
|
354
|
+
// The machine itself, from the throttle watcher.
|
|
355
|
+
let cpu = null;
|
|
356
|
+
try { cpu = JSON.parse(fs.readFileSync(CPU_FILE, 'utf8')); } catch {}
|
|
357
|
+
if (cpu && t - cpu.at < CPU_FRESH) {
|
|
358
|
+
if (cpu.stuckSince && !cpu.swapping)
|
|
359
|
+
out.push({ id: 'cores', cause: 'machine', level: 'urgent', after: STUCK_AFTER, at: cpu.stuckSince,
|
|
360
|
+
title: `The load is ${cpu.load} on ${cpu.cores} cores while ${cpu.idle}% of the CPU sits idle: work is ready to run and some cores have stopped taking it`,
|
|
361
|
+
fix: 'Restart the Mac. On 2026-11-10 nothing else brought its cores back. Until then dibs moves nothing to background priority.' });
|
|
362
|
+
for (const o of cpu.orphans || [])
|
|
363
|
+
out.push({ id: `orphan:${o.pid}`, cause: 'machine', level: 'warn',
|
|
364
|
+
title: `${o.name} ${o.pid} has run ${Math.round(o.age / HOUR)} hours outside dibs, using ${Math.round(o.cpu / HOUR)} CPU-hours, and its script ${o.script} is gone`,
|
|
365
|
+
fix: `Likely left behind by a session that ended. dibs leaves it running; if nobody needs it, end it: kill ${o.pid}` });
|
|
366
|
+
}
|
|
367
|
+
|
|
333
368
|
// Disk under the floor: nothing new starts.
|
|
334
369
|
const floor = bytes(cfg.minDisk || '0');
|
|
335
370
|
if (floor && m.diskFree != null && m.diskFree < floor)
|
|
336
371
|
out.push({ id: 'disk', cause: 'disk', level: 'urgent',
|
|
337
|
-
title: `Free disk is ${gb(m.diskFree).replace(/G$/, ' GB')}, under the ${gb(floor).replace(/G$/, ' GB')} dibs keeps free, so
|
|
372
|
+
title: `Free disk is ${gb(m.diskFree).replace(/G$/, ' GB')}, under the ${gb(floor).replace(/G$/, ' GB')} dibs keeps free, so only jobs that write next to nothing start; the rest wait for room`,
|
|
338
373
|
fix: diskFix() });
|
|
339
374
|
return out;
|
|
340
375
|
}
|
|
@@ -418,7 +453,9 @@ export function scan({ s, cfg, hist, m = machine(), t = now(), force = false } =
|
|
|
418
453
|
let found = detect({ s, cfg, hist, m, t, st, users });
|
|
419
454
|
// The machine-wide reading only once memory is what holds jobs back.
|
|
420
455
|
if (!users && found.some(a => a.want === 'users')) {
|
|
421
|
-
|
|
456
|
+
// Memory first, then the process table it's named from: both as they are now.
|
|
457
|
+
const use = memoryUse();
|
|
458
|
+
users = memoryUsers(s, processesNow(), use);
|
|
422
459
|
st.top = { at: t, list: users };
|
|
423
460
|
found = detect({ s, cfg, hist, m, t, st, users });
|
|
424
461
|
}
|
|
@@ -485,6 +522,7 @@ export function alerts(args, cfg) {
|
|
|
485
522
|
: `No open alert matches ${which}. dibs alerts lists them.`);
|
|
486
523
|
}
|
|
487
524
|
const t = now();
|
|
525
|
+
tableFirst();
|
|
488
526
|
const s = withState(s => { markIdle(s); return s; });
|
|
489
527
|
let list = scan({ s, cfg, hist: history(), t, force: true });
|
|
490
528
|
if (args.includes('--all')) list = shown(load(), t, true);
|
package/src/board.mjs
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// joined to a coordinator, on every other machine too.
|
|
3
3
|
import { resCfg } from './config.mjs';
|
|
4
4
|
import { tag, isMine } from './proc.mjs';
|
|
5
|
-
import { idleFor } from './acquire.mjs';
|
|
5
|
+
import { idleFor, UNPOLLED } from './acquire.mjs';
|
|
6
6
|
import { forecast, byRank, remaining, used, overBy, verdict, memUsed, cpuUsed, shownFree, swapGrowing, diskSqueeze, BREAKER_LINE, QUICK_LINE } from './schedule.mjs';
|
|
7
7
|
import { grewLine, cappedLine } from './measure.mjs';
|
|
8
8
|
import { pauseLabel } from './preempt.mjs';
|
|
@@ -29,7 +29,6 @@ const blockedBy = v => { const r = waitReason(v); return r && !/^(behind|held by
|
|
|
29
29
|
// line and the machine, then a shared rate limit), or, when nothing does, that
|
|
30
30
|
// nobody has decided for it lately. On 2026-10-20 two test runs showed no
|
|
31
31
|
// reason at all and didn't start, with free slots and memory.
|
|
32
|
-
const UNPOLLED = 3 * 6e4; // a waiter's dibs decides every few seconds, and notes it once a minute (acquire.mjs POLLED_EVERY)
|
|
33
32
|
function waitingOn(s, q, cfg, hist, t) {
|
|
34
33
|
const v = verdict(s, q, cfg, hist, t);
|
|
35
34
|
if (!v.ok) return blockedBy(v);
|
package/src/broker.mjs
CHANGED
|
@@ -11,12 +11,14 @@ import net from 'node:net';
|
|
|
11
11
|
import path from 'node:path';
|
|
12
12
|
import { spawn, spawnSync } from 'node:child_process';
|
|
13
13
|
import { fileURLToPath } from 'node:url';
|
|
14
|
-
import { HOME, paths, loadConfig } from './config.mjs';
|
|
14
|
+
import { HOME, paths, loadConfig, machine } from './config.mjs';
|
|
15
15
|
import { pstart, makeAlive } from './proc.mjs';
|
|
16
16
|
import { processes } from './platform.mjs';
|
|
17
17
|
import { withState, history, kick, quiet, KEEP_PLACE } from './state.mjs';
|
|
18
|
+
import { sweepLock } from './lock.mjs';
|
|
18
19
|
import { decide, step, waiter, full, markIdle, saidText, abandon, POLL } from './acquire.mjs';
|
|
19
20
|
import { byRank } from './schedule.mjs';
|
|
21
|
+
import { inversions, lift } from './override.mjs';
|
|
20
22
|
import { noticeScan } from './notices.mjs';
|
|
21
23
|
import { event } from './events.mjs';
|
|
22
24
|
import { now, noSpace, sleepSync, signalExit, notifyLine, LEAN } from './util.mjs';
|
|
@@ -186,17 +188,19 @@ function keepFor(q, shell) {
|
|
|
186
188
|
// up on the broker (why is keep: the place stays for its in-process retry).
|
|
187
189
|
// id 0: interrupted before it knew its id; its place is the one under its pid.
|
|
188
190
|
export function leaveLine(id, shell, why) {
|
|
189
|
-
|
|
191
|
+
// A low job lifted for this waiter alone goes back down as it leaves (src/override.mjs inversions).
|
|
192
|
+
lift(withState(s => {
|
|
190
193
|
// Its place by id when it knows it, else by its pid. A place kept with nobody on it (for its own
|
|
191
194
|
// retry in Node, or taken for gone) is its too: interrupted, it gives that up as well.
|
|
192
195
|
const q = s.queue.find(x => (id ? x.id === id && (x.pid === shell || (why !== 'keep' && !x.pid)) : x.pid === shell)
|
|
193
196
|
|| (why !== 'keep' && x.keptFor === shell));
|
|
194
|
-
if (!q) return;
|
|
195
|
-
if (why === 'keep')
|
|
197
|
+
if (!q) return [];
|
|
198
|
+
if (why === 'keep') { keepFor(q, shell); return []; }
|
|
196
199
|
s.queue = s.queue.filter(x => x !== q);
|
|
197
200
|
if (q.wake?.notify) notified(q, signalExit(why));
|
|
198
201
|
if (q.wake) event({ kind: 'left', id: q.id, res: q.res, who: q.who, prio: q.prio || 'normal', type: q.kind, ms: now() - q.enq, why });
|
|
199
|
-
|
|
202
|
+
return inversions(s, loadConfig());
|
|
203
|
+
}));
|
|
200
204
|
}
|
|
201
205
|
|
|
202
206
|
// --notify's line for a thin wait that ended before its command started (src/commands.mjs notifyOnExit).
|
|
@@ -260,7 +264,7 @@ export function broker() {
|
|
|
260
264
|
const ctl = new net.Socket({ fd: fs.openSync(paths.ctl, O_RDWR | O_NONBLOCK), readable: true, writable: false });
|
|
261
265
|
const code = fs.readFileSync(path.join(SRC, 'version.mjs'), 'utf8');
|
|
262
266
|
const waits = new Map(); // queue id -> its wait (src/acquire.mjs waiter), with its FIFO as out
|
|
263
|
-
let cfg = loadConfig(), hist = history(), histAt = 0, beat = 0, idleSince = now(), pending = false, forced = false, pruned = 0, seen = '',
|
|
267
|
+
let cfg = loadConfig(), hist = history(), histAt = 0, beat = 0, idleSince = now(), pending = false, forced = false, pruned = 0, seen = '', fullAt = 0;
|
|
264
268
|
|
|
265
269
|
const exit = () => {
|
|
266
270
|
for (const w of waits.values()) w.out.close();
|
|
@@ -284,18 +288,25 @@ export function broker() {
|
|
|
284
288
|
pending = forced = false;
|
|
285
289
|
const t = now();
|
|
286
290
|
// A release changed the code: the waiters' shells start the new one.
|
|
287
|
-
|
|
291
|
+
// Said in the log, so a waiter's "broker gone, starting another" that follows reads as a release, not a crash.
|
|
292
|
+
try {
|
|
293
|
+
if (fs.readFileSync(path.join(SRC, 'version.mjs'), 'utf8') !== code) {
|
|
294
|
+
event({ kind: 'thin', why: 'a new version of dibs: the broker hands its waiters to a new one', pid: me.pid, waiting: waits.size });
|
|
295
|
+
return leave(true);
|
|
296
|
+
}
|
|
297
|
+
} catch {}
|
|
288
298
|
if (t - pruned > PRUNE_EVERY) { pruned = t; prune(); }
|
|
289
299
|
// With nobody to wait for, the lock is taken only to keep the beat fresh.
|
|
290
300
|
let quietNow = false, text = '';
|
|
291
301
|
try { text = fs.readFileSync(paths.state, 'utf8'); quietNow = !waits.size && !thinWaiters(JSON.parse(text)).length; } catch {}
|
|
292
|
-
if (!quietNow && !kicked && text === seen && t -
|
|
302
|
+
if (!quietNow && !kicked && text === seen && t - fullAt < QUIET_POLL && [...waits.values()].every(w => running(w.me.pid))) return;
|
|
293
303
|
if (quietNow) {
|
|
294
304
|
if (t - idleSince > IDLE_EXIT) return leave(false);
|
|
295
305
|
if (t - beat > BEAT) withState(s => { if (s.broker?.pid === me.pid || !s.broker) s.broker = { ...me, beat: (beat = t) }; });
|
|
296
306
|
return;
|
|
297
307
|
}
|
|
298
|
-
processes(); // read the process table before taking the lock, not while holding it
|
|
308
|
+
processes(); // read the process table and the machine before taking the lock, not while holding it
|
|
309
|
+
machine();
|
|
299
310
|
noticeScan();
|
|
300
311
|
try { cfg = loadConfig(); } catch {}
|
|
301
312
|
try { const m = fs.statSync(paths.history).mtimeMs; if (m !== histAt) { histAt = m; hist = history(); } } catch {}
|
|
@@ -347,7 +358,7 @@ export function broker() {
|
|
|
347
358
|
}
|
|
348
359
|
}
|
|
349
360
|
done();
|
|
350
|
-
idleSince =
|
|
361
|
+
idleSince = fullAt = now();
|
|
351
362
|
try { seen = fs.readFileSync(paths.state, 'utf8'); } catch {}
|
|
352
363
|
};
|
|
353
364
|
const done = () => { for (const [id, w] of waits) if (w.out.done) waits.delete(id); };
|
|
@@ -358,8 +369,12 @@ export function broker() {
|
|
|
358
369
|
tick();
|
|
359
370
|
}
|
|
360
371
|
|
|
361
|
-
// FIFOs of shells that are gone. Only in ~/.dibs/w, the folder dibs made for them.
|
|
372
|
+
// FIFOs of shells that are gone. Only in ~/.dibs/w, the folder dibs made for them. And what writers
|
|
373
|
+
// killed mid-change left beside the state and message locks (src/lock.mjs sweepLock): a claim
|
|
374
|
+
// sweeps too, but only after a death it sees, and the broker is always around while anyone waits.
|
|
362
375
|
function prune() {
|
|
376
|
+
sweepLock(paths.lock, [paths.state]);
|
|
377
|
+
sweepLock(path.join(HOME, 'messages.lock'), [path.join(HOME, 'messages.json'), path.join(HOME, 'inbox.json'), path.join(HOME, 'listeners.json')]);
|
|
363
378
|
let names = [];
|
|
364
379
|
try { names = fs.readdirSync(WAKE); } catch { return; }
|
|
365
380
|
for (const n of names) {
|