@dibssoftware/dibs 0.0.180 → 0.0.195

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 (107) hide show
  1. package/CHANGELOG.md +111 -1
  2. package/README.md +10 -8
  3. package/bin/dibs.mjs +379 -74
  4. package/docs/agents.md +303 -0
  5. package/docs/council.md +88 -0
  6. package/docs/files.md +3 -3
  7. package/docs/guard.md +86 -11
  8. package/docs/json.md +211 -0
  9. package/docs/later.md +5 -5
  10. package/docs/machines.md +6 -6
  11. package/docs/questions.md +104 -3
  12. package/docs/reference.md +124 -30
  13. package/docs/relay.md +135 -11
  14. package/docs/releasing.md +7 -1
  15. package/docs/scheduling.md +28 -6
  16. package/docs/secrets.md +53 -0
  17. package/docs/simulators.md +3 -3
  18. package/docs/windows.md +3 -3
  19. package/package.json +1 -1
  20. package/skills/dibs/SKILL.md +79 -149
  21. package/src/about.mjs +341 -0
  22. package/src/acquire.mjs +113 -28
  23. package/src/after.mjs +127 -0
  24. package/src/agents.mjs +2 -1
  25. package/src/alerts.mjs +109 -48
  26. package/src/answers.mjs +2 -2
  27. package/src/board.mjs +21 -16
  28. package/src/broker.mjs +23 -7
  29. package/src/carry.mjs +287 -0
  30. package/src/codex.mjs +132 -0
  31. package/src/commands.mjs +254 -86
  32. package/src/config.mjs +85 -14
  33. package/src/connect.mjs +4 -2
  34. package/src/cool.mjs +28 -12
  35. package/src/council.mjs +482 -0
  36. package/src/cwd.mjs +9 -0
  37. package/src/decisions.mjs +250 -0
  38. package/src/declare.mjs +96 -0
  39. package/src/diskreport.mjs +306 -0
  40. package/src/diskuse.mjs +420 -0
  41. package/src/diskwarn.mjs +68 -13
  42. package/src/doctor.mjs +149 -0
  43. package/src/doors.mjs +547 -0
  44. package/src/durable.mjs +143 -0
  45. package/src/envs.mjs +372 -0
  46. package/src/events.mjs +7 -2
  47. package/src/files.mjs +121 -7
  48. package/src/guard.mjs +288 -105
  49. package/src/guardd.mjs +8 -1
  50. package/src/halt.mjs +63 -0
  51. package/src/handoffs.mjs +362 -0
  52. package/src/history.mjs +34 -4
  53. package/src/hogs.mjs +36 -8
  54. package/src/jobprogress.mjs +283 -0
  55. package/src/later.mjs +21 -10
  56. package/src/lock.mjs +51 -11
  57. package/src/measure.mjs +60 -14
  58. package/src/media.mjs +240 -0
  59. package/src/news.mjs +31 -0
  60. package/src/notes.mjs +49 -8
  61. package/src/notices.mjs +126 -43
  62. package/src/ondemand.mjs +25 -2
  63. package/src/outcome.mjs +163 -0
  64. package/src/overlap.mjs +2 -2
  65. package/src/override.mjs +149 -79
  66. package/src/owner.mjs +15 -2
  67. package/src/people.mjs +236 -0
  68. package/src/pickup.mjs +72 -0
  69. package/src/picture.mjs +321 -0
  70. package/src/plain.mjs +84 -18
  71. package/src/platform.mjs +29 -7
  72. package/src/preempt.mjs +123 -15
  73. package/src/primer.mjs +91 -20
  74. package/src/prints.mjs +99 -0
  75. package/src/proc.mjs +11 -1
  76. package/src/progress.mjs +49 -3
  77. package/src/proof.mjs +102 -0
  78. package/src/push.mjs +271 -0
  79. package/src/questions.mjs +328 -57
  80. package/src/quota.mjs +1 -1
  81. package/src/recap.mjs +205 -0
  82. package/src/relay.mjs +262 -26
  83. package/src/remote.mjs +23 -10
  84. package/src/reviewgate.mjs +268 -0
  85. package/src/reviews.mjs +377 -0
  86. package/src/route.mjs +263 -0
  87. package/src/rules.mjs +216 -0
  88. package/src/schedule.mjs +238 -44
  89. package/src/schema.mjs +62 -0
  90. package/src/scratch.mjs +2 -2
  91. package/src/serve.mjs +3 -2
  92. package/src/service.mjs +5 -1
  93. package/src/signed.mjs +97 -0
  94. package/src/simpool.mjs +46 -1
  95. package/src/spend.mjs +375 -0
  96. package/src/state.mjs +43 -17
  97. package/src/talk.mjs +1082 -134
  98. package/src/thin.sh +2 -0
  99. package/src/trail.mjs +290 -0
  100. package/src/trailnote.mjs +209 -0
  101. package/src/util.mjs +7 -0
  102. package/src/vault.mjs +435 -0
  103. package/src/vendors.mjs +327 -0
  104. package/src/version.mjs +1 -1
  105. package/src/web.mjs +354 -60
  106. package/src/work.mjs +487 -0
  107. package/src/worker.mjs +7 -1
package/src/commands.mjs CHANGED
@@ -3,36 +3,51 @@ import fs from 'node:fs';
3
3
  import net from 'node:net';
4
4
  import path from 'node:path';
5
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';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { resCfg, machine, HOME, paths, PACES, PACE_OVERLAP, paced, paceKnobs, hardware, writePace, loadConfig, readConfig } from './config.mjs';
8
+ import { logChange, actor } from './owner.mjs';
9
+ import { identity, isMine, tag, makeAlive } from './proc.mjs';
9
10
  import { launch, stopTree, processes, descendants, which, starts, scoped, watchdog, OS } from './platform.mjs';
