@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
package/src/alerts.mjs ADDED
@@ -0,0 +1,499 @@
1
+ // dibs alerts: nothing goes wrong quietly. On 2026-11-02 the person learned
2
+ // from a screenshot of another agent that every deploy had waited 40 minutes
3
+ // behind one TestFlight ship, and that swap had held up every test run for
4
+ // half an hour; nothing had told them. Each alert here names its cause and the
5
+ // one thing that fixes it, shows once, stays until the cause is gone, and then
6
+ // says when it went. The board, the page and the Mac app all show the same
7
+ // list; the app turns a new one into a notification, at most one per cause
8
+ // every 30 minutes.
9
+ //
10
+ // Six causes:
11
+ // wait a job waiting far longer than usual, worst when a person waits on it
12
+ // memory memory pressure or swap holding new jobs back, with what to close
13
+ // idle a slot held by a job that has done nothing for a long time
14
+ // ended jobs that failed, were stopped, or were lost on another machine
15
+ // dibs dibs itself: a service down or restarting, a crash, the hook failing
16
+ // disk free disk under the floor
17
+ //
18
+ // alerts.json keeps the open ones, the resolved ones for a day, and what the
19
+ // scan needs between runs: how far into the event log and the hook's log it
20
+ // has read, recent waits per resource, and the services' start counts. Every
21
+ // process that shows the board scans at most every SCAN_EVERY, and so does the
22
+ // throttle watcher, so alerts keep up even when nobody looks.
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+ import { HOME, machine } from './config.mjs';
26
+ import { verdict } from './schedule.mjs';
27
+ import { stuckFor, minutes, andList } from './plain.mjs';
28
+ import { processes, memoryUse } from './platform.mjs';
29
+ import { treeOf } from './measure.mjs';
30
+ import { withState, history } from './state.mjs';
31
+ import { markIdle } from './acquire.mjs';
32
+ import { sessionFiles } from './proc.mjs';
33
+ import { EVENTS } from './events.mjs';
34
+ import { serviceHealth } from './service.mjs';
35
+ import { hogHint } from './hogs.mjs';
36
+ import { now, bytes, clock, gb, die } from './util.mjs';
37
+ import { dim, red, amber, wrap } from './style.mjs';
38
+
39
+ export const FILE = path.join(HOME, 'alerts.json');
40
+ const LOCK = path.join(HOME, 'alerts.lock');
41
+ const GUARD_LOG = path.join(HOME, 'guard.log');
42
+ const MIN = 6e4, HOUR = 36e5, DAY = 864e5;
43
+
44
+ // Reads are cheap but not free (a verdict per waiter, the tail of two logs);
45
+ // the app polls every 2 s, so a scan stands for this long.
46
+ const SCAN_EVERY = 15e3;
47
+ // A wait is long past this, or past WAIT_TIMES its usual wait, whichever is later.
48
+ const WAIT_FLOOR = 10 * MIN;
49
+ const WAIT_TIMES = 3;
50
+ // Waits remembered per resource for "usual": enough for a median that one odd day doesn't move.
51
+ const WAITS_KEPT = 40;
52
+ // Memory holding jobs back must last this long before it's an alert: a build's peak passes in a minute or two.
53
+ const PRESSURE_AFTER = 10 * MIN;
54
+ // The machine-wide memory reading costs about half a second of top: once a minute at most, only while it matters.
55
+ const TOP_EVERY = MIN;
56
+ // A failure, a lost job or a crash stays a day unless it's resolved sooner.
57
+ const EVENT_KEEP = DAY;
58
+ // A restart or a hook failure counts as over once this long passes without another.
59
+ const CALM_AFTER = HOUR;
60
+ // launchctl costs a process per service: once a minute.
61
+ const SERVICES_EVERY = MIN;
62
+ // Resolved alerts the board and the app still show, so the person sees it went away.
63
+ export const RESOLVED_SHOWN = 2 * HOUR;
64
+ // The first read of the event log starts this far from its end, not at its start: the log runs to 20 MB.
65
+ const FIRST_READ = 2 * 1024 ** 2;
66
+ // The rules a waiter is held by when the machine's memory, not a turn or dibs's budget, is in the way.
67
+ const PRESSURE = new Set(['pressure', 'swap', 'swaproom', 'ram', 'oversize']);
68
+ // Bumped when what makes an alert changes, so an upgrade rebuilds the open ones instead of closing them.
69
+ const RULES = 2;
70
+ // The same command failing this many times in a row, with no pass between, is worth the person's attention.
71
+ const REPEATS = 3;
72
+ // Exit codes a stopped command dies with: Ctrl-C, SIGKILL, SIGTERM.
73
+ const STOPPED = new Set([130, 137, 143]);
74
+
75
+ // A time as the person reads it: the clock today, with the weekday within a
76
+ // week either way, with the date further off. "at 6:40 PM" from yesterday
77
+ // read as a time still to come.
78
+ export function stamp(at, t = now()) {
79
+ const d = new Date(at);
80
+ if (d.toDateString() === new Date(t).toDateString()) return clock(at);
81
+ const day = Math.abs(t - at) < 6 * DAY ? d.toLocaleDateString([], { weekday: 'short' }) : d.toLocaleDateString([], { month: 'short', day: 'numeric' });
82
+ return `${day} ${clock(at)}`;
83
+ }
84
+
85
+ const what = x => (x.purpose || x.cmd || (x.res || []).join(', ') || 'a job').replace(/\s+/g, ' ').slice(0, 70);
86
+ const job = x => `${x.who}'s #${x.id} (${what(x)})`;
87
+ const personWaits = q => q.prio === 'urgent' || q.prio === 'high' || typeof q.by === 'number';
88
+ const isDeploy = res => (res || []).some(r => r === 'deploy' || r.startsWith('deploy-') || r.startsWith('deploy:'));
89
+ // A failure the person cares about: a deploy, or a job they were waiting on.
90
+ // Held by the machine's memory: pressure or swap, or a job that fits dibs's budget but not what's really free.
91
+ const pressed = v => PRESSURE.has(v.rule) || (v.rule === 'memory' && (v.pressure || v.real));
92
+ const matters = x => isDeploy(x.res) || x.prio === 'urgent' || x.prio === 'high' || typeof x.due === 'number';
93
+
94
+ function load() {
95
+ try { return { seen: {}, open: {}, resolved: [], dismissed: {}, waits: {}, ended: [], svc: {}, restarts: [], hook: [], ...JSON.parse(fs.readFileSync(FILE, 'utf8')) }; }
96
+ catch { return { seen: {}, open: {}, resolved: [], dismissed: {}, waits: {}, ended: [], svc: {}, restarts: [], hook: [] }; }
97
+ }
98
+
99
+ function save(st) {
100
+ const tmp = `${FILE}.${process.pid}`;
101
+ fs.writeFileSync(tmp, JSON.stringify(st));
102
+ fs.renameSync(tmp, FILE);
103
+ }
104
+
105
+ // One scan at a time. Whoever finds the lock taken shows what the file already
106
+ // says; a lock left by a process that died is broken after 30 s.
107
+ function locked(fn) {
108
+ try { fs.mkdirSync(LOCK); } catch (e) {
109
+ if (e.code !== 'EEXIST') return null;
110
+ try { if (now() - fs.statSync(LOCK).mtimeMs < 30e3) return null; fs.rmSync(LOCK, { recursive: true, force: true }); fs.mkdirSync(LOCK); } catch { return null; }
111
+ }
112
+ try { return fn(); } finally { fs.rmSync(LOCK, { recursive: true, force: true }); }
113
+ }
114
+
115
+ // The lines a log gained since the offset last read. A file shorter than the
116
+ // offset was rotated: read it from the start.
117
+ function tail(file, off, first = FIRST_READ) {
118
+ let size = 0;
119
+ try { size = fs.statSync(file).size; } catch { return { lines: [], off: 0 }; }
120
+ let from = off == null ? Math.max(0, size - first) : off > size ? 0 : off;
121
+ if (from === size) return { lines: [], off: size };
122
+ const fd = fs.openSync(file, 'r');
123
+ try {
124
+ const buf = Buffer.alloc(size - from);
125
+ fs.readSync(fd, buf, 0, buf.length, from);
126
+ const text = buf.toString('utf8');
127
+ // A line still being written stays for next time; a first read starting mid-line drops its first.
128
+ const end = text.lastIndexOf('\n') + 1;
129
+ let lines = text.slice(0, end).split('\n').filter(Boolean);
130
+ if (off == null && from > 0) lines = lines.slice(1);
131
+ return { lines, off: from + Buffer.byteLength(text.slice(0, end)) };
132
+ } finally { fs.closeSync(fd); }
133
+ }
134
+
135
+ // The event log since last time: waits per resource, and failed, stopped and
136
+ // lost jobs and crashes, with what closes them.
137
+ function readEvents(st, t) {
138
+ const { lines, off } = tail(EVENTS, st.off);
139
+ st.off = off;
140
+ const stops = new Map();
141
+ for (const line of lines) {
142
+ let e;
143
+ try { e = JSON.parse(line); } catch { continue; }
144
+ if (e.kind === 'start' && e.type === 'run' && e.res?.[0]) {
145
+ const w = (st.waits[e.res[0]] ||= []);
146
+ w.push(e.ms || 0);
147
+ if (w.length > WAITS_KEPT) w.splice(0, w.length - WAITS_KEPT);
148
+ } else if (e.kind === 'override' && e.act === 'stop' && e.id != null) stops.set(e.id, e.by || 'someone');
149
+ else if (e.kind === 'end' && e.type === 'run') {
150
+ // A later success of the same command closes its failures.
151
+ if (e.code === 0 && e.key) for (const x of st.ended) if (x.key === e.key && !x.fixedAt) x.fixedAt = e.at;
152
+ const by = stops.get(e.id);
153
+ const x = { at: e.at, id: e.id, who: e.who, res: e.res, cmd: e.cmd, purpose: e.purpose, key: e.key, code: e.code, prio: e.prio, due: e.due };
154
+ if (by || STOPPED.has(e.code)) st.ended.push({ kind: 'stopped', ...x, by: by || null });
155
+ else if (e.code != null && e.code !== 0) st.ended.push({ kind: 'failed', ...x });
156
+ } else if (e.kind === 'lost' || e.kind === 'crash') st.ended.push({ kind: e.kind, at: e.at, who: e.who, cmd: e.cmd, code: e.code, why: e.why, verb: e.verb });
157
+ }
158
+ st.ended = st.ended.filter(x => t - x.at < EVENT_KEEP);
159
+ }
160
+
161
+ // The hook's own failures (src/guard.mjs logError): when, and what.
162
+ function readHook(st, t) {
163
+ const { lines, off } = tail(GUARD_LOG, st.hookOff, 64 * 1024);
164
+ st.hookOff = off;
165
+ for (const line of lines) {
166
+ const m = line.match(/^(\S+)\s+(.*)$/);
167
+ const at = m && Date.parse(m[1]);
168
+ if (at) st.hook.push({ at, msg: m[2].slice(0, 200) });
169
+ }
170
+ st.hook = st.hook.filter(x => t - x.at < CALM_AFTER);
171
+ }
172
+
173
+ // Services: down, or started again by launchd after exiting with an error.
174
+ function readServices(st, t) {
175
+ if (st.svcAt && t - st.svcAt < SERVICES_EVERY) return;
176
+ st.svcAt = t;
177
+ const health = serviceHealth();
178
+ for (const [k, h] of Object.entries(health)) {
179
+ const was = st.svc[k];
180
+ if (was && h.runs > was.runs && h.exit && h.exit !== 0) st.restarts.push({ k, at: t, exit: h.exit, runs: h.runs - was.runs });
181
+ st.svc[k] = { ...h };
182
+ }
183
+ for (const k of Object.keys(st.svc)) if (!health[k]) delete st.svc[k];
184
+ st.restarts = st.restarts.filter(r => t - r.at < CALM_AFTER);
185
+ }
186
+
187
+ // What uses the most memory, machine-wide, grouped the way a person closes
188
+ // things: an app with all its helpers, Safari's pages, the simulator, each
189
+ // Claude session, and dibs's own jobs by number. Top five.
190
+ export function memoryUsers(s, procs, use) {
191
+ const sessions = new Map(sessionFiles().map(x => [x.pid, x]));
192
+ const owner = new Map();
193
+ for (const l of s.leases || []) if (l.kind === 'run') for (const pid of treeOf(l, s, procs)) owner.set(pid, l);
194
+ const groups = new Map();
195
+ for (const p of procs) {
196
+ const bytes = use.get(p.pid);
197
+ if (!bytes) continue;
198
+ const l = owner.get(p.pid);
199
+ const name = l ? `dibs job #${l.id} (${l.who})` : appOf(p, sessions);
200
+ const g = groups.get(name) || { name, bytes: 0, n: 0, dibs: !!l, ...(l && { id: l.id }) };
201
+ g.bytes += bytes; g.n++;
202
+ groups.set(name, g);
203
+ }
204
+ return [...groups.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5);
205
+ }
206
+
207
+ function appOf(p, sessions) {
208
+ const a = p.args || '';
209
+ if (/\blaunchd_sim\b|\/CoreSimulator\/Devices\/|\.simruntime\//.test(a)) return 'the iOS Simulator';
210
+ if (/com\.apple\.WebKit\.(WebContent|GPU|Networking)/.test(a)) return 'Safari and other web pages';
211
+ if (/(^|\/)claude(\s|$)/.test(a)) {
212
+ const x = sessions.get(p.pid);
213
+ return x?.name ? `Claude Code session ${x.name}` : `Claude Code (pid ${p.pid})`;
214
+ }
215
+ const app = a.match(/\/([^/]+)\.app\//);
216
+ if (app) return app[1];
217
+ // A script under an interpreter is the script: "node" alone says nothing about which.
218
+ const [cmd, ...args] = a.split(/\s+/);
219
+ const name = path.basename(cmd || `pid ${p.pid}`);
220
+ const script = INTERPRETERS.test(name) && args.find(x => !x.startsWith('-'));
221
+ return script ? `${name} ${path.basename(script)}` : name;
222
+ }
223
+
224
+ const INTERPRETERS = /^(node|bun|deno|python3?(\.\d+)?|ruby|perl)$/;
225
+ const sized = g => `${g.name} (${gb(g.bytes).replace(/G$/, ' GB')}${g.n > 1 && g.name.startsWith('Safari') ? `, ${g.n} pages` : ''})`;
226
+
227
+ // Every alert the state calls for now: { id, cause, level, title, fix, after?, at? }.
228
+ // level: urgent (a person is held up or dibs is broken), warn, or note.
229
+ export function detect({ s, cfg, hist, m, t, st, users }) {
230
+ const out = [];
231
+ const waiting = (s.queue || []).filter(q => q.pid);
232
+ const verdicts = new Map(waiting.map(q => [q.id, verdict(s, q, cfg, hist, t)]));
233
+
234
+ // A job waiting far longer than its resource usually makes anyone wait.
235
+ for (const q of waiting) {
236
+ const v = verdicts.get(q.id);
237
+ if (v.ok) continue;
238
+ const usual = Math.max(0, ...q.res.map(r => median(st.waits[r] || [])));
239
+ const waited = t - q.enq;
240
+ if (waited < Math.max(WAIT_FLOOR, WAIT_TIMES * usual)) continue;
241
+ out.push({ id: `wait:#${q.id}`, cause: 'wait', level: personWaits(q) ? 'urgent' : 'warn', job: q.id, who: q.who, at: q.enq,
242
+ ...(pressed(v) && !users && { want: 'users' }),
243
+ title: `${job(q)} has waited ${minutes(waited)}${usual >= MIN ? `, where ${q.res[0]} usually takes ${minutes(usual)}` : ''}${personWaits(q) ? `, and it's ${typeof q.by === 'number' ? `due by ${stamp(q.by, t)}` : q.prio}` : ''}`,
244
+ why: v.why, fix: waitFix(s, q, v, t, users) });
245
+ }
246
+
247
+ // Memory holding new jobs back.
248
+ const held = waiting.filter(q => pressed(verdicts.get(q.id)));
249
+ if (held.length) {
250
+ const swap = held.some(q => /^swap/.test(verdicts.get(q.id).rule));
251
+ const list = users || [];
252
+ const close = list.filter(g => !g.dibs);
253
+ const ours = list.filter(g => g.dibs);
254
+ out.push({ id: 'memory', cause: 'memory', level: 'urgent', after: PRESSURE_AFTER, at: Math.min(...held.map(q => q.enq)), ...(!users && { want: 'users' }),
255
+ title: `${swap ? 'Swap' : 'Memory pressure'} is holding back ${held.length} job${held.length > 1 ? 's' : ''} (${andList(held.slice(0, 3).map(q => `#${q.id}`))}${held.length > 3 ? ' and more' : ''})`,
256
+ why: verdicts.get(held[0].id).why,
257
+ detail: list.length ? `Using the most memory: ${list.map(sized).join(', ')}.` : '',
258
+ fix: memoryFix(list) });
259
+ }
260
+
261
+ // A slot held by a run that has used no CPU for a long while someone waits for it.
262
+ for (const l of s.leases || []) {
263
+ const idle = stuckFor(l, t);
264
+ if (!idle) continue;
265
+ const behind = waiting.filter(q => q.res.some(r => l.res.includes(r)));
266
+ if (!behind.length) continue;
267
+ out.push({ id: `idle:#${l.id}`, cause: 'idle', level: behind.some(personWaits) ? 'urgent' : 'warn', job: l.id, who: l.who, at: l.idleSince,
268
+ title: `${job(l)} has held ${l.res.join(', ')} for ${minutes(t - l.start)} and used no CPU for ${minutes(idle)}, while ${behind.length} job${behind.length > 1 ? 's wait' : ' waits'}`,
269
+ fix: `If it's stuck, stop it: dibs stop ${l.id} --owner ${l.who}. If it's working somewhere dibs can't see, leave it.` });
270
+ }
271
+
272
+ // Jobs that failed, were stopped, or were lost, and dibs's own crashes. An
273
+ // agent's test run failing while it works is normal: on 2026-11-03 one
274
+ // session's 53 failed test runs filled the list. What's loud is what the
275
+ // person cares about: a deploy, a job a person waits on (high, urgent or
276
+ // --by), the same command failing REPEATS times in a row, a lost job and a
277
+ // crash. The rest is quiet: in dibs alerts --all only.
278
+ const failed = new Map();
279
+ for (const x of st.ended) {
280
+ if (x.fixedAt) continue;
281
+ if (x.kind === 'failed' && matters(x)) {
282
+ out.push({ id: `failed:#${x.id}`, cause: 'ended', level: 'warn', at: x.at, job: x.id, who: x.who,
283
+ title: `${job(x)} failed at ${stamp(x.at, t)} (exit ${x.code})${x.due ? `, and it was due by ${stamp(x.due, t)}` : x.prio === 'urgent' || x.prio === 'high' ? `, and it was ${x.prio}` : ''}`,
284
+ fix: `${x.who} is the one to fix it; this closes when the same command passes.` });
285
+ } else if (x.kind === 'failed') {
286
+ // Failures of the exact same command, all since its last pass (a pass closes the ones before it).
287
+ const k = `${x.who}|${x.cmd || (x.res || []).join(',')}`;
288
+ const g = failed.get(k) || { ...x, n: 0, first: x.at };
289
+ g.n++; g.at = Math.max(g.at, x.at); g.code = x.code;
290
+ failed.set(k, g);
291
+ } else if (x.kind === 'stopped') {
292
+ // Stopped on purpose (exit 143 or 137, or dibs stop): on record in dibs alerts --all, nowhere louder.
293
+ out.push({ id: `stopped:#${x.id}`, cause: 'ended', level: 'note', at: x.at, job: x.id, who: x.who, quiet: true,
294
+ title: `${job(x)} was stopped${x.by ? ` by ${x.by}` : ''} at ${stamp(x.at, t)}${x.code != null ? ` (exit ${x.code})` : ''}`,
295
+ fix: `If it should finish, ${x.who} runs it again; nothing else waits on it.` });
296
+ } else if (x.kind === 'lost') {
297
+ out.push({ id: `lost:${x.at}`, cause: 'ended', level: 'urgent', at: x.at, who: x.who,
298
+ title: `${x.who}'s job was lost${x.code === 77 ? ' after it started' : ' before it started'} at ${stamp(x.at, t)}: ${x.why || x.cmd}`,
299
+ fix: x.code === 77 ? 'It may have run. Check what it changed before running it again.' : 'It never ran, so it\'s safe to run again.' });
300
+ } else if (x.kind === 'crash') {
301
+ out.push({ id: `crash:${x.at}`, cause: 'dibs', level: 'urgent', at: x.at, who: x.who,
302
+ title: `dibs crashed at ${stamp(x.at, t)} running dibs ${x.verb || ''} for ${x.who}`,
303
+ fix: `It's a bug in dibs. Report it: dibs ask "crash in dibs ${x.verb || ''}"` });
304
+ }
305
+ }
306
+ for (const [k, g] of failed) {
307
+ const loud = g.cmd && g.n >= REPEATS;
308
+ out.push({ id: `failed:${hash(k)}`, cause: 'ended', level: loud ? 'warn' : 'note', at: g.first, last: g.at, who: g.who, ...(!loud && { quiet: true }),
309
+ title: `${g.who}'s ${what(g)} failed${g.n > 1 ? ` ${g.n} times in a row, last` : ''} at ${stamp(g.at, t)} (exit ${g.code})`,
310
+ fix: `${g.who} is the one to fix it; this closes when the same command passes.` });
311
+ }
312
+
313
+ // dibs itself.
314
+ for (const [k, h] of Object.entries(st.svc || {}))
315
+ if (!h.running)
316
+ out.push({ id: `service:${k}`, cause: 'dibs', level: 'urgent',
317
+ title: `dibs's ${k} service isn't running${h.exit ? ` (it last exited with code ${h.exit})` : ''}: ${h.what}`,
318
+ fix: `Start it again: dibs service install ${k}. Why it stopped is in ~/.dibs/${k}.log.` });
319
+ for (const k of new Set((st.restarts || []).map(r => r.k))) {
320
+ const rs = st.restarts.filter(r => r.k === k);
321
+ const last = rs[rs.length - 1];
322
+ out.push({ id: `restart:${k}`, cause: 'dibs', level: 'warn', at: rs[0].at,
323
+ title: `dibs's ${k} service crashed (exit ${last.exit}) and launchd started it again${rs.length > 1 ? `, ${rs.length} times in the last hour` : ''}, last at ${stamp(last.at, t)}`,
324
+ fix: `Look in ~/.dibs/${k}.log for why, and report it: dibs ask "the ${k} service keeps exiting with ${last.exit}"` });
325
+ }
326
+ if (st.hook?.length) {
327
+ const last = st.hook[st.hook.length - 1];
328
+ out.push({ id: 'hook', cause: 'dibs', level: 'warn', at: st.hook[0].at,
329
+ title: `The Claude Code hook failed ${st.hook.length} time${st.hook.length > 1 ? 's' : ''} in the last hour, last at ${stamp(last.at, t)}: ${last.msg}`,
330
+ fix: `Those tool calls ran without dibs's checks. Report it: dibs ask "hook: ${last.msg.slice(0, 60)}"` });
331
+ }
332
+
333
+ // Disk under the floor: nothing new starts.
334
+ const floor = bytes(cfg.minDisk || '0');
335
+ if (floor && m.diskFree != null && m.diskFree < floor)
336
+ out.push({ id: 'disk', cause: 'disk', level: 'urgent',
337
+ title: `Free disk is ${gb(m.diskFree).replace(/G$/, ' GB')}, under the ${gb(floor).replace(/G$/, ' GB')} dibs keeps free, so no new job starts`,
338
+ fix: diskFix() });
339
+ return out;
340
+ }
341
+
342
+ // The one thing that lets a long-waiting job start, by what holds it.
343
+ function waitFix(s, q, v, t, users) {
344
+ const boost = `dibs boost ${q.id} urgent -m "why"`;
345
+ if (v.rule === 'slot' || v.rule === 'files' || v.rule === 'together') {
346
+ // With one deploy per project (the per-repo lock), the one in the way is this project's.
347
+ const on = (s.leases || []).filter(x => x.res.includes(v.on));
348
+ const l = on.find(x => q.repo && x.repo === q.repo) || on[0] || v.ahead;
349
+ if (l && stuckFor(l, t)) return `${job(l)} holds ${v.on} and has done nothing for ${minutes(stuckFor(l, t))}: stop it with dibs stop ${l.id} --owner ${l.who}.`;
350
+ if (l) return `${job(l)} has held ${v.on} for ${minutes(t - l.start)}. If ${q.who}'s job can't wait, ${boost} puts it first in line; ${l.who} decides whether to stop theirs.`;
351
+ }
352
+ if (v.rule === 'ahead' && v.ahead) return `${job(v.ahead)} is ahead. If this one matters more: ${boost}.`;
353
+ // What uses the memory, said here: an alert that points at another one that isn't there is no help.
354
+ if (pressed(v)) return memoryFix(users || []);
355
+ if (v.rule === 'memory') {
356
+ const big = (s.leases || []).filter(l => l.mem).sort((a, b) => b.mem - a.mem).slice(0, 3);
357
+ return `dibs's memory budget is handed out to running jobs${big.length ? `, the biggest ${andList(big.map(l => `${job(l)} with ${gb(l.mem).replace(/G$/, ' GB')}`))}` : ''}. It starts as they end; if it can't wait: ${boost}.`;
358
+ }
359
+ if (v.rule === 'disk' || v.rule === 'drain') return diskFix();
360
+ if (v.rule === 'load' || v.rule === 'cpu') return `The machine is busy. If a person waits on this: dibs boost ${q.id} high -m "why".`;
361
+ if (v.rule === 'idle') return `It's idle-priority work, which waits for everything else: dibs boost ${q.id} normal.`;
362
+ if (v.rule === 'reset') return `${v.on} is being reset after the last job; if that takes too long, check its onRelease in ~/.dibs/config.json.`;
363
+ return `${v.why}. If it can't wait: ${boost}.`;
364
+ }
365
+
366
+ // What to close, from the biggest memory users on the machine.
367
+ function memoryFix(list) {
368
+ const close = list.filter(g => !g.dibs), ours = list.filter(g => g.dibs);
369
+ if (close.length) return `Close what you can of ${andList(close.slice(0, 3).map(sized))}. dibs won't close apps it didn't start.${ours.length ? ` Or stop a dibs job: dibs stop ${ours[0].id}.` : ''}`;
370
+ if (ours.length) return `dibs's own jobs use it: dibs stop ${ours[0].id} frees the most.`;
371
+ return "Close apps you aren't using; dibs won't close what it didn't start.";
372
+ }
373
+
374
+ function diskFix() {
375
+ return `Free disk: build output, caches and scratch folders${hogHint()}.`;
376
+ }
377
+
378
+ const median = xs => { if (!xs.length) return 0; const a = [...xs].sort((x, y) => x - y); return a[Math.floor(a.length / 2)]; };
379
+ const hash = k => { let h = 5381; for (const c of String(k)) h = ((h << 5) + h + c.charCodeAt(0)) >>> 0; return h.toString(36); };
380
+
381
+ // Open what's new, keep what's still true, and close the rest with when.
382
+ export function merge(st, found, t) {
383
+ const live = new Set();
384
+ for (const c of found) {
385
+ // Since when the problem itself began (the job queued, the first failure), not this scan.
386
+ if (c.after && t - (st.seen[c.id] ??= c.at ?? t) < c.after) continue;
387
+ if (st.dismissed[c.id]) continue;
388
+ live.add(c.id);
389
+ const { after, want, at, ...a } = c;
390
+ st.open[c.id] = { ...a, since: at ?? st.open[c.id]?.since ?? (after ? st.seen[c.id] : t), resolvedAt: null };
391
+ }
392
+ const pending = new Set(found.map(c => c.id));
393
+ for (const id of Object.keys(st.seen)) if (!pending.has(id)) delete st.seen[id];
394
+ for (const [id, a] of Object.entries(st.open)) {
395
+ if (live.has(id)) continue;
396
+ st.resolved.push({ ...a, resolvedAt: t, ...(st.dismissed[id] && { dismissed: true }) });
397
+ delete st.open[id];
398
+ }
399
+ st.resolved = st.resolved.filter(a => t - a.resolvedAt < DAY).slice(-200);
400
+ for (const [id, at] of Object.entries(st.dismissed)) if (t - at > DAY) delete st.dismissed[id];
401
+ }
402
+
403
+ // Read what's new and bring alerts.json up to date, unless another process
404
+ // did within SCAN_EVERY. Returns the list to show. Never throws: the board,
405
+ // the watcher and the page call it, and none of them may fail over an alert.
406
+ export function scan({ s, cfg, hist, m = machine(), t = now(), force = false } = {}) {
407
+ try {
408
+ const was = load();
409
+ if (!force && was.at && t - was.at < SCAN_EVERY) return shown(was, t);
410
+ const st = locked(() => {
411
+ const st = load();
412
+ // Alerts made by older rules aren't resolved, only no longer said that way: start the open list over.
413
+ if (st.rules !== RULES) { st.open = {}; st.seen = {}; st.rules = RULES; }
414
+ readEvents(st, t);
415
+ readHook(st, t);
416
+ readServices(st, t);
417
+ let users = st.top && t - st.top.at < TOP_EVERY ? st.top.list : null;
418
+ let found = detect({ s, cfg, hist, m, t, st, users });
419
+ // The machine-wide reading only once memory is what holds jobs back.
420
+ if (!users && found.some(a => a.want === 'users')) {
421
+ users = memoryUsers(s, processes(), memoryUse());
422
+ st.top = { at: t, list: users };
423
+ found = detect({ s, cfg, hist, m, t, st, users });
424
+ }
425
+ merge(st, found, t);
426
+ st.at = t;
427
+ save(st);
428
+ return st;
429
+ });
430
+ return shown(st || load(), t);
431
+ } catch (e) {
432
+ // The one thing that may not fail quietly is this.
433
+ return [{ id: 'alerts', cause: 'dibs', level: 'urgent', since: t, resolvedAt: null,
434
+ title: `dibs couldn't check for problems: ${String(e?.message || e).split('\n')[0]}`,
435
+ fix: `It's a bug in dibs. Report it: dibs ask "alerts: ${String(e?.message || e).slice(0, 60)}"` }];
436
+ }
437
+ }
438
+
439
+ // Open alerts, worst first, then the ones resolved in the last RESOLVED_SHOWN.
440
+ const RANK = { urgent: 0, warn: 1, note: 2 };
441
+ export function shown(st, t = now(), all = false) {
442
+ const open = Object.values(st.open || {}).filter(a => all || !a.quiet).sort((a, b) => RANK[a.level] - RANK[b.level] || b.since - a.since);
443
+ const gone = (st.resolved || []).filter(a => all || (!a.quiet && t - a.resolvedAt < RESOLVED_SHOWN)).sort((a, b) => b.resolvedAt - a.resolvedAt);
444
+ return [...open, ...gone];
445
+ }
446
+
447
+ // Close one alert, or all, for a day; a cause that comes back after that opens it again.
448
+ export function dismiss(which, t = now()) {
449
+ return locked(() => {
450
+ const st = load();
451
+ const ids = which === 'all' ? Object.keys(st.open) : Object.keys(st.open).filter(id => id === which || id === `#${which}` || id.endsWith(`:#${which}`) || id.endsWith(`:${which}`));
452
+ for (const id of ids) st.dismissed[id] = t;
453
+ merge(st, Object.values(st.open).filter(a => !ids.includes(a.id)), t);
454
+ save(st);
455
+ return ids;
456
+ }) || [];
457
+ }
458
+
459
+ // The plain board is what agents read between steps: a failure, a stop or a
460
+ // lost job is on it for this long after it happened, then only in the alerts
461
+ // (the page, the app, dibs alerts), which the person reads.
462
+ export const BOARD_KEEP = 30 * MIN;
463
+ export const onBoard = (a, t = now()) => a.cause !== 'ended' || t - (a.last ?? a.since) < BOARD_KEEP;
464
+
465
+ // The board's lines for the alerts: each open one with its fix, worst first,
466
+ // then the ones resolved lately, with when.
467
+ export function alertLines(list, t = now()) {
468
+ const out = [];
469
+ for (const a of list) {
470
+ if (a.resolvedAt) out.push(dim(`Resolved at ${stamp(a.resolvedAt, t)}${a.dismissed ? ' (dismissed)' : ''}: ${a.title}.`));
471
+ else {
472
+ const paint = a.level === 'urgent' ? red : a.level === 'warn' ? amber : x => x;
473
+ out.push(paint(`${a.level === 'note' ? '' : '! '}${a.title} (since ${stamp(a.since, t)}).`), wrap(` Fix: ${a.fix}`, ' '));
474
+ }
475
+ }
476
+ return out;
477
+ }
478
+
479
+ // dibs alerts [--json] [--all] | dibs alerts dismiss <id|all>
480
+ export function alerts(args, cfg) {
481
+ if (args[0] === 'dismiss') {
482
+ const which = args[1] || die('dismiss which? dibs alerts lists them by id, or: dibs alerts dismiss all');
483
+ const ids = dismiss(which.replace(/^#/, ''));
484
+ return console.log(ids.length ? `Dismissed ${andList(ids)} for a day. If the cause is still there after that, it opens again.`
485
+ : `No open alert matches ${which}. dibs alerts lists them.`);
486
+ }
487
+ const t = now();
488
+ const s = withState(s => { markIdle(s); return s; });
489
+ let list = scan({ s, cfg, hist: history(), t, force: true });
490
+ if (args.includes('--all')) list = shown(load(), t, true);
491
+ if (args.includes('--json')) return console.log(JSON.stringify(list, null, 1));
492
+ const quiet = args.includes('--all') ? 0 : Object.values(load().open).filter(a => a.quiet).length;
493
+ const more = quiet ? dim(`${quiet} more not worth your attention (agents' own test runs failing, jobs stopped on purpose): dibs alerts --all`) : '';
494
+ if (!list.length) return console.log(['Nothing is wrong that dibs can see. Open problems and what fixes them show here, and on the board.', more].filter(Boolean).join('\n'));
495
+ console.log(alertLines(list, t).join('\n'));
496
+ if (more) console.log(`\n${more}`);
497
+ const open = list.filter(a => !a.resolvedAt);
498
+ if (open.length) console.log(dim(`\nIds, for dibs alerts dismiss <id>: ${open.map(a => a.id).join(', ')}`));
499
+ }
@@ -0,0 +1,65 @@
1
+ // dibs ask, on a machine where nobody maintains dibs: the closest passages in
2
+ // the docs that ship with it, found by the words they share with the question.
3
+ // Plain keyword overlap is enough for "how do I ..." about a small tool, and
4
+ // needs no index or model.
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+
9
+ const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
10
+ const DOCS = ['skills/dibs/SKILL.md', 'README.md', ...['reference', 'guard', 'files', 'questions', 'later', 'machines', 'simulators', 'scheduling', 'relay'].map(d => `docs/${d}.md`)];
11
+ export const ISSUES = 'https://github.com/dibssoftware/dibs/issues';
12
+ // Two passages answer most questions; more is reading the docs.
13
+ const SHOW = 2;
14
+ // A passage this long is a table or a wall of text: cut to its start.
15
+ const MAX_CHARS = 600;
16
+ const STOP = new Set(('the a an and or but to of in on for with is are was be it this that how do does i my me you your can why what when '
17
+ + 'should would could not no if at as by from so get got use using run dibs it\'s don\'t doesn\'t there their they them about into just').split(' '));
18
+
19
+ const words = text => text.toLowerCase().match(/[a-z0-9][a-z0-9:_-]*/g)?.filter(w => (w.length > 2 || /^\d+$/.test(w)) && !STOP.has(w)) || [];
20
+
21
+ // A list or a table is one paragraph but many answers: shown whole and cut to its
22
+ // start, the item that matched was often past the cut. Each item and each table
23
+ // row is its own passage; a paragraph stays whole.
24
+ function pieces(block) {
25
+ const lines = block.split('\n');
26
+ if (lines.every(l => l.startsWith('|'))) return lines.filter(l => !/^\|[\s:|-]+\|$/.test(l)).slice(1);
27
+ // docs/reference.md's paste-in block for agents is one fence of bullets: each bullet answers on its own.
28
+ if (lines[0] === '```markdown') return lines.filter(l => l.startsWith('- '));
29
+ if (!/^(- |\d+\. )/.test(lines[0])) return [block];
30
+ const items = [];
31
+ for (const l of lines) if (/^(- |\d+\. )/.test(l) || !items.length) items.push(l); else items[items.length - 1] += `\n${l}`;
32
+ return items;
33
+ }
34
+
35
+ // Every paragraph of the docs, with the heading it sits under.
36
+ function passages() {
37
+ const out = [];
38
+ for (const rel of DOCS) {
39
+ let text;
40
+ try { text = fs.readFileSync(path.join(ROOT, rel), 'utf8'); } catch { continue; }
41
+ let heading = '';
42
+ for (const block of text.split(/\n\s*\n/)) {
43
+ const b = block.trim();
44
+ if (!b || b.startsWith('---')) continue;
45
+ if (/^#+ /.test(b) && !b.includes('\n')) { heading = b.replace(/^#+ /, ''); continue; }
46
+ for (const text of pieces(b)) out.push({ file: rel, heading, text });
47
+ }
48
+ }
49
+ return out;
50
+ }
51
+
52
+ // The best passages for a question: each question word found counts once, a
53
+ // rare word more than a common one, and the heading counts like the text.
54
+ export function answer(question) {
55
+ const want = [...new Set(words(question))];
56
+ if (!want.length) return [];
57
+ const all = passages();
58
+ const has = all.map(p => new Set(words(`${p.heading} ${p.text}`)));
59
+ const weight = new Map(want.map(w => [w, Math.log(1 + all.length / (1 + has.filter(s => s.has(w)).length))]));
60
+ return all.map((p, i) => ({ ...p, score: want.reduce((n, w) => n + (has[i].has(w) ? weight.get(w) : 0), 0), hits: want.filter(w => has[i].has(w)).length }))
61
+ .filter(p => p.hits >= Math.min(2, want.length))
62
+ .sort((a, b) => b.score - a.score)
63
+ .slice(0, SHOW)
64
+ .map(p => ({ where: `${p.file}${p.heading ? ` (${p.heading})` : ''}`, text: p.text.length > MAX_CHARS ? `${p.text.slice(0, MAX_CHARS).replace(/\s+\S*$/, '')} ...` : p.text }));
65
+ }