@dibssoftware/dibs 0.0.0-stage → 0.0.179

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 (75) hide show
  1. package/CHANGELOG.md +594 -0
  2. package/LICENSE +670 -0
  3. package/README.md +85 -2
  4. package/bin/dibs-guard.mjs +7 -0
  5. package/bin/dibs.mjs +548 -0
  6. package/docs/benchmarks.md +193 -0
  7. package/docs/files.md +30 -0
  8. package/docs/guard.md +91 -0
  9. package/docs/later.md +43 -0
  10. package/docs/machines.md +147 -0
  11. package/docs/questions.md +78 -0
  12. package/docs/reference.md +157 -0
  13. package/docs/relay.md +196 -0
  14. package/docs/releasing.md +27 -0
  15. package/docs/scheduling.md +163 -0
  16. package/docs/simulators.md +17 -0
  17. package/package.json +45 -4
  18. package/skills/dibs/SKILL.md +183 -0
  19. package/src/acquire.mjs +700 -0
  20. package/src/admin.mjs +145 -0
  21. package/src/agents.mjs +145 -0
  22. package/src/alerts.mjs +499 -0
  23. package/src/answers.mjs +65 -0
  24. package/src/board.mjs +202 -0
  25. package/src/broker.mjs +369 -0
  26. package/src/commands.mjs +810 -0
  27. package/src/config.mjs +324 -0
  28. package/src/connect.mjs +106 -0
  29. package/src/cool.mjs +160 -0
  30. package/src/diskwarn.mjs +154 -0
  31. package/src/events.mjs +96 -0
  32. package/src/files.mjs +1123 -0
  33. package/src/guard.mjs +613 -0
  34. package/src/history.mjs +247 -0
  35. package/src/hogs.mjs +227 -0
  36. package/src/later.mjs +487 -0
  37. package/src/measure.mjs +262 -0
  38. package/src/news.mjs +101 -0
  39. package/src/nodecheck.mjs +17 -0
  40. package/src/notes.mjs +171 -0
  41. package/src/notices.mjs +160 -0
  42. package/src/ondemand.mjs +572 -0
  43. package/src/overlap.mjs +151 -0
  44. package/src/override.mjs +360 -0
  45. package/src/owner.mjs +30 -0
  46. package/src/plain.mjs +470 -0
  47. package/src/platform.mjs +357 -0
  48. package/src/preempt.mjs +438 -0
  49. package/src/primer.mjs +89 -0
  50. package/src/proc.mjs +99 -0
  51. package/src/progress.mjs +187 -0
  52. package/src/qr.mjs +204 -0
  53. package/src/questions.mjs +389 -0
  54. package/src/quota.mjs +81 -0
  55. package/src/reads.mjs +54 -0
  56. package/src/relay.mjs +779 -0
  57. package/src/remote.mjs +584 -0
  58. package/src/reset.mjs +127 -0
  59. package/src/schedule.mjs +1020 -0
  60. package/src/scratch.mjs +61 -0
  61. package/src/serve.mjs +742 -0
  62. package/src/service.mjs +221 -0
  63. package/src/shard.mjs +59 -0
  64. package/src/simctl.mjs +42 -0
  65. package/src/simpool.mjs +258 -0
  66. package/src/state.mjs +201 -0
  67. package/src/stats.mjs +328 -0
  68. package/src/style.mjs +44 -0
  69. package/src/talk.mjs +702 -0
  70. package/src/thin.sh +130 -0
  71. package/src/trust.mjs +152 -0
  72. package/src/util.mjs +184 -0
  73. package/src/version.mjs +2 -0
  74. package/src/web.mjs +1119 -0
  75. package/src/worker.mjs +318 -0