10
- import { withState, withStateIfRoom, history, record, peakOf, peek, KEEP_PLACE } from './state.mjs';
11
+ import { withState, withStateIfRoom, history, record, peakOf, peek, pidsOf, KEEP_PLACE } from './state.mjs';
11
12
  import { acquire, markIdle, tableFirst, 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';
13
+ import { rank, rankParts, byRank, forecast, verdict, remaining, used, sum, lent, pausedFor, overLoad, loadWhy, loadAhead, holdingOf, swapping, swapWhy, diskSqueeze, keptFree, BACKGROUND, roomFor, halted, haltUntil, haltBy, fairShare } from './schedule.mjs';
14
+ import { noticeHandler, YIELD_GRACE } from './preempt.mjs';
15
+ import { checkout, checkin, jobSize, shutNamed } from './simpool.mjs';
15
16
  import { bytes, dur, gb, clock, die, say, now, ms, sleep, SIGNALS, signalExit, noSpace, inClaudeCode, OFF_LIMITS } from './util.mjs';
17
+ import { jsonLines } from './durable.mjs';
16
18
  import { boardOf, boardLines, handedOut, elsewhere, elsewhereLines, elsewherePlain, waitReason, limitsLine } from './board.mjs';
17
19
  import { plainBoard, lineParts, headline, startPhrase, whyLines, askFirst, named, andList, minutes, lower, usingText, nextText, ends, freeText, machineHold } from './plain.mjs';
18
20
  import { bold, dim, amber, columns, wrap, quoted } from './style.mjs';
19
21
  import { quotasNow, isQuota } from './quota.mjs';
20
22
  import { agentsNow } from './agents.mjs';
21
23
  import { forYou } from './questions.mjs';
22
- import { notesForYou, listeners } from './talk.mjs';
24
+ import { notesForYou, listeners, listenerPids, projectsNow } from './talk.mjs';
25
+ import { handoffsNow } from './handoffs.mjs';
26
+ import { workNow, workLine } from './work.mjs';
27
+ import { reviewsNow, reviewLine } from './reviews.mjs';
23
28
  import { remoteConf, shortHost } from './remote.mjs';
24
29
  import { sample, sized, grewLine, grewPlain, tellOverAsk } from './measure.mjs';
25
30
  import { clash, isFiles, short, takeAgent, callKey, sameAgent, fileKey, shellRes, projectKey } from './files.mjs';
26
31
  import { sideBySide } from './overlap.mjs';
27
32
  import { laterBoard, laterLines, laterPlain } from './later.mjs';
33
+ import { afterJob, aftersNow, afterText, afterLines } from './after.mjs';
28
34
  import { noticeScan, NOTICE_EVERY, twinOf } from './notices.mjs';
29
35
  import { answer, ISSUES } from './answers.mjs';
30
- import { event } from './events.mjs';
36
+ import { SCHEMA, jobOf, jobsOf, doneJobs, endJson } from './schema.mjs';
37
+ import { event, readEvents } from './events.mjs';
38
+ import { requireDeclaration, described, declared } from './declare.mjs';
31
39
  import { scan as scanAlerts, alertLines, onBoard } from './alerts.mjs';
40
+ import { door, briefing, gitHead, isEnv } from './envs.mjs';
41
+ import { outputWatch, note as noteProgress, progressOf } from './jobprogress.mjs';
42
+ import { yieldsOf, yieldLine } from './history.mjs';
32
43
 
33
44
  const REQUESTS = path.join(HOME, 'requests.jsonl');
34
45
  // Exit codes dibs gives its own meaning (AGENTS.md).
35
- const DIBS_CODES = new Set([1, 2, 3, 70, 74, 75, 76, 77, 127]);
46
+ const DIBS_CODES = new Set([1, 2, 3, 70, 74, 75, 76, 77, 78, 124, 127]);
47
+ // --time-limit's code: timeout(1)'s, which scripts already read as "ran out of time".
48
+ export const OVER_LIMIT = 124;
49
+ // After --time-limit's SIGTERM, how long the command gets to save and exit before SIGKILL.
50
+ const LIMIT_GRACE = 5e3;
36
51
  const json = x => console.log(JSON.stringify(x, null, 1));
37
52
 
38
53
  export function freePort() {
@@ -89,13 +104,13 @@ export async function run(o, cfg) {
89
104
  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
105
  die(twin.text, 2);
91
106
  }
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');
107
+ if (!o.cmd || !o.cmd.length) die('nothing to run: put the command after --, like dibs run sim -m "check the login screen" -- ./ui-test.sh');
108
+ if (!o.res.length) die('which resource? Name it before the --, like dibs run sim -m "..." -- <command>. The list: dibs help all');
94
109
  if (!which(o.cmd[0])) {
95
110
  // dibs run test -- "npm test && npm run lint": the whole line arrived as one program name.
96
111
  const line = o.cmd.length === 1 && /[\s;&|<>$]/.test(o.cmd[0]);
97
112
  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);
113
+ + `${line ? ` To run a shell line, use: dibs run ${shellRes(o.res.map(r => short(r)))} -m ${quoted([o.purpose || '...'])} -- sh -c ${quoted(o.cmd)}` : ''}`, 127);
99
114
  }
100
115
  // Inside a dibs run that already has these resources (a script that wraps
101
116
  // its own steps in dibs), go straight ahead instead of queueing behind yourself.
@@ -104,9 +119,16 @@ export async function run(o, cfg) {
104
119
  // over an API inside one run would make every call for free.
105
120
  const outer = o.lease ? null : outerLease();
106
121
  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);
122
+ // A one-way environment (env:prod) needs the person's yes before the line, not after the wait.
123
+ if (!o.lease) await door(o, cfg);
124
+ if (o.after) await afterJob(o);
108
125
  const lease = await acquire({ ...o, outer }, 'run', cfg);
126
+ // What the last holder left on each environment, before this command touches it.
127
+ for (const line of briefing(lease)) say(line);
128
+ const head = lease.res.some(isEnv) ? gitHead(process.cwd()) : null;
109
129
  const env = { ...process.env, DIBS_LEASE: String(lease.id) };
130
+ // --pausable: the signal that asks this job to save its progress and exit 0 (src/preempt.mjs yieldFor).
131
+ if (lease.pausable) Object.assign(env, { DIBS_PAUSABLE: '1', DIBS_CHECKPOINT_SIGNAL: 'USR1' });
110
132
  const sim = await simFor(lease, cfg);
111
133
  if (sim) { Object.assign(env, { SIM: sim.udid, SIM_NAME: sim.name }); say(`SIM=${sim.udid} SIM_NAME=${sim.name}`); }
112
134
  await addPorts(env, o.ports);
@@ -132,11 +154,12 @@ export async function run(o, cfg) {
132
154
  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
155
  };
134
156
  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;
157
+ let finished = false, tracker = null, ran = null, overLimit = false;
136
158
  let took = null; // how long a run the quick lane let in really took
