@dibssoftware/dibs 0.0.0-stage → 0.0.178

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 (72) hide show
  1. package/CHANGELOG.md +577 -0
  2. package/LICENSE +670 -0
  3. package/README.md +234 -2
  4. package/bin/dibs-guard.mjs +7 -0
  5. package/bin/dibs.mjs +526 -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/relay.md +196 -0
  13. package/docs/releasing.md +25 -0
  14. package/docs/scheduling.md +163 -0
  15. package/docs/simulators.md +17 -0
  16. package/package.json +44 -4
  17. package/skills/dibs/SKILL.md +162 -0
  18. package/src/acquire.mjs +697 -0
  19. package/src/admin.mjs +145 -0
  20. package/src/agents.mjs +145 -0
  21. package/src/alerts.mjs +437 -0
  22. package/src/answers.mjs +65 -0
  23. package/src/board.mjs +202 -0
  24. package/src/broker.mjs +369 -0
  25. package/src/commands.mjs +801 -0
  26. package/src/config.mjs +320 -0
  27. package/src/connect.mjs +106 -0
  28. package/src/cool.mjs +160 -0
  29. package/src/diskwarn.mjs +161 -0
  30. package/src/events.mjs +94 -0
  31. package/src/files.mjs +1100 -0
  32. package/src/guard.mjs +583 -0
  33. package/src/history.mjs +247 -0
  34. package/src/hogs.mjs +214 -0
  35. package/src/later.mjs +487 -0
  36. package/src/measure.mjs +262 -0
  37. package/src/nodecheck.mjs +17 -0
  38. package/src/notices.mjs +121 -0
  39. package/src/ondemand.mjs +572 -0
  40. package/src/overlap.mjs +151 -0
  41. package/src/override.mjs +351 -0
  42. package/src/owner.mjs +30 -0
  43. package/src/plain.mjs +467 -0
  44. package/src/platform.mjs +357 -0
  45. package/src/preempt.mjs +438 -0
  46. package/src/primer.mjs +61 -0
  47. package/src/proc.mjs +98 -0
  48. package/src/progress.mjs +158 -0
  49. package/src/qr.mjs +204 -0
  50. package/src/questions.mjs +389 -0
  51. package/src/quota.mjs +81 -0
  52. package/src/reads.mjs +54 -0
  53. package/src/relay.mjs +779 -0
  54. package/src/remote.mjs +584 -0
  55. package/src/reset.mjs +127 -0
  56. package/src/schedule.mjs +995 -0
  57. package/src/scratch.mjs +61 -0
  58. package/src/serve.mjs +736 -0
  59. package/src/service.mjs +221 -0
  60. package/src/shard.mjs +59 -0
  61. package/src/simctl.mjs +42 -0
  62. package/src/simpool.mjs +258 -0
  63. package/src/state.mjs +201 -0
  64. package/src/stats.mjs +328 -0
  65. package/src/style.mjs +44 -0
  66. package/src/talk.mjs +523 -0
  67. package/src/thin.sh +130 -0
  68. package/src/trust.mjs +152 -0
  69. package/src/util.mjs +184 -0
  70. package/src/version.mjs +2 -0
  71. package/src/web.mjs +1117 -0
  72. package/src/worker.mjs +318 -0