@@ -0,0 +1,810 @@
1
+ // One function per subcommand.
2
+ import fs from 'node:fs';
3
+ import net from 'node:net';
4
+ import path from 'node:path';
5
+ import { spawn } from 'node:child_process';
6
+ import { resCfg, machine, HOME, paths, PACES, PACE_OVERLAP, paced, paceKnobs, hardware, writePace, loadConfig } from './config.mjs';
7
+ import { logChange } from './owner.mjs';
8
+ import { identity, isMine, tag } from './proc.mjs';
9
+ import { launch, stopTree, processes, descendants, which, starts, scoped, watchdog, OS } from './platform.mjs';
10
+ import { withState, withStateIfRoom, history, record, KEEP_PLACE } from './state.mjs';
11
+ import { acquire, markIdle, idleFor, describeLease, commandKey, holdUntil, outerLease, defaultMaxWait, HOLD_CAP } from './acquire.mjs';
12
+ import { rank, rankParts, byRank, forecast, verdict, remaining, used, sum, lent, pausedFor, overLoad, loadWhy, loadAhead, holdingOf, swapping, swapWhy, diskSqueeze, BACKGROUND, roomFor } from './schedule.mjs';
13
+ import { noticeHandler } from './preempt.mjs';
14
+ import { checkout, checkin, jobSize } from './simpool.mjs';
15
+ import { bytes, dur, gb, clock, die, say, now, ms, sleep, SIGNALS, signalExit, noSpace, inClaudeCode, OFF_LIMITS } from './util.mjs';
16
+ import { boardOf, boardLines, handedOut, elsewhere, elsewhereLines, elsewherePlain, waitReason, limitsLine } from './board.mjs';
17
+ import { plainBoard, lineParts, headline, startPhrase, whyLines, askFirst, named, andList, minutes, lower, usingText, nextText, ends, freeText, machineHold } from './plain.mjs';
18
+ import { bold, dim, amber, columns, wrap, quoted } from './style.mjs';
19
+ import { quotasNow, isQuota } from './quota.mjs';
20
+ import { agentsNow } from './agents.mjs';
21
+ import { forYou } from './questions.mjs';
22
+ import { notesForYou, listeners } from './talk.mjs';
23
+ import { remoteConf, shortHost } from './remote.mjs';
24
+ import { sample, sized, grewLine, grewPlain, tellOverAsk } from './measure.mjs';
25
+ import { clash, isFiles, short, takeAgent, callKey, sameAgent, fileKey, shellRes, projectKey } from './files.mjs';
26
+ import { sideBySide } from './overlap.mjs';
27
+ import { laterBoard, laterLines, laterPlain } from './later.mjs';
28
+ import { noticeScan, NOTICE_EVERY, twinOf } from './notices.mjs';
29
+ import { answer, ISSUES } from './answers.mjs';
30
+ import { event } from './events.mjs';
31
+ import { scan as scanAlerts, alertLines, onBoard } from './alerts.mjs';
32
+
33
+ const REQUESTS = path.join(HOME, 'requests.jsonl');
34
+ // Exit codes dibs gives its own meaning (AGENTS.md).
35
+ const DIBS_CODES = new Set([1, 2, 3, 70, 74, 75, 76, 77, 127]);
36
+ const json = x => console.log(JSON.stringify(x, null, 1));
37
+
38
+ export function freePort() {
39
+ return new Promise((res, rej) => {
40
+ const srv = net.createServer();
41
+ srv.unref();
42
+ srv.on('error', rej);
43
+ srv.listen(0, '127.0.0.1', () => { const p = srv.address().port; srv.close(() => res(p)); });
44
+ });
45
+ }
46
+
47
+ // --notify <file>: one JSON line when dibs exits, however it exits, so an agent
48
+ // can wait on a file instead of polling the board. A kill -9 writes nothing.
49
+ // started is true once the command was launched here, false if it never was,
50
+ // and null for a job sent to another machine, where this process can't tell.
51
+ let started = null;
52
+ export function notifyOnExit(o) {
53
+ if (!o.notify) return;
54
+ const file = path.resolve(o.notify);
55
+ try { fs.accessSync(path.dirname(file), fs.constants.W_OK); } catch { die(`--notify ${o.notify}: can't write in ${path.dirname(file)}`); }
56
+ const t0 = now();
57
+ process.on('exit', code => {
58
+ // Handed to the broker or to its own run: whoever ends the wait writes the line (src/broker.mjs).
59
+ if (o.thin?.handed || handedOn) return;
60
+ const line = { at: new Date().toISOString(), code, started, res: o.res, cmd: (o.cmd || []).join(' '), cwd: process.cwd(), secs: Math.round((now() - t0) / 1000), pid: o.thin?.shell ?? process.pid };
61
+ try { fs.appendFileSync(file, JSON.stringify(line) + '\n'); } catch (e) { say(`couldn't write to --notify ${o.notify}: ${e.message}`); }
62
+ });
63
+ }
64
+
65
+ // Which agent of this session is calling, when the guard hook saw it ask
66
+ // (src/files.mjs). Its type labels it on the board unless --as says.
67
+ function stamp(o, verb) {
68
+ const a = takeAgent(verb, o.res, callKey(verb));
69
+ if (!a) return;
70
+ o.agentId = a.agentId;
71
+ if (a.agentType) o.as ??= a.agentType;
72
+ }
73
+
74
+ // The caller, with the subagent stamp() found. ours(): a lease or wait that
75
+ // is this agent's own, not a sibling subagent's; unstamped ones (no guard
76
+ // hook) belong to the whole session, as before.
77
+ const caller = o => ({ ...identity(o), agentId: o.agentId });
78
+ const ours = (x, me) => isMine(x, me) && sameAgent(x, me);
79
+
80
+ // dibs run <res> -- <cmd>: wait, run, release when it exits.
81
+ export async function run(o, cfg) {
82
+ started = false;
83
+ // --lease: a thin waiter's turn (src/thin.sh). The checks before the line were made when it got in line.
84
+ if (!o.lease) stamp(o, 'run');
85
+ // A retried tool call is Claude Code's problem; scheduled and remote jobs aren't tool calls. A full disk skips the check.
86
+ const twin = !o.lease && inClaudeCode() && !process.env.DIBS_LATER_JOB && !process.env.DIBS_REMOTE_JOB && twinOf(withStateIfRoom(s => s) || {}, o, identity(o));
87
+ if (twin) {
88
+ const id = identity(o);
89
+ event({ kind: 'twin', id: twin.id, res: o.res, who: id.who, agent: id.agent, agentId: o.agentId, label: id.label, cmd: o.cmd.join(' ') });
90
+ die(twin.text, 2);
91
+ }
92
+ if (!o.cmd || !o.cmd.length) die('nothing to run: put the command after --, like dibs run sim -- ./ui-test.sh');
93
+ if (!o.res.length) die('which resource? Name it before the --, like dibs run sim -- <command>. The list: dibs help all');
94
+ if (!which(o.cmd[0])) {
95
+ // dibs run test -- "npm test && npm run lint": the whole line arrived as one program name.
96
+ const line = o.cmd.length === 1 && /[\s;&|<>$]/.test(o.cmd[0]);
97
+ die(`couldn't start ${o.cmd[0]}: it isn't on your PATH. Nothing ran (exit 127).`
98
+ + `${line ? ` To run a shell line, use: dibs run ${shellRes(o.res.map(r => short(r)))} -- sh -c ${quoted(o.cmd)}` : ''}`, 127);
99
+ }
100
+ // Inside a dibs run that already has these resources (a script that wraps
101
+ // its own steps in dibs), go straight ahead instead of queueing behind yourself.
102
+ // Needing more than it has, it waits only for the rest, ahead of waiters that hold nothing.
103
+ // A quota is never "had": each call pays its tokens, or a script looping
104
+ // over an API inside one run would make every call for free.
105
+ const outer = o.lease ? null : outerLease();
106
+ if (outer && o.res.every(r => !isQuota(r) && outer.res.includes(r))) return o.thin && !o.thin.inline ? o.thin.fat() : runNested(o);
107
+ if (o.after) await after(o);
108
+ const lease = await acquire({ ...o, outer }, 'run', cfg);
109
+ const env = { ...process.env, DIBS_LEASE: String(lease.id) };
110
+ const sim = await simFor(lease, cfg);
111
+ if (sim) { Object.assign(env, { SIM: sim.udid, SIM_NAME: sim.name }); say(`SIM=${sim.udid} SIM_NAME=${sim.name}`); }
112
+ await addPorts(env, o.ports);
113
+ const child = launch(cfg.enforce ? scoped(o.cmd, lease) : o.cmd, { env, background: BACKGROUND.has(lease.prio) || !!lease.loadPast, gate: true });
114
+ // Children that split off into their own process group still belong to the
115
+ // lease: note them as they appear, so they're stopped with it.
116
+ const groups = new Set();
117
+ // Each group's leader's start time, so whoever reaps the lease can tell the
118
+ // group from a later one that reused its number (src/state.mjs killLease).
119
+ const groupStarts = {};
120
+ let recorded = ''; // the groups the state has, so a change a full disk kept out is tried again next tick
121
+ // If dibs is killed outright, this kills the job instead of leaving it to the next dibs call.
122
+ const wd = watchdog();
123
+ // A group that has emptied is forgotten at once, before its number can be reused.
124
+ const track = () => {
125
+ if (!child.pid || OS === 'windows') return;
126
+ const found = [...descendants(child.pid)].filter(g => g !== child.pid && !groups.has(g));
127
+ const st = found.length ? starts(found) : null;
128
+ for (const g of found) { groups.add(g); wd.add(g); if (st?.get(g)) groupStarts[g] = st.get(g); }
129
+ const live = new Set(processes().map(p => p.pgid));
130
+ for (const g of groups) if (!live.has(g)) { groups.delete(g); delete groupStarts[g]; wd.drop(g); }
131
+ const cur = [...groups].join();
132
+ if (cur !== recorded && withStateIfRoom(s => { const l = s.leases.find(x => x.id === lease.id); if (l) Object.assign(l, { groups: [...groups], groupStarts: { ...groupStarts } }); return true; })) recorded = cur;
133
+ };
134
+ const stopAll = sig => { stopTree(child.pid, sig); if (OS !== 'windows') for (const g of groups) stopTree(g, sig); };
135
+ let finished = false, tracker = null, ran = null;
136
+ let took = null; // how long a run the quick lane let in really took
137
+ const finish = code => {
138
+ if (finished) return;
139
+ finished = true;
140
+ clearInterval(tracker);
141
+ stopAll('SIGKILL');
142
+ wd.done();
143
+ if (sim) try { checkin(lease); } catch (e) { say(`couldn't put the simulator back in the pool (${e.message}). The next dibs command does it.`); }
144
+ let again = null;
145
+ try {
146
+ withState(s => {
147
+ const l = s.leases.find(x => x.id === lease.id);
148
+ if (l?.requeue) { again = requeue(s, l, cfg); return; }
149
+ // Groups stopped by a pause that this process never tracked would stay stopped forever.
150
+ if (OS !== 'windows') for (const g of l?.stopped || []) stopTree(g, 'SIGKILL');
151
+ if (l) l.code = code; // for the end event in the history (src/events.mjs)
152
+ if (l?.ownerStop) say(`stopped by ${l.stopBy || 'the owner (the person at this machine)'} on purpose (dibs stop)${l.stopReason ? `: "${l.stopReason}"` : ''}. This job was ended and its processes killed.`
153
+ + `${l.stopReason ? '' : ' Find out why before running it again: dibs history, or ask whoever stopped it.'}`);
154
+ s.leases = s.leases.filter(x => x.id !== lease.id);
155
+ // A failing run is often the one that ran out of memory: its size counts too.
156
+ if (l && (code === 0 || l.peak?.mem)) record(l.key, now() - l.start - pausedFor(l), l.who, l.peak, code !== 0);
157
+ if (l?.quick) took = now() - l.start - pausedFor(l);
158
+ tellOverAsk(l);
159
+ });
160
+ } catch (e) {
161
+ // The job is already stopped. Its lease names this process, so the next
162
+ // dibs call to read the state sees it gone, drops the lease and kills anything left.
163
+ // Either way the command's own code comes back, not dibs's trouble.
164
+ if (noSpace(e)) say(`the disk is full, so dibs couldn't record that this job ended. The next dibs command cleans it up. Free some disk space. ${OFF_LIMITS}`);
165
+ else say(`dibs hit a bug recording that this job ended (${e.message}). Your command's exit code comes back anyway, and the next dibs command cleans up. Report it: dibs ask "..."`);
166
+ }
167
+ if (again) return runAgain(o, lease, again);
168
+ // Over the quick lane's limit: its next runs wait their turn until one comes in under (src/schedule.mjs quickPass).
169
+ const under = cfg.quickUnder == null ? null : ms(cfg.quickUnder);
170
+ if (took != null && under != null && took >= under) say(`this took ${dur(took)}, over the ${dur(under)} the quick lane is for, so its next runs wait their turn until one finishes in under ${dur(under)}.`);
171
+ // A failing command's code can look like one of dibs's own (75, 74, 127), so say whose it is.
172
+ if (code && code < 128) say(`${path.basename(o.cmd[0])} exited with code ${code}${DIBS_CODES.has(code) ? ". That's your command's code, not dibs's" : ''}.`);
173
+ // One line that says it all, for an agent that has lost the output above (a compacted context).
174
+ say(`#${lease.id} ${lease.res.map(r => short(r)).join(',')}, waited ${dur(lease.waited || 0)}, ${ran == null ? 'never started' : `ran ${dur(now() - ran)}`}, exit ${code}`);
175
+ process.exit(code);
176
+ };
177
+ // Signals are handled from here on, before the slow steps below, so one that
178
+ // arrives early still reaches the job instead of killing dibs alone.
179
+ for (const sig of SIGNALS) process.on(sig, () => {
180
+ stopAll(sig); // signal first; finding split-off groups takes a process-table read
181
+ if (OS !== 'windows') stopAll('SIGCONT'); // a paused job can't act on the signal until it runs
182
+ track();
183
+ stopAll(sig);
184
+ setTimeout(() => finish(signalExit(sig)), 3000).unref();
185
+ });
186
+ // Low and idle work can be paused for urgent work (src/preempt.mjs); say so when it happens.
187
+ // Notices about this job and others go to their agents while it runs (src/notices.mjs).
188
+ setInterval(noticeScan, NOTICE_EVERY).unref();
189
+ const notify = OS !== 'windows';
190
+ if (notify) process.on('SIGUSR2', noticeHandler(() => withStateIfRoom(s => s.leases.find(x => x.id === lease.id))));
191
+ // The command starts only once its group is on record, so a wrapper killed
192
+ // at any point has its job reaped with it, or the job never starts.
193
+ // The gate shell execs the command, so its start time is the command's.
194
+ const note = facts => s => { const l = s.leases.find(x => x.id === lease.id); if (l) Object.assign(l, facts); };
195
+ const pgstart = child.pid ? starts([child.pid])?.get(child.pid) ?? null : null;
196
+ // requeuable: this dibs run can put its job back in line if the watcher stops it (src/preempt.mjs diskRequeue).
197
+ try { withState(note({ pgid: child.pid, pgstart, notify, background: BACKGROUND.has(lease.prio) || !!lease.loadPast, requeuable: true })); } catch (e) {
198
+ if (!noSpace(e)) throw e;
199
+ // Unrecorded, the job couldn't be reaped if dibs died: it doesn't start. The lease goes with this process.
200
+ stopTree(child.pid, 'SIGKILL');
201
+ wd.done();
202
+ die(`the disk is full, so dibs couldn't record your job before starting it. Your command did NOT run (exit 74). Free some disk space, then run it again. ${OFF_LIMITS}`, 74);
203
+ }
204
+ child.go();
205
+ started = true;
206
+ ran = now();
207
+ if (child.pid) wd.add(child.pid);
208
+ if (child.pid && !pgstart) withStateIfRoom(note({ pgstart: starts([child.pid])?.get(child.pid) ?? null }));
209
+ // Each tick also measures every lease on the machine, when it's this run's turn (src/measure.mjs).
210
+ tracker = setInterval(() => { track(); sample(); }, 3000);
211
+ tracker.unref();
212
+ child.on('error', e => { say(`couldn't start ${o.cmd[0]}: ${e.message}`); finish(127); });
213
+ // No last track(): once the child has exited, its process groups are found by the
214
+ // reaping below (finish), and walking the process table here cost 30 ms of every return.
215
+ child.on('exit', (code, sig) => finish(code ?? signalExit(sig)));
216
+ }
217
+
218
+ // A run the watcher stopped while it sat paused for low disk (src/preempt.mjs
219
+ // diskRequeue): its lease gives way to a place at the front of its line, kept
220
+ // for this process alone (keptFor, so it goes if this process dies), which the
221
+ // same command picks up when it runs again (acquire's ticket). Called under the lock.
222
+ function requeue(s, l, cfg) {
223
+ const t = now();
224
+ s.leases = s.leases.filter(x => x !== l);
225
+ // What it really used goes into the history, so every later run of the command is planned at it too.
226
+ if (l.peak?.mem) record(l.key, t - l.start - pausedFor(l), l.who, l.peak, true);
227
+ const res = l.res;
228
+ const front = Math.min(l.start - (l.waited || 0), ...s.queue.filter(q => q.res.some(r => res.includes(r))).map(q => q.enq)) - 1;
229
+ // Booked at what it really used, up to all the memory dibs shares out (usual keeps the rest).
230
+ const used = Math.max(l.use?.mem || 0, l.peak?.mem || 0), budget = bytes(cfg.budget);
231
+ const size = used > l.mem ? (used > budget ? { mem: Math.max(l.mem, budget), usual: used } : { mem: used, usual: l.usual }) : { mem: l.mem, usual: l.usual };
232
+ const q = { id: ++s.seq, ticket: `${l.spid || l.who}|${res.join(',')}|${l.cmd}`, res, ...size, cpu: Math.max(l.cpu || 0, Math.ceil(l.peak?.cpu || 0)), asked: l.asked ?? l.mem, askedCpu: l.askedCpu,
233
+ pid: null, pstart: l.pstart, keptFor: l.pid, keepUntil: t + KEEP_PLACE, enq: front, who: l.who, agent: l.agent, label: l.label, spid: l.spid,
234
+ purpose: l.purpose, cmd: l.cmd, key: l.key, kind: 'run', agentId: l.agentId, sessionId: l.sessionId, cwd: l.cwd, ppid: l.ppid, requeued: l.requeue.why };
235
+ if (l.prio) q.prio = l.prio;
236
+ if (l.by) q.by = l.by;
237
+ if (l.requeue.why === 'over') q.requeues = (l.requeues || 0) + 1;
238
+ s.queue.push(q);
239
+ return { id: q.id, why: l.requeue.why, mem: q.mem };
240
+ }
241
+
242
+ // Run the same dibs run again, as this same process where Node allows it
243
+ // (process.execve keeps the pid the agent's tool call is waiting on), so it
244
+ // waits in line like any other and picks up the place requeue() kept.
245
+ const BIN = path.join(path.dirname(new URL(import.meta.url).pathname), '..', 'bin', 'dibs.mjs');
246
+ let handedOn = false;
247
+ function runAgain(o, lease, again) {
248
+ say(again.why === 'over'
249
+ ? `stopped #${lease.id}: it was using far more memory than it booked while swap filled the disk. It's back at the front of the line as #${again.id},`
250
+ + ` booked at ${gb(again.mem)}, and runs again from the start once that much memory is really free. Nothing for you to do: this call carries on.`
251
+ : `stopped #${lease.id}: it sat paused for low disk while its memory went to swap and filled the disk.`
252
+ + ` It's back at the front of the line as #${again.id} and runs again from the start when there's room. Nothing for you to do: this call carries on.`);
253
+ const args = process.argv.slice(2);
254
+ const at = args.indexOf('--lease');
255
+ if (at >= 0 && at < (args.indexOf('--') >>> 0)) args.splice(at, 2);
256
+ handedOn = true;
257
+ if (process.execve && OS !== 'windows') process.execve('/bin/sh', ['/bin/sh', BIN, ...args], process.env);
258
+ // No execve (Node before 22.15, or Windows): the same command in a child, whose code is this one's.
259
+ const child = spawn(process.execPath, [BIN, ...args], { stdio: 'inherit' });
260
+ for (const sig of SIGNALS) process.on(sig, () => child.kill(sig));
261
+ child.on('exit', (code, sig) => process.exit(code ?? signalExit(sig)));
262
+ }
263
+
264
+ // --after #42: wait for one of your earlier jobs (or anyone's) to end before
265
+ // joining the line, so a second step can't overtake the first. The wait counts
266
+ // against the same limit as the queue.
267
+ const AFTER_POLL = 1500;
268
+ async function after(o) {
269
+ const id = Number(String(o.after).replace(/^#/, ''));
270
+ if (!Number.isInteger(id) || id <= 0) die(`--after takes a job number from the board, like --after #42 (dibs mine shows yours)`);
271
+ const t0 = now();
272
+ const limit = o.maxWait ?? defaultMaxWait();
273
+ let first = true;
274
+ for (;;) {
275
+ const x = withState(s => { const l = s.leases.find(l => l.id === id) || s.queue.find(q => q.id === id && q.pid); return l && { ...l }; });
276
+ if (!x) {
277
+ if (first) say(`#${id} isn't running or waiting (it may have ended already), so this joins the line now.`);
278
+ else say(`#${id} ended after ${dur(now() - t0)}; joining the line.`);
279
+ if (limit !== Infinity) o.maxWait = Math.max(0, limit - (now() - t0));
280
+ return;
281
+ }
282
+ if (first) {
283
+ first = false;
284
+ say(`waiting for #${id} (${tag(x)}, ${x.res.map(r => short(r)).join(',')}${x.purpose ? `, "${x.purpose}"` : ''}) to end before joining the line.`
285
+ + `${limit === Infinity ? '' : ` Gives up at ${clock(t0 + limit)} (exit 75: your command won't have run).`}`);
286
+ }
287
+ if (now() - t0 >= limit) die(`#${id} is still going after ${dur(now() - t0)}, so this never joined the line. Your command did NOT run (exit 75). Run it again later, or add --wait.`, 75);
288
+ await sleep(AFTER_POLL);
289
+ }
290
+ }
291
+
292
+ // A name that isn't configured but is close to one that is (simulator, tset,
293
+ // xcode) is almost always a slip. Run under it and it gets a queue of its own,
294
+ // and two agents slipping differently both get the real thing at once. A name
295
+ // far from every known one is someone's own lock ("one migration at a time"),
296
+ // which dibs allows.
297
+ const ALIAS = { simulator: 'sim', simulators: 'sim', simctl: 'sim', xcode: 'xcode-build', xcodebuild: 'xcode-build', build: 'xcode-build', builds: 'xcode-build',
298
+ tests: 'test', testing: 'test', browser: 'playwright', browsers: 'playwright', e2e: 'playwright', deploys: 'deploy', ship: 'deploy' };
299
+ export function checkNames(res, cfg) {
300
+ const known = Object.keys(cfg.resources);
301
+ for (const r of res) {
302
+ if (isFiles(r) || isQuota(r) || cfg.resources[r]) continue;
303
+ const near = closeTo(r, known);
304
+ if (near) die(`no resource named ${r}. Did you mean ${near}? (A new name of your own: add it under "resources" in ${paths.config}.)`);
305
+ }
306
+ }
307
+ function closeTo(r, known) {
308
+ const low = r.toLowerCase();
309
+ if (ALIAS[low] && known.includes(ALIAS[low])) return ALIAS[low];
310
+ // sim-promax, test2, deploy_site: a known name with a suffix is a deliberate name of its own.
311
+ return known.find(k => k === low) || (known.some(k => low.startsWith(k) && /[-_0-9]/.test(low[k.length] || '')) ? null
312
+ : known.find(k => edits(low, k) <= (low.length >= 7 ? 2 : 1))) || null;
313
+ }
314
+ // Edits between two words, a swap of neighbours counting as one (tset is one from test).
315
+ function edits(a, b) {
316
+ const d = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
317
+ for (let j = 1; j <= b.length; j++) d[0][j] = j;
318
+ for (let i = 1; i <= a.length; i++)
319
+ for (let j = 1; j <= b.length; j++) {
320
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
321
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
322
+ }
323
+ return d[a.length][b.length];
324
+ }
325
+ export const nearest = (word, list) => list.find(k => edits(word, k) <= (word.length >= 5 ? 2 : 1)) || null;
326
+
327
+ // A pool lease's own simulator, booted. If it can't be had, the lease is given back.
328
+ async function simFor(lease, cfg) {
329
+ try { return await checkout(lease, cfg); } catch (e) {
330
+ withState(s => { s.leases = s.leases.filter(x => x.id !== lease.id); });
331
+ die(`${e.message}. Your command did not run.`, 1);
332
+ }
333
+ }
334
+
335
+ // A run inside a run that already holds the resources: no new lease, and
336
+ // nothing to track, since the outer run stops every group when it ends.
337
+ async function runNested(o) {
338
+ started = true;
339
+ const env = { ...process.env };
340
+ await addPorts(env, o.ports);
341
+ const child = launch(o.cmd, { env, background: false });
342
+ const stop = sig => stopTree(child.pid, sig);
343
+ for (const sig of SIGNALS) process.on(sig, () => { stop(sig); setTimeout(() => process.exit(signalExit(sig)), 3000).unref(); });
344
+ child.on('error', e => { say(`couldn't start ${o.cmd[0]}: ${e.message}`); process.exit(127); });
345
+ const t0 = now();
346
+ child.on('exit', (code, sig) => {
347
+ stop('SIGKILL');
348
+ say(`inside #${process.env.DIBS_LEASE}, ran ${dur(now() - t0)}, exit ${code ?? signalExit(sig)}`);
349
+ process.exit(code ?? signalExit(sig));
350
+ });
351
+ }
352
+
353
+ // A free port in env for each --port name. Picked after any wait in line, so
354
+ // nobody takes them in between.
355
+ async function addPorts(env, names) {
356
+ for (const name of names) env[name] = String(await freePort());
357
+ if (names.length) say(names.map(n => `${n}=${env[n]}`).join(' '));
358
+ }
359
+
360
+ function myHolds(s, id, res, o = {}) {
361
+ return s.leases.filter(l => l.kind === 'hold' && isMine(l, id) && sameAgent(l, o) && (!res.size || l.res.some(r => res.has(fileKey(r)))));
362
+ }
363
+ const CROWDED_EXTEND = 10 * 6e4;
364
+
365
+ // dibs hold <res>: take it across several tool calls, or extend it if you already have it.
366
+ export async function hold(o, cfg) {
367
+ if (!o.lease) stamp(o, 'hold');
368
+ const id = identity(o);
369
+ const want = new Set(o.res);
370
+ // With others waiting, a hold extends 10 minutes at a time, and not past an hour in total.
371
+ const extended = o.lease ? [] : withState(s => {
372
+ const mine = myHolds(s, id, want, o);
373
+ for (const l of mine) {
374
+ const waiting = s.queue.filter(q => q.pid && q.res.some(r => l.res.some(x => clash(x, r))));
375
+ l.waiters = waiting.map(tag);
376
+ // Asking again never shortens a hold.
377
+ if (!waiting.length) { l.expires = Math.max(l.expires, holdUntil(o)); continue; }
378
+ if (now() - l.start >= HOLD_CAP) { l.refused = true; continue; }
379
+ l.expires = Math.max(l.expires, Math.min(now() + Math.min(o.for ?? CROWDED_EXTEND, CROWDED_EXTEND), l.start + HOLD_CAP));
380
+ }
381
+ return mine.map(l => ({ ...l }));
382
+ });
383
+ // Bare `dibs hold` (or the old `dibs renew`) extends every hold you have; with none, it's a slip.
384
+ if (!o.res.length && !extended.length) die('hold what? dibs hold sim --for 20m -m "why" (what you have: dibs mine)');
385
+ // An hour is the most any hold gets, so a longer --for is cut to that, and says so.
386
+ const capped = o.for > HOLD_CAP ? ` (${dur(o.for)} asked; an hour is the most a hold gets. Hold again before it ends to extend.)` : '';
387
+ for (const l of extended) {
388
+ if (l.refused) {
389
+ console.log(`Can't give you more time on ${l.res.join(', ')}: you've had it ${dur(now() - l.start)} and ${l.waiters.join(', ')} ${l.waiters.length > 1 ? 'are' : 'is'} waiting. It ends at ${clock(l.expires)}. Give it back as soon as you can: dibs release ${shellRes(l.res.map(r => short(r)))}`);
390
+ process.exitCode = 1;
391
+ } else console.log(`You still have ${l.res.join(', ')}, now until ${clock(l.expires)}.${l.waiters.length ? '' : capped}`
392
+ + `${l.waiters.length ? ` ${l.waiters.join(', ')} ${l.waiters.length > 1 ? 'are' : 'is'} waiting for it, so more time comes 10 minutes at a time. Give it back the moment you're done: dibs release ${shellRes(l.res.map(r => short(r)))}` : ''}`);
393
+ }
394
+ const missing = o.res.filter(r => !extended.some(l => l.res.includes(r)));
395
+ if (!missing.length) return;
396
+ const lease = await acquire({ ...o, res: missing }, 'hold', cfg);
397
+ const sim = await simFor(lease, cfg);
398
+ const names = shellRes(lease.res.map(r => short(r)));
399
+ console.log(wrap(bold(`Reserved for you until ${clock(lease.expires)}: ${andList(lease.res.map(r => named(cfg, r).the))}.`) + capped
400
+ + (lease.pid ? ` It also ends when your session does.` : ' No agent session found, so it ends at that time or when you run dibs release.')
401
+ + (lease.label ? ` (held as ${tag(lease)})` : ''), ' '));
402
+ if (sim) console.log(` Your simulator: ${sim.name}, udid ${sim.udid}. Runs under this hold get SIM and SIM_NAME.`);
403
+ if (lease.res.some(isFiles)) console.log(" Other agents' edits there are turned away (with dibs guard installed). Yours go through.");
404
+ console.log(` Run things on it, no waiting: dibs run ${names} -- <command>`);
405
+ console.log(` More time: dibs hold ${names} --for 20m Done: dibs release ${names}`);
406
+ }
407
+
408
+ // dibs release [res]: give back your holds.
409
+ export function release(o) {
410
+ stamp(o, 'release');
411
+ const id = identity(o);
412
+ // Shut pool simulators down before the holds go, so they don't outlive them.
413
+ for (const l of withState(s => myHolds(s, id, new Set(o.res), o))) checkin(l);
414
+ const ls = withState(s => {
415
+ const mine = myHolds(s, id, new Set(o.res), o);
416
+ s.leases = s.leases.filter(l => !mine.includes(l));
417
+ return mine;
418
+ });
419
+ if (!ls.length) die(`you have nothing reserved${o.res.length ? ` matching ${o.res.join(', ')}` : ''} to give back. See what you have: dibs mine`, 1);
420
+ for (const l of ls) console.log(`Gave back ${l.res.join(', ')} after ${dur(now() - l.start)}.`);
421
+ }
422
+
423
+ // dibs when <res>: when you'd get it, without joining the line.
424
+ export function when(o, cfg) {
425
+ if (!o.res.length) die('when for what? dibs when sim (or several: dibs when sim,xcode-build)');
426
+ const id = identity(o);
427
+ const hist = history();
428
+ const t = now();
429
+ const res = [...new Set(o.res)];
430
+ const key = `${res.join(',')}|${o.cmd ? commandKey(o.cmd) : 'hold'}`;
431
+ const probe = { id: -1, res, enq: t, pid: 1, who: id.who, agent: id.agent, spid: id.spid, prio: o.prio, by: o.by, est: o.est, declared: o.mem != null,
432
+ ...sized(jobSize(cfg, res, o), hist, key, cfg), key };
433
+ const s = withState(s => { markIdle(s); return s; });
434
+ probe.holding = holdingOf(s, probe, cfg, t);
435
+ const v = verdict(s, probe, cfg, hist, t);
436
+ const at = v.ok ? t : forecast(s, cfg, hist, t, probe).get(-1);
437
+ const ahead = s.queue.filter(q => q.pid && q.res.some(r => res.includes(r)) && rank(q, hist, t) < rank(probe, hist, t)).length;
438
+ if (o.json) return json({ resources: res, freeNow: v.ok, start: at, waitMs: at - t, ahead, blockedBy: v.ok ? null : v.rule, why: v.why || null,
439
+ mem: probe.mem, cpu: probe.cpu, askedMem: probe.asked ?? null, askedCpu: probe.askedCpu ?? null });
440
+ const names = andList(res.map(r => named(cfg, r).the));
441
+ const go = `dibs run ${shellRes(res.map(r => short(r)))} -- <command>`;
442
+ const grew = grewPlain(probe, key.split('|')[1]);
443
+ if (v.ok) {
444
+ console.log(bold(`Free now: ${names}.`) + ` Take ${res.length > 1 ? 'them' : 'it'}: ${go}`);
445
+ if (grew) console.log(dim(wrap(` ${grew}`, ' ')));
446
+ return;
447
+ }
448
+ // Where you'd land, worked out as if you joined the queue now.
449
+ const p = plainBoard({ ...s, queue: [...s.queue, probe] }, cfg, hist, t);
450
+ const w = p.waiting.get(-1);
451
+ console.log(bold(`You'd be ${lower(w.headline)}, ${startPhrase(w)}.`));
452
+ console.log(wrap(` You'd wait for ${w.waitingFor}.`, ' '));
453
+ if (v.alongside) console.log(wrap(` ${v.alongside}`, ' '));
454
+ if (grew) console.log(dim(wrap(` ${grew}`, ' ')));
455
+ console.log(`To join the queue: ${go}`);
456
+ }
457
+
458
+ // dibs why: why you're waiting, in sentences. --detail: how your place in line was worked out.
459
+ export function why(o, cfg) {
460
+ stamp(o, 'why');
461
+ const id = caller(o);
462
+ const hist = history();
463
+ const t = now();
464
+ const s = withState(s => { markIdle(s); return s; });
465
+ const mine = s.queue.filter(q => q.pid && ours(q, id));
466
+ if (!mine.length) {
467
+ const holds = s.leases.filter(l => ours(l, id));
468
+ if (o.detail) return console.log(`you're not waiting for anything.${holds.length ? ` You hold: ${holds.map(l => l.res.join(',')).join('; ')}.` : ''}`);
469
+ return console.log(`You're not waiting for anything.${holds.length ? ` You have ${andList(holds.flatMap(l => l.res.map(r => named(cfg, r).the)))}.` : ''}`);
470
+ }
471
+ if (!o.detail) {
472
+ const p = plainBoard(s, cfg, hist, t, undefined, id);
473
+ for (const q of mine) {
474
+ const [head, ...rest] = whyLines(p, q, cfg);
475
+ console.log(bold(wrap(head)));
476
+ for (const x of rest) console.log(wrap(x, ' '));
477
+ const ask = askFirst(s, p, q);
478
+ if (ask) console.log(ask);
479
+ }
480
+ return console.log(dim('The numbers behind this: dibs why --detail'));
481
+ }
482
+ const order = s.queue.filter(q => q.pid).sort(byRank(hist, t));
483
+ const fc = forecast(s, cfg, hist, t);
484
+ // A wait on the machine has no start time, whatever the slots alone forecast; plain why says the same.
485
+ const p = plainBoard(s, cfg, hist, t);
486
+ for (const q of mine) {
487
+ const v = verdict(s, q, cfg, hist, t);
488
+ const { parts } = rankParts(q, hist, t);
489
+ const w = p.waiting.get(q.id);
490
+ console.log(`${q.res.join(', ')}${q.purpose ? ` ("${q.purpose}")` : ''}: #${order.indexOf(q) + 1} in the queue, `
491
+ + `${w?.startsIn == null && w?.startsText === 'unknown' ? 'start time unknown (it waits on the machine, not a job)' : `expect to start ~${clock(fc.get(q.id) || t)}`}`);
492
+ console.log(` blocked by ${v.ok ? 'nothing, starting now' : `${v.rule}: ${v.why}`}`);
493
+ if (v.alongside) console.log(` ${v.alongside}`);
494
+ if (q.holding) console.log(` holds ${q.holding.res.join(', ')}, so it goes first: ahead of waiters that hold nothing, like high priority (urgent work still goes before it)`);
495
+ console.log(` place in the queue: arrived ${clock(q.enq)}${parts.map(p => `, ${p.label} ${p.shift > 0 ? '+' : '-'}${dur(Math.abs(p.shift))}`).join('')}`);
496
+ }
497
+ }
498
+
499
+ // dibs mine [res]: what you hold and wait for. Exit 1 if nothing matches, so scripts can ask "do I hold sim?".
500
+ export function mine(o, cfg) {
501
+ stamp(o, 'mine');
502
+ const id = caller(o);
503
+ const want = new Set(o.res);
504
+ const match = x => !want.size || x.res.some(r => want.has(r));
505
+ const s = withState(s => s);
506
+ const held = s.leases.filter(l => ours(l, id) && match(l));
507
+ const waiting = s.queue.filter(q => ours(q, id) && match(q));
508
+ if (o.json) { json({ held, waiting }); process.exit(held.length || waiting.length ? 0 : 1); }
509
+ if (!held.length && !waiting.length) {
510
+ console.log(`You don't have ${want.size ? andList(o.res.map(r => named(cfg, r).the)) : 'anything'} and aren't waiting for ${want.size ? 'it' : 'anything'}.`);
511
+ process.exit(1);
512
+ }
513
+ const p = plainBoard(s, cfg, history(), now(), undefined, id);
514
+ // Several jobs from one session read alike; the -m and number tell them apart.
515
+ const reason = x => ` (#${x.id}${x.purpose ? `, "${x.purpose}"` : ''})`;
516
+ for (const l of held) {
517
+ const h = p.held.get(l.id);
518
+ console.log(l.kind === 'hold'
519
+ ? `You've reserved ${andList(l.res.map(r => named(cfg, r).the))}${reason(l)} until ${clock(l.expires)} (${h.endsText}). Give it back: dibs release ${shellRes(l.res.map(r => short(r)))}`
520
+ : `You're ${lower(h.headline)}${reason(l)}: ${l.cmd.slice(0, 50)}, ${h.endsText}.`);
521
+ }
522
+ for (const q of waiting) {
523
+ const w = p.waiting.get(q.id);
524
+ console.log(q.pid ? `You're ${lower(w.headline)}${reason(q)}, ${startPhrase(w)}. Why: dibs why` : `${w.headline}${reason(q)}. Run the same command again within 2 min to keep it.`);
525
+ }
526
+ }
527
+
528
+ // dibs who <res>: who holds it, until when, and who's next.
529
+ export function who(o, cfg) {
530
+ if (!o.res.length) return status(o, cfg);
531
+ const hist = history();
532
+ const t = now();
533
+ const s = withState(s => { markIdle(s); return s; });
534
+ const order = s.queue.filter(q => q.pid).sort(byRank(hist, t));
535
+ const rows = [];
536
+ for (const r of o.res) {
537
+ // A file lease is held by whoever holds any path overlapping it.
538
+ // One holder with two overlapping file leases is still one holder.
539
+ const held = s.leases.filter(l => l.res.some(x => clash(x, r))).filter((l, i, all) => all.findIndex(x => x.who === l.who) === i);
540
+ const next = order.filter(q => q.res.some(x => clash(x, r))).map(q => q.who);
541
+ const n = named(cfg, r);
542
+ const room = isFiles(r) ? 'nobody has these files or any that overlap them' : `${resCfg(cfg, r).slots - used(s, r)} of ${resCfg(cfg, r).slots} free`;
543
+ const hold = isFiles(r) ? '' : machineHold(s, cfg);
544
+ // One per project: say whether it's this folder's project holding it, or others, beside which it starts.
545
+ const perProject = !isFiles(r) && resCfg(cfg, r).exclusiveBy === 'repo' && held.length
546
+ ? (roomFor(s, { repo: projectKey(process.cwd()), cwd: process.cwd() }, r, cfg).open > 0 ? ' (other projects: one from this folder starts beside them)' : '')
547
+ : '';
548
+ const using = held.length ? `${usingText(held.map(l => ({ who: l.who, hold: l.kind === 'hold', ...ends(l, hist, t) })), n)}${perProject}` : `free (${room})${hold ? `, but nothing new starts until ${hold}` : ''}`;
549
+ rows.push([n.label, using, next.length ? nextText(next) : 'Nobody waiting',
550
+ ...held.map(l => dim(`${l.who}: ${l.purpose ? `"${l.purpose}", ` : ''}${l.cmd ? `running ${l.cmd.slice(0, 40)}` : 'reserved'}, started ${t - l.start < 6e4 ? 'just now' : `${minutes(t - l.start)} ago`}`
551
+ + `${isFiles(r) ? ` (${s.leases.filter(x => x.who === l.who).flatMap(x => x.res.filter(y => clash(y, r))).map(x => short(x).slice('files:'.length)).join(', ')})` : ''}`))]);
552
+ }
553
+ console.log(columns(rows).join('\n'));
554
+ }
555
+
556
+ // Let another agent go first: they take your place on every resource you both
557
+ // want, and any hold you have on what they're waiting for is released.
558
+ export function yieldTo(o) {
559
+ const [target, ...rest] = o.res;
560
+ if (!target) die('who should go first? dibs yield <agent> (names are on the board: dibs)');
561
+ const only = new Set(rest);
562
+ const id = identity(o);
563
+ if (target === id.agent || target === id.who) die("that's you");
564
+ const hist = history();
565
+ const lines = withState(s => {
566
+ const t = now();
567
+ const theirs = s.queue.filter(q => (q.agent === target || q.who === target) && (!only.size || q.res.some(r => only.has(r))));
568
+ if (!theirs.length) return [`${target} isn't waiting for anything${only.size ? ' you named' : ''}. Nothing changed. Who's waiting: dibs`];
569
+ const out = [];
570
+ const want = new Set(theirs.flatMap(q => q.res));
571
+ const holds = s.leases.filter(l => l.kind === 'hold' && isMine(l, id) && l.res.some(r => want.has(r)));
572
+ for (const l of holds) out.push(`Gave back your hold on ${l.res.join(', ')}.`);
573
+ s.leases = s.leases.filter(l => !holds.includes(l));
574
+ const yours = s.queue.filter(q => isMine(q, id));
575
+ const front = Math.min(t, ...s.queue.map(x => rank(x, hist, t))) - 1;
576
+ for (const q of theirs) {
577
+ const shared = yours.filter(m => m.res.some(r => q.res.includes(r)));
578
+ let to = shared.length ? Math.min(...shared.map(m => rank(m, hist, t))) - 1 : null;
579
+ if (holds.some(l => l.res.some(r => q.res.includes(r)))) to = Math.min(to ?? Infinity, front);
580
+ if (to != null && to < rank(q, hist, t)) { q.yieldRank = to; q.yieldBy = id.agent || id.who; out.push(`${tag(q)} now goes before you for ${q.res.join(', ')}.`); }
581
+ }
582
+ if (!out.length) out.push(`${target} is already ahead of you, and you have nothing they need. Nothing changed.`);
583
+ return out;
584
+ });
585
+ for (const l of lines) console.log(l);
586
+ }
587
+
588
+ // dibs ask "...": a request or bug report for whoever maintains dibs.
589
+ export function ask(args, cfg) {
590
+ const text = args.filter(a => !a.startsWith('-')).join(' ').trim();
591
+ if (!text) die('ask what? dibs ask "it should ..."');
592
+ const id = identity();
593
+ fs.appendFileSync(REQUESTS, JSON.stringify({ at: now(), who: id.who, agent: id.agent, text }) + '\n');
594
+ const found = answer(text);
595
+ const out = found.length ? ['From the docs:', ...found.map(f => ` ${f.where}:\n${f.text.split('\n').map(l => ` ${l}`).join('\n')}`), ''] : [];
596
+ // Without a maintainer (someone else's machine), the request stays in a file nobody reads: point bugs at the project.
597
+ if (cfg.maintainer) out.push(`Noted for the dibs maintainer, ${cfg.maintainer}.${inClaudeCode() ? ` For a faster answer, SendMessage ${cfg.maintainer}.` : ''}`);
598
+ else out.push(`${found.length ? "If that doesn't answer it, or it's a bug" : "Nothing in the docs matched. If it's a bug or something dibs should do"}, open an issue: ${ISSUES}`);
599
+ console.log(out.join('\n'));
600
+ }
601
+
602
+ export function requests(o) {
603
+ let list = [];
604
+ try { list = fs.readFileSync(REQUESTS, 'utf8').trim().split('\n').filter(Boolean).map(l => JSON.parse(l)); } catch {}
605
+ if (o.json) return json(list);
606
+ if (!list.length) return console.log('no requests yet');
607
+ for (const r of list.slice(-30)) console.log(`${new Date(r.at).toLocaleString()} ${r.who}: ${r.text}`);
608
+ }
609
+
610
+ // dibs pace [quiet|normal|max|off] [--json]: show or switch how hard dibs drives this machine.
611
+ const KNOBS = ['cores', 'budget', 'maxLoad', 'coolLoad', 'roomyLoad', 'roomyMemFree'];
612
+ // What `dibs pace --json` prints, for dibs web too.
613
+ export function paceJson() {
614
+ const cfg = loadConfig();
615
+ const file = JSON.parse(fs.readFileSync(paths.config, 'utf8'));
616
+ const hw = hardware();
617
+ return { pace: cfg.pace || null, hardware: { cores: hw.cores, mem: hw.mem }, knobs: Object.fromEntries(KNOBS.map(k => [k, cfg[k] ?? null])),
618
+ pinned: cfg.pace ? paced(file).pinned : [], paces: Object.fromEntries(Object.keys(PACES).map(p => [p, paceKnobs(p, hw)])), overlap: cfg.overlap };
619
+ }
620
+
621
+ export function pace(args) {
622
+ const word = args.find(a => !a.startsWith('-'));
623
+ if (word && word !== 'off' && !PACES[word]) die(`pace is one of ${Object.keys(PACES).join(', ')}, or off. See them: dibs pace`);
624
+ if (word) { writePace(word === 'off' ? null : word); logChange('pace', { pace: word }); }
625
+ const cfg = loadConfig();
626
+ const file = JSON.parse(fs.readFileSync(paths.config, 'utf8'));
627
+ const pinned = cfg.pace ? paced(file).pinned : [];
628
+ const hw = hardware();
629
+ if (args.includes('--json')) return json(paceJson());
630
+ const machineIs = `this machine (${hw.cores} cores, ${gb(hw.mem).replace(/G$/, ' GB')})`;
631
+ console.log(bold(cfg.pace ? `Speed: ${cfg.pace}, on ${machineIs}.` : 'Speed: not set. dibs uses the numbers in config.json, with no limit on how busy the machine gets.'));
632
+ console.log(wrap(`Side by side: ${sideBySide(cfg)}${file.overlap != null && cfg.pace ? ' (set in config.json, which wins over the speed)' : ''}`));
633
+ if (word) return;
634
+ const WHAT = { quiet: "the fan stays calm; you won't feel it at the Mac", normal: 'the usual numbers, with a limit at 1 job per core', max: 'finish fast: three quarters of memory' };
635
+ const TOGETHER = { off: 'no', fit: 'if they fit', squeeze: 'squeeze in' };
636
+ console.log(`\n${' '.repeat(11)}${'cores'.padEnd(7)}${'memory'.padEnd(8)}${'busy limit'.padEnd(12)}together`);
637
+ for (const p of Object.keys(PACES)) {
638
+ const k = paceKnobs(p);
639
+ const row = ` ${p.padEnd(9)}${String(k.cores).padEnd(7)}${k.budget.replace(/G$/, ' GB').padEnd(8)}${String(k.maxLoad).padEnd(12)}${TOGETHER[PACE_OVERLAP[p]].padEnd(13)}${WHAT[p]}`;
640
+ console.log(p === cfg.pace ? amber(row) : row);
641
+ }
642
+ console.log(`\n${dim(wrap('cores and memory: what jobs dibs starts may use at once, with cores counted as each running job is measured using them.'
643
+ + ' busy limit: past this load, normal and lower work waits. together: whether a job may start next to the ones filling its queue when the machine has room;'
644
+ + ` squeeze in also lets a job that usually takes under ${minutes(ms(loadConfig().squeezeUnder))} start even if it takes the machine past its busy limit.`))}`);
645
+ if (pinned.length) console.log(`Your config.json sets ${andList(pinned)}, which win over the speed. To let the speed decide, remove them from ${paths.config}`);
646
+ console.log('Switch: dibs pace quiet|normal|max Back to config.json: dibs pace off\nAll six settings: dibs pace --json');
647
+ }
648
+
649
+ // Processes burning CPU that no lease accounts for, grouped by what they run.
650
+ // The bar is lower than dibs throttle's (50%): this only reports, it doesn't act.
651
+ const BUSY_CPU = 40; // % of a core
652
+ function untracked(s) {
653
+ const ours = new Set(s.leases.flatMap(l => [l.pgid, ...(l.groups || [])]).filter(Boolean));
654
+ const groups = new Map();
655
+ for (const p of processes()) {
656
+ if (p.cpu < BUSY_CPU || ours.has(p.pgid)) continue;
657
+ // "node audit.mjs" says more than "node".
658
+ const [bin, ...args] = p.args.split(/\s+/);
659
+ const base = path.basename(bin).replace(/\.exe$/i, '');
660
+ if (/^(WindowServer|kernel_task|claude|codex|dibs)$/.test(base)) continue;
661
+ const script = /^(node|python3?|bun|deno|ruby)$/.test(base) ? args.find(a => !a.startsWith('-')) : null;
662
+ const name = script ? `${base} ${path.basename(script)}` : base;
663
+ const g = groups.get(name) || { name, n: 0, cpu: 0 };
664
+ g.n++; g.cpu += p.cpu;
665
+ groups.set(name, g);
666
+ }
667
+ return [...groups.values()].sort((a, b) => b.cpu - a.cpu).slice(0, 5);
668
+ }
669
+
670
+ // What `dibs --json` prints, as an object: the CLI prints it, and dibs web
671
+ // serves it from a read of the state taken without the lock (src/state.mjs peek).
672
+ // outside: the CPU hogs no lease accounts for, which costs a walk of the process table.
673
+ export function boardJson(s, cfg, { hist = history(), m = machine(), t = now(), rc = remoteConf(() => null), away = null, outside = true } = {}) {
674
+ const fc = forecast(s, cfg, hist, t);
675
+ const p = plainBoard(s, cfg, hist, t, m);
676
+ const order = [...s.queue].sort(byRank(hist, t));
677
+ return {
678
+ // The name the group knows this machine by, so the app can tell its own section from the others.
679
+ me: { name: rc?.name || shortHost() },
680
+ machine: { ...m, memHandedOut: sum(s.leases, l => l.mem), memBudget: bytes(cfg.budget), coresHandedOut: sum(s.leases.filter(l => !lent(l)), l => l.cpu ?? 1), cores: cfg.cores,
681
+ pace: cfg.pace, maxLoad: cfg.maxLoad, loadAhead: loadAhead(s, m) },
682
+ resets: s.resets || [],
683
+ held: s.leases.map(l => ({ ...l, remaining: remaining(l, hist, t), idleMs: idleFor(l, t), plain: p.held.get(l.id) })),
684
+ waiting: order.map((q, i) => ({ place: i + 1, ...q, expectStart: fc.get(q.id) || null, rank: rankParts(q, hist, t),
685
+ blocked: q.pid ? waitReason(verdict(s, q, cfg, hist, t)) : null, plain: p.waiting.get(q.id) })),
686
+ lines: p.lines,
687
+ // The board's Limits line, and what holds every new job back ('' when nothing does).
688
+ limits: limitsLine(s, cfg, m), hold: p.hold,
689
+ outside: outside ? untracked(s) : [],
690
+ quotas: quotasNow(s, cfg, t),
691
+ agents: agentsNow(cfg),
692
+ questions: forYou(cfg, t),
693
+ notes: notesForYou(),
694
+ // Agents waiting on dibs listen for a message: dibs tell reaches them within seconds.
695
+ listening: listeners(),
696
+ caps: s.caps || {},
697
+ later: laterBoard(t),
698
+ // What's wrong, each with its fix (src/alerts.mjs): open ones, then those resolved lately.
699
+ alerts: scanAlerts({ s, cfg, hist, m, t }),
700
+ ...(away ? { elsewhere: away } : {}),
701
+ };
702
+ }
703
+
704
+ export async function status(o, cfg) {
705
+ const hist = history();
706
+ const s = withState(s => { markIdle(s); return s; });
707
+ const m = machine();
708
+ const t = now();
709
+ // A broken remote.json still leaves this machine's board worth showing.
710
+ let broken = null;
711
+ const rc = remoteConf(msg => { broken = msg; return null; });
712
+ const away = rc ? await elsewhere(rc) : broken && { error: broken };
713
+ if (o.json) return json(boardJson(s, cfg, { hist, m, t, rc, away }));
714
+ stamp(o, 'status');
715
+ const me = caller(o);
716
+ if (!o.detail) return console.log(plainStatus(s, cfg, hist, m, t, rc, away, broken, me).join('\n'));
717
+ const b = boardOf(s, cfg, hist, t, me);
718
+ // With other machines to show, this one's section gets its name too.
719
+ const others = (away?.machines || []).some(x => x.name !== rc.name);
720
+ const out = [`${others ? `${rc.name} (this one) ` : ''}${cfg.pace ? `pace ${cfg.pace}, ` : ''}${handedOut(b)} `
721
+ + `machine: ${m.memFree}% memory free, disk ${m.diskFree == null ? 'unknown' : `${gb(m.diskFree)} free`}, swap ${gb(m.swapUsed)}, load ${m.load.toFixed(1)}`
722
+ + `${cfg.maxLoad != null ? ` (ceiling ${cfg.maxLoad})` : ''}`];
723
+ out.unshift(...alertLines(scanAlerts({ s, cfg, hist, m, t }).filter(a => onBoard(a, t)), t));
724
+ const asks = forYou(cfg, t), notes = notesForYou();
725
+ const plural = (n, w) => `${n} ${w}${n > 1 ? 's' : ''}`;
726
+ if (asks || notes) out.unshift(`${[asks && plural(asks, 'question'), notes && plural(notes, 'note')].filter(Boolean).join(' and ')} for you: dibs ${notes ? 'threads' : 'questions'}`);
727
+ out.push(`limits: ${limitsLine(s, cfg, m)}`);
728
+ const hot = overLoad(s, cfg, m);
729
+ if (hot) out.push(`over the load ceiling: ${loadWhy(hot, cfg)}`);
730
+ const sw = swapping(cfg, m);
731
+ if (sw) out.push(`${sw.rule === 'pressure' ? 'memory pressure' : 'swapping'}: ${swapWhy(sw)}`);
732
+ const squeeze = diskSqueeze(cfg, bytes(cfg.minDisk), m);
733
+ if (squeeze) out.push(`${squeeze.rule === 'drain' ? 'disk filling' : 'disk for swap'}: ${squeeze.why}`);
734
+ if (m.diskFree != null && m.diskFree < bytes(cfg.minDisk)) out.push(`disk: ${gb(m.diskFree)} free, under minDisk ${cfg.minDisk}, so nothing starts`);
735
+ for (const x of s.resets || []) out.push(`resetting ${x.res} after ${x.agent || x.who}'s turn (onRelease, ${dur(t - (x.started || x.at))} so far)`);
736
+ out.push(...boardLines(b, t), ...laterLines(laterBoard(t)));
737
+ const outside = untracked(s);
738
+ if (outside.length) out.push(`busy outside dibs: ${outside.map(x => `${x.name}${x.n > 1 ? ` x${x.n}` : ''} ${Math.round(x.cpu)}%`).join(', ')}`);
739
+ if (broken) out.push(`other machines: ${broken}`);
740
+ else if (away) out.push(...elsewhereLines(away, rc, me, t));
741
+ out.push(`you are ${me.agent || me.who}. Why you're waiting: dibs why. To trade places, ${inClaudeCode() ? 'SendMessage the agent ahead' : 'ask the agent ahead to let you go first'}; they run: dibs yield <your name>`);
742
+ console.log(out.join('\n'));
743
+ }
744
+
745
+ // Plain `dibs`: the one thing that matters most, then what each line is doing,
746
+ // for someone who's never seen dibs. `dibs --detail` is the full board, with ids and numbers.
747
+ function plainStatus(s, cfg, hist, m, t, rc, away, broken, me) {
748
+ const p = plainBoard(s, cfg, hist, t, m, me);
749
+ const agent = !!me.agent;
750
+ const out = [bold(headline(p))];
751
+ // What's wrong comes before anything else, so it can't be missed.
752
+ const alerted = alertLines(scanAlerts({ s, cfg, hist, m, t }).filter(a => onBoard(a, t)), t);
753
+ if (alerted.length) out.push('', ...alerted, '');
754
+ // An agent reading the board wants its own place first.
755
+ if (agent) {
756
+ for (const q of s.queue.filter(q => q.pid && ours(q, me))) {
757
+ const w = p.waiting.get(q.id);
758
+ out.push(amber(`You: ${lower(w.headline)}, ${startPhrase(w)}. Why: dibs why`));
759
+ }
760
+ for (const l of s.leases.filter(l => ours(l, me))) out.push(`You: ${lower(p.held.get(l.id).headline)}, ${p.held.get(l.id).endsText}.`);
761
+ }
762
+ // Questions and agents' notes (src/talk.mjs) both live in the threads; questions alone have their own list.
763
+ const asks = forYou(cfg, t), notes = notesForYou();
764
+ const count = (n, w) => `${n} ${w}${n > 1 ? 's' : ''}`;
765
+ if (asks && !notes) out.push(amber(`${count(asks, 'question')} ${asks > 1 ? 'are' : 'is'} waiting for your answer: dibs questions`));
766
+ else if (notes) out.push(amber(`${[asks && count(asks, 'question'), count(notes, 'note')].filter(Boolean).join(' and ')} ${asks + notes > 1 ? 'are' : 'is'} waiting for you: dibs threads`));
767
+ const ears = listeners();
768
+ if (ears.length) out.push(dim(`Listening for messages (dibs tell reaches them within seconds): ${ears.join(', ')}`));
769
+ const { busy, free } = lineParts(p);
770
+ out.push('', ...columns([...busy.map(b => [b.label, b.now, b.next]), ...(free.length ? [['Free', dim(freeText(p, free))]] : [])]));
771
+
772
+ const hot = overLoad(s, cfg, m);
773
+ const others = (away?.machines || []).some(x => x.name !== rc.name);
774
+ // The load average per core: under half, the person at the Mac feels nothing; past one, everything slows down.
775
+ const perCore = m.load / (m.cores || hardware().cores);
776
+ const sw = swapping(cfg, m);
777
+ const diskLow = m.diskFree != null && m.diskFree < bytes(cfg.minDisk);
778
+ const squeeze = diskSqueeze(cfg, bytes(cfg.minDisk), m);
779
+ const GB = b => gb(b).replace(/G$/, ' GB');
780
+ // The same reason the wait lines give (plain.mjs machineHold), worded so nobody reads it as a cue to raise priority.
781
+ const hold = machineHold(s, cfg, m);
782
+ const feel = diskLow ? 'out of disk' : squeeze ? (squeeze.rule === 'drain' ? `disk filling fast (free disk fell ${GB(squeeze.fell)} in 5 min)` : 'short of disk for swap to grow into') : sw ? (sw.rule === 'pressure' ? 'memory pressure is high' : `swapping (swap grew ${gb(sw.grew).replace(/G$/, ' GB')} in 5 min, ${gb(sw.used).replace(/G$/, ' GB')} in use)`) : hot ? 'too busy for new work' : hold ? 'memory fully handed out' : perCore < 0.5 ? 'quiet' : perCore < 1 ? 'busy' : 'very busy';
783
+ const holdBack = hold ? `Nothing new starts until ${hold}. Keep waiting: raising the priority is not the fix` : '';
784
+ const outside = untracked(s);
785
+ const subs = agentsNow(cfg);
786
+ const mine = new Map();
787
+ for (const a of subs?.running || []) mine.set(a.who, (mine.get(a.who) || 0) + 1);
788
+ const rows = [
789
+ [others ? `${rc.name} (here)` : 'This machine', `${feel}: ${m.memFree}% of memory free, `
790
+ + `${m.diskFree == null ? 'free disk unknown' : `${gb(m.diskFree).replace(/G$/, ' GB')} of disk free`}${cfg.pace ? `, speed set to ${cfg.pace}` : ''}`,
791
+ holdBack],
792
+ ['Limits', dim(limitsLine(s, cfg, m))],
793
+ // Busy processes dibs didn't start, which explain a busy machine with nothing in line.
794
+ ...(outside.length ? [['Outside dibs', dim(outside.map(x => `${x.name} (${x.n > 1 ? `${x.n} processes, ` : ''}${(x.cpu / 100).toFixed(1)} cores)`).join(', '))]] : []),
795
+ ...(s.resets || []).map(x => ['Resetting', `${named(cfg, x.res).label}, after ${x.agent || x.who}'s turn`]),
796
+ ...Object.entries(s.caps || {}).map(([who, c]) => ['Capped', `${who}, at ${c.prio} priority, by ${c.by || 'the person at this machine'}`]),
797
+ ...quotasNow(s, cfg, t).map(q => [named(cfg, `quota:${q.name}`).label,
798
+ q.error || `${q.left} of ${q.limit} left, refills to ${q.limit} every ${minutes(q.per).replace(/^1 hr$/, 'hour').replace(/^1 min$/, 'minute')}`]),
799
+ ...(mine.size ? [['Subagents', `${subs.running.length} of ${subs.slots} running (${[...mine].map(([who, k]) => `${k} for ${who}`).join(', ')})`]] : []),
800
+ ];
801
+ // Runs scheduled with dibs later, soonest first: what, then when.
802
+ const later = laterBoard(t).map(v => laterPlain(v, cfg));
803
+ if (later.length) out.push('', ...columns([['Later', ...later.flatMap(x => [x.what, dim(` ${x.when}`)])]]));
804
+ out.push('', ...columns(rows));
805
+ if (broken) out.push('', wrap(`Other machines: ${broken}`, ' '));
806
+ else if (away) { const x = elsewherePlain(away, rc, cfg); if (x.length) out.push('', ...x); }
807
+ // An agent needs its own name to read the board; the person at the machine doesn't.
808
+ out.push('', dim(agent ? `You're ${me.agent}. Why you're waiting: dibs why. Everything, with ids and numbers: dibs --detail` : 'More: dibs why, dibs --detail'));
809
+ return out;
810
+ }