137
159
  const finish = code => {
138
160
  if (finished) return;
139
161
  finished = true;
162
+ if (overLimit) code = OVER_LIMIT;
140
163
  clearInterval(tracker);
141
164
  stopAll('SIGKILL');
142
165
  wd.done();
@@ -146,6 +169,7 @@ export async function run(o, cfg) {
146
169
  withState(s => {
147
170
  const l = s.leases.find(x => x.id === lease.id);
148
171
  if (l?.requeue) { again = requeue(s, l, cfg); return; }
172
+ if (l && !sim) shutNamed(s, l);
149
173
  // Groups stopped by a pause that this process never tracked would stay stopped forever.
150
174
  if (OS !== 'windows') for (const g of l?.stopped || []) stopTree(g, 'SIGKILL');
151
175
  if (l) l.code = code; // for the end event in the history (src/events.mjs)
@@ -153,7 +177,7 @@ export async function run(o, cfg) {
153
177
  + `${l.stopReason ? '' : ' Find out why before running it again: dibs history, or ask whoever stopped it.'}`);
154
178
  s.leases = s.leases.filter(x => x.id !== lease.id);
155
179
  // 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, peakOf(l), code !== 0);
180
+ if (l && (code === 0 || l.peak?.mem)) record(l.key, now() - l.start - pausedFor(l), l.who, peakOf(l), code !== 0, l.repo);
157
181
  if (l?.quick) took = now() - l.start - pausedFor(l);
158
182
  tellOverAsk(l);
159
183
  });
@@ -165,13 +189,18 @@ export async function run(o, cfg) {
165
189
  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
190
  }
167
191
  if (again) return runAgain(o, lease, again);
192
+ // --json or DIBS_JSON=1: the end as one JSON line after the end line, the last thing dibs writes (docs/json.md).
193
+ // Written as the process exits, so it comes after every other line; writeSync, since a pipe's write may not finish otherwise.
194
+ if (o.json || process.env.DIBS_JSON === '1') {
195
+ const ranMs = ran == null ? null : now() - ran;
196
+ process.once('exit', () => { try { fs.writeSync(2, `${JSON.stringify(endJson(lease, code, ranMs))}\n`); } catch {} });
197
+ }
168
198
  // Over the quick lane's limit: its next runs wait their turn until one comes in under (src/schedule.mjs quickPass).
169
199
  const under = cfg.quickUnder == null ? null : ms(cfg.quickUnder);
170
200
  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}`);
201
+ // One line that says it all, for an agent that has lost the output above (a compacted context)
202
+ // and for the person glancing at its session. The id goes last, for agents that look for it.
203
+ say(endLine({ ...lease, ...(overLimit && { overLimit: o.timeLimit }) }, code, ran == null ? null : now() - ran));
175
204
  process.exit(code);
176
205
  };
177
206
  // Signals are handled from here on, before the slow steps below, so one that
@@ -186,35 +215,80 @@ export async function run(o, cfg) {
186
215
  // Low and idle work can be paused for urgent work (src/preempt.mjs); say so when it happens.
187
216
  // Notices about this job and others go to their agents while it runs (src/notices.mjs).
188
217
  setInterval(noticeScan, NOTICE_EVERY).unref();
218
+ // Windows has no SIGUSR2: there each tick of this run reads its own lease (a plain read, no lock)
219
+ // and says the same things, a few seconds later at most.
189
220
  const notify = OS !== 'windows';
190
- if (notify) process.on('SIGUSR2', noticeHandler(() => withStateIfRoom(s => s.leases.find(x => x.id === lease.id))));
221
+ const heard = noticeHandler(() => (notify ? withStateIfRoom(s => s.leases.find(x => x.id === lease.id)) : peek().leases?.find(x => x.id === lease.id)));
222
+ if (notify) process.on('SIGUSR2', heard);
191
223
  // The command starts only once its group is on record, so a wrapper killed
192
224
  // at any point has its job reaped with it, or the job never starts.
193
225
  // The gate shell execs the command, so its start time is the command's.
194
226
  const note = facts => s => { const l = s.leases.find(x => x.id === lease.id); if (l) Object.assign(l, facts); };
195
227
  const pgstart = child.pid ? starts([child.pid])?.get(child.pid) ?? null : null;
196
228
  // 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) {
229
+ try { withState(note({ pgid: child.pid, pgstart, notify, background: BACKGROUND.has(lease.prio) || !!lease.loadPast, requeuable: true, ...(head && { head }) })); } catch (e) {
198
230
  if (!noSpace(e)) throw e;
199
231
  // Unrecorded, the job couldn't be reaped if dibs died: it doesn't start. The lease goes with this process.
200
232
  stopTree(child.pid, 'SIGKILL');
201
233
  wd.done();
202
234
  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
235
  }
236
+ // Progress the job prints, when its output goes to a file (src/jobprogress.mjs), until it reports its own.
237
+ let output = outputWatch();
238
+ const progressed = () => {
239
+ const p = output?.();
240
+ if (!p) return;
241
+ const t = now();
242
+ const r = withStateIfRoom(s => { const l = s.leases.find(x => x.id === lease.id); if (l?.progress?.src === 'job') return 'job'; if (l) noteProgress(l, p, t, 'output'); });
243
+ if (r === 'job') output = null;
244
+ };
204
245
  child.go();
205
246
  started = true;
206
247
  ran = now();
207
248
  if (child.pid) wd.add(child.pid);
208
249
  if (child.pid && !pgstart) withStateIfRoom(note({ pgstart: starts([child.pid])?.get(child.pid) ?? null }));
209
250
  // 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);
251
+ tracker = setInterval(() => { track(); sample(); if (!notify) heard(); progressed(); }, 3000);
211
252
  tracker.unref();
253
+ // --time-limit counts from here, the start, never the wait; time dibs kept it paused doesn't count either.
254
+ if (o.timeLimit) {
255
+ const check = () => {
256
+ const l = peek().leases?.find(x => x.id === lease.id);
257
+ const left = ran + o.timeLimit + (l ? pausedFor(l) : 0) - now();
258
+ if (left > 0) return void setTimeout(check, left).unref();
259
+ overLimit = true;
260
+ say(`it ran past its --time-limit of ${dur(o.timeLimit)} (counted from its start, not the wait), so dibs is stopping it (exit ${OVER_LIMIT}).`);
261
+ stopAll('SIGTERM');
262
+ if (OS !== 'windows') stopAll('SIGCONT');
263
+ setTimeout(() => finish(OVER_LIMIT), LIMIT_GRACE).unref();
264
+ };
265
+ setTimeout(check, o.timeLimit).unref();
266
+ }
212
267
  child.on('error', e => { say(`couldn't start ${o.cmd[0]}: ${e.message}`); finish(127); });
213
268
  // No last track(): once the child has exited, its process groups are found by the
214
269
  // reaping below (finish), and walking the process table here cost 30 ms of every return.
215
270
  child.on('exit', (code, sig) => finish(code ?? signalExit(sig)));
216
271
  }
217
272
 
273
+ // What a run's end says on its own: "tests passed in 2m04s (waited 3s). #26565",
274
+ // "the build failed (exit 65) after 41s. #26566". With -m, its words lead: "Full suite" failed (exit 1) after 3m00s.
275
+ const SUBJECT = { test: ['tests', 'passed', 'failed'], playwright: ['browser tests', 'passed', 'failed'], 'xcode-build': ['the build', 'worked', 'failed'],
276
+ deploy: ['the deploy', 'worked', 'failed'], sim: ['the simulator run', 'worked', 'failed'], 'sim-own': ['the simulator run', 'worked', 'failed'] };
277
+ export function endLine(lease, code, ranMs) {
278
+ const res = lease.res.map(r => short(r));
279
+ const [what, good, bad] = SUBJECT[res.find(r => SUBJECT[r])] || ['it', 'worked', 'failed'];
280
+ const subject = lease.purpose ? `"${String(lease.purpose).replace(/\s+/g, ' ').trim().slice(0, 80)}"` : what;
281
+ const waited = (lease.waited || 0) >= 1000 ? ` (waited ${dur(lease.waited)})` : '';
282
+ // A failing command's code can look like one of dibs's own (75, 74, 127), so say whose it is.
283
+ const exit = DIBS_CODES.has(code) ? `exit ${code}, your command's code, not dibs's` : `exit ${code}`;
284
+ const verdict = ranMs == null ? `never started (exit ${code})${waited}`
285
+ : lease.overLimit ? `ran past its --time-limit of ${dur(lease.overLimit)} and was stopped (exit ${code}) after ${dur(ranMs)}${waited}`
286
+ : code === 0 ? `${good} in ${dur(ranMs)}${waited}`
287
+ : code >= 128 ? `was stopped (exit ${code}) after ${dur(ranMs)}${waited}`
288
+ : `${bad} (${exit}) after ${dur(ranMs)}${waited}`;
289
+ return `${subject} ${verdict}. #${lease.id}`;
290
+ }
291
+
218
292
  // A run the watcher stopped while it sat paused for low disk (src/preempt.mjs
219
293
  // diskRequeue): its lease gives way to a place at the front of its line, kept
220
294
  // for this process alone (keptFor, so it goes if this process dies), which the
