@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/relay.mjs CHANGED
@@ -30,6 +30,7 @@ import crypto from 'node:crypto';
30
30
  import { HOME } from './config.mjs';
31
31
  import { die, now, log, sleep, dur } from './util.mjs';
32
32
  import { makeAlive, singleInstance } from './proc.mjs';
33
+ import { underLock, commit } from './lock.mjs';
33
34
  import { qr, render } from './qr.mjs';
34
35
  import { logChange } from './owner.mjs';
35
36
  import { remoteAccess, LOCAL_ONLY_TEXT, lookOnlyText, remoteMcp, MCP_ORIGIN, mcpCodes } from './web.mjs';
@@ -39,6 +40,8 @@ export const RELAY = process.env.DIBS_RELAY_URL || 'wss://app.dibs.cc';
39
40
  const KEYS = path.join(HOME, 'relay-keys.json');
40
41
  const FILE = path.join(HOME, 'relay.json');
41
42
  const LOCK = path.join(HOME, 'relay.lock');
43
+ // Writes take milliseconds: a holder still at it past this is stuck on something else.
44
+ const LOCK_WAIT = 5000;
42
45
  export const STATUS = path.join(HOME, 'relay-status.json');
43
46
  const PIDFILE = path.join(HOME, 'relay.pid');
44
47
 
