@dibssoftware/dibs 0.0.179 → 0.0.181

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/CHANGELOG.md +31 -2
  2. package/README.md +4 -2
  3. package/bin/dibs-guard.mjs +10 -1
  4. package/bin/dibs.mjs +37 -10
  5. package/docs/benchmarks.md +1 -1
  6. package/docs/files.md +1 -1
  7. package/docs/guard.md +6 -0
  8. package/docs/questions.md +6 -2
  9. package/docs/reference.md +4 -4
  10. package/docs/relay.md +24 -9
  11. package/docs/releasing.md +4 -3
  12. package/docs/scheduling.md +4 -4
  13. package/docs/windows.md +14 -0
  14. package/package.json +1 -1
  15. package/skills/dibs/SKILL.md +6 -6
  16. package/src/acquire.mjs +93 -27
  17. package/src/agents.mjs +7 -22
  18. package/src/alerts.mjs +75 -29
  19. package/src/board.mjs +1 -2
  20. package/src/broker.mjs +26 -11
  21. package/src/commands.mjs +37 -14
  22. package/src/config.mjs +21 -4
  23. package/src/cool.mjs +105 -10
  24. package/src/diskwarn.mjs +4 -0
  25. package/src/events.mjs +10 -1
  26. package/src/files.mjs +52 -88
  27. package/src/guard.mjs +76 -30
  28. package/src/guardd.mjs +97 -0
  29. package/src/guardw.mjs +19 -0
  30. package/src/later.mjs +20 -25
  31. package/src/lock.mjs +308 -0
  32. package/src/measure.mjs +27 -7
  33. package/src/ondemand.mjs +5 -2
  34. package/src/override.mjs +39 -2
  35. package/src/plain.mjs +2 -2
  36. package/src/platform.mjs +175 -42
  37. package/src/preempt.mjs +51 -3
  38. package/src/primer.mjs +1 -1
  39. package/src/proc.mjs +45 -5
  40. package/src/questions.mjs +8 -22
  41. package/src/relay.mjs +137 -32
  42. package/src/remote.mjs +12 -8
  43. package/src/schedule.mjs +139 -26
  44. package/src/serve.mjs +16 -3
  45. package/src/service.mjs +9 -4
  46. package/src/state.mjs +139 -47
  47. package/src/stats.mjs +3 -2
  48. package/src/talk.mjs +169 -83
  49. package/src/trust.mjs +7 -1
  50. package/src/util.mjs +28 -2
  51. package/src/version.mjs +1 -1
  52. package/src/web.mjs +17 -26
  53. package/src/worker.mjs +2 -1