@@ -223,9 +297,11 @@ function requeue(s, l, cfg) {
223
297
  const t = now();
224
298
  s.leases = s.leases.filter(x => x !== l);
225
299
  // 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, peakOf(l), true);
300
+ if (l.peak?.mem) record(l.key, t - l.start - pausedFor(l), l.who, peakOf(l), true, l.repo);
227
301
  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;
302
+ let front = Math.min(l.start - (l.waited || 0), ...s.queue.filter(q => q.res.some(r => res.includes(r))).map(q => q.enq)) - 1;
303
+ // A job that stepped aside for a waiter goes back in line behind it, not in front.
304
+ if (l.requeue.why === 'yield' && l.requeue.toEnq != null) front = Math.max(front, l.requeue.toEnq + 1);
229
305
  // Booked at what it really used, up to all the memory dibs shares out (usual keeps the rest).
230
306
  const used = Math.max(l.use?.mem || 0, l.peak?.mem || 0), budget = bytes(cfg.budget);
231
307
  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 };
@@ -234,18 +310,26 @@ function requeue(s, l, cfg) {
234
310
  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
311
  if (l.prio) q.prio = l.prio;
236
312
  if (l.by) q.by = l.by;
313
+ if (l.repo) q.repo = l.repo;
314
+ if (l.pausable) q.pausable = true;
237
315
  if (l.requeue.why === 'over') q.requeues = (l.requeues || 0) + 1;
316
+ // Whom it stepped aside for: it doesn't start again until that one has (src/schedule.mjs decide).
317
+ if (l.requeue.why === 'yield') Object.assign(q, { yieldTo: l.requeue.to, yieldToWho: l.requeue.toWho, yieldedAt: t });
238
318
  s.queue.push(q);
239
- return { id: q.id, why: l.requeue.why, mem: q.mem };
319
+ return { id: q.id, why: l.requeue.why, mem: q.mem, to: l.requeue.to, toWho: l.requeue.toWho, toPrio: l.requeue.toPrio, killed: !!l.requeue.killed };
240
320
  }
241
321
 
242
322
  // Run the same dibs run again, as this same process where Node allows it
243
323
  // (process.execve keeps the pid the agent's tool call is waiting on), so it
244
324
  // 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');
325
+ const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'dibs.mjs');
246
326
  let handedOn = false;