@@ -109,6 +112,52 @@ export const tokenHash = rt => b64u(sha(Buffer.concat([utf8('dibs-relay-token-v1
109
112
  const MAX_HASHES = 56;
110
113
  // Sign-in codes the relay's index takes from one machine at once (relay/src/index.js MAX_CODES).
111
114
  const MAX_CODES = 10;
115
+
116
+ // The pairing code shown beside the QR code, for typing at app.dibs.cc instead of scanning:
117
+ // 12 Crockford base32 characters, 7KQM-2XRP-9DHT. The first 4 (R) name a drop at the relay; the
118
+ // other 8 (K, 40 bits) never leave this Mac and the person's eyes. The drop holds the link's
119
+ // fragment (mid, secret, fingerprint) sealed with AES-256-GCM under
120
+ // PBKDF2-SHA256(K, salt "dibs-code-v1" || R, 600,000 iterations). The page fetches the drop by R,
121
+ // derives the key from K and opens it, then pairs exactly as the link does, so the relay never
122
+ // learns the secret. Someone who gets the box (the relay itself, or a guesser who hit a live R)
123
+ // has 2^40 keys to try at 600,000 PBKDF2 rounds each: 3.3e17 HMAC-SHA256 calls on average. A
124
+ // top-end GPU does about 9e9 a second, so finding K inside the link's ten minutes takes some
125
+ // 60,000 of them, and the secret inside is worthless after those ten minutes or once the link is
126
+ // used. The relay hands out each box at most 3 times (relay/src/codebook.js), limits fetches per
127
+ // address, and drops the box when the link is used, revoked or expires.
128
+ const CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
129
+ export const CODE_ITERATIONS = 600000;
130
+ const CODE_SALT = 'dibs-code-v1';
131
+ // What people type: lower case, spaces and dashes are fine, and O, I and L read as 0, 1 and 1.
132
+ export const normCode = s => String(s || '').toUpperCase().replace(/[^0-9A-Z]/g, '').replace(/O/g, '0').replace(/[IL]/g, '1');
133
+ export const isCode = s => /^[0-9A-HJKMNP-TV-Z]{12}$/.test(s);
134
+ const randomCrockford = n => Array.from({ length: n }, () => CROCKFORD[crypto.randomInt(32)]).join('');
135
+ // DIBS_FAKE_CODES: codes to hand out first, comma-separated, so a test can make two Macs pick the
136
+ // same drop name. Read once per process.
137
+ const fakeCodes = (process.env.DIBS_FAKE_CODES || '').split(',').map(normCode).filter(isCode);
138
+ // A new code whose drop name none of this Mac's open links uses.
139
+ function freshCode() {
140
+ const mine = new Set(load().pairs.map(p => p.cr));
141
+ for (;;) {
142
+ const c = fakeCodes.shift() || randomCrockford(12);
143
+ if (!mine.has(c.slice(0, 4))) return c;
144
+ }
145
+ }
146
+ // How long dibs pair --remote waits for the relay to take its code (the connector notices the new
147
+ // link within TOKEN_SYNC, then it's one round trip), and how many fresh codes it tries when
148
+ // another Mac already holds the drop name. One clash is a 1 in a million event; three in a row
149
+ // means something else is wrong.
150
+ const CODE_ACK_WAIT = 5000;
151
+ const CODE_TRIES = 3;
152
+ export const showCode = c => `${c.slice(0, 4)}-${c.slice(4, 8)}-${c.slice(8, 12)}`;
153
+ const codeKey = (k, r) => crypto.pbkdf2Sync(utf8(k), utf8(CODE_SALT + r), CODE_ITERATIONS, 32, 'sha256');
154
+ // iv (12) || ciphertext || tag (16), base64url, with the salt as associated data.
155
+ export function sealCode(frag, r, k) {
156
+ const iv = crypto.randomBytes(12);
157
+ const c = crypto.createCipheriv('aes-256-gcm', codeKey(k, r), iv);
158
+ c.setAAD(utf8(CODE_SALT + r));
159
+ return b64u(Buffer.concat([iv, c.update(utf8(frag)), c.final(), c.getAuthTag()]));
160
+ }
112
161
  function openBox(key, box) {
113
162
  if (box.length !== BOX_LEN) return null;
114
163
  try {
@@ -156,31 +205,15 @@ export function load() {
156
205
 
157
206
  // `dibs pair` and the connector both write relay.json; this keeps one from undoing the other.
158
207
  function locked(fn) {
159
- fs.mkdirSync(HOME, { recursive: true });
160
- const t0 = now();
161
- for (;;) {
162
- try { fs.mkdirSync(LOCK); break; } catch (e) {
163
- if (e.code !== 'EEXIST') throw e;
164
- try {
165
- if (now() - fs.statSync(LOCK).mtimeMs > 5000) {
166
- const aside = `${LOCK}.stale.${process.pid}`;
167
- fs.renameSync(LOCK, aside);
168
- fs.rmSync(aside, { recursive: true, force: true });
169
- }
170
- } catch {}
171
- if (now() - t0 > 5000) throw new Error(`${LOCK} stayed locked; remove it if no dibs is running`);
172
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
173
- }
174
- }
175
- try {
208
+ const r = underLock(LOCK, h => {
176
209
  const w = load();
177
210
  const out = fn(w);
178
211
  w.pairs = w.pairs.filter(p => p.exp > now());
179
- const tmp = `${FILE}.${process.pid}`;
180
- fs.writeFileSync(tmp, JSON.stringify(w), { mode: 0o600 });
181
- fs.renameSync(tmp, FILE);
212
+ commit(h, FILE, JSON.stringify(w), { mode: 0o600 });
182
213
  return out;
183
- } finally { fs.rmSync(LOCK, { recursive: true, force: true }); }
214
+ }, { wait: LOCK_WAIT, files: [FILE] });
215
+ if (!r) throw new Error(`${LOCK} is held by a dibs that's still running; try again in a moment`);
216
+ return r.out;
184
217
  }
185
218
 
186
219
  // A one-time pairing link. The secret is shown once and only its derived pieces are kept.
@@ -189,12 +222,57 @@ function locked(fn) {
189
222
  export function newPairing({ act = false, account = false } = {}) {
190
223
  const k = keys();
191
224
  const secret = crypto.randomBytes(32);
225
+ const frag = `${k.mid}.${b64u(secret)}.${k.fp}`;
226
+ // A browser link gets a code to type as well. The account link opens on /account, which has
227
+ // its own sign-in, so it has none.
228
+ const code = account ? null : freshCode();
229
+ const box = code && sealCode(frag, code.slice(0, 4), code.slice(4));
230
+ const pid = b64u(pairId(secret));
192
231
  locked(w => {
193
- w.pairs.push({ pid: b64u(pairId(secret)), key: b64u(pairKey(secret)), nk: b64u(nameKey(secret)), th: tokenHash(pairTicket(secret)), exp: now() + PAIR_LIFE, fails: 0, ...(act ? { act: true } : {}), ...(account ? { acct: true } : {}) });
232
+ w.pairs.push({ pid, key: b64u(pairKey(secret)), nk: b64u(nameKey(secret)), th: tokenHash(pairTicket(secret)), exp: now() + PAIR_LIFE, fails: 0, ...(act ? { act: true } : {}), ...(account ? { acct: true } : {}), ...(code ? { cr: code.slice(0, 4), cb: box } : {}) });
194
233
  w.pairs = w.pairs.slice(-MAX_PAIRS);
195
234
  });
196
- const frag = `${k.mid}.${b64u(secret)}.${k.fp}`;
197
- return { link: account ? `${PAGE}account#join=${frag}` : `${PAGE}#p=${frag}`, mid: k.mid, fp: k.fp, life: PAIR_LIFE, exp: now() + PAIR_LIFE, act };
235
+ return { link: account ? `${PAGE}account#join=${frag}` : `${PAGE}#p=${frag}`, ...(code ? { code: showCode(code) } : {}), pid, frag, mid: k.mid, fp: k.fp, life: PAIR_LIFE, exp: now() + PAIR_LIFE, act };
236
+ }
237
+
238
+ // A new code for an open link whose drop name another Mac holds at the relay: the same link,
239
+ // sealed again under a fresh drop name and key. Null if the link is gone (used, revoked, expired).
240
+ export function recode(pid, frag) {
241
+ const code = freshCode();
242
+ const box = sealCode(frag, code.slice(0, 4), code.slice(4));
243
+ return locked(w => {
244
+ const p = w.pairs.find(x => x.pid === pid);
245
+ if (!p) return null;
246
+ Object.assign(p, { cr: code.slice(0, 4), cb: box });
247
+ delete p.ca;
248
+ return showCode(code);
249
+ });
250
+ }
251
+
252
+ // The relay's answer to a drops message: which drop names it holds for this Mac (ok) and which
253
+ // another machine already holds (taken). Kept on each open link as ca, for pairRemote to wait on.
254
+ export function dropsAck(m) {
255
+ const ok = new Set(Array.isArray(m?.ok) ? m.ok : []), taken = new Set(Array.isArray(m?.taken) ? m.taken : []);
256
+ locked(w => {
257
+ for (const p of w.pairs) {
258
+ if (typeof p.cr !== 'string') continue;
259
+ if (taken.has(p.cr)) p.ca = 'taken';
260
+ else if (ok.has(p.cr)) p.ca = 'ok';
261
+ }
262
+ });
263
+ }
264
+
265
+ // What the relay said about this link's code: 'ok', 'taken', 'gone' (the link was used or
266
+ // revoked meanwhile, so the code no longer matters), or null if it hasn't said within CODE_ACK_WAIT.
267
+ async function codeAck(pid, code) {
268
+ const r = normCode(code).slice(0, 4), until = now() + CODE_ACK_WAIT;
269
+ while (now() < until) {
270
+ const p = load().pairs.find(x => x.pid === pid);
271
+ if (!p) return 'gone';
272
+ if (p.cr === r && p.ca) return p.ca;
273
+ await sleep(100);
274
+ }
275
+ return null;
198
276
  }
199
277
 
200
278
  export const devices = () => Object.entries(load().devices).map(([id, d]) => ({ id, ...d }));
@@ -487,7 +565,8 @@ export function macPeer({ k = keys(), send, kick, call, admit = () => {}, clock
487
565
  sid: hkdf(c.ss, salt, 'dibs-relay-v1 sid', 32), seqIn: 0, seqOut: 0, began: clock(), ss: null, th: null,
488
566
  });
489
567
  try { locked(w => { if (w.devices[c.did]) w.devices[c.did].seen = clock(); }); } catch {}
490
- // Key confirmation: the page waits for this before it sends a call.
568
+ // Key confirmation. The page may already have sent its first call behind hello3 (it reads this
569
+ // before any answer); that frame is handled after this function, so the keys are in place.
491
570
  out(ch, c, { t: 'ready' });
492
571
  }
493
572
 
@@ -562,6 +641,12 @@ export function relayTokens(w = load(), t = now()) {
562
641
  return { t: 'tokens', h, p: w.pairs.filter(p => p.exp > t && typeof p.th === 'string').map(p => p.th), c: w.mcp ? mcpCodes().slice(-MAX_CODES) : [] };
563
642
  }
564
643
 
644
+ // The sealed boxes of open links' codes, by drop name, for the relay to hand to whoever types
645
+ // the code (see CROCKFORD above). Sent apart from the tokens, which have a size limit of their own.
646
+ export function relayDrops(w = load(), t = now()) {
647
+ return { t: 'drops', d: w.pairs.filter(p => p.exp > t && typeof p.cr === 'string' && typeof p.cb === 'string' && p.ca !== 'taken').map(p => ({ r: p.cr, b: p.cb, exp: p.exp })) };
648
+ }
649
+
565
650
  function status(state, extra = {}) {
566
651
  try {
567
652
  const tmp = `${STATUS}.${process.pid}`;
@@ -669,13 +754,15 @@ export function connectOnce(base, k, call) {
669
754
  let ws;
670
755
  try { ws = new WebSocket(url); } catch (e) { return resolve(e.message); }
671
756
  ws.binaryType = 'arraybuffer';
672
- let authed = false, lastHeard = now(), done = false, sentTokens = '';
757
+ let authed = false, lastHeard = now(), done = false, sentTokens = '', sentDrops = '';
673
758
  const finish = why => { if (done) return; done = true; clearInterval(beat); clearInterval(watch); clearInterval(approvals); peer.closeAll(); try { ws.close(); } catch {} resolve(why); };
674
759
  // The relay's list of who may connect follows relay.json within a second: a new link opens
675
760
  // the pairing pool, a pairing adds a hash, a revoke removes one (and its open sessions end).
676
761
  const syncTokens = () => {
677
762
  if (!authed || ws.readyState !== 1) return;
678
- const t = JSON.stringify(relayTokens());
763
+ const w = load();
764
+ const t = JSON.stringify(relayTokens(w)), d = JSON.stringify(relayDrops(w));
765
+ if (d !== sentDrops) { sentDrops = d; ws.send(d); }
679
766
  if (t === sentTokens) return;
680
767
  sentTokens = t;
681
768
  ws.send(t);
@@ -723,6 +810,7 @@ export function connectOnce(base, k, call) {
723
810
  if (m.t === 'http' && typeof m.id === 'string') {
724
811
  return mcpAnswer(m, k).catch(() => offJson(500)).then(r => { if (ws.readyState === 1) ws.send(httpRes(m.id, r)); });
725
812
  }
813
+ if (m.t === 'drops-res') { try { dropsAck(m); } catch (e) { log(`relay: couldn't note which codes the relay took: ${e.message}`); } return; }
726
814
  if (m.t === 'open' && unb64u(m.ch, 16)) return peer.open(m.ch);
727
815
  if (m.t === 'gone' && unb64u(m.ch, 16)) return peer.gone(m.ch);
728
816
  return;
@@ -740,15 +828,32 @@ export function connectOnce(base, k, call) {
740
828
  const ago = t => (t ? `${dur(now() - t)} ago` : 'never');
741
829
 
742
830
  // The remote half of `dibs pair`: --remote [--allow-actions], and its rows in --list and --revoke.
743
- export function pairRemote({ act = false } = {}) {
831
+ export async function pairRemote({ act = false } = {}) {
744
832
  const p = newPairing({ act });
745
833
  logChange('pair remote', { actions: act });
746
- console.log(`${render(qr(p.link))}\n${p.link}\n`);
747
- console.log(`Scan the code with the phone you want to use, or open the link in that browser. Don't paste it into a chat: whoever opens it first gets in.`);
748
- console.log(`One use, until ${clockOf(p.exp)} (${p.life / MIN} minutes). That browser checks it reached this Mac by its fingerprint ${p.fp.slice(0, 16)}...`);
834
+ // The code is shown only once the relay has taken it, so the one printed works. Another Mac
835
+ // holding the same drop name gets a fresh code for the same link; no answer from the relay
836
+ // (it's slow, or the connector isn't running) prints the code with a warning.
837
+ const s = statusLine();
838
+ const connected = !!s?.startsWith('connected');
839
+ let code = p.code, ack = connected ? await codeAck(p.pid, code) : null;
840
+ for (let i = 1; ack === 'taken' && i < CODE_TRIES; i++) {
841
+ code = recode(p.pid, p.frag);
842
+ ack = code ? await codeAck(p.pid, code) : 'gone';
843
+ }
844
+ const page = PAGE.replace(/^https?:\/\//, '').replace(/\/$/, '');
845
+ if (ack === 'taken') {
846
+ console.log(`${render(qr(p.link))}\n`);
847
+ console.log(`Scan the QR code with your phone. Its code clashed with another Mac's at the relay, so there's none to type this time: run dibs pair --remote again for one.`);
848
+ } else {
849
+ console.log(`${render(qr(p.link))}\nCode: ${code}\n`);
850
+ console.log(`Scan the QR code with your phone, or type the code at ${page}.`);
851
+ if (connected && !ack) console.log(`The relay hasn't confirmed the code yet, so it may not work. The QR code works either way.`);
852
+ }
853
+ console.log(`It works once, until ${clockOf(p.exp)} (${p.life / MIN} minutes). That browser checks it reached this Mac by its fingerprint ${p.fp.slice(0, 16)}...`);
854
+ console.log(`The QR code as a link:\n${p.link}\n`);
749
855
  console.log(act ? 'It can act: boost, pause, resume and stop jobs, cap an agent, set the pace, cancel scheduled runs. Never message agents, answer their questions, or change the hook or your hours. Revoke it if the device is lost.'
750
856
  : 'It can only look. To let a browser change things too: dibs pair --remote --allow-actions');
751
- const s = statusLine();
752
857
  if (!s || s.startsWith('not running')) console.log(`\nThis Mac isn't connected to the relay yet. Turn it on: dibs service install relay`);
753
858
  }
754
859
  // dibs connect --account: a link a browser signed in to a dibs account opens, to add this Mac to
package/src/remote.mjs CHANGED
@@ -125,10 +125,16 @@ export function tarExtract(dir, buf, only = null) {
125
125
  return members;
126
126
  }
127
127
 
128
+ // A path with its links resolved, the same way every time it's compared. On
129
+ // Windows only the native call also expands 8.3 names (C:\Users\RUNNER~1): the JS
130
+ // one left a temp folder short and the home folder long, so the job's folder came
131
+ // out as ../../RUNNER~1/... relative to its own project.
132
+ const real = p => { try { return (OS === 'windows' ? fs.realpathSync.native : fs.realpathSync)(p); } catch { return p; } };
133
+
128
134
  // The folder a working copy comes from: the git repo around cwd, or cwd itself.
129
135
  function projectRoot(cwd = process.cwd()) {
130
- try { return fs.realpathSync(execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()); }
131
- catch { return cwd; }
136
+ try { return real(execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()); }
137
+ catch { return real(cwd); }
132
138
  }
133
139
  // A load-held job may go to an on-demand machine on its own (acquire.mjs step)
134
140
  // only when it can run there. Never one that needs macOS: a resource that
@@ -167,14 +173,13 @@ export function mayShip(me, cfg, cwd) {
167
173
  if (macOnly(me.cmd, cwd) || !remoteConf(() => null) || namesPaths(me.cmd)) return false;
168
174
  const root = gitRoot(cwd);
169
175
  if (!root) return false;
170
- let home = os.homedir();
171
- try { home = fs.realpathSync(home); } catch {}
176
+ const home = real(os.homedir());
172
177
  return !(root === path.parse(root).root || home === root || home.startsWith(root.endsWith(path.sep) ? root : root + path.sep));
173
178
  }
174
179
  // Only a git working copy ships on its own: that's what the copy is, and a
175
180
  // folder outside git may hold anything.
176
181
  function gitRoot(cwd) {
177
- try { return fs.realpathSync(execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()); }
182
+ try { return real(execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim()); }
178
183
  catch { return null; }
179
184
  }
180
185
  // A command that names a path of this machine (/Users/..., ~/...) means a file the
@@ -258,7 +263,7 @@ function workingCopy(root, cwd = process.cwd()) {
258
263
  if (st.isDirectory()) continue; // a submodule
259
264
  (SECRET.test(f) ? secret : kept).push(f);
260
265
  }
261
- const cwdRel = path.relative(root, fs.realpathSync(cwd)).split(path.sep).join('/');
266
+ const cwdRel = path.relative(root, real(cwd)).split(path.sep).join('/');
262
267
  return { files: kept.sort(), secret, cwdRel };
263
268
  }
264
269
 
@@ -292,8 +297,7 @@ export async function remoteRun(o, cfg) {
292
297
  if (o.on && !ruleAllows(rule, o.on, rc.name)) return refuse(o.on, rule);
293
298
  const root = projectRoot();
294
299
  // Your home folder, or a folder above it, holds far more than a project, keys included.
295
- let home = os.homedir();
296
- try { home = fs.realpathSync(home); } catch {}
300
+ const home = real(os.homedir());
297
301
  if (root === path.parse(root).root || home === root || home.startsWith(root.endsWith(path.sep) ? root : root + path.sep)) {
298
302
  const msg = `${root} is your home folder or above it, and dibs won't send all of that to another machine. Run from the project's folder`;
299
303
  if (o.on && o.on !== rc.name) die(msg);
package/src/schedule.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  // Who goes next. Pure functions of the state, config, history and clock, so
2
2
  // they can be tested without processes.
3
3
  import { resCfg, machine, hardware, RECENT, SWAP_WINDOW } from './config.mjs';
4
- import { bytes, ms, dur, gb, now, runsOf, indexed } from './util.mjs';
4
+ import { bytes, ms, dur, gb, now, runsOf, indexed, unpolled } from './util.mjs';
5
5
  import { tag, isMine } from './proc.mjs';
6
6
  import { isFiles, overlap, short, clash, coversAgent, elsewhere } from './files.mjs';
7
7
  import { poolBlock } from './simpool.mjs';
@@ -210,10 +210,17 @@ export const sum = (xs, f) => xs.reduce((a, x) => a + f(x), 0);
210
210
  // never queue behind yourself. Two subagents of one session are different
211
211
  // agents when the guard told dibs which is which (src/files.mjs).
212
212
  const covers = (h, x) => (h.kind === 'hold' && !!x.spid && h.pid === x.spid && coversAgent(h, x)) || (!!x.outer && h.id === x.outer);
213
- export const holdsOf = (s, me) => new Set(s.leases.filter(l => covers(l, me)).flatMap(l => l.res));
213
+ // A hold or outer run is one slot, so it covers one run on each of its resources at a time; a
214
+ // second run alongside the first needs a slot of its own. On 2026-11-10 at 23:44 a session's hold
215
+ // on playwright covered four of its subagents' runs at once, each 5 to 7.5 GB, past slots: 2 and
216
+ // past the memory budget (a covered run is charged nothing): swap reached 13.7 GB and the Mac froze.
217
+ const inside = (s, h, r, not) => s.leases.filter(o => o !== h && o.id !== not && o.covered?.includes(r) && covers(h, o));
218
+ export const holdsOf = (s, me) => new Set(s.leases.filter(l => covers(l, me)).flatMap(l => l.res.filter(r => !inside(s, l, r, me.id).length)));
214
219
  // Slots of r in use. A run covered by its own hold or outer run doesn't count
215
- // twice, but only while that lasts: once it ends, the run is a user again.
216
- export const coveredNow = (s, l, r) => l.covered?.includes(r) && s.leases.some(h => h.res.includes(r) && covers(h, l));
220
+ // twice, but only while that lasts: once it ends, the run is a user again. Of several runs that
221
+ // say they're covered by one hold (a state written before the rule above), only the first is.
222
+ export const coveredNow = (s, l, r) => l.covered?.includes(r)
223
+ && s.leases.some(h => h !== l && h.res.includes(r) && covers(h, l) && !inside(s, h, r, l.id).some(o => o.id < l.id));
217
224
 
218
225
  // What a waiter already holds while it waits, or null: the dibs run it's
219
226
  // nested in, unless that runs at low or idle priority, and its session's holds
@@ -368,12 +375,36 @@ const usedNow = l => (l.kind === 'run' && l.use?.mem != null ? l.use.mem : plann
368
375
  export const memOf = (l, t = now()) => {
369
376
  const planned = plannedOf(l);
370
377
  if (l.kind !== 'run' || l.use?.mem == null) return planned;
378
+ // Stopped, it keeps every byte it had (they go to swap, not back to the machine), and it isn't
379
+ // measured while paused: never the idle discount, always the most it was seen using.
380
+ if (l.pausedAt) return Math.max(planned, l.peak?.mem || 0);
371
381
  if (steady(l, t)) return l.idleSince && t - l.idleSince >= IDLE_BOOK ? l.use.mem : l.use.mem + BUSY_MARGIN;
372
382
  if (t - l.start - pausedFor(l, t) < BOOK_AFTER) return planned;
373
383
  const peak = Math.max(l.peak?.mem || 0, l.use.mem);
374
384
  return Math.min(peak + BUSY_MARGIN, Math.max(planned, peak));
375
385
  };
376
386
 
387
+ // How far into a run this command reaches its peak, the latest of its last
388
+ // PEAK_RUNS measured runs, or null when one of them didn't say (recorded before
389
+ // 0.0.180) or none was measured.
390
+ const PEAK_RUNS = 5;
391
+ function peaksBy(hist, key) {
392
+ const runs = runsOf(hist || [], key).filter(h => h.mem > 0).slice(-PEAK_RUNS);
393
+ return runs.length && runs.every(h => h.peakIn != null) ? Math.max(...runs.map(h => h.peakIn)) : null;
394
+ }
395
+ // A measured run that has gone well past where its command's runs peak is done
396
+ // growing into its ask: it books what memOf says, not the ask. On 2026-11-03 an
397
+ // Xcode job booked at 11G, measured at 0.1 GB, held a 6G deploy on "the machine
398
+ // doesn't have the room" for as long as it ran. A command that peaks late (a
399
+ // link, an archive) keeps its ask until then, so its ramp has the room.
400
+ const PEAK_SLACK = 2 * MIN;
401
+ const pastPeak = (l, hist, t) => {
402
+ if (l.kind !== 'run' || l.use?.mem == null || !l.key || !hist) return false;
403
+ const p = peaksBy(hist, l.key);
404
+ return p != null && t - l.start - pausedFor(l, t) > p * 1.25 + PEAK_SLACK;
405
+ };
406
+ export const growTo = (hist, t = now()) => l => (pastPeak(l, hist, t) ? memOf(l, t) : plannedOf(l));
407
+
377
408
  // The lease a run sits inside, when its own hold or outer dibs run covers all
378
409
  // it asked for, or null.
379
410
  const coverOf = (s, l) => (l.covered && l.res.every(r => coveredNow(s, l, r)) ? s.leases.find(h => h !== l && covers(h, l)) || null : null);
@@ -397,7 +428,10 @@ export function memUsed(s, of = memOf) {
397
428
  // The leases taking the most memory, biggest first, for a memory wait to name.
398
429
  // asked: what it asked for (--mem or its resource's default); use: what its
399
430
  // last measurement found, or null before the first.
400
- export const memHolders = (s, n = 3) => s.leases.filter(l => memOf(l) > 0 && !coverOf(s, l)).sort((a, b) => memOf(b) - memOf(a)).slice(0, n)
431
+ // Ranked by what each one was measured using, where there's a measurement: on 2026-11-03 an
432
+ // 11 GB booking using 0.1 GB took the blame for a pressure wait it wasn't causing.
433
+ const blame = l => l.use?.mem ?? memOf(l);
434
+ export const memHolders = (s, n = 3) => s.leases.filter(l => memOf(l) > 0 && !coverOf(s, l)).sort((a, b) => blame(b) - blame(a)).slice(0, n)
401
435
  .map(l => ({ id: l.id, who: l.agent || l.who, label: l.label, purpose: l.purpose || '', mem: memOf(l), asked: l.asked ?? l.mem ?? 0, use: l.use?.mem ?? null, idleSince: l.idleSince || null }));
402
436
 
403
437
  // Memory the OS says is free right now, in bytes, or null.
@@ -478,7 +512,8 @@ export const cpuUsed = s => Math.round(sum(s.leases.filter(l => !lent(l) && !l.p
478
512
  const YOUNG = 3 * MIN, REAL_WAIT = 2 * MIN;
479
513
  export const swapTaken = m => (swapGrowing(m) ? m.swapGrowth : 0);
480
514
  // noSwap: swap growth doesn't count (the stall breaker let it by).
481
- function overBudget(s, q, cfg, strict = false, noSwap = false, t = now()) {
515
+ // hist: what the running jobs' own runs say about when they peak (growTo); without it, asks stand.
516
+ function overBudget(s, q, cfg, strict = false, noSwap = false, t = now(), hist = null) {
482
517
  // A job as big as the whole budget runs when nothing else is.
483
518
  if (!othersOf(s, q).length) return null;
484
519
  const m = machine();
@@ -493,7 +528,9 @@ function overBudget(s, q, cfg, strict = false, noSwap = false, t = now()) {
493
528
  // growing, the job plus a reserve free): it starts. Booking keeps a job's peak
494
529
  // for minutes after it falls; on 2026-10-20 twenty jobs waited "blocked by
495
530
  // memory" with 8.6 GB free and 1 of 10 cores busy.
496
- const fitsUse = () => memUsed(s, usedNow) + swap + q.mem <= budget && realRoom(q, cfg, m);
531
+ // A light job can't make the paging worse, so only critical pressure takes the room away from it (as for the swap gate).
532
+ const room = () => ((q.mem || 0) <= LIGHT_MEM && !(m.vmPressure >= 2)) || realRoom(q, cfg, m);
533
+ const fitsUse = () => memUsed(s, usedNow) + swap + q.mem <= budget && room();
497
534
  if (mem + q.mem > budget && !fitsUse())
498
535
  return { rule: 'memory', used: mem, of: budget, need: q.mem, ...(swap && { swap }),
499
536
  why: `memory budget: ${gb(mem)} of ${gb(budget)} handed out or in use${swap ? ` (${gb(swap)} of it swap that grew in the last 5 min)` : ''}, you need ${gb(q.mem)}` };
@@ -501,7 +538,8 @@ function overBudget(s, q, cfg, strict = false, noSwap = false, t = now()) {
501
538
  // what they asked for. One of them may still grow into its ask, so the room
502
539
  // must be real: memory pressure normal, swap still, and the job plus a
503
540
  // reserve free on the machine.
504
- if (memUsed(s, plannedOf) + swap + q.mem > budget && !realRoom(q, cfg, m))
541
+ // A running job past where its command's runs peak counts at what it books (growTo), not its ask.
542
+ if (memUsed(s, growTo(hist, t)) + swap + q.mem > budget && !room())
505
543
  return { rule: 'memory', used: mem, of: budget, need: q.mem, pressure: true, free: realFree(m), reserve: ROOM_RESERVE, high: m.vmPressure >= 1, growing: swapGrowing(m),
506
544
  why: `memory: running jobs ask for more than they use, but the machine doesn't have the room to show for it (${realFree(m) == null ? 'free memory unknown' : `${gb(realFree(m))} free`}${m.vmPressure >= 1 ? ', memory pressure high' : ''}${swapGrowing(m) ? ', swap growing' : ''}), you need ${gb(q.mem)} plus ${gb(ROOM_RESERVE)} to spare` };
507
545
  // Within the budget, the machine must still have it: what's really available
@@ -597,7 +635,7 @@ function soonestStart(s, q, cfg, hist, t = now()) {
597
635
  at = Math.max(at, Math.min(...s.leases.filter(l => l.res.includes(r) && !lent(l, r) && !onTop(l, r) && (across || !byRepo(cfg, r) || laneOf(l) === laneOf(q))).map(l => slotEnd(s, l, hist, t, r))));
598
636
  }
599
637
  }
600
- if (overBudget(s, q, cfg)) at = Math.max(at, budgetFrees(s, q, cfg, hist, t));
638
+ if (overBudget(s, q, cfg, false, false, t, hist)) at = Math.max(at, budgetFrees(s, q, cfg, hist, t));
601
639
  return at;
602
640
  }
603
641
  // Whether q's turn at the budget rests only on jobs whose run time dibs knows
@@ -730,6 +768,14 @@ const INSTANT = 15e3;
730
768
  // (2 GB for a test run) doesn't book it past the budget. Critical pressure and
731
769
  // the disk floor still do. On 2026-10-23 a 70 ms node --test of one file waited
732
770
  // minutes on "memory pressure high" behind a 4 GB Docker build.
771
+ // Light by its own runs: the last ten measured at LIGHT_MEM or less, at least LIGHT_RUNS of them,
772
+ // whatever it asked for. On 2026-11-03 a deploy that asked for 6 GB and used under 0.5 GB waited on
773
+ // memory pressure that an 11 GB Xcode booking using 0.1 GB was blamed for.
774
+ const LIGHT_RUNS = 3;
775
+ export function measuredLight(me, hist) {
776
+ const runs = runsOf(hist, me.key).slice(-10).filter(h => h.mem != null);
777
+ return runs.length >= LIGHT_RUNS && runs.every(h => h.mem <= LIGHT_MEM);
778
+ }
733
779
  export function featherweight(me, hist) {
734
780
  const d = typical(hist, me.key) ?? (me.declared ? null : me.est);
735
781
  if (d == null || d >= INSTANT) return false;
@@ -799,7 +845,9 @@ function ownDisk(hist, key) {
799
845
  // A --disk given in so many words is the job's own: on 2026-10-26 a streaming loader that writes one
800
846
  // 12 MB chunk was held for 23 GB it had "eaten" on a run whose swap grew while it sat paused.
801
847
  export function diskNeed(s, me, cfg, hist) {
802
- const floor = bytes(cfg.minDisk);
848
+ const floor = floorFor(me, cfg);
849
+ // A job that writes next to nothing keeps only ALONE_ROOM free, under the floor (tinyDisk).
850
+ if (tinyDisk(me, hist, cfg)) return { need: (me.diskDeclared ? me.disk || 0 : 0) + ALONE_ROOM, ate: null, others: othersOf(s, me).length > 0, tiny: true };
803
851
  // With others running, a resource that declares disk (simulators, builds, browsers, heavy) also
804
852
  // counts what its kind of job usually eats. Alone, or on a resource that declares none, the
805
853
  // job's own runs still count: starting a job that always eats more than there is only fails it.
@@ -815,7 +863,60 @@ export function diskNeed(s, me, cfg, hist) {
815
863
  return { need: Math.max(learned ?? me.disk ?? 0, floor, ate != null ? ate + (others ? floor : ALONE_ROOM) : 0), ate, others };
816
864
  }
817
865
  // A job alone still leaves this much free past what it eats: the system writes while it runs too.
818
- const ALONE_ROOM = 1024 ** 3;
866
+ export const ALONE_ROOM = 1024 ** 3;
867
+
868
+ // A job the person is waiting on (high, urgent, or a --by deadline with its reason) may take the headroom
869
+ // down to this, the same hard floor the watcher pauses jobs at (src/preempt.mjs DISK_FLOOR),
870
+ // and isn't held for the room kept for swap. On 2026-11-02 and 03 a Shop ship
871
+ // (#18328) waited about a day while idle sessions' swap kept free disk under 9 GB.
872
+ const HARD_FLOOR = 3 * 1024 ** 3;
873
+ // A --by deadline counts only with its reason (-m): a bare one costs nothing to type.
874
+ export const waitedOn = q => q.prio === 'high' || q.prio === 'urgent' || (q.by != null && !!q.purpose);
875
+ const floorFor = (q, cfg) => (waitedOn(q) ? Math.min(bytes(cfg.minDisk), HARD_FLOOR) : bytes(cfg.minDisk));
876
+
877
+ // A job that eats less than this of the disk starts under minDisk: holding it back
878
+ // frees nothing. On 2026-11-02 and 03 a post-deploy check that only makes HTTP calls,
879
+ // a test suite that writes nothing (--disk 200M) and a later job that uploads a 100 MB
880
+ // archive were all refused (exit 74) with 4.4 to 5 GB free, and a prod build went out unchecked.
881
+ export const TINY_DISK = 100 * 1024 ** 2;
882
+ // Whether a job is that small. Its own runs say first: at least TINY_RUNS good ones, the
883
+ // middle of the last ten (the most of them until there are DISK_RUNS) under TINY_DISK, and
884
+ // the last run, failed or not, under it too: one that ate more takes the exemption away
885
+ // until it's back down. A failed run alone, stopped early, says nothing about what a whole
886
+ // one eats. With too few runs, only a small --disk does (diskNeed takes it at its word).
887
+ export function tinyDisk(me, hist, cfg) {
888
+ // A --disk of minDisk or more says it isn't small, whatever its resource.
889
+ if (me.diskDeclared && (me.disk || 0) >= bytes(cfg.minDisk)) return false;
890
+ // A run the watcher cleared caches under reads low: the clean's room hid what it wrote (src/diskwarn.mjs clean).
891
+ const runs = runsOf(hist || [], me.key).filter(h => h.ate != null && !h.cleaned).slice(-10);
892
+ if (runs.length && runs.at(-1).ate >= TINY_DISK) return false;
893
+ const good = runs.filter(h => !h.failed).map(h => h.ate);
894
+ if (good.length >= TINY_RUNS) return (good.length < DISK_RUNS ? Math.max(...good) : mid(good)) < TINY_DISK;
895
+ // Too few runs to go by: only its own word makes it small. A first npm ci or a bundling deploy
896
+ // writes gigabytes, so a resource's kind alone never does. Up to CLAIM_MAX on a resource that
897
+ // declares no disk (tests, deploys, locks), or under TINY_DISK anywhere.
898
+ if (!me.diskDeclared) return false;
899
+ const claim = me.disk || 0;
900
+ return claim < TINY_DISK || (claim <= CLAIM_MAX && me.res.every(r => isFiles(r) || !resCfg(cfg, r).disk));
901
+ }
902
+ // Why a job held at the floor is held there, and, when its --disk is smaller, why that didn't
903
+ // lower it: agents read --disk 1G as the floor's size, and a deploy hit exit 74 twice at 2.6 GB
904
+ // free on 2026-11-10 with --disk 1G.
905
+ const GBs = b => gb(b).replace(/G$/, ' GB');
906
+ export function floorWhy(me, cfg) {
907
+ const floor = floorFor(me, cfg);
908
+ const base = `the ${GBs(floor)} dibs keeps free${waitedOn(me) && floor < bytes(cfg.minDisk) ? ' for a job a person waits on' : ''}`;
909
+ if (!me.diskDeclared || (me.disk || 0) >= floor) return base;
910
+ const little = me.res.every(r => isFiles(r) || !resCfg(cfg, r).disk);
911
+ return `${base}; --disk ${GBs(me.disk || 0)} doesn't lower that: only a --disk ${little ? 'of 1 GB or less' : 'under 100 MB'}`
912
+ + ` starts a job below it, or two runs of the same command that each wrote under 100 MB`;
913
+ }
914
+ // Runs it takes to be small by history alone: one could be a run that happened to write little.
915
+ const TINY_RUNS = 2;
916
+ // The most a --disk alone can claim on a resource that declares no disk, itself included: agents
917
+ // write --disk 1G, and a deploy that said so waited out 2.6 GB free twice on 2026-11-10. On
918
+ // 2026-11-03 a test suite that writes nothing said --disk 200M and was refused at 4.4 GB free.
919
+ const CLAIM_MAX = 1024 ** 3;
819
920
 
820
921
  // The verdict, and for a job held by something else (its turn, memory, cores) a
821
922
  // word that free disk will hold it next, while there's still time to free some.
@@ -835,7 +936,7 @@ function decide(s, me, cfg, hist, t) {
835
936
  const quick = !!(me.quickPass ?? quickPass(me, hist, cfg)) && s.leases.filter(l => l.quick).length < QUICK_MAX;
836
937
  // A quick job dibs hasn't seen use much memory is booked small, as a featherweight is.
837
938
  const lightQuick = quick && !me.declared && runsOf(hist, me.key).slice(-10).every(h => h.mem == null || h.mem <= LIGHT_MEM);
838
- if ((me.mem || 0) > LIGHT_MEM && (featherweight(me, hist) || lightQuick)) me = { ...me, mem: LIGHT_MEM, feather: true };
939
+ if ((me.mem || 0) > LIGHT_MEM && (featherweight(me, hist) || lightQuick || measuredLight(me, hist))) me = { ...me, mem: LIGHT_MEM, feather: true };
839
940
  const myRank = rank(me, hist, t);
840
941
  // When it would be done, at its slow runs: passing a waiter is a promise not to delay it.
841
942
  const myEnd = t + Math.max(expected(me, hist), slow(hist, me.key) || 0);
@@ -851,8 +952,11 @@ function decide(s, me, cfg, hist, t) {
851
952
  const lightTurn = (me.mem || 0) <= LIGHT_MEM && me.res.every(r => cfg.resources[r]?.exclusive);
852
953
  const pastCeiling = pastsCeiling(me) || quick || lightTurn;
853
954
  // Over the ceiling, a waiter that passes it doesn't wait behind ones the ceiling holds back.
955
+ // Nor behind a place nobody is deciding for (its dibs stopped looking), or one the owner stopped:
956
+ // neither can start, so neither holds anyone back. Just after the machine wakes (graceUntil,
957
+ // src/state.mjs) every place is old, so none is taken for one nobody decides for.
854
958
  const ahead = s.queue
855
- .filter(q => q.pid && q.id !== me.id && !(hot && pastCeiling && !pastsCeiling(q)))
959
+ .filter(q => q.pid && q.id !== me.id && !q.ownerStop && !(unpolled(q, t) && !(s.graceUntil > t)) && !(hot && pastCeiling && !pastsCeiling(q)))
856
960
  .filter(q => { const r = rank(q, hist, t); return r < myRank || (r === myRank && q.id < me.id); })
857
961
  .filter(q => reservesFor(s, q, me, cfg))
858
962
  .sort(byRank(hist, t));
@@ -862,12 +966,12 @@ function decide(s, me, cfg, hist, t) {
862
966
  // whole heavy line. It keeps its place, and once the disk has room for it,
863
967
  // it's ahead of everyone again. A job that would eat into that room waits.
864
968
  const floor = bytes(cfg.minDisk);
865
- const diskStuck = q => m.diskFree != null && m.diskFree < Math.max(q.disk || 0, floor);
969
+ const diskStuck = q => m.diskFree != null && m.diskFree < (tinyDisk(q, hist, cfg) ? (q.diskDeclared ? q.disk || 0 : 0) + ALONE_ROOM : Math.max(q.disk || 0, floor));
866
970
  const leavesRoom = m.diskFree != null && m.diskFree - floor >= (me.disk || 0);
867
971
  const blocks = q => {
868
972
  if (leavesRoom && diskStuck(q)) return false;
869
973
  // A waiter held for memory blocks a job of known length only when its own start is known, and comes first.
870
- if (known(me, hist) && overBudget(s, q, cfg) && !budgetSure(s, q, cfg, hist, t)) return false;
974
+ if (known(me, hist) && overBudget(s, q, cfg, false, false, t, hist) && !budgetSure(s, q, cfg, hist, t)) return false;
871
975
  const at = soonestStart(s, q, cfg, hist, t);
872
976
  if (q.mem >= BIG_SHARE * bytes(cfg.budget) && at - t > RESERVE_SOON) return false;
873
977
  return at < myEnd;
@@ -911,14 +1015,17 @@ function decide(s, me, cfg, hist, t) {
911
1015
  // checking the disk again refused (exit 74) a run right after "you already have the
912
1016
  // simulator, so you go ahead" (2026-11-03). The watcher's low-disk pauses still hold it.
913
1017
  if (me.res.every(r => mine.has(r))) return { ok: true, covered: [...me.res] };
914
- // Below minDisk nothing else starts, urgent work included:
915
- // a full disk breaks every job on the machine, and on macOS swap needs it too.
1018
+ // Below minDisk nothing else starts, urgent work included, but a job that writes next to
1019
+ // nothing (tinyDisk): a full disk breaks every job on the machine, and on macOS swap needs it too.
916
1020
  const others = othersOf(s, me);
917
1021
  // The floor plus what it usually eats (diskNeed).
918
- const { need: needDisk, ate, others: crowded } = diskNeed(s, me, cfg, hist);
1022
+ const { need: needDisk, ate, others: crowded, tiny } = diskNeed(s, me, cfg, hist);
919
1023
  // An unreadable disk (null) doesn't stop work; the board and dibs run say it's unknown.
920
- if (m.diskFree != null && m.diskFree < needDisk)
921
- return { ok: false, rule: 'disk', why: `disk: ${gb(m.diskFree)} free, you need ${gb(needDisk)}${ate != null && ate + (crowded ? bytes(cfg.minDisk) : ALONE_ROOM) >= needDisk ? ` (${crowded ? `the ${gb(bytes(cfg.minDisk))} dibs keeps free` : `${gb(ALONE_ROOM)} to spare`}, plus the ${gb(ate)} this usually takes; --disk <size> says this run needs less)` : ''}`, disk: true, free: m.diskFree, need: needDisk, alone: !others.length, ...(ate != null && { usual: ate }) };
1024
+ if (m.diskFree != null && m.diskFree < needDisk) {
1025
+ const floored = !tiny && needDisk === floorFor(me, cfg) && floorWhy(me, cfg);
1026
+ if (floored) return { ok: false, rule: 'disk', why: `disk: ${gb(m.diskFree)} free, you need ${gb(needDisk)} (${floored})`, disk: true, free: m.diskFree, need: needDisk, floorWhy: floored };
1027
+ return { ok: false, rule: 'disk', why: `disk: ${gb(m.diskFree)} free, you need ${gb(needDisk)}${tiny ? (me.diskDeclared ? ` (the ${gb(me.disk || 0)} its --disk says, and ${gb(ALONE_ROOM)} kept free)` : ` (a job that writes next to nothing still leaves ${gb(ALONE_ROOM)} free)`) : ate != null && ate + (crowded ? floorFor(me, cfg) : ALONE_ROOM) >= needDisk ? ` (${crowded ? `the ${gb(floorFor(me, cfg))} dibs keeps free` : `${gb(ALONE_ROOM)} to spare`}, plus the ${gb(ate)} this usually takes; --disk <size> says this run needs less)` : ''}`, disk: true, free: m.diskFree, need: needDisk, ...(ate != null && { usual: ate }) };
1028
+ }
922
1029
  // While the machine swaps, only urgent work starts on top of what's running.
923
1030
  // With nothing else working, one job may start: waiting can't make the swap
924
1031
  // go down then, and swap the OS hasn't reclaimed yet mustn't stop dibs for good.
@@ -932,35 +1039,41 @@ function decide(s, me, cfg, hist, t) {
932
1039
  if (sw && sw.level !== 'critical' && !light && sw.rule === 'pressure' && probation(s, me, cfg, hist, t)) trial = true;
933
1040
  if (sw && (light || trial || quick) && sw.level !== 'critical') sw = null;
934
1041
  // The same for the disk swap grows on: one job may still start alone, since waiting frees nothing then.
1042
+ // Swap grows with memory, not with what a job writes, so a job let under the floor (tinyDisk) keeps the room past the floor.
935
1043
  // A light job can't grow the swap, so on a resource that writes little (exclusive, or declaring
936
1044
  // no disk: tests, deploys) only the floor holds it. On 2026-10-26 every start waited on the room
937
1045
  // kept for swap with 6.8 GB free, one-second test runs included.
938
1046
  const writesLittle = me.res.every(r => cfg.resources[r]?.exclusive || !resCfg(cfg, r).disk);
939
- const squeeze = (me.prio || 'normal') !== 'urgent' && busy && !sw && !quick && !(light && writesLittle) && diskSqueeze(cfg, needDisk, m);
1047
+ const squeeze = !waitedOn(me) && busy && !sw && !quick && !(light && writesLittle) && diskSqueeze(cfg, tiny ? Math.max(needDisk, bytes(cfg.minDisk)) : needDisk, m);
940
1048
  let breaker = (sw || squeeze) && breaksStall(s, me, cfg, hist, t, m);
941
1049
  if (sw && !breaker) return { ok: false, why: swapWhy(sw), ...sw, machine: true };
942
1050
  if (squeeze && !breaker) return { ok: false, ...squeeze, machine: true };
943
1051
  // A light job may pass one stuck on the budget, but not once that one has
944
1052
  // waited long, unless it'll be done before that one could start. Waiters
945
1053
  // stuck on something else (machine memory, disk) don't hold anyone up.
946
- const head = ahead.find(q => q.res.every(r => roomFor(s, q, r, cfg).open > 0) && !neverFits(cfg, q) && overBudget(s, q, cfg));
1054
+ const head = ahead.find(q => q.res.every(r => roomFor(s, q, r, cfg).open > 0) && !neverFits(cfg, q) && overBudget(s, q, cfg, false, false, t, hist));
947
1055
  if (!quick && head && t - head.enq > ms(cfg.starveAfter) && blocks(head))
948
1056
  return { ok: false, rule: 'ahead', why: `${tag(head)} has waited ${dur(t - head.enq)}, so it goes first`, ahead: head, starved: true };
949
- let budget = overBudget(s, me, cfg, side.length > 0, breaker, t);
1057
+ let budget = overBudget(s, me, cfg, side.length > 0, breaker, t, hist);
950
1058
  // Nothing starts past the memory budget (0.0.125). Jobs book what they're
951
1059
  // measured using once they've run a few minutes (memOf), so the gap between
952
1060
  // asks and use goes to waiters that way, with the machine's pressure as the guard.
953
1061
  // Held only by swap growth, the budget is a machine gate like swap itself: the stall breaker may pass it.
954
- const swapOnly = budget?.swap && !overBudget(s, me, cfg, side.length > 0, true);
1062
+ const swapOnly = budget?.swap && !overBudget(s, me, cfg, side.length > 0, true, t, hist);
955
1063
  if (swapOnly && breaksStall(s, me, cfg, hist, t, m)) { budget = null; breaker = true; }
1064
+ // A quick job booked as a featherweight is done before the budget it would pass means
1065
+ // anything; the machine's own pressure still holds it at critical. On 2026-11-03 a
1066
+ // test whose last run took 14.9 s at 95 MB waited 29 minutes on the budget, then ran in 0.8 s (#18336).
1067
+ if (budget && quick && me.feather) budget = null;
956
1068
  if (budget) return { ok: false, ...budget, ...(swapOnly && { machine: true }) };
957
1069
  if (me.mem >= BIG_JOB && m.memFree < cfg.minFreeMem && s.leases.some(working) && !breaker)
958
1070
  return { ok: false, rule: 'ram', why: `machine memory: ${m.memFree}% free, big jobs need ${cfg.minFreeMem}%` };
959
1071
  // Stopped last time for using far more than it booked (src/preempt.mjs diskRequeue):
960
1072
  // it starts again only once what it's now booked at is really free and swap
961
1073
  // has stopped growing, or it would land in the same crunch.
962
- if (me.requeued === 'over' && ((realFree(m) ?? 0) < me.mem || swapGrowing(m)))
963
- return { ok: false, rule: 'oversize', machine: true, why: `${gb(me.mem)} of memory to be really free and swap to hold still, since it used far more than it booked last time`
1074
+ // Stopped under memory pressure that pausing couldn't ease (pressureRequeue): the same.
1075
+ if ((me.requeued === 'over' || me.requeued === 'memory') && ((realFree(m) ?? 0) < me.mem || swapGrowing(m)))
1076
+ return { ok: false, rule: 'oversize', machine: true, why: `${gb(me.mem)} of memory to be really free and swap to hold still, since ${me.requeued === 'over' ? 'it used far more than it booked last time' : 'memory pressure stopped it last time'}`
964
1077
  + ` (now ${gb(realFree(m) ?? 0)} free${swapGrowing(m) ? ', swap growing' : ''})` };
965
1078
  const pool = poolBlock(s, me, cfg, mine, m);
966
1079
  if (pool) return { ok: false, ...pool };