package/src/lock.mjs ADDED
@@ -0,0 +1,308 @@
1
+ // The lock every shared file in ~/.dibs changes under: state.json (src/state.mjs), and
2
+ // messages, questions, later jobs, the subagent ledger, alerts and the web's pairing file.
3
+ //
4
+ // A lock is a directory, <name>, as every dibs before it made, so an older dibs still running
5
+ // during a rollout and this one keep out of each other's way. What holds:
6
+ //
7
+ // 1. One holder. A process holds the lock while <name>/owner.<pid>.<start>.<nonce> is its own
8
+ // file. The directory is made whole beside it (<name>.new.*, with that file and a pid file
9
+ // for older dibs to read) and renamed into place. A rename onto a directory that has
10
+ // anything in it fails (ENOTEMPTY on APFS, ENOTEMPTY or EEXIST on Linux), so of two makers
11
+ // one wins, and no lock is ever seen without its owner.
12
+ // 2. Staleness is the owner's death, never the lock's age. A lock is stale when its owner is
13
+ // gone (kill 0 says so, or ps shows that pid started at another time: a reused pid), a
14
+ // zombie, or stopped (a paused job's own dibs, which nobody can resume while it holds the
15
+ // lock everyone needs). A live owner, however slow, is waited for; one holding past
16
+ // STUCK_AFTER is reported (onStuck), since a hung one stops every dibs command. A lock held 30 s used to be
17
+ // taken from its live owner: at load 238 (2026-11-08) a starved holder lost it
18
+ // mid-change, two writers ran at once, and each crashed on the other's files (exit 70).
19
+ // 3. Takeover is atomic and never moves the lock. The taker renames the stale owner's file to
20
+ // its own owner name, inside <name>: of two takers one wins, and a fresh lock that replaced
21
+ // the stale one has no file of that name, so it can't be taken by mistake. (Moving the whole
22
+ // lock aside to look at it, then back, could hide a live owner's lock from it for a moment:
23
+ // its release then left the lock in place and everyone waited on it for good.)
24
+ // 4. A holder checks its owner file is still there just before it commits (commit() below), so
25
+ // a holder taken over while stopped never writes over its taker's change. Each writer's
26
+ // temporary file has its pid in the name: two writers never share one.
27
+ // 5. Release removes only the holder's own lock, checked by its owner file, and never throws.
28
+ // A lock with this process's pid and another nonce is one it no longer holds: stale.
29
+ //
30
+ // A lock made by an older dibs (a directory with only a pid file in it) is judged by that pid,
31
+ // the same way; with no pid in it after PIDLESS_STALE, its writer died before writing one.
32
+ // That older dibs can still take a lock from a live owner after 30 s (and a new lock renamed
33
+ // in the moment between its mkdir and its pid write replaces it): both end once every running
34
+ // dibs process is this version.
35
+ import fs from 'node:fs';
36
+ import path from 'node:path';
37
+ import { spawnSync } from 'node:child_process';
38
+ import { sleepSync } from './util.mjs';
39
+
40
+ const WIN = process.platform === 'win32';
41
+ // This process's start, to tell it from a later process given the same pid.
42
+ const START = Math.round(Date.now() - process.uptime() * 1000);
43
+ // An older dibs makes its lock empty and writes its pid just after.
44
+ const PIDLESS_STALE = 3000;
45
+ // A live owner holds for milliseconds. Held past this, ps is asked whether it's stopped, a zombie
46
+ // or a newer process under a reused pid: one ps call, then again after twice as long each time, up
47
+ // to ASK_MOST apart, so forty waiters on one slow owner don't each run ps every 2 s.
48
+ const ASK_AFTER = 2000, ASK_MOST = 30e3;
49
+ // START is Node's own start, which comes after the exec ps reports (seconds after, under memory
50
+ // pressure), so the owner's real start is never after it. A pid reused by a later process started
51
+ // after it: only a ps start this much later than START is another process (ps counts whole seconds).
52
+ const SAME_START = 5000;
53
+ // A stale lock that can't be taken (a plain file where the lock goes, a folder of another user's):
54
+ // after this many tries in a row, the waiter gives up (LockBroken), naming the path to remove.
55
+ const CLAIM_TRIES = 200;
56
+ // A live owner holding this long is hung, not slow (a ps that never returns, a frozen disk, a
57
+ // debugger): waiters keep waiting, but say so once each (onStuck), so the person hears of it.
58
+ export const STUCK_AFTER = 60e3;
59
+
60
+ let made = 0;
61
+ const nonce = () => `${process.pid}.${START}.${(++made).toString(36)}${Math.random().toString(36).slice(2, 6)}`;
62
+
63
+ export class LostLock extends Error {
64
+ constructor(lock) { super(`${lock} was taken over while this process held it`); this.code = 'ELOSTLOCK'; }
65
+ }
66
+ export class LockBroken extends Error {
67
+ constructor(lock) {
68
+ super(`${lock} is in the way and dibs can't take it over (a file, or a folder it may not change). Nothing ran. If no dibs is running, remove it: rm -rf ${lock}`);
69
+ this.code = 'ELOCKBROKEN';
70
+ }
71
+ }
72
+
73
+ // Waits for the lock and returns its handle ({ owns, release }), or null once `wait` ms pass.
74
+ // fake: called while the lock is made, so a test can make that step fail as a full disk would.
75
+ // files: data files whose per-process temporary copies (commit) a dead writer may have left.
76
+ export function acquire(lock, { wait = Infinity, fake, files = [], onStuck } = {}) {
77
+ fs.mkdirSync(path.dirname(lock), { recursive: true });
78
+ const owner = `owner.${nonce()}`;
79
+ const t0 = Date.now();
80
+ let seen = null, told = false, failed = 0;
81
+ for (;;) {
82
+ // Made only where there's no lock: a rename onto an older dibs's lock in the moment it's still
83
+ // an empty folder (made, its pid not written yet) would replace it under its writer.
84
+ const o = holder(lock);
85
+ if (!o) {
86
+ if (make(lock, owner, fake)) return handle(lock, owner);
87
+ continue;
88
+ }
89
+ if (seen?.key !== o.key) seen = { key: o.key, since: Date.now(), asked: 0, gap: ASK_AFTER };
90
+ if (stale(o, seen)) {
91
+ if (claim(lock, o, owner)) { sweep(lock, files); return handle(lock, owner); }
92
+ if (++failed >= CLAIM_TRIES) throw new LockBroken(lock);
93
+ } else failed = 0;
94
+ if (Date.now() - t0 >= wait) return null;
95
+ if (told !== o.key && onStuck) {
96
+ const held = heldFor(lock, o);
97
+ if (held > STUCK_AFTER) { told = o.key; try { onStuck(o, held); } catch {} }
98
+ }
99
+ sleepSync(10 + Math.random() * 20);
100
+ }
101
+ }
102
+
103
+ // How long the owner has held it: its owner file dates from when it took the lock (a claim
104
+ // touches the file it renamed in); an older dibs's lock dates from its directory.
105
+ function heldFor(lock, o) {
106
+ try { return Date.now() - (o.old ? fs.statSync(lock) : fs.statSync(path.join(lock, o.name))).mtimeMs; } catch { return 0; }
107
+ }
108
+
109
+ // Who holds the lock and for how long, for a board that mustn't wait for it: { key, pid, held }, or null.
110
+ export function heldBy(lock) {
111
+ const o = holder(lock);
112
+ return o ? { key: o.key, pid: o.pid, held: heldFor(lock, o) } : null;
113
+ }
114
+
115
+ // Made whole, then renamed into place: false if someone else's lock is there.
116
+ function make(lock, owner, fake) {
117
+ const tmp = `${lock}.new.${owner.slice(6)}`;
118
+ try {
119
+ fs.mkdirSync(tmp);
120
+ fake?.();
121
+ fs.writeFileSync(path.join(tmp, 'pid'), String(process.pid));
122
+ fs.writeFileSync(path.join(tmp, owner), '');
123
+ if (exists(lock)) throw Object.assign(new Error('taken'), { code: 'EEXIST' });
124
+ fs.renameSync(tmp, lock);
125
+ return true;
126
+ } catch (e) {
127
+ try { fs.rmSync(tmp, { recursive: true, force: true }); } catch {}
128
+ // Windows refuses a rename onto any directory with EPERM.
129
+ if (e.code === 'ENOTEMPTY' || e.code === 'EEXIST' || e.code === 'ENOTDIR' || (WIN && e.code === 'EPERM')) return false;
130
+ throw e;
131
+ }
132
+ }
133
+
134
+ const exists = p => { try { fs.lstatSync(p); return true; } catch { return false; } };
135
+
136
+ // Who holds it: { key, pid, start, name } for a lock of this version, { key, pid, ino, age, old } for an
137
+ // older dibs's, or null when it's gone or changed while being read (look again).
138
+ function holder(lock) {
139
+ let a, names, b;
140
+ try { a = fs.statSync(lock); names = a.isDirectory() ? fs.readdirSync(lock) : []; b = fs.statSync(lock); }
141
+ catch (e) { if (e.code === 'ENOENT') return null; throw e; }
142
+ if (a.ino !== b.ino) return null;
143
+ if (!a.isDirectory()) return { key: `file.${b.ino}`, pid: 0, ino: b.ino, age: Date.now() - b.mtimeMs, old: true, file: true };
144
+ const name = names.find(n => n.startsWith('owner.'));
145
+ if (name) {
146
+ const [, pid, start] = name.split('.');
147
+ return { key: name, name, pid: Number(pid) || 0, start: Number(start) || 0 };
148
+ }
149
+ let pid = 0;
150
+ try { pid = Number(fs.readFileSync(path.join(lock, 'pid'), 'utf8')) || 0; } catch {}
151
+ return { key: `old.${b.ino}.${pid}`, pid, ino: b.ino, age: Date.now() - b.mtimeMs, old: true };
152
+ }
153
+
154
+ const answers = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
155
+
156
+ function stale(o, seen) {
157
+ if (!o.pid) return o.age > PIDLESS_STALE;
158
+ if (o.pid === process.pid) return true; // single-threaded: not a lock this process is in
159
+ if (!answers(o.pid)) return true;
160
+ const t = Date.now();
161
+ if (WIN || t - seen.since < ASK_AFTER || t - seen.asked < seen.gap) return false;
162
+ if (seen.asked) seen.gap = Math.min(seen.gap * 2, ASK_MOST);
163
+ seen.asked = t;
164
+ const p = psOf(o.pid);
165
+ if (p === undefined) return false; // can't tell: wait, rather than take a live owner's lock
166
+ if (p === null || /^[TZ]/.test(p.stat)) return true;
167
+ return !!o.start && t - p.elapsed - o.start > SAME_START;
168
+ }
169
+
170
+ // The command line a pid runs, for saying who dibs is stuck behind, or '' when ps can't say.
171
+ // Windows has no ps: the process's command line comes from WMI, as src/platform.mjs reads it.
172
+ export function commandOf(pid) {
173
+ const r = WIN
174
+ ? spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`],
175
+ { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 30e3 })
176
+ : spawnSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
177
+ return (r.stdout || '').trim().slice(0, 200);
178
+ }
179
+
180
+ // { stat, elapsed ms } from ps, null when the process is gone, undefined when ps can't say.
181
+ function psOf(pid) {
182
+ const r = spawnSync('ps', ['-o', 'stat=,etime=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
183
+ if (r.status == null) return undefined;
184
+ const m = r.stdout.trim().match(/^(\S+)\s+(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/);
185
+ if (!m) return r.status === 0 ? undefined : null;
186
+ const [, stat, d = 0, h = 0, mi, s] = m;
187
+ return { stat, elapsed: (((Number(d) * 24 + Number(h)) * 60 + Number(mi)) * 60 + Number(s)) * 1000 };
188
+ }
189
+
190
+ // Takes the stale lock where it stands. An older dibs's lock is claimed through its pid file the
191
+ // same way; with nothing in it to claim (it died before writing its pid), it's emptied, and the
192
+ // next make() renames a whole lock over the empty directory.
193
+ function claim(lock, o, owner) {
194
+ if (o.file) return false; // a plain file where the lock goes: not dibs's to take (LockBroken)
195
+ const mine = path.join(lock, owner), from = path.join(lock, o.old ? 'pid' : o.name);
196
+ try {
197
+ if (o.old && !o.pid) {
198
+ for (const n of fs.readdirSync(lock)) if (!n.startsWith('owner.')) fs.rmSync(path.join(lock, n), { recursive: true, force: true });
199
+ return false;
200
+ }
201
+ fs.renameSync(from, mine);
202
+ } catch { return false; }
203
+ try {
204
+ // An older dibs's pid file: the one judged only if it still names the dead pid in the same folder.
205
+ // An older waiter may have taken the lock over meanwhile and written its own live pid, or a lock
206
+ // of this version may have replaced the folder (another owner file): either way, not ours.
207
+ const theirs = o.old
208
+ && (Number(fs.readFileSync(mine, 'utf8')) !== o.pid || fs.statSync(lock).ino !== o.ino || fs.readdirSync(lock).some(n => n.startsWith('owner.') && n !== owner));
209
+ if (theirs) { fs.renameSync(mine, from); return false; }
210
+ const at = new Date();
211
+ fs.utimesSync(mine, at, at);
212
+ fs.writeFileSync(path.join(lock, 'pid'), String(process.pid));
213
+ return true;
214
+ } catch (e) {
215
+ // Half claimed: put back what was there, so the next waiter judges the lock as it was.
216
+ try { fs.renameSync(mine, from); } catch {}
217
+ if (e.code === 'ENOSPC' || e.code === 'EDQUOT') throw e;
218
+ return false;
219
+ }
220
+ }
221
+
222
+ // What a writer killed mid-change leaves beside the lock: a lock it was making, one it moved
223
+ // aside, its temporary data file. Only names with a pid in them, and only a dead pid's. Run when a
224
+ // dead owner's lock is claimed, and now and then by the broker (sweepLock).
225
+ export const sweepLock = (lock, files = []) => sweep(lock, files);
226
+ function sweep(lock, files) {
227
+ const dir = path.dirname(lock), base = path.basename(lock);
228
+ const dibsMade = [new RegExp(`^${re(base)}\\.(?:new|gone)\\.(\\d+)\\.`), new RegExp(`^${re(base)}\\.stale-(\\d+)-`),
229
+ ...files.filter(f => path.dirname(f) === dir).map(f => new RegExp(`^${re(path.basename(f))}\\.(\\d+)\\.tmp$`))];
230
+ let names = [];
231
+ try { names = fs.readdirSync(dir); } catch { return; }
232
+ for (const n of names) {
233
+ const pid = dibsMade.map(r => n.match(r)?.[1]).find(Boolean);
234
+ if (pid && !answers(Number(pid))) try { fs.rmSync(path.join(dir, n), { recursive: true, force: true }); } catch {}
235
+ }
236
+ }
237
+ const re = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
238
+
239
+ function handle(lock, owner) {
240
+ const mine = path.join(lock, owner);
241
+ return {
242
+ owns: () => fs.existsSync(mine),
243
+ release() {
244
+ // Nobody moves a live owner's lock (3), so the one found here is still this one when it's
245
+ // renamed aside: whole, in one step, so nobody sees it half removed.
246
+ try {
247
+ if (!fs.existsSync(mine)) return false;
248
+ const aside = `${lock}.gone.${nonce()}`;
249
+ fs.renameSync(lock, aside);
250
+ fs.rmSync(aside, { recursive: true, force: true });
251
+ return true;
252
+ } catch { return false; }
253
+ },
254
+ };
255
+ }
256
+
257
+ // The holder's write of a whole file: a temporary copy named for this process (no two writers share
258
+ // one, and a write cut short by a full disk leaves the old file whole), then a rename, only while it
259
+ // still holds the lock (LostLock if not, with nothing written). fake as in acquire.
260
+ // Returns whether it still held the lock just after the rename: false means another writer took it in
261
+ // the moment between the check and the rename (only possible from a holder stopped right there), and
262
+ // one of the two changes may be lost; the caller puts that on record.
263
+ export function commit(h, file, text, opts = {}) {
264
+ return commitAll(h, [[file, text, opts]]);
265
+ }
266
+
267
+ // Several files as one change: every copy written, one check that the lock is still held, then the
268
+ // renames. Checking before each instead could lose the lock after the first file landed, and the
269
+ // change made again would land twice in that file (a message sent twice).
270
+ export function commitAll(h, files) {
271
+ const tmps = [];
272
+ try {
273
+ for (const [file, text, { mode, fake } = {}] of files) {
274
+ const tmp = `${file}.${process.pid}.tmp`;
275
+ tmps.push(tmp);
276
+ fake?.();
277
+ fs.writeFileSync(tmp, text, mode ? { mode } : undefined);
278
+ }
279
+ if (!h.owns()) throw new LostLock(path.dirname(files[0][0]));
280
+ } catch (e) { for (const tmp of tmps) try { fs.rmSync(tmp, { force: true }); } catch {} throw e; }
281
+ files.forEach(([file], i) => replace(tmps[i], file));
282
+ return h.owns();
283
+ }
284
+
285
+ // Windows refuses to rename over a file another process has open (EPERM, EACCES or EBUSY), and
286
+ // readers open the state without the lock, for a few milliseconds each: on 4-core CI runners a
287
+ // writer in the five-writer lock test crashed on it in 3 of 6 runs (2026-11-13). Those clear in a moment, so the
288
+ // rename is tried again for up to REPLACE_FOR; anything else, or past that, throws as before.
289
+ const REPLACE_FOR = 2000, BUSY = new Set(['EPERM', 'EACCES', 'EBUSY']);
290
+ function replace(tmp, file) {
291
+ for (let t0 = Date.now(), gap = 5; ; gap = Math.min(gap * 2, 100)) {
292
+ try { return fs.renameSync(tmp, file); }
293
+ catch (e) { if (!WIN || !BUSY.has(e.code) || Date.now() - t0 > REPLACE_FOR) throw e; }
294
+ sleepSync(gap);
295
+ }
296
+ }
297
+
298
+ // fn under the lock, done again from the start if the lock was lost before it wrote.
299
+ // null when wait passes first.
300
+ export function underLock(lock, fn, opts = {}) {
301
+ for (;;) {
302
+ const h = acquire(lock, opts);
303
+ if (!h) return null;
304
+ try { return { out: fn(h) }; }
305
+ catch (e) { if (!(e instanceof LostLock)) throw e; }
306
+ finally { h.release(); }
307
+ }
308
+ }
package/src/measure.mjs CHANGED
@@ -5,7 +5,7 @@ const GB = b => gb(b).replace(/G$/, ' GB');
5
5
  // its peak goes into history with its run time, and the next run of the same
6
6
  // command is planned at what it really took.
7
7
  //
8
- // Memory is physical footprint (src/platform.mjs footprints), CPU is the
8
+ // Memory is physical footprint (src/platform.mjs footprints; the working set on Windows), CPU is the
9
9
  // process table's % of a core, both summed over every process group the lease
10
10
  // spans plus, for a pool simulator, the simulator's own launchd_sim tree,
11
11
  // which runs outside the job's. Reading footprints costs a top call, so
@@ -48,7 +48,7 @@ export function treeOf(l, s, procs) {
48
48
  for (const x of s.leases || [])
49
49
  if (x.id !== l.id && x.kind === 'run' && x.pgid && x.pgid !== l.pgid && groups.has(x.pgid))
50
50
  for (const g of [x.pgid, ...(x.groups || [])]) groups.delete(g);
51
- const pids = new Set(procs.filter(p => groups.has(p.pgid)).map(p => p.pid));
51
+ const pids = OS === 'windows' ? windowsTree(l, groups, s, procs) : new Set(procs.filter(p => groups.has(p.pgid)).map(p => p.pid));
52
52
  const holds = new Set(s.leases.filter(h => h.kind === 'hold' && h.pid && h.pid === l.spid).map(h => h.id));
53
53
  // A hold's simulator counts in one of the runs under it, the first: two test
54
54
  // runs on one held simulator each counting it charged it twice.
@@ -74,6 +74,21 @@ export function treeOf(l, s, procs) {
74
74
  return pids;
75
75
  }
76
76
 
77
+ // Windows has no process groups (each process's group is its pid): a lease is its groups' processes
78
+ // and everything under them by parent, less the trees of runs nested in it, measured as their own.
79
+ function windowsTree(l, groups, s, procs) {
80
+ const kids = new Map();
81
+ for (const p of procs) if (p.ppid !== p.pid) { if (!kids.has(p.ppid)) kids.set(p.ppid, []); kids.get(p.ppid).push(p.pid); }
82
+ const nested = new Set((s.leases || []).filter(x => x.id !== l.id && x.kind === 'run' && x.pgid && x.pgid !== l.pgid).map(x => x.pgid));
83
+ const pids = new Set(), stack = procs.filter(p => groups.has(p.pgid)).map(p => p.pid);
84
+ while (stack.length) {
85
+ const pid = stack.pop();
86
+ if (pids.has(pid) || nested.has(pid)) continue;
87
+ pids.add(pid);
88
+ stack.push(...(kids.get(pid) || []));
89
+ }
90
+ return pids;
91
+ }
77
92
  // Memory in bytes and CPU in cores for a set of pids. A process top didn't
78
93
  // list (it started since) counts at its RSS.
79
94
  export function usage(pids, procs, foot) {
@@ -111,7 +126,7 @@ function shareDisk(s, got, m, t) {
111
126
  const last = s.diskSample;
112
127
  s.diskSample = { free: m.diskFree ?? null, swap: m.swapUsed ?? null, ...(m.swapFiles != null && { files: m.swapFiles }), at: t };
113
128
  const runs = s.leases.filter(l => got.has(l.id) && !l.pausedAt);
114
- for (const l of runs) l.ate ??= 0;
129
+ for (const l of runs) { l.ate ??= 0; l.ateLast = 0; }
115
130
  if (!last || last.free == null || m.diskFree == null || t - last.at > 3 * SAMPLE_EVERY) return;
116
131
  const swapGrew = Math.max(0, last.swap != null && m.swapUsed != null ? m.swapUsed - last.swap : 0,
117
132
  last.files != null && m.swapFiles != null ? m.swapFiles - last.files : 0);
@@ -119,13 +134,14 @@ function shareDisk(s, got, m, t) {
119
134
  if (!fell || !runs.length) return;
120
135
  const w = l => Math.max(l.disk || 0, DISK_WEIGHT);
121
136
  const all = runs.reduce((a, l) => a + w(l), 0);
122
- for (const l of runs) l.ate += fell * w(l) / all;
137
+ // ateLast, this reading's share alone: which run is writing now, for the hard stop (src/preempt.mjs).
138
+ for (const l of runs) { l.ateLast = fell * w(l) / all; l.ate += l.ateLast; }
123
139
  }
124
140
 
125
141
  // Measure every run lease on the machine, if this process won the slot.
126
142
  // Called from each `dibs run` on its group-tracking tick. True if it measured.
127
143
  export function sample(t = now()) {
128
- if (OS === 'windows' || !claim(t)) return false;
144
+ if (!claim(t)) return false;
129
145
  // A plain read: the state file is replaced whole, never written in place.
130
146
  let s;
131
147
  try { s = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch { return false; }
@@ -148,9 +164,13 @@ export function sample(t = now()) {
148
164
  l.use = { ...u, at: t };
149
165
  // When its memory last rose past what it had reached: a job let in by the
150
166
  // stall breaker counts as settled once this is a while ago (schedule.mjs).
151
- if (!(u.mem <= (l.peak?.mem ?? -1) * 1.05)) l.peakAt = t;
167
+ // How far into the run that was goes into history, so a later run of the same
168
+ // command that has run past it is known to be done growing (schedule.mjs pastPeak).
169
+ const rose = !(u.mem <= (l.peak?.mem ?? -1) * 1.05);
170
+ if (rose) l.peakAt = t;
171
+ const at = rose ? t - l.start : l.peak?.in;
152
172
  l.peak = { mem: Math.max(l.peak?.mem || 0, u.mem), cpu: Math.max(l.peak?.cpu || 0, u.cpu), fit: true,
153
- ...(l.ate != null && { ate: l.ate }) };
173
+ ...(at != null && { in: at }), ...(l.ate != null && { ate: l.ate }) };
154
174
  const x = overAsk(l);
155
175
  if (!x) continue;
156
176
  if (!l.overAsk) {
package/src/ondemand.mjs CHANGED
@@ -26,6 +26,7 @@ import fs from 'node:fs';
26
26
  import os from 'node:os';
27
27
  import path from 'node:path';
28
28
  import { spawn, execFile } from 'node:child_process';
29
+ import { runnable } from './platform.mjs';
29
30
  import { fileURLToPath } from 'node:url';
30
31
  import { HOME } from './config.mjs';
31
32
  import { event } from './events.mjs';
@@ -186,7 +187,8 @@ const hhmm = (t = now()) => new Date(t).toTimeString().slice(0, 5);
186
187
  export function boat(args, { timeout = 60e3 } = {}) {
187
188
  return new Promise(resolve => {
188
189
  // --no-update first: after `--` it would go to the command run on the VM.
189
- execFile(process.env.DIBS_BOAT || 'boat', ['--no-update', ...args], { timeout, maxBuffer: 16 * 1024 ** 2, encoding: 'utf8' }, (e, out, err) => {
190
+ const [cmd, ...argv] = runnable([process.env.DIBS_BOAT || 'boat', '--no-update', ...args]);
191
+ execFile(cmd, argv, { timeout, maxBuffer: 16 * 1024 ** 2, encoding: 'utf8', windowsVerbatimArguments: cmd === 'cmd.exe', windowsHide: true }, (e, out, err) => {
190
192
  const r = { code: e ? (typeof e.code === 'number' ? e.code : 1) : 0, out: out || '', err: (err || e?.message || '').trim() };
191
193
  const j = args[0] === 'exec' && !args.includes('--detach') ? json(r.out) : null;
192
194
  if (j && typeof j.stdout === 'string') Object.assign(r, { out: j.stdout, err: (j.stderr || r.err).trim(), code: j.exitCode ?? r.code });
@@ -288,7 +290,8 @@ export function ondemand(list, srv, { port, tick = TICK, log: say = log, clock =
288
290
  // The reverse forward lives as long as the VM is up, started again if it drops.
289
291
  const forward = vm => {
290
292
  if (vm.forward || !['waking', 'running'].includes(vm.state)) return;
291
- const p = spawn(process.env.DIBS_BOAT || 'boat', ['--no-update', 'forward', vm.id, '--reverse', '--local', String(port)], { stdio: 'ignore' });
293
+ const [cmd, ...argv] = runnable([process.env.DIBS_BOAT || 'boat', '--no-update', 'forward', vm.id, '--reverse', '--local', String(port)]);
294
+ const p = spawn(cmd, argv, { stdio: 'ignore', windowsVerbatimArguments: cmd === 'cmd.exe', windowsHide: true });
292
295
  vm.forward = p;
293
296
  p.on('exit', () => { vm.forward = null; if (['waking', 'running'].includes(vm.state)) setTimeout(() => forward(vm), 2000).unref(); });
294
297
  p.on('error', () => {});
package/src/override.mjs CHANGED
@@ -20,10 +20,10 @@ import { tag, makeAlive, identity, isMine } from './proc.mjs';
20
20
  import { descendants, processes, pidsIn, stopTree, lower, raise, OS } from './platform.mjs';
21
21
  import { withState, history } from './state.mjs';
22
22
  import { ownerPause, pauseLabel } from './preempt.mjs';
23
- import { PRIORITIES, BACKGROUND, NEEDS_REASON, priority, byRank } from './schedule.mjs';
23
+ import { PRIORITIES, BACKGROUND, NEEDS_REASON, priority, byRank, roomFor } from './schedule.mjs';
24
24
  import { actor } from './owner.mjs';
25
25
  import { event } from './events.mjs';
26
- import { die, now, say, sleepSync } from './util.mjs';
26
+ import { die, now, say, sleepSync, unpolled } from './util.mjs';
27
27
  import { takeAgent, callKey } from './files.mjs';
28
28
  import { quoted } from './style.mjs';
29
29
 
@@ -203,6 +203,35 @@ export function boost(args) {
203
203
  recordAll('boost', r.filter(c => !c.same).map(({ id, res, who, prio, from }) => ({ id, res, who, prio, from })), who, reason);
204
204
  }
205
205
 
206
+ // Priority inversion: a low or idle run is at background QoS, which macOS starves while
207
+ // normal work fills every core (a 0.08 s loop took 13.6 s at load 35, 2026-11-03). One
208
+ // holding a full slot that a normal-or-higher waiter wants makes that waiter wait on the
209
+ // starving, so it's lifted to normal QoS while such a waiter is in line, and dropped back
210
+ // once none is. Under the state lock: marks the leases and returns the moves, made after it.
211
+ export function inversions(s, cfg) {
212
+ const moves = [];
213
+ for (const l of s.leases) {
214
+ if (l.kind !== 'run' || !l.pgid || !(l.background ?? BACKGROUND.has(l.prio))) continue;
215
+ const stuck = s.queue.find(q => q.pid && !BACKGROUND.has(q.prio || 'normal') && q.res.some(r => l.res.includes(r) && roomFor(s, q, r, cfg).open <= 0));
216
+ if (stuck && !l.lifted) { l.lifted = stuck.id; moves.push({ id: l.id, res: l.res, who: l.who, pgid: l.pgid, pgstart: l.pgstart, groups: l.groups, bg: false, for: stuck.id }); }
217
+ else if (!stuck && l.lifted) { moves.push({ id: l.id, res: l.res, who: l.who, pgid: l.pgid, pgstart: l.pgstart, groups: l.groups, bg: true, for: l.lifted }); delete l.lifted; }
218
+ }
219
+ return moves;
220
+ }
221
+ // Make the moves inversions() decided, after the lock, with boost's catch-up rounds.
222
+ export function lift(moves) {
223
+ for (const m of moves) {
224
+ const groups = [...groupsOf(m)];
225
+ const move = pid => (m.bg ? lower(pid) : raise(pid));
226
+ for (let i = 0; i <= CATCH_UP; i++) {
227
+ if (i) sleepSync(CATCH_GAP);
228
+ for (const pid of pidsIn(groups)) move(pid);
229
+ }
230
+ event({ kind: 'override', act: m.bg ? 'unlift' : 'lift', id: m.id, res: m.res, who: m.who, for: m.for,
231
+ why: m.bg ? `dropped #${m.id} back to background priority: nobody is stuck behind it now` : `lifted #${m.id} so #${m.for} isn't stuck behind it` });
232
+ }
233
+ }
234
+
206
235
  // Why the owner can't pause this lease, or null. Resources marked pausable:
207
236
  // false (sim, xcode-build and deploy by default) stay unpaused unless --force:
208
237
  // a frozen deploy, simulator or build can time out against the services it
@@ -296,6 +325,14 @@ export function stop(args) {
296
325
  x.ownerStop = now();
297
326
  if (who.agent || who.via) x.stopBy = who.name;
298
327
  if (reason) x.stopReason = reason;
328
+ if (c.kind === 'wait') {
329
+ // Recorded apart from the place, so its waiter can say why once the place is gone. A place
330
+ // its dibs is still deciding for stays until that dibs sees the stop (its waiter says so and
331
+ // leaves; src/state.mjs reap takes it after STOP_GRACE); one nothing decides for goes now.
332
+ // On 2026-11-04 "took #19783 out of line" left #19783 at the head of heavy, twice.
333
+ (s.stopped ||= {})[x.id] = { at: x.ownerStop, by: x.stopBy, reason: x.stopReason };
334
+ if (unpolled(x, now())) s.queue = s.queue.filter(q => q !== x);
335
+ }
299
336
  // SIGKILL ends stopped processes too, so a paused run needs no SIGCONT first.
300
337
  // The lock is still held, so the run's own dibs can't remove the lease
301
338
  // (and its group number can't be handed out again) in between.
package/src/plain.mjs CHANGED
@@ -219,7 +219,7 @@ function waitingFor(s, q, v, cfg, hist, t, m, f) {
219
219
  + `${v.high ? ' with memory pressure high' : ''}${v.growing ? ' and swap growing' : ''}, and it needs ${GB(v.need)} plus ${GB(v.reserve)} to spare`;
220
220
  return `room in memory: ${memoryPicture(s, cfg, m, v.need, t)}`;
221
221
  case 'cpu': return `free processor cores (jobs running now are using ${v.used} of the ${v.of} cores dibs shares out, and it needs ${v.need})`;
222
- case 'disk': return `more free disk (${GB(v.free)} free, it needs ${GB(v.need)})${hogHint()}`;
222
+ case 'disk': return `more free disk (${GB(v.free)} free, it needs ${GB(v.need)}${v.floorWhy ? `: ${v.floorWhy}` : ''})${hogHint()}`;
223
223
  case 'pressure': return `memory pressure to ease (the OS says it's high, so dibs starts nothing new until it eases): ${memoryPicture(s, cfg, m, q.mem, t)}`;
224
224
  case 'swaproom': return `more free disk for swap to grow into (${GB(v.free)} free; while this machine swaps, dibs starts nothing new until ${GB(v.need)} is free or nothing else is running)${hogHint()}`;
225
225
  case 'drain': return `free disk to stop falling (it fell ${GB(v.fell)} in 5 min to ${GB(v.free)}; dibs starts nothing new while it falls this fast and anything else is running)${hogHint()}`;
@@ -417,7 +417,7 @@ export function lineParts(p) {
417
417
  let now = rows.length ? usingText(rows, named(p.cfg, l.res)) : 'free';
418
418
  if (notes.length) now += ` (${rows.length > 1 ? notes.map(([w, x]) => `${w} is ${lower(x)}`).join('; ') : lower(notes[0][1])})`;
419
419
  let next = '';
420
- const names = l.waiting.map(id => p.names.get(id));
420
+ const names = l.waiting.map(id => `${p.names.get(id)} (#${id})`); // the id, for dibs why, boost or stop
421
421
  if (names.length) {
422
422
  // Say why the next one waits only when it isn't simply its turn here:
423
423
  // stuck on the machine, or on another resource it needs too.