247
327
  function runAgain(o, lease, again) {
248
- say(again.why === 'over'
328
+ say(again.why === 'yield'
329
+ ? `#${lease.id} stepped aside for ${again.toWho}'s ${again.toPrio === 'normal' ? '' : `${again.toPrio} `}job (#${again.to}), which needed the room: you started it with --pausable.`
330
+ + `${again.killed ? ` It didn't exit within ${dur(YIELD_GRACE)} of SIGUSR1, so dibs ended it.` : ''}`
331
+ + ` It's back in line as #${again.id}, right behind #${again.to}, and runs the same command again (it picks up where it left off if it saved a checkpoint). Nothing for you to do: this call carries on.`
332
+ : again.why === 'over'
249
333
  ? `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
334
  + ` 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
335
  : again.why === 'memory'
@@ -264,34 +348,6 @@ function runAgain(o, lease, again) {
264
348
  child.on('exit', (code, sig) => process.exit(code ?? signalExit(sig)));
265
349
  }
266
350
 
267
- // --after #42: wait for one of your earlier jobs (or anyone's) to end before
268
- // joining the line, so a second step can't overtake the first. The wait counts
269
- // against the same limit as the queue.
270
- const AFTER_POLL = 1500;
271
- async function after(o) {
272
- const id = Number(String(o.after).replace(/^#/, ''));
273
- if (!Number.isInteger(id) || id <= 0) die(`--after takes a job number from the board, like --after #42 (dibs mine shows yours)`);
274
- const t0 = now();
275
- const limit = o.maxWait ?? defaultMaxWait();
276
- let first = true;
277
- for (;;) {
278
- 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 }; });
279
- if (!x) {
280
- if (first) say(`#${id} isn't running or waiting (it may have ended already), so this joins the line now.`);
281
- else say(`#${id} ended after ${dur(now() - t0)}; joining the line.`);
282
- if (limit !== Infinity) o.maxWait = Math.max(0, limit - (now() - t0));
283
- return;
284
- }
285
- if (first) {
286
- first = false;
287
- say(`waiting for #${id} (${tag(x)}, ${x.res.map(r => short(r)).join(',')}${x.purpose ? `, "${x.purpose}"` : ''}) to end before joining the line.`
288
- + `${limit === Infinity ? '' : ` Gives up at ${clock(t0 + limit)} (exit 75: your command won't have run).`}`);
289
- }
290
- 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);
291
- await sleep(AFTER_POLL);
292
- }
293
- }
294
-
295
351
  // A name that isn't configured but is close to one that is (simulator, tset,
296
352
  // xcode) is almost always a slip. Run under it and it gets a queue of its own,
297
353
  // and two agents slipping differently both get the real thing at once. A name
@@ -302,7 +358,7 @@ const ALIAS = { simulator: 'sim', simulators: 'sim', simctl: 'sim', xcode: 'xcod
302
358
  export function checkNames(res, cfg) {
303
359
  const known = Object.keys(cfg.resources);
304
360
  for (const r of res) {
305
- if (isFiles(r) || isQuota(r) || cfg.resources[r]) continue;
361
+ if (isFiles(r) || isQuota(r) || isEnv(r) || cfg.resources[r]) continue;
306
362
  const near = closeTo(r, known);
307
363
  if (near) die(`no resource named ${r}. Did you mean ${near}? (A new name of your own: add it under "resources" in ${paths.config}.)`);
308
364
  }
@@ -384,7 +440,7 @@ export async function hold(o, cfg) {
384
440
  return mine.map(l => ({ ...l }));
385
441
  });
386
442
  // Bare `dibs hold` (or the old `dibs renew`) extends every hold you have; with none, it's a slip.
387
- if (!o.res.length && !extended.length) die('hold what? dibs hold sim --for 20m -m "why" (what you have: dibs mine)');
443
+ if (!o.res.length && !extended.length) die('hold what? dibs hold sim --for 20m -m "check the onboarding screens by hand" (what you have: dibs mine)');
388
444
  // An hour is the most any hold gets, so a longer --for is cut to that, and says so.
389
445
  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.)` : '';
390
446
  for (const l of extended) {
@@ -396,7 +452,14 @@ export async function hold(o, cfg) {
396
452
  }
397
453
  const missing = o.res.filter(r => !extended.some(l => l.res.includes(r)));
398
454
  if (!missing.length) return;
399
- const lease = await acquire({ ...o, res: missing }, 'hold', cfg);
455
+ // Asking again for what you hold needs no words; a new hold does, before it gets in line.
456
+ requireDeclaration({ ...o, res: missing }, 'hold', o.typed || ['hold', ...o.res]);
457
+ if (!o.lease) await door({ ...o, res: missing }, cfg);
458
+ const asked = { ...o, res: missing };
459
+ if (o.after) await afterJob(asked);
460
+ const lease = await acquire(asked, 'hold', cfg);
461
+ const head = lease.res.some(isEnv) ? gitHead(process.cwd()) : null;
462
+ if (head) withStateIfRoom(s => { const l = s.leases.find(x => x.id === lease.id); if (l) l.head = head; });
400
463
  const sim = await simFor(lease, cfg);
401
464
  const names = shellRes(lease.res.map(r => short(r)));
402
465
  console.log(wrap(bold(`Reserved for you until ${clock(lease.expires)}: ${andList(lease.res.map(r => named(cfg, r).the))}.`) + capped
@@ -404,7 +467,8 @@ export async function hold(o, cfg) {
404
467
  + (lease.label ? ` (held as ${tag(lease)})` : ''), ' '));
405
468
  if (sim) console.log(` Your simulator: ${sim.name}, udid ${sim.udid}. Runs under this hold get SIM and SIM_NAME.`);
406
469
  if (lease.res.some(isFiles)) console.log(" Other agents' edits there are turned away (with dibs guard installed). Yours go through.");
407
- console.log(` Run things on it, no waiting: dibs run ${names} -- <command>`);
470
+ for (const line of briefing(lease)) console.log(wrap(` ${line}`, ' '));
471
+ console.log(` Run things on it, no waiting: dibs run ${names} -m "..." -- <command>`);
408
472
  console.log(` More time: dibs hold ${names} --for 20m Done: dibs release ${names}`);
409
473
  }
410
474
 
@@ -432,7 +496,7 @@ export function when(o, cfg) {
432
496
  const res = [...new Set(o.res)];
433
497
  const key = `${res.join(',')}|${o.cmd ? commandKey(o.cmd) : 'hold'}`;
434
498
  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,
435
- ...sized(jobSize(cfg, res, o), hist, key, cfg), key };
499
+ ...sized(jobSize(cfg, res, o), hist, key, cfg, projectKey(process.cwd())), key };
436
500
  const s = marked();
437
501
  probe.holding = holdingOf(s, probe, cfg, t);
438
502
  const v = verdict(s, probe, cfg, hist, t);
@@ -441,7 +505,7 @@ export function when(o, cfg) {
441
505
  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,
442
506
  mem: probe.mem, cpu: probe.cpu, askedMem: probe.asked ?? null, askedCpu: probe.askedCpu ?? null });
443
507
  const names = andList(res.map(r => named(cfg, r).the));
444
- const go = `dibs run ${shellRes(res.map(r => short(r)))} -- <command>`;
508
+ const go = `dibs run ${shellRes(res.map(r => short(r)))} -m "..." -- <command>`;
445
509
  const grew = grewPlain(probe, key.split('|')[1]);
446
510
  if (v.ok) {
447
511
  console.log(bold(`Free now: ${names}.`) + ` Take ${res.length > 1 ? 'them' : 'it'}: ${go}`);
@@ -461,11 +525,20 @@ export function when(o, cfg) {
461
525
  // dibs why: why you're waiting, in sentences. --detail: how your place in line was worked out.
462
526
  export function why(o, cfg) {
463
527
  stamp(o, 'why');
528
+ if (o.json) return json(whyJson(cfg, caller(o)));
464
529
  const id = caller(o);
465
530
  const hist = history();
466
531
  const t = now();
467
532
  const s = marked();
468
533
  const mine = s.queue.filter(q => q.pid && ours(q, id));
534
+ // Who stepped aside for whom, so an agent whose job lost hours can see who made it.
535
+ const ys = yieldsOf(id.who, t);
536
+ if (ys.length) {
537
+ console.log(bold('In the last day:'));
538
+ for (const y of ys.slice(-5)) console.log(wrap(`${clock(y.at)} ${yieldLine(y)}.`, ' '));
539
+ }
540
+ for (const a of aftersNow(s, t).filter(a => ours(a, id))) console.log(afterSentence(a, cfg, ` (#${a.id}${a.purpose ? `, "${a.purpose}"` : ''})`));
541
+ if (!mine.length && (s.afters || []).some(a => ours(a, id))) return;
469
542
  if (!mine.length) {
470
543
  const holds = s.leases.filter(l => ours(l, id));
471
544
  if (o.detail) return console.log(`you're not waiting for anything.${holds.length ? ` You hold: ${holds.map(l => l.res.join(',')).join('; ')}.` : ''}`);
@@ -482,13 +555,14 @@ export function why(o, cfg) {
482
555
  }
483
556
  return console.log(dim('The numbers behind this: dibs why --detail'));
484
557
  }
485
- const order = s.queue.filter(q => q.pid).sort(byRank(hist, t));
558
+ const fair = fairShare(s, cfg, t);
559
+ const order = s.queue.filter(q => q.pid).sort(byRank(hist, t, fair));
486
560
  const fc = forecast(s, cfg, hist, t);
487
561
  // A wait on the machine has no start time, whatever the slots alone forecast; plain why says the same.
488
562
  const p = plainBoard(s, cfg, hist, t);
489
563
  for (const q of mine) {
490
564
  const v = verdict(s, q, cfg, hist, t);
491
- const { parts } = rankParts(q, hist, t);
565
+ const { parts } = rankParts(q, hist, t, fair);
492
566
  const w = p.waiting.get(q.id);
493
567
  console.log(`${q.res.join(', ')}${q.purpose ? ` ("${q.purpose}")` : ''}: #${order.indexOf(q) + 1} in the queue, `
494
568
  + `${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)}`}`);
@@ -499,6 +573,39 @@ export function why(o, cfg) {
499
573
  }
500
574
  }
501
575
 
576
+ // dibs why --json: each of the caller's waits as a job (docs/json.md), with the sentences plain why prints
577
+ // and how its place in line was worked out; its leases beside them.
578
+ function whyJson(cfg, id) {
579
+ const hist = history(), t = now(), s = marked();
580
+ const mine = s.queue.filter(q => q.pid && ours(q, id));
581
+ const order = s.queue.filter(q => q.pid).sort(byRank(hist, t));
582
+ const ctx = { s, cfg, hist, t, order, fc: forecast(s, cfg, hist, t), mine: () => true };
583
+ const p = mine.length ? plainBoard(s, cfg, hist, t, undefined, id) : null;
584
+ const jobs = mine.map(q => ({ ...jobOf(q, ctx), why: whyLines(p, q, cfg).map(x => x.trim()),
585
+ rank: rankParts(q, hist, t).parts.map(x => ({ reason: x.label, aheadMs: x.shift })) }));
586
+ return { schema: SCHEMA, waiting: jobs.length > 0, jobs, holding: s.leases.filter(l => ours(l, id)).map(l => jobOf(l, ctx)) };
587
+ }
588
+
589
+ // dibs jobs [--since 1h] [--json]: every job on this machine, running, paused and waiting, and the
590
+ // ones that ended lately with their exit codes. The ids are what dibs stop, boost and pause take.
591
+ const DONE_SHOWN = 36e5;
592
+ export function jobs(o, cfg) {
593
+ const hist = history();
594
+ const t = now();
595
+ const s = marked();
596
+ const id = identity(o);
597
+ const order = [...s.queue].sort(byRank(hist, t));
598
+ const mineOf = x => isMine(x, id);
599
+ const list = [...jobsOf(s, { s, cfg, hist, t, order, fc: forecast(s, cfg, hist, t), mine: mineOf }),
600
+ ...doneJobs(readEvents(t), t - (o.since ? ms(o.since) : DONE_SHOWN), x => x.who === id.who).reverse()];
601
+ if (o.json) return json({ schema: SCHEMA, jobs: list });
602
+ if (!list.length) return console.log(`No jobs now, and none ended in the last ${dur(o.since ? ms(o.since) : DONE_SHOWN)}.`);
603
+ const when = j => j.state === 'waiting' ? `waiting ${dur(j.waitedMs)}${j.place ? `, #${j.place} in line` : ', place kept'}${j.blocked ? `, ${j.blocked}` : ''}`
604
+ : j.state === 'done' ? `ended ${clock(j.endedAt)}, exit ${j.exitCode ?? 'unknown'} after ${dur(j.ranMs)}`
605
+ : `${j.state === 'paused' ? j.paused : j.kind === 'hold' ? 'reserved' : 'running'} ${dur(j.ranMs)}`;
606
+ console.log(columns(list.map(j => [`#${j.id}`, `${j.agent}${j.label ? ` (${j.label})` : ''}, ${j.resource}, "${j.what || j.cmd || 'reserved'}": ${when(j)}`])).join('\n'));
607
+ }
608
+
502
609
  // dibs mine [res]: what you hold and wait for. Exit 1 if nothing matches, so scripts can ask "do I hold sim?".
503
610
  export function mine(o, cfg) {
504
611
  stamp(o, 'mine');
@@ -508,8 +615,15 @@ export function mine(o, cfg) {
508
615
  const s = withState(s => s);
509
616
  const held = s.leases.filter(l => ours(l, id) && match(l));
510
617
  const waiting = s.queue.filter(q => ours(q, id) && match(q));
511
- if (o.json) { json({ held, waiting }); process.exit(held.length || waiting.length ? 0 : 1); }
512
- if (!held.length && !waiting.length) {
618
+ const after = aftersNow(s).filter(a => ours(a, id) && match(a));
619
+ if (o.json) {
620
+ const hist = history(), t = now();
621
+ const order = s.queue.filter(q => q.pid).sort(byRank(hist, t));
622
+ const ctx = { s, cfg, hist, t, order, fc: forecast(s, cfg, hist, t), mine: () => true };
623
+ json({ schema: SCHEMA, jobs: [...held, ...waiting].map(x => jobOf(x, ctx)), held, waiting, after });
624
+ process.exit(held.length || waiting.length || after.length ? 0 : 1);
625
+ }
626
+ if (!held.length && !waiting.length && !after.length) {
513
627
  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'}.`);
514
628
  process.exit(1);
515
629
  }
@@ -526,8 +640,13 @@ export function mine(o, cfg) {
526
640
  const w = p.waiting.get(q.id);
527
641
  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.`);
528
642
  }
643
+ for (const a of after) console.log(afterSentence(a, cfg, reason(a)));
529
644
  }
530
645
 
646
+ // A run or hold waiting --after another job, as one sentence for dibs mine and dibs why.
647
+ const afterSentence = (a, cfg, reason) => `You're waiting for ${a.deps.map(d => `#${d.id} (${d.who}${d.purpose ? `, "${d.purpose}"` : ''})`).join(', ') || a.after.map(x => `#${x}`).join(', ')} to end`
648
+ + `${a.ok ? ', and go only if it succeeds' : ''}, then join the line for ${andList(a.res.map(r => named(cfg, r).the))}${reason}. This wait counts against no time limit.`;
649
+
531
650
  // dibs who <res>: who holds it, until when, and who's next.
532
651
  export function who(o, cfg) {
533
652
  if (!o.res.length) return status(o, cfg);
@@ -548,9 +667,9 @@ export function who(o, cfg) {
548
667
  const perProject = !isFiles(r) && resCfg(cfg, r).exclusiveBy === 'repo' && held.length
549
668
  ? (roomFor(s, { repo: projectKey(process.cwd()), cwd: process.cwd() }, r, cfg).open > 0 ? ' (other projects: one from this folder starts beside them)' : '')
550
669
  : '';
551
- 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}` : ''}`;
670
+ const using = held.length ? `${usingText(held.map(l => ({ who: l.who, id: l.id, hold: l.kind === 'hold', ...ends(l, hist, t) })), n)}${perProject}` : `free (${room})${hold ? `, but nothing new starts until ${hold}` : ''}`;
552
671
  rows.push([n.label, using, next.length ? nextText(next) : 'Nobody waiting',
553
- ...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`}`
672
+ ...held.map(l => dim(`${l.who}: "${described(l, cfg)}", ${l.cmd ? `running ${l.cmd.slice(0, 40)}` : 'reserved'}, started ${t - l.start < 6e4 ? 'just now' : `${minutes(t - l.start)} ago`}`
554
673
  + `${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(', ')})` : ''}`))]);
555
674
  }
556
675
  console.log(columns(rows).join('\n'));
@@ -604,7 +723,7 @@ export function ask(args, cfg) {
604
723
 
605
724
  export function requests(o) {
606
725
  let list = [];
607
- try { list = fs.readFileSync(REQUESTS, 'utf8').trim().split('\n').filter(Boolean).map(l => JSON.parse(l)); } catch {}
726
+ try { list = jsonLines(fs.readFileSync(REQUESTS, 'utf8')); } catch {} // a line cut short hides only itself
608
727
  if (o.json) return json(list);
609
728
  if (!list.length) return console.log('no requests yet');
610
729
  for (const r of list.slice(-30)) console.log(`${new Date(r.at).toLocaleString()} ${r.who}: ${r.text}`);
@@ -615,7 +734,7 @@ const KNOBS = ['cores', 'budget', 'maxLoad', 'coolLoad', 'roomyLoad', 'roomyMemF
615
734
  // What `dibs pace --json` prints, for dibs web too.
616
735
  export function paceJson() {
617
736
  const cfg = loadConfig();
618
- const file = JSON.parse(fs.readFileSync(paths.config, 'utf8'));
737
+ const file = readConfig();
619
738
  const hw = hardware();
620
739
  return { pace: cfg.pace || null, hardware: { cores: hw.cores, mem: hw.mem }, knobs: Object.fromEntries(KNOBS.map(k => [k, cfg[k] ?? null])),
621
740
  pinned: cfg.pace ? paced(file).pinned : [], paces: Object.fromEntries(Object.keys(PACES).map(p => [p, paceKnobs(p, hw)])), overlap: cfg.overlap };
@@ -626,7 +745,7 @@ export function pace(args) {
626
745
  if (word && word !== 'off' && !PACES[word]) die(`pace is one of ${Object.keys(PACES).join(', ')}, or off. See them: dibs pace`);
627
746
  if (word) { writePace(word === 'off' ? null : word); logChange('pace', { pace: word }); }
628
747
  const cfg = loadConfig();
629
- const file = JSON.parse(fs.readFileSync(paths.config, 'utf8'));
748
+ const file = readConfig();
630
749
  const pinned = cfg.pace ? paced(file).pinned : [];
631
750
  const hw = hardware();
632
751
  if (args.includes('--json')) return json(paceJson());
@@ -676,18 +795,23 @@ function untracked(s) {
676
795
  // What `dibs --json` prints, as an object: the CLI prints it, and dibs web
677
796
  // serves it from a read of the state taken without the lock (src/state.mjs peek).
678
797
  // outside: the CPU hogs no lease accounts for, which costs a walk of the process table.
679
- export function boardJson(s, cfg, { hist = history(), m = machine(), t = now(), rc = remoteConf(() => null), away = null, outside = true } = {}) {
798
+ export function boardJson(s, cfg, { hist = history(), m = machine(), t = now(), rc = remoteConf(() => null), away = null, outside = true, mine = null } = {}) {
680
799
  const fc = forecast(s, cfg, hist, t);
681
800
  const p = plainBoard(s, cfg, hist, t, m);
682
- const order = [...s.queue].sort(byRank(hist, t));
801
+ const fair = fairShare(s, cfg, t);
802
+ const order = [...s.queue].sort(byRank(hist, t, fair));
683
803
  return {
804
+ schema: SCHEMA,
805
+ // Every job in the documented shape (docs/json.md); held and waiting below are the older view of the same.
806
+ jobs: jobsOf(s, { s, cfg, hist, t, order, fc, mine }),
684
807
  // The name the group knows this machine by, so the app can tell its own section from the others.
685
808
  me: { name: rc?.name || shortHost() },
686
809
  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,
687
810
  pace: cfg.pace, maxLoad: cfg.maxLoad, loadAhead: loadAhead(s, m) },
688
811
  resets: s.resets || [],
689
- held: s.leases.map(l => ({ ...l, remaining: remaining(l, hist, t), idleMs: idleFor(l, t), plain: p.held.get(l.id) })),
690
- waiting: order.map((q, i) => ({ place: i + 1, ...q, expectStart: fc.get(q.id) || null, rank: rankParts(q, hist, t),
812
+ // purpose is what the job is doing in words, its agent's or made from what's known (declared false): screens lead with it.
813
+ held: s.leases.map(l => ({ ...l, purpose: described(l, cfg), declared: declared(l), remaining: remaining(l, hist, t), idleMs: idleFor(l, t), progress: progressOf(l, t), plain: p.held.get(l.id) })),
814
+ waiting: order.map((q, i) => ({ place: i + 1, ...q, purpose: described(q, cfg), declared: declared(q), expectStart: fc.get(q.id) || null, rank: rankParts(q, hist, t, fair),
691
815
  blocked: q.pid ? waitReason(verdict(s, q, cfg, hist, t)) : null, plain: p.waiting.get(q.id) })),
692
816
  lines: p.lines,
693
817
  // The board's Limits line, and what holds every new job back ('' when nothing does).
@@ -699,8 +823,20 @@ export function boardJson(s, cfg, { hist = history(), m = machine(), t = now(),
699
823
  notes: notesForYou(),
700
824
  // Agents waiting on dibs listen for a message: dibs tell reaches them within seconds.
701
825
  listening: listeners(),
826
+ // Which product each agent said it works on (dibs project): work for anyone goes by it.
827
+ projects: projectsNow(),
702
828
  caps: s.caps || {},
829
+ // dibs halt: no new job starts until it lifts (src/halt.mjs). null when none is on.
830
+ halt: halted(s, t),
831
+ // Tasks agents handed over (src/handoffs.mjs), open or taken.
832
+ handoffs: handoffsNow(t),
833
+ // Work items (src/work.mjs): in flight, and closed lately with their proof.
834
+ work: workNow(t),
835
+ // Reviews agents asked of each other (src/reviews.mjs): open ones, and answers of the last day.
836
+ reviews: reviewsNow(t),
703
837
  later: laterBoard(t),
838
+ // Runs and holds waiting --after another job ends (src/after.mjs), not yet in line.
839
+ after: aftersNow(s, t),
704
840
  // What's wrong, each with its fix (src/alerts.mjs): open ones, then those resolved lately.
705
841
  alerts: scanAlerts({ s, cfg, hist, m, t }),
706
842
  ...(away ? { elsewhere: away } : {}),
@@ -718,6 +854,9 @@ function marked() {
718
854
  const BOARD_WAIT = 2000;
719
855
  export async function status(o, cfg) {
720
856
  const hist = history();
857
+ // One ps for the start times of the state's pids and the listeners' (src/proc.mjs keeps
858
+ // them 10 s): the state lock's own read and the board's line of listeners took one each.
859
+ try { makeAlive([...pidsOf(peek()), ...listenerPids()]); } catch {}
721
860
  tableFirst();
722
861
  const s = withState(s => { markIdle(s); return s; }, BOARD_WAIT) ?? peek();
723
862
  const m = machine();
@@ -726,10 +865,14 @@ export async function status(o, cfg) {
726
865
  let broken = null;
727
866
  const rc = remoteConf(msg => { broken = msg; return null; });
728
867
  const away = rc ? await elsewhere(rc) : broken && { error: broken };
729
- if (o.json) return json(boardJson(s, cfg, { hist, m, t, rc, away }));
868
+ if (o.json) { const id = identity(o); return json(boardJson(s, cfg, { hist, m, t, rc, away, mine: x => isMine(x, id) })); }
730
869
  stamp(o, 'status');
731
870
  const me = caller(o);
732
- if (!o.detail) return console.log(plainStatus(s, cfg, hist, m, t, rc, away, broken, me).join('\n'));
871
+ // The person at the terminal reads agents first, in plain words; agents keep the board as it was, resources first,
872
+ // since they read it to plan (src/picture.mjs).
873
+ const person = !me.agent && !actor().agent;
874
+ const agentsFirst = person && !o.detail ? (await import('./picture.mjs')).agentLines(t) : null;
875
+ if (!o.detail) return console.log(plainStatus(s, cfg, hist, m, t, rc, away, broken, me, agentsFirst).join('\n'));
733
876
  const b = boardOf(s, cfg, hist, t, me);
734
877
  // With other machines to show, this one's section gets its name too.
735
878
  const others = (away?.machines || []).some(x => x.name !== rc.name);
@@ -740,6 +883,12 @@ export async function status(o, cfg) {
740
883
  const asks = forYou(cfg, t), notes = notesForYou();
741
884
  const plural = (n, w) => `${n} ${w}${n > 1 ? 's' : ''}`;
742
885
  if (asks || notes) out.unshift(`${[asks && plural(asks, 'question'), notes && plural(notes, 'note')].filter(Boolean).join(' and ')} for you: dibs ${notes ? 'threads' : 'questions'}`);
886
+ const h = halted(s, t);
887
+ if (h) out.unshift(`halted: no new job starts ${haltUntil(h)} (set by ${haltBy(h)}); running ones go on. Lift it: dibs halt off`);
888
+ const flight = workNow(t).filter(i => i.state !== 'done' && i.state !== 'dropped');
889
+ if (flight.length) out.push(`work: ${flight.map(i => workLine(i, t)).join('; ')}`);
890
+ const asked = reviewsNow(t).filter(x => x.state === 'open');
891
+ if (asked.length) out.push(`reviews: ${asked.map(x => reviewLine(x, t)).join('; ')}`);
743
892
  out.push(`limits: ${limitsLine(s, cfg, m)}`);
744
893
  const hot = overLoad(s, cfg, m);
745
894
  if (hot) out.push(`over the load ceiling: ${loadWhy(hot, cfg)}`);
@@ -747,25 +896,30 @@ export async function status(o, cfg) {
747
896
  if (sw) out.push(`${sw.rule === 'pressure' ? 'memory pressure' : 'swapping'}: ${swapWhy(sw)}`);
748
897
  const squeeze = diskSqueeze(cfg, bytes(cfg.minDisk), m);
749
898
  if (squeeze) out.push(`${squeeze.rule === 'drain' ? 'disk filling' : 'disk for swap'}: ${squeeze.why}`);
750
- if (m.diskFree != null && m.diskFree < bytes(cfg.minDisk)) out.push(`disk: ${gb(m.diskFree)} free, under minDisk ${cfg.minDisk}, so nothing starts`);
899
+ if (m.diskFree != null && m.diskFree < bytes(cfg.minDisk)) out.push(`disk: ${gb(m.diskFree)} free; dibs keeps ${keptFree(cfg)}, so nothing starts`);
751
900
  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)`);
752
- out.push(...boardLines(b, t), ...laterLines(laterBoard(t)));
901
+ out.push(...boardLines(b, t), ...afterLines(aftersNow(s, t), a => ` #${a.id}${isMine(a, me) ? ' <- you' : ''}`), ...laterLines(laterBoard(t)));
753
902
  const outside = untracked(s);
754
903
  if (outside.length) out.push(`busy outside dibs: ${outside.map(x => `${x.name}${x.n > 1 ? ` x${x.n}` : ''} ${Math.round(x.cpu)}%`).join(', ')}`);
755
904
  if (broken) out.push(`other machines: ${broken}`);
756
905
  else if (away) out.push(...elsewhereLines(away, rc, me, t));
757
- 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>`);
906
+ out.push(`you are ${me.agent || me.who}. Why you're waiting: dibs why. dibs yield <your name>, run by an agent ahead of you, puts you ahead of it.`);
758
907
  console.log(out.join('\n'));
759
908
  }
760
909
 
761
910
  // Plain `dibs`: the one thing that matters most, then what each line is doing,
762
911
  // for someone who's never seen dibs. `dibs --detail` is the full board, with ids and numbers.
763
- function plainStatus(s, cfg, hist, m, t, rc, away, broken, me) {
912
+ // agentsFirst: the agents' lines the person's board opens with (null for an agent).
913
+ function plainStatus(s, cfg, hist, m, t, rc, away, broken, me, agentsFirst = null) {
764
914
  const p = plainBoard(s, cfg, hist, t, m, me);
765
915
  const agent = !!me.agent;
766
- const out = [bold(headline(p))];
767
- // What's wrong comes before anything else, so it can't be missed.
768
- const alerted = alertLines(scanAlerts({ s, cfg, hist, m, t }).filter(a => onBoard(a, t)), t);
916
+ const out = [...(agentsFirst?.length ? [...agentsFirst, ''] : []), bold(headline(p))];
917
+ // What's wrong comes before anything else, so it can't be missed. The person sees what has
918
+ // cleared up as one count, not a line each.
919
+ const listed = scanAlerts({ s, cfg, hist, m, t }).filter(a => onBoard(a, t));
920
+ const cleared = agentsFirst ? listed.filter(a => a.resolvedAt) : [];
921
+ if (cleared.length) out.push(dim(`${cleared.length} alert${cleared.length === 1 ? '' : 's'} cleared since ${clock(Math.min(...cleared.map(a => a.resolvedAt)))}.`));
922
+ const alerted = alertLines(listed.filter(a => !cleared.includes(a)), t);
769
923
  if (alerted.length) out.push('', ...alerted, '');
770
924
  // An agent reading the board wants its own place first.
771
925
  if (agent) {
@@ -780,8 +934,13 @@ function plainStatus(s, cfg, hist, m, t, rc, away, broken, me) {
780
934
  const count = (n, w) => `${n} ${w}${n > 1 ? 's' : ''}`;
781
935
  if (asks && !notes) out.push(amber(`${count(asks, 'question')} ${asks > 1 ? 'are' : 'is'} waiting for your answer: dibs questions`));
782
936
  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`));
937
+ const h = halted(s, t);
938
+ if (h) out.push(amber(`No new dibs job starts ${haltUntil(h)} (set by ${haltBy(h)}). Running jobs go on. Lift it: dibs halt off`));
783
939
  const ears = listeners();
784
940
  if (ears.length) out.push(dim(`Listening for messages (dibs tell reaches them within seconds): ${ears.join(', ')}`));
941
+ const byProject = new Map();
942
+ for (const x of projectsNow()) byProject.set(x.project, [...(byProject.get(x.project) || []), x.agent]);
943
+ if (byProject.size) out.push(dim(`Projects: ${[...byProject].map(([p, a]) => `${p} (${a.join(', ')})`).join('; ')}`));
785
944
  const { busy, free } = lineParts(p);
786
945
  out.push('', ...columns([...busy.map(b => [b.label, b.now, b.next]), ...(free.length ? [['Free', dim(freeText(p, free))]] : [])]));
787
946
 
@@ -795,8 +954,8 @@ function plainStatus(s, cfg, hist, m, t, rc, away, broken, me) {
795
954
  const GB = b => gb(b).replace(/G$/, ' GB');
796
955
  // The same reason the wait lines give (plain.mjs machineHold), worded so nobody reads it as a cue to raise priority.
797
956
  const hold = machineHold(s, cfg, m);
798
- 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';
799
- const holdBack = hold ? `Nothing new starts until ${hold}. Keep waiting: raising the priority is not the fix` : '';
957
+ const feel = h ? 'holding new jobs' : 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';
958
+ const holdBack = hold && !h ? `Nothing new starts until ${hold}. Keep waiting: raising the priority is not the fix` : '';
800
959
  const outside = untracked(s);
801
960
  const subs = agentsNow(cfg);
802
961
  const mine = new Map();
@@ -814,7 +973,16 @@ function plainStatus(s, cfg, hist, m, t, rc, away, broken, me) {
814
973
  q.error || `${q.left} of ${q.limit} left, refills to ${q.limit} every ${minutes(q.per).replace(/^1 hr$/, 'hour').replace(/^1 min$/, 'minute')}`]),
815
974
  ...(mine.size ? [['Subagents', `${subs.running.length} of ${subs.slots} running (${[...mine].map(([who, k]) => `${k} for ${who}`).join(', ')})`]] : []),
816
975
  ];
976
+ // Work items and handoffs (src/work.mjs): in flight, then what closed lately and its proof.
977
+ const items = workNow(t);
978
+ if (items.length) out.push('', ...columns([['Work', ...items.map(i => workLine(i, t))]]));
979
+ const reviews = reviewsNow(t);
980
+ if (reviews.length) out.push('', ...columns([['Reviews', ...reviews.map(x => reviewLine(x, t))]]));
817
981
  // Runs scheduled with dibs later, soonest first: what, then when.
982
+ // Runs and holds waiting for another job to end before they get in line.
983
+ const after = aftersNow(s, t);
984
+ if (after.length) out.push('', ...columns([['After', ...after.flatMap(a => [`#${a.id}: ${tag(a)}'s "${a.purpose}" for ${a.res.map(r => named(cfg, r).the).join(' and ')}`,
985
+ dim(` ${afterText(a)} (${a.deps.map(d => `${d.who}'s "${d.purpose || d.res.join(',')}"`).join(', ') || 'gone'}), waiting ${minutes(a.waited)}`)])]]));
818
986
  const later = laterBoard(t).map(v => laterPlain(v, cfg));
819
987
  if (later.length) out.push('', ...columns([['Later', ...later.flatMap(x => [x.what, dim(` ${x.when}`)])]]));
820
988
  out.push('', ...columns(rows));