@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/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';
15
- import { verdict, forecast, expected, remaining, byRank, holdingOf, PRIORITY_SHIFT, PRIORITIES, NEEDS_REASON, used, overBy, STALL, neverFits, explicitAsk, capToMachine } from './schedule.mjs';
14
+ import { capWaiter, inversions, lift } from './override.mjs';
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
- withState(s => {
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
- const POLLED_EVERY = 60e3;
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) || me;
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,18 +346,17 @@ 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();
351
+ // Kept on the entry, so other waiters rank it at the front too (src/schedule.mjs quickPass).
352
+ if (quickPass(cur, hist, cfg)) cur.quickPass = true; else delete cur.quickPass;
312
353
  let v = verdict(s, cur, cfg, hist);
313
- // A rate limit that would stop it anyway is checked before pausing anyone for it.
314
- if (!v.ok && v.rule === 'slot') v = quotaBlock(s, cur, cfg, hist) || preempt(s, cur, cfg, hist) || v;
354
+ // A rate limit that would stop it anyway is checked before pausing anyone for it. The quick lane never pauses anyone.
355
+ if (!v.ok && v.rule === 'slot' && !cur.quickPass) v = quotaBlock(s, cur, cfg, hist) || preempt(s, cur, cfg, hist) || v;
315
356
  if (v.ok) v = quotaBlock(s, cur, cfg, hist) || v;
316
357
  // What held it and for how long, for its start event: on 2026-10-24 a 2-second test waited
317
- // 3 minutes with 11 GB of disk free, and the log said only that it waited. Kept in the
318
- // waiter's memory, so a poll that changes nothing still leaves the state file alone.
319
- const t = now();
320
- if (w.heldRule) w.heldBy = { ...w.heldBy, [w.heldRule]: (w.heldBy?.[w.heldRule] || 0) + t - w.heldAt };
321
- w.heldRule = v.ok ? null : v.rule || 'other';
322
- 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);
323
360
  // For the stall breaker (schedule.mjs): whether the machine, not the line, holds this one back.
324
361
  if (!v.ok && v.machine) cur.machineHeld = true; else delete cur.machineHeld;
325
362
  // When the load ceiling alone started holding it: after LOAD_STARVE it starts anyway (schedule.mjs).
@@ -345,7 +382,7 @@ export function decide(s, w) {
345
382
  // Sitting on one resource while waiting for another wastes it for everyone.
346
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.
347
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));
348
- return { v, line: waitLine(s, cur, v, cfg, hist, w.talk.told), idle: !s.leases.length, sitting, holding: cur.holding };
385
+ return { v, line: waitLine(s, cur, v, cfg, hist, w.talk.told), sitting, holding: cur.holding };
349
386
  }
350
387
  s.queue = s.queue.filter(x => x.id !== me.id);
351
388
  takeQuota(s, cur, cfg);
@@ -353,10 +390,11 @@ export function decide(s, w) {
353
390
  purpose: cur.purpose, cmd: me.cmd, key: me.key, est: info.est, prio: cur.prio, by: cur.by,
354
391
  cwd: info.cwd, ppid: info.ppid, start: now(), waited: now() - cur.enq, agentId: info.agentId, sessionId: info.sessionId,
355
392
  owner: cur.owner, askedPrio: cur.askedPrio };
356
- if (w.heldBy) lease.held = Object.fromEntries(Object.entries(w.heldBy).map(([k, x]) => [k, Math.round(x)]));
393
+ if (cur.held) lease.held = Object.fromEntries(Object.entries(cur.held).map(([k, x]) => [k, Math.round(x)]));
357
394
  if (v.covered.length) lease.covered = v.covered;
358
395
  if (v.alongside) lease.alongside = v.alongside;
359
396
  if (v.trial) lease.trial = true;
397
+ if (v.quick) lease.quick = true;
360
398
  if (cur.repo) lease.repo = cur.repo;
361
399
  if (v.loadPast) Object.assign(lease, { loadPast: true, loadWaited: v.loadWaited });
362
400
  // The stall breaker's clock (schedule.mjs) runs from the last start the gates allowed.