@@ -0,0 +1,262 @@
1
+ const GB = b => gb(b).replace(/G$/, ' GB');
2
+ // What jobs really use. A job's memory (--mem, or its resource's default) is
3
+ // a guess, and macOS can't cap a process tree without root, so instead of a
4
+ // cage this keeps the numbers honest: each running lease's tree is measured,
5
+ // its peak goes into history with its run time, and the next run of the same
6
+ // command is planned at what it really took.
7
+ //
8
+ // Memory is physical footprint (src/platform.mjs footprints), CPU is the
9
+ // process table's % of a core, both summed over every process group the lease
10
+ // spans plus, for a pool simulator, the simulator's own launchd_sim tree,
11
+ // which runs outside the job's. Reading footprints costs a top call, so
12
+ // it's taken at most once per SAMPLE_EVERY across the machine: whichever
13
+ // `dibs run` claims the slot measures every lease at once.
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { HOME, paths, hardware, machine } from './config.mjs';
17
+ import { processes, footprints, OS } from './platform.mjs';
18
+ import { withStateIfRoom } from './state.mjs';
19
+ import { gb, now, bytes, runsOf, say, KEY_SPLIT } from './util.mjs';
20
+ import { event } from './events.mjs';
21
+
22
+ // top costs about 0.3s of CPU per call, so 10s keeps it near 3% of one core
23
+ // while anything runs, and nothing while nothing does. A build's peak lasts
24
+ // longer than that; a spike shorter than it can be missed.
25
+ export const SAMPLE_EVERY = Number(process.env.DIBS_SAMPLE_MS) || 10e3;
26
+ // The learned size is the most any of the last few measured runs used: one
27
+ // light run doesn't undo a heavy one, and a command that got lighter is
28
+ // believed after this many runs.
29
+ const LEARN_RUNS = 5;
30
+
31
+ // One process per slot wins the right to measure. The file name is the slot,
32
+ // and creating it fails for everyone else.
33
+ function claim(t) {
34
+ const slot = Math.floor(t / SAMPLE_EVERY);
35
+ try { fs.writeFileSync(path.join(HOME, `sample-${slot}`), '', { flag: 'wx' }); } catch { return false; }
36
+ try { for (const f of fs.readdirSync(HOME)) if (/^sample-\d+$/.test(f) && f !== `sample-${slot}`) fs.rmSync(path.join(HOME, f), { force: true }); } catch {}
37
+ return true;
38
+ }
39
+
40
+ // Every pid that belongs to a lease: its process groups, less those of runs
41
+ // nested in it, and the launchd_sim tree of any pool simulator it's using (its
42
+ // own, or its session's hold's).
43
+ export function treeOf(l, s, procs) {
44
+ const groups = new Set([l.pgid, ...(l.groups || [])].filter(Boolean));
45
+ // A dibs run nested in this one (a ship calling dibs run xcode-build) shows
46
+ // up among its groups, but it's measured as its own lease: counting it here
47
+ // too would plan and flag the outer job at the inner one's size.
48
+ for (const x of s.leases || [])
49
+ if (x.id !== l.id && x.kind === 'run' && x.pgid && x.pgid !== l.pgid && groups.has(x.pgid))
50
+ for (const g of [x.pgid, ...(x.groups || [])]) groups.delete(g);
51
+ const pids = new Set(procs.filter(p => groups.has(p.pgid)).map(p => p.pid));
52
+ const holds = new Set(s.leases.filter(h => h.kind === 'hold' && h.pid && h.pid === l.spid).map(h => h.id));
53
+ // A hold's simulator counts in one of the runs under it, the first: two test
54
+ // runs on one held simulator each counting it charged it twice.
55
+ const first = d => !(s.leases || []).some(x => x.kind === 'run' && x.id < l.id && x.spid === l.spid && x.covered?.includes(d.res));
56
+ const udids = (s.pool || []).filter(d => d.udid && (d.lease === l.id || (holds.has(d.lease) && l.covered?.includes(d.res) && first(d)))).map(d => d.udid);
57
+ // The shared simulator (sim) is whichever booted one the pool didn't make. A
58
+ // job holding it does its work there, outside its own groups: on 2026-11-02 a
59
+ // TestFlight ship measured 0.1 GB and no CPU for 40 minutes while it ran in
60
+ // the simulator, so dibs took it for idle and planned it at nothing.
61
+ const pooled = (s.pool || []).map(d => d.udid).filter(Boolean);
62
+ const shared = l.res?.includes('sim') || (l.covered?.includes('sim') && first({ res: 'sim' }));
63
+ if (!udids.length && !shared) return pids;
64
+ const kids = new Map();
65
+ for (const p of procs) { if (!kids.has(p.ppid)) kids.set(p.ppid, []); kids.get(p.ppid).push(p.pid); }
66
+ const mine = p => (udids.some(u => p.args.includes(`/${u}/`)) || (shared && !pooled.some(u => p.args.includes(`/${u}/`))));
67
+ const stack = procs.filter(p => /\blaunchd_sim\b/.test(p.args) && mine(p)).map(p => p.pid);
68
+ while (stack.length) {
69
+ const pid = stack.pop();
70
+ if (pids.has(pid)) continue;
71
+ pids.add(pid);
72
+ stack.push(...(kids.get(pid) || []));
73
+ }
74
+ return pids;
75
+ }
76
+
77
+ // Memory in bytes and CPU in cores for a set of pids. A process top didn't
78
+ // list (it started since) counts at its RSS.
79
+ export function usage(pids, procs, foot) {
80
+ let mem = 0, cpu = 0;
81
+ for (const p of procs) {
82
+ if (!pids.has(p.pid)) continue;
83
+ mem += foot?.get(p.pid) ?? p.rss ?? 0;
84
+ cpu += p.cpu / 100;
85
+ }
86
+ return { mem, cpu: Math.round(cpu * 10) / 10 };
87
+ }
88
+
89
+ // Jobs can't use more memory than the machine has in use. Footprints count
90
+ // memory processes share (a browser's GPU and IPC buffers) once per process:
91
+ // on 2026-10-20 Playwright runs read 11 to 13 GB while the 16 GB Mac had more
92
+ // than half its memory free, and every later browser run was planned at the
93
+ // whole budget. When the jobs' sum is more than what's in use, each is scaled
94
+ // down by the same share.
95
+ export function fit(got, m = machine()) {
96
+ if (m.memFree == null) return;
97
+ const inUse = (m.memTotal || hardware().mem) * (1 - m.memFree / 100);
98
+ const total = [...got.values()].reduce((a, u) => a + u.mem, 0);
99
+ if (!(total > inUse)) return;
100
+ for (const u of got.values()) u.mem = Math.round(u.mem * inUse / total);
101
+ }
102
+
103
+ // What each run ate of free disk: every fall between two measurements, less
104
+ // what swap grew by (that's memory, not anyone's files: the swap files' size where
105
+ // the OS says it, since macOS adds a gigabyte file before it's used), shared among the runs
106
+ // measured then, by the disk their resources declare (DISK_WEIGHT at least).
107
+ // Crediting each run with the whole fall, as 0.0.153 did, gave a deploy 3 GB
108
+ // for a simulator's writes and held it on the disk. A rise frees nobody's share.
109
+ const DISK_WEIGHT = 0.25 * 1024 ** 3;
110
+ function shareDisk(s, got, m, t) {
111
+ const last = s.diskSample;
112
+ s.diskSample = { free: m.diskFree ?? null, swap: m.swapUsed ?? null, ...(m.swapFiles != null && { files: m.swapFiles }), at: t };
113
+ const runs = s.leases.filter(l => got.has(l.id) && !l.pausedAt);
114
+ for (const l of runs) l.ate ??= 0;
115
+ if (!last || last.free == null || m.diskFree == null || t - last.at > 3 * SAMPLE_EVERY) return;
116
+ const swapGrew = Math.max(0, last.swap != null && m.swapUsed != null ? m.swapUsed - last.swap : 0,
117
+ last.files != null && m.swapFiles != null ? m.swapFiles - last.files : 0);
118
+ const fell = Math.max(0, last.free - m.diskFree - swapGrew);
119
+ if (!fell || !runs.length) return;
120
+ const w = l => Math.max(l.disk || 0, DISK_WEIGHT);
121
+ const all = runs.reduce((a, l) => a + w(l), 0);
122
+ for (const l of runs) l.ate += fell * w(l) / all;
123
+ }
124
+
125
+ // Measure every run lease on the machine, if this process won the slot.
126
+ // Called from each `dibs run` on its group-tracking tick. True if it measured.
127
+ export function sample(t = now()) {
128
+ if (OS === 'windows' || !claim(t)) return false;
129
+ // A plain read: the state file is replaced whole, never written in place.
130
+ let s;
131
+ try { s = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch { return false; }
132
+ const runs = (s.leases || []).filter(l => l.kind === 'run' && l.pgid);
133
+ if (!runs.length) return false;
134
+ const procs = processes();
135
+ const trees = new Map(runs.map(l => [l.id, treeOf(l, s, procs)]));
136
+ const foot = footprints([...new Set([...trees.values()].flatMap(x => [...x]))]);
137
+ const got = new Map([...trees].map(([id, pids]) => [id, usage(pids, procs, foot)]));
138
+ const mm = machine();
139
+ // Made-up footprints come with a made-up machine that doesn't match them.
140
+ if (!process.env.DIBS_FAKE_FOOTPRINT) fit(got);
141
+ // On a full disk this measurement is dropped; the next slot takes another.
142
+ const tell = withStateIfRoom(s => {
143
+ const out = [];
144
+ shareDisk(s, got, mm, t);
145
+ for (const l of s.leases) {
146
+ const u = got.get(l.id);
147
+ if (!u) continue;
148
+ l.use = { ...u, at: t };
149
+ // When its memory last rose past what it had reached: a job let in by the
150
+ // stall breaker counts as settled once this is a while ago (schedule.mjs).
151
+ if (!(u.mem <= (l.peak?.mem ?? -1) * 1.05)) l.peakAt = t;
152
+ l.peak = { mem: Math.max(l.peak?.mem || 0, u.mem), cpu: Math.max(l.peak?.cpu || 0, u.cpu), fit: true,
153
+ ...(l.ate != null && { ate: l.ate }) };
154
+ const x = overAsk(l);
155
+ if (!x) continue;
156
+ if (!l.overAsk) {
157
+ event({ kind: 'overask', id: l.id, res: l.res, who: l.who, agent: l.agent, sessionId: l.sessionId, key: l.key, ...x });
158
+ if (l.notify && l.pid) out.push(l.pid);
159
+ }
160
+ l.overAsk = { ...x, at: l.overAsk?.at ?? t };
161
+ }
162
+ return out;
163
+ }) || [];
164
+ // The run's own dibs says it on its stderr (src/preempt.mjs noticeHandler), once the state has it.
165
+ for (const pid of tell) try { process.kill(pid, 'SIGUSR2'); } catch {}
166
+ return true;
167
+ }
168
+
169
+ // A job that used far more memory than it asked for: what it used, what it
170
+ // asked, what dibs planned and the --mem to pass next time, or null. Over
171
+ // OVER_ASK times its plan and by OVER_ASK_MIN or more: footprints wobble, and
172
+ // half a gigabyte over on a small job isn't worth an agent's attention. A job
173
+ // dibs already plans at the whole budget (usual) has nothing better to ask for.
174
+ const OVER_ASK = 1.5;
175
+ const OVER_ASK_MIN = 1024 ** 3;
176
+ export function overAsk(l) {
177
+ const used = Math.max(l?.peak?.mem || 0, l?.use?.mem || 0);
178
+ if (!l || l.usual != null || !(l.mem > 0) || used < l.mem * OVER_ASK || used - l.mem < OVER_ASK_MIN) return null;
179
+ return { used, asked: l.asked ?? l.mem, planned: l.mem, suggest: `${Math.ceil(used / 1024 ** 3)}G` };
180
+ }
181
+ // Running leases that used far more than they asked, with overAsk on each: for the hook's notice to the holder.
182
+ export const overAsks = s => s.leases.filter(l => l.overAsk);
183
+ export const overAskLine = x => `this job used ${GB(x.used)} of memory but asked for ${GB(x.asked)}${x.planned > x.asked ? ` (dibs planned ${GB(x.planned)})` : ''}.`
184
+ + ` Next time pass --mem ${x.suggest}, so dibs plans for it and doesn't start other jobs into memory this one will take.`;
185
+ // Said once per run, on its stderr: while it runs (the sampler's SIGUSR2) or when it ends.
186
+ let told = false;
187
+ export function tellOverAsk(l) {
188
+ const x = l && (l.overAsk || overAsk(l));
189
+ if (told || !x) return;
190
+ told = true;
191
+ say(overAskLine(x));
192
+ }
193
+
194
+ // The most the last LEARN_RUNS measured runs of a command used, never more
195
+ // than the machine has, or null when none was measured.
196
+ // A command never measured borrows from its family: the same resources,
197
+ // program and next word (util.mjs KEY_SPLIT), so npx playwright test a.spec.ts
198
+ // learns from b.spec.ts. On 2026-10-15 each Playwright spec ran under its own
199
+ // key, used 5.5 GB of the 3 GB asked, and none ever learned it. The next word
200
+ // matters for wrappers: npm run build and npm run lint, or wrangler d1 and
201
+ // wrangler deploy, are different programs, and a family of just the wrapper
202
+ // lent one's size to the others.
203
+ function family(key) {
204
+ const [head, more = ''] = String(key).split(KEY_SPLIT);
205
+ const next = more.split(' ')[0];
206
+ return next ? `${head}${KEY_SPLIT}${next}` : head;
207
+ }
208
+ // Only runs measured with fit() count: earlier ones counted shared memory in
209
+ // every process, and planned browser runs at three times what they used.
210
+ export function learned(hist, key, cores = hardware().cores) {
211
+ let runs = runsOf(hist, key).filter(h => h.mem > 0 && h.fit);
212
+ if (!runs.length) runs = hist.filter(h => h.mem > 0 && h.fit && family(h.key) === family(key));
213
+ runs = runs.slice(-LEARN_RUNS);
214
+ if (!runs.length) return null;
215
+ // The middle run, not the biggest: one run that read 15 GB (a browser's shared
216
+ // memory counted in every process) planned every later Playwright run at the
217
+ // whole budget on 2026-10-20, and twenty jobs waited on a Mac with 8.6 GB free.
218
+ // A run that outgrows its plan books what it uses anyway (memOf).
219
+ const mems = runs.map(h => h.mem).sort((a, b) => a - b);
220
+ const mem = mems[Math.floor(mems.length / 2)];
221
+ return { mem: Math.min(mem, hardware().mem), cpu: Math.min(Math.max(...runs.map(h => h.cpu || 0)), cores) };
222
+ }
223
+
224
+ // A job's size as dibs plans it: what it asked for, raised to what its
225
+ // command has really used. asked and askedCpu keep the declared numbers. A
226
+ // command that has used more than the whole memory budget is planned at the
227
+ // budget, with usual saying what it used: it waits for the budget to empty,
228
+ // not for a machine with no leases at all.
229
+ export function sized(size, hist, key, cfg) {
230
+ const got = learned(hist, key, cfg.cores);
231
+ if (!got) return size;
232
+ const out = { ...size };
233
+ const budget = bytes(cfg.budget);
234
+ if (got.mem > size.mem) Object.assign(out, got.mem > budget && size.mem <= budget ? { mem: budget, asked: size.mem, usual: got.mem } : { mem: got.mem, asked: size.mem });
235
+ // Like memory: a learned number past the CPU budget is planned at the budget, so the job can still start alone.
236
+ if (Math.ceil(got.cpu) > size.cpu) Object.assign(out, { cpu: size.cpu <= cfg.cores ? Math.min(Math.ceil(got.cpu), cfg.cores) : Math.ceil(got.cpu), askedCpu: size.cpu });
237
+ return out;
238
+ }
239
+
240
+ // "uses ~6.1G (asked 4.0G) and 5 cores (asked 3)", or for a job planned at
241
+ // the budget "usually uses ~14.1G and 8 cores (asked 4); planned at the 11.0G
242
+ // budget", or '' when it fits what it asked.
243
+ export const cappedLine = x => (x.usual != null ? `usually uses ~${gb(x.usual)}; planned at the ${gb(x.mem)} budget` : '');
244
+ // The same, in a sentence: "xcodebuild used up to 6.0 GB of memory in recent
245
+ // runs (it asks for 4.0 GB), so dibs plans for that." A job bigger than all
246
+ // the memory dibs shares out is planned at all of it, and waits for it to be free.
247
+ export function grewPlain(x, key) {
248
+ const what = key.replace(KEY_SPLIT, ' ');
249
+ const cores = x.askedCpu != null ? `${x.cpu} cores (it asks for ${x.askedCpu})` : '';
250
+ if (x.usual != null)
251
+ return `${what} usually uses up to ${GB(x.usual)} of memory${cores ? ` and ${cores}` : ''}, more than the ${GB(x.mem)} dibs shares out at once,`
252
+ + ` so dibs plans it at all ${GB(x.mem)}: it starts when no other job is using that memory.`;
253
+ const parts = [x.asked != null ? `${GB(x.mem)} of memory (it asks for ${GB(x.asked)})` : '', cores].filter(Boolean);
254
+ return parts.length ? `${what} used up to ${parts.join(' and ')} in recent runs, so dibs plans for that.` : '';
255
+ }
256
+
257
+ export function grewLine(x) {
258
+ const cores = x.askedCpu != null ? `${x.cpu} cores (asked ${x.askedCpu})` : '';
259
+ if (x.usual != null) return `usually uses ~${gb(x.usual)}${cores ? ` and ${cores}` : ''}; planned at the ${gb(x.mem)} budget`;
260
+ const parts = [x.asked != null ? `~${gb(x.mem)} (asked ${gb(x.asked)})` : '', cores].filter(Boolean);
261
+ return parts.length ? `uses ${parts.join(' and ')}` : '';
262
+ }
@@ -0,0 +1,17 @@
1
+ // Node versions with a known hole dibs shouldn't run its long-lived parts on.
2
+ // CVE-2026-111497 ("Node2Shell", 2026-10-21): an out-of-bounds write in the
3
+ // Brotli decoder, reachable through any br-encoded body. Fixed in 22.23.4,
4
+ // 24.22.1 and 26.12.1; other lines older than 27 get no fix.
5
+ const FIXED = { 22: [22, 23, 4], 24: [24, 22, 1], 26: [26, 12, 1] };
6
+ const FIRST_SAFE_MAJOR = 27;
7
+
8
+ // null when this Node is fine, else a sentence saying why it isn't.
9
+ export function unpatched(version = process.versions.node) {
10
+ const v = String(version).replace(/^v/, '').split('.').map(Number);
11
+ const fix = FIXED[v[0]];
12
+ const why = `Node ${v.join('.')} has the Brotli hole CVE-2026-111497`;
13
+ if (v[0] >= FIRST_SAFE_MAJOR) return null;
14
+ if (!fix) return `${why}, and Node ${v[0]} gets no fix. Use Node 22.23.4, 24.22.1, 26.12.1 or newer`;
15
+ for (let i = 1; i < 3; i++) if (v[i] !== fix[i]) return v[i] > fix[i] ? null : `${why}. Upgrade to ${fix.join('.')} or newer`;
16
+ return null;
17
+ }
@@ -0,0 +1,121 @@
1
+ // Notices about an agent's own jobs, left in its inbox (src/talk.mjs) so the
2
+ // guard hook hands each over once, beside its next tool call. Most agents have
3
+ // nobody watching the board for them: this is how they hear that a job of
4
+ // theirs looks stuck while others wait, used far more memory than it asked
5
+ // for, or was paused for low disk or memory and shouldn't be run again.
6
+ //
7
+ // The scan reads state.json without its lock (writes are renames, so it is
8
+ // always whole) and runs from processes that are alive anyway: every waiting
9
+ // dibs and every running one. Each notice has a name (idle:#12), so however
10
+ // many of them scan, an agent hears about each thing once.
11
+ import fs from 'node:fs';
12
+ import { paths } from './config.mjs';
13
+ import { notify } from './talk.mjs';
14
+ import { minutes, stuckFor } from './plain.mjs';
15
+ import { stuckLeases } from './acquire.mjs';
16
+ import { overAskLine } from './measure.mjs';
17
+ import { now, callerPid, clock } from './util.mjs';
18
+ import { read as readPosts, tasks, QUIET_AFTER } from './progress.mjs';
19
+ import { quoted } from './style.mjs';
20
+
21
+ // Which runs look stuck and which used more memory than they asked for is
22
+ // decided where the board decides it (stuckLeases, l.overAsk), so the notice
23
+ // and the board never disagree. This file only delivers.
24
+ // How often one process looks. The facts change on a scale of minutes.
25
+ export const NOTICE_EVERY = 20e3;
26
+
27
+ let last = 0;
28
+ const sent = new Set();
29
+
30
+ const what = l => `#${l.id} (${l.purpose ? `"${l.purpose}", ` : ''}${(l.cmd || l.res.join(',')).slice(0, 60)})`;
31
+
32
+ // [lease, once, text] for each notice the state holds, for the lease's agent.
33
+ export function noticesIn(s, t = now()) {
34
+ const out = [];
35
+ const waiting = (s.queue || []).filter(q => q.pid);
36
+ const stuck = new Set(stuckLeases({ queue: [], leases: [], ...s }, t));
37
+ for (const l of s.leases || []) {
38
+ const others = waiting.filter(q => q.res.some(r => l.res.includes(r)));
39
+ if (stuck.has(l) && others.length)
40
+ out.push([l, `idle:#${l.id}`, `your job ${what(l)} has used no CPU for ${minutes(stuckFor(l, t))} while ${others.length} other `
41
+ + `${others.length === 1 ? 'job waits' : 'jobs wait'} for ${l.res.join(', ')}. If it's stuck, end it: stop the tool call or background task `
42
+ + `running it, or kill ${l.pid} (its dibs run, which takes the whole job down and frees the turn). If it's still working, leave it.`]);
43
+ if (l.overAsk?.used && l.overAsk.asked && l.overAsk.suggest)
44
+ out.push([l, `mem:#${l.id}`, `your job ${what(l)}: ${overAskLine(l.overAsk)}`]);
45
+ if (l.loadPast)
46
+ out.push([l, `loadpast:#${l.id}`, `your job ${what(l)} waited ${minutes(l.loadWaited || 0)} for the machine's load to fall, so it started anyway at background priority on the efficiency cores. `
47
+ + 'It runs slower there. If a person is waiting on it now, raise it: dibs boost ' + l.id + ' high -m "why".']);
48
+ const watcher = (l.pauses || []).filter(p => p.watcher && !p.gone);
49
+ if (l.pausedAt && watcher.length)
50
+ out.push([l, `paused:#${l.id}:${l.pausedAt}`, `your job ${what(l)} was paused because free ${watcher.some(p => p.disk) ? 'disk' : 'memory'} is low. `
51
+ + "It keeps its turn and resumes by itself when there's room: don't run it again or end it."]);
52
+ }
53
+ return out;
54
+ }
55
+
56
+ // Leave the notices the state holds, at most every NOTICE_EVERY ms from this process.
57
+ // Never throws: a notice is a nicety, and its callers are mid-wait or mid-run.
58
+ export function noticeScan(t = now()) {
59
+ if (t - last < NOTICE_EVERY) return;
60
+ last = t;
61
+ try {
62
+ const s = JSON.parse(fs.readFileSync(paths.state, 'utf8'));
63
+ for (const [l, once, text] of noticesIn(s, t)) {
64
+ if (sent.has(once)) continue;
65
+ sent.add(once);
66
+ notify(l, once, text);
67
+ }
68
+ } catch {}
69
+ }
70
+
71
+ // [to, once, text] for each task still in progress that needs a word from its
72
+ // agent: past its ETA, or with no post for QUIET_AFTER. Expired tasks are let go.
73
+ // Only tasks posted from a Claude Code session: the hook is how the notice arrives.
74
+ export function progressNoticesIn(posts, t = now()) {
75
+ const out = [];
76
+ for (const k of tasks(posts, t)) {
77
+ if (k.state !== 'doing' || !k.session) continue;
78
+ const to = { sessionId: k.session, who: k.who };
79
+ const name = k.task ? `"${k.task}"` : `in ${k.project || 'this folder'}`;
80
+ const again = (...more) => quoted(['dibs', 'progress', 'where it stands', ...(k.task ? ['--task', k.task] : []), ...more]);
81
+ if (k.overdue) out.push([to, `late:${k.who}:${k.task || k.project}:${k.eta}`, `your progress task ${name} was due at ${clock(k.eta)} and is still open. `
82
+ + `If it's finished, say so: ${again('--done')}. If not, post where it stands with a new time: ${again('--eta', '30m')}.`]);
83
+ else if (t - k.last > QUIET_AFTER) out.push([to, `quiet:${k.who}:${k.task || k.project}:${k.last}`, `your progress task ${name} has had no post for ${minutes(t - k.last)}. `
84
+ + `Post where it stands (${again()}), or close it: --done if it's finished, --blocked if it's stuck.`]);
85
+ }
86
+ return out;
87
+ }
88
+
89
+ const DAY = 864e5;
90
+ // From the throttle watcher (src/cool.mjs), which is always running: no waiter needed.
91
+ export function progressScan(t = now()) {
92
+ try {
93
+ for (const [to, once, text] of progressNoticesIn(readPosts({ since: t - DAY }), t)) {
94
+ if (sent.has(once)) continue;
95
+ sent.add(once);
96
+ notify(to, once, text);
97
+ }
98
+ } catch {}
99
+ }
100
+
101
+ // The same command from the same agent, already waiting or running, started
102
+ // by another tool call: almost always a retry after Claude Code moved the
103
+ // first call to the background. Running it again would run it twice, so the
104
+ // second copy refuses (exit 2) and says where the first one is. A copy from
105
+ // the same shell (a script starting several at once) has the same parent and
106
+ // isn't a retry; neither is one with a different -m, which is how an agent
107
+ // asks for a second copy on purpose. Entries from before 0.0.86 carry no
108
+ // parent or folder and never match. Returns { id, text }: the first copy's id and what to say.
109
+ export function twinOf(s, o, id, t = now()) {
110
+ const cmd = (o.cmd || []).join(' ');
111
+ const res = [...o.res].sort().join();
112
+ const same = x => x.cmd === cmd && [...x.res].sort().join() === res && (x.purpose || '') === (o.purpose || '')
113
+ && x.cwd === process.cwd() && x.ppid && x.ppid !== callerPid()
114
+ && (id.spid ? x.spid === id.spid && (x.agentId || null) === (o.agentId || null) : !x.spid && x.who === id.who);
115
+ const x = (s.leases || []).find(l => l.kind === 'run' && same(l)) || (s.queue || []).find(q => q.pid && same(q));
116
+ if (!x) return null;
117
+ const running = !!(s.leases || []).includes(x);
118
+ return { id: x.id, text: `you already have this exact command ${running ? `running as #${x.id} (for ${minutes(t - x.start)})` : `waiting in line as #${x.id}`}, `
119
+ + 'from an earlier call. Nothing ran here (exit 2): a second copy would run it twice. That earlier call reports when it ends; '
120
+ + "if it went to the background, wait for its notice instead of running it again. To run a second copy at the same time on purpose, give it a different -m." };
121
+ }