@@ -378,11 +416,20 @@ export function decide(s, w) {
378
416
  // through w.out (exit 74, 75, or the owner's stop).
379
417
  export function step(r, w) {
380
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
+ }
381
423
  if (r.stopped) {
382
424
  left(w, 'owner stop');
383
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.`
384
426
  + `${r.reason ? '' : ' Find out why before trying again: dibs history, or ask whoever stopped it.'}`, signalExit('SIGTERM'));
385
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
+ }
386
433
  if (r.never) {
387
434
  left(w, 'never fits');
388
435
  const text = neverText(r.never, me, cfg, null);
@@ -413,16 +460,25 @@ export function step(r, w) {
413
460
  out.say(`you're keeping ${andList(kept.map(x => named(cfg, x).the))} reserved while you wait, so nobody else can use it.`
414
461
  + ` Give it back (dibs release ${kept[0]}) or ask for everything at once: dibs run ${[...new Set([...kept, ...me.res])].join(',')} -- <command>`);
415
462
  }
416
- // Waiting can't free disk when nothing else is running.
417
- if (r.v.disk && (r.idle || r.v.alone)) {
418
- left(w, 'not enough disk');
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');
419
471
  leave(w, false);
420
- return out.die(`not enough free disk: ${gb(r.v.free).replace(/G$/, ' GB')} free, it needs ${gb(r.v.need).replace(/G$/, ' GB')}, and nothing running will free any.`
421
- + ` Your command did NOT run (exit 74). Free some space, or pass --disk with what this job really needs if that's less, then run it again:\n ${w.info.again}\n ${OFF_LIMITS}`, 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);
422
474
  }
423
475
  if (now() - w.started >= w.maxWait) {
424
476
  note(w, 'timeout', { ms: now() - me.enq });
425
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);
426
482
  if (!w.maxWait)
427
483
  return out.die(`not free yet. ${r.line.why} --no-wait doesn't wait, so your command did NOT run (exit 75).`
428
484
  + ` See when it frees up: dibs when ${shellRes(me.res.map(x => short(x)))}`, 75);
@@ -454,7 +510,7 @@ export function step(r, w) {
454
510
  // every MOVE_EVERY), or now and then.
455
511
  const l = r.line;
456
512
  const what = w.talk.step(l);
457
- 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) : '');
458
514
  else if (what === 'change') out.said(`still queued (${dur(now() - w.started)}). ${l.head}`, l.why);
459
515
  else if (what === 'moved') out.say(`still queued (${dur(now() - w.started)}). You ${l.moved}`);
460
516
  else if (what === 'repeat') out.say(`still queued (${dur(now() - w.started)}). ${l.head}`);
@@ -587,12 +643,11 @@ export async function acquire(o, kind, cfg) {
587
643
  if (!nested) capToMachine(cfg, size);
588
644
  const { mem, cpu, disk, asked, askedCpu, usual } = size;
589
645
  const grew = grewPlain({ mem, cpu, asked, askedCpu, usual }, key.split('|')[1]);
646
+ // Booked at what it really used, not at its ask: dibs's own bookkeeping, kept
647
+ // in the history and said to nobody. On 2026-11-03 these were 6 of 35 notices,
648
+ // and "typecheck used up to 4 cores, pass --cpu 4" came on every merge.
590
649
  if (grew) {
591
- say(grew);
592
- // Once per command per agent, through the hook too: an agent that reads only
593
- // its tool's result still learns that its --mem was overruled, and why its job waits.
594
- notify({ sessionId: process.env.CLAUDE_CODE_SESSION_ID, who: id.who, agentId: o.agentId }, `sized:${key}:${Math.round(mem / 2 ** 30)}`,
595
- `${grew} dibs booked it at that, not at what you asked for. To have your own number match, pass --mem ${Math.ceil((usual ?? mem) / 2 ** 30)}G${askedCpu != null ? ` --cpu ${cpu}` : ''}.`);
650
+ event({ kind: 'sized', key, who: id.who, mem, cpu, ...(asked != null && { asked }), ...(askedCpu != null && { askedCpu }), ...(usual != null && { usual }) });
596
651
  }
597
652
  // Running the same request again soon after a timed-out wait keeps your place.
598
653
  const ticket = `${id.spid || id.who}|${res.join(',')}|${cmd}`;
@@ -609,6 +664,7 @@ export async function acquire(o, kind, cfg) {
609
664
  if (machine().diskFree == null) say("couldn't read free disk space, so the disk check is off for this request.");
610
665
 
611
666
  const started = now();
667
+ if (maxWait !== Infinity) setLockDeadline(started + maxWait);
612
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,
613
669
  cwd: process.cwd(), ppid: callerPid(), sstart: id.sstart, size: { mem, cpu, asked, askedCpu, usual }, again: again(), path: o.thin?.fifo,
614
670
  notify: o.notify ? path.resolve(o.notify) : undefined, follow: process.env.DIBS_REMOTE_JOB ? { pid: callerPid(), pstart: pstart(callerPid()) } : undefined }, cfg, hist, stderrOut);
@@ -619,9 +675,16 @@ export async function acquire(o, kind, cfg) {
619
675
  const hold = sig => { early ||= sig; if (w.full) process.exit(signalExit(sig)); };
620
676
  for (const sig of SIGNALS) process.on(sig, hold);
621
677
  w.me = await saved(w, s => {
622
- // Only a place someone left behind can be picked up again, never a live waiter's.
623
- let q = s.queue.find(x => x.ticket === ticket && !x.pid);
624
- if (q) { Object.assign(q, { pid, pstart: myStart, keepUntil: null }); delete q.wake; delete q.keptFor; }
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; }
625
688
  else {
626
689
  q = { id: ++s.seq, ticket, res, mem, cpu, disk, asked, askedCpu, usual, pid, pstart: myStart, enq: now(), polledAt: now(),
627
690
  who: id.who, agent: id.agent, label: id.label, spid: id.spid, purpose: o.purpose || '', cmd, key, kind,
@@ -633,12 +696,15 @@ export async function acquire(o, kind, cfg) {
633
696
  if (sent) q.sent = true; // placed here by the coordinator for its size (neverFits)
634
697
  s.queue.push(q);
635
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)));
636
701
  // Without -m, a wait for the rest of what a ship needs says what the ship is for.
637
702
  if (!q.purpose) q.purpose = holdingOf(s, q, cfg)?.purpose || '';
638
703
  if (o.prio && !q.owner) q.prio = o.prio; // a place picked up again keeps the owner's word on it
639
704
  capWaiter(s, q);
640
705
  if (o.by) q.by = o.by;
641
706
  if (o.est) q.est = o.est;
707
+ if (o.quick) q.quick = true; // trusted the first time; its runs decide after (quickPass)
642
708
  if (o.cost != null) q.cost = o.cost;
643
709
  if (o.mem != null) q.declared = true; // a size to go on before dibs has measured it (src/overlap.mjs)
644
710
  if (o.cpu != null) q.cpuDeclared = true; // asked for in so many words, which alone can make it never fit (neverFits)
@@ -670,6 +736,7 @@ export async function acquire(o, kind, cfg) {
670
736
  processes(); // read the process table before taking the lock, not while holding it
671
737
  noticeScan(); // a waiter is who notices a job ahead of it is stuck: tell that job's agent (src/notices.mjs)
672
738
  }
739
+ machine(); // and the machine's readings, which decide() needs: a fresh one is up to 3 spawns
673
740
  // A budget changed while this waits counts, as it does for the broker's waiters.
674
741
  const at = configAt();
675
742
  if (at !== cfgAt) { cfgAt = at; w.cfg = freshConfig() || w.cfg; }
@@ -683,6 +750,7 @@ export async function acquire(o, kind, cfg) {
683
750
  const to = await loadShipTarget(me, cfg, w.info.cwd, { temp: MEMORY_HELD.has(x.ship) });
684
751
  if (to) return shipTo(w, to, bail, x.ship);
685
752
  } else if (x) {
753
+ setLockDeadline(null); // it runs now: its changes to the state wait as long as they must
686
754
  for (const sig of SIGNALS) process.removeListener(sig, bail);
687
755
  if (o.thin) o.thin.go(x.lease);
688
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 { now, sleepSync, fakeFull } from './util.mjs';
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
- fs.mkdirSync(HOME, { recursive: true });
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
- } finally {
66
- fs.rmSync(LOCK, { recursive: true, force: true });
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