@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.
- package/CHANGELOG.md +577 -0
- package/LICENSE +670 -0
- package/README.md +234 -2
- package/bin/dibs-guard.mjs +7 -0
- package/bin/dibs.mjs +526 -0
- package/docs/benchmarks.md +193 -0
- package/docs/files.md +30 -0
- package/docs/guard.md +91 -0
- package/docs/later.md +43 -0
- package/docs/machines.md +147 -0
- package/docs/questions.md +78 -0
- package/docs/relay.md +196 -0
- package/docs/releasing.md +25 -0
- package/docs/scheduling.md +163 -0
- package/docs/simulators.md +17 -0
- package/package.json +44 -4
- package/skills/dibs/SKILL.md +162 -0
- package/src/acquire.mjs +697 -0
- package/src/admin.mjs +145 -0
- package/src/agents.mjs +145 -0
- package/src/alerts.mjs +437 -0
- package/src/answers.mjs +65 -0
- package/src/board.mjs +202 -0
- package/src/broker.mjs +369 -0
- package/src/commands.mjs +801 -0
- package/src/config.mjs +320 -0
- package/src/connect.mjs +106 -0
- package/src/cool.mjs +160 -0
- package/src/diskwarn.mjs +161 -0
- package/src/events.mjs +94 -0
- package/src/files.mjs +1100 -0
- package/src/guard.mjs +583 -0
- package/src/history.mjs +247 -0
- package/src/hogs.mjs +214 -0
- package/src/later.mjs +487 -0
- package/src/measure.mjs +262 -0
- package/src/nodecheck.mjs +17 -0
- package/src/notices.mjs +121 -0
- package/src/ondemand.mjs +572 -0
- package/src/overlap.mjs +151 -0
- package/src/override.mjs +351 -0
- package/src/owner.mjs +30 -0
- package/src/plain.mjs +467 -0
- package/src/platform.mjs +357 -0
- package/src/preempt.mjs +438 -0
- package/src/primer.mjs +61 -0
- package/src/proc.mjs +98 -0
- package/src/progress.mjs +158 -0
- package/src/qr.mjs +204 -0
- package/src/questions.mjs +389 -0
- package/src/quota.mjs +81 -0
- package/src/reads.mjs +54 -0
- package/src/relay.mjs +779 -0
- package/src/remote.mjs +584 -0
- package/src/reset.mjs +127 -0
- package/src/schedule.mjs +995 -0
- package/src/scratch.mjs +61 -0
- package/src/serve.mjs +736 -0
- package/src/service.mjs +221 -0
- package/src/shard.mjs +59 -0
- package/src/simctl.mjs +42 -0
- package/src/simpool.mjs +258 -0
- package/src/state.mjs +201 -0
- package/src/stats.mjs +328 -0
- package/src/style.mjs +44 -0
- package/src/talk.mjs +523 -0
- package/src/thin.sh +130 -0
- package/src/trust.mjs +152 -0
- package/src/util.mjs +184 -0
- package/src/version.mjs +2 -0
- package/src/web.mjs +1117 -0
- package/src/worker.mjs +318 -0
package/src/alerts.mjs
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
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 memory, not a turn, is in the way.
|
|
67
|
+
const MEMORY_RULES = new Set(['pressure', 'swap', 'swaproom', 'ram', 'oversize']);
|
|
68
|
+
// Exit codes a stopped command dies with: Ctrl-C, SIGKILL, SIGTERM.
|
|
69
|
+
const STOPPED = new Set([130, 137, 143]);
|
|
70
|
+
|
|
71
|
+
const what = x => (x.purpose || x.cmd || (x.res || []).join(', ') || 'a job').replace(/\s+/g, ' ').slice(0, 70);
|
|
72
|
+
const job = x => `${x.who}'s #${x.id} (${what(x)})`;
|
|
73
|
+
const personWaits = q => q.prio === 'urgent' || q.prio === 'high' || typeof q.by === 'number';
|
|
74
|
+
|
|
75
|
+
function load() {
|
|
76
|
+
try { return { seen: {}, open: {}, resolved: [], dismissed: {}, waits: {}, ended: [], svc: {}, restarts: [], hook: [], ...JSON.parse(fs.readFileSync(FILE, 'utf8')) }; }
|
|
77
|
+
catch { return { seen: {}, open: {}, resolved: [], dismissed: {}, waits: {}, ended: [], svc: {}, restarts: [], hook: [] }; }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function save(st) {
|
|
81
|
+
const tmp = `${FILE}.${process.pid}`;
|
|
82
|
+
fs.writeFileSync(tmp, JSON.stringify(st));
|
|
83
|
+
fs.renameSync(tmp, FILE);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// One scan at a time. Whoever finds the lock taken shows what the file already
|
|
87
|
+
// says; a lock left by a process that died is broken after 30 s.
|
|
88
|
+
function locked(fn) {
|
|
89
|
+
try { fs.mkdirSync(LOCK); } catch (e) {
|
|
90
|
+
if (e.code !== 'EEXIST') return null;
|
|
91
|
+
try { if (now() - fs.statSync(LOCK).mtimeMs < 30e3) return null; fs.rmSync(LOCK, { recursive: true, force: true }); fs.mkdirSync(LOCK); } catch { return null; }
|
|
92
|
+
}
|
|
93
|
+
try { return fn(); } finally { fs.rmSync(LOCK, { recursive: true, force: true }); }
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// The lines a log gained since the offset last read. A file shorter than the
|
|
97
|
+
// offset was rotated: read it from the start.
|
|
98
|
+
function tail(file, off, first = FIRST_READ) {
|
|
99
|
+
let size = 0;
|
|
100
|
+
try { size = fs.statSync(file).size; } catch { return { lines: [], off: 0 }; }
|
|
101
|
+
let from = off == null ? Math.max(0, size - first) : off > size ? 0 : off;
|
|
102
|
+
if (from === size) return { lines: [], off: size };
|
|
103
|
+
const fd = fs.openSync(file, 'r');
|
|
104
|
+
try {
|
|
105
|
+
const buf = Buffer.alloc(size - from);
|
|
106
|
+
fs.readSync(fd, buf, 0, buf.length, from);
|
|
107
|
+
const text = buf.toString('utf8');
|
|
108
|
+
// A line still being written stays for next time; a first read starting mid-line drops its first.
|
|
109
|
+
const end = text.lastIndexOf('\n') + 1;
|
|
110
|
+
let lines = text.slice(0, end).split('\n').filter(Boolean);
|
|
111
|
+
if (off == null && from > 0) lines = lines.slice(1);
|
|
112
|
+
return { lines, off: from + Buffer.byteLength(text.slice(0, end)) };
|
|
113
|
+
} finally { fs.closeSync(fd); }
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// The event log since last time: waits per resource, and failed, stopped and
|
|
117
|
+
// lost jobs and crashes, with what closes them.
|
|
118
|
+
function readEvents(st, t) {
|
|
119
|
+
const { lines, off } = tail(EVENTS, st.off);
|
|
120
|
+
st.off = off;
|
|
121
|
+
const stops = new Map();
|
|
122
|
+
for (const line of lines) {
|
|
123
|
+
let e;
|
|
124
|
+
try { e = JSON.parse(line); } catch { continue; }
|
|
125
|
+
if (e.kind === 'start' && e.type === 'run' && e.res?.[0]) {
|
|
126
|
+
const w = (st.waits[e.res[0]] ||= []);
|
|
127
|
+
w.push(e.ms || 0);
|
|
128
|
+
if (w.length > WAITS_KEPT) w.splice(0, w.length - WAITS_KEPT);
|
|
129
|
+
} else if (e.kind === 'override' && e.act === 'stop' && e.id != null) stops.set(e.id, e.by || 'someone');
|
|
130
|
+
else if (e.kind === 'end' && e.type === 'run') {
|
|
131
|
+
// A later success of the same command closes its failures.
|
|
132
|
+
if (e.code === 0 && e.key) for (const x of st.ended) if (x.key === e.key && !x.fixedAt) x.fixedAt = e.at;
|
|
133
|
+
const by = stops.get(e.id);
|
|
134
|
+
if (by || STOPPED.has(e.code)) st.ended.push({ kind: 'stopped', at: e.at, id: e.id, who: e.who, res: e.res, cmd: e.cmd, purpose: e.purpose, key: e.key, code: e.code, by: by || null });
|
|
135
|
+
else if (e.code != null && e.code !== 0) st.ended.push({ kind: 'failed', at: e.at, id: e.id, who: e.who, res: e.res, cmd: e.cmd, purpose: e.purpose, key: e.key, code: e.code });
|
|
136
|
+
} 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 });
|
|
137
|
+
}
|
|
138
|
+
st.ended = st.ended.filter(x => t - x.at < EVENT_KEEP);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
// The hook's own failures (src/guard.mjs logError): when, and what.
|
|
142
|
+
function readHook(st, t) {
|
|
143
|
+
const { lines, off } = tail(GUARD_LOG, st.hookOff, 64 * 1024);
|
|
144
|
+
st.hookOff = off;
|
|
145
|
+
for (const line of lines) {
|
|
146
|
+
const m = line.match(/^(\S+)\s+(.*)$/);
|
|
147
|
+
const at = m && Date.parse(m[1]);
|
|
148
|
+
if (at) st.hook.push({ at, msg: m[2].slice(0, 200) });
|
|
149
|
+
}
|
|
150
|
+
st.hook = st.hook.filter(x => t - x.at < CALM_AFTER);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// Services: down, or started again by launchd after exiting with an error.
|
|
154
|
+
function readServices(st, t) {
|
|
155
|
+
if (st.svcAt && t - st.svcAt < SERVICES_EVERY) return;
|
|
156
|
+
st.svcAt = t;
|
|
157
|
+
const health = serviceHealth();
|
|
158
|
+
for (const [k, h] of Object.entries(health)) {
|
|
159
|
+
const was = st.svc[k];
|
|
160
|
+
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 });
|
|
161
|
+
st.svc[k] = { ...h };
|
|
162
|
+
}
|
|
163
|
+
for (const k of Object.keys(st.svc)) if (!health[k]) delete st.svc[k];
|
|
164
|
+
st.restarts = st.restarts.filter(r => t - r.at < CALM_AFTER);
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// What uses the most memory, machine-wide, grouped the way a person closes
|
|
168
|
+
// things: an app with all its helpers, Safari's pages, the simulator, each
|
|
169
|
+
// Claude session, and dibs's own jobs by number. Top five.
|
|
170
|
+
export function memoryUsers(s, procs, use) {
|
|
171
|
+
const sessions = new Map(sessionFiles().map(x => [x.pid, x]));
|
|
172
|
+
const owner = new Map();
|
|
173
|
+
for (const l of s.leases || []) if (l.kind === 'run') for (const pid of treeOf(l, s, procs)) owner.set(pid, l);
|
|
174
|
+
const groups = new Map();
|
|
175
|
+
for (const p of procs) {
|
|
176
|
+
const bytes = use.get(p.pid);
|
|
177
|
+
if (!bytes) continue;
|
|
178
|
+
const l = owner.get(p.pid);
|
|
179
|
+
const name = l ? `dibs job #${l.id} (${l.who})` : appOf(p, sessions);
|
|
180
|
+
const g = groups.get(name) || { name, bytes: 0, n: 0, dibs: !!l, ...(l && { id: l.id }) };
|
|
181
|
+
g.bytes += bytes; g.n++;
|
|
182
|
+
groups.set(name, g);
|
|
183
|
+
}
|
|
184
|
+
return [...groups.values()].sort((a, b) => b.bytes - a.bytes).slice(0, 5);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function appOf(p, sessions) {
|
|
188
|
+
const a = p.args || '';
|
|
189
|
+
if (/\blaunchd_sim\b|\/CoreSimulator\/Devices\//.test(a)) return 'the iOS Simulator';
|
|
190
|
+
if (/com\.apple\.WebKit\.(WebContent|GPU|Networking)/.test(a)) return 'Safari and other web pages';
|
|
191
|
+
if (/(^|\/)claude(\s|$)/.test(a)) {
|
|
192
|
+
const x = sessions.get(p.pid);
|
|
193
|
+
return x?.name ? `Claude Code session ${x.name}` : `Claude Code (pid ${p.pid})`;
|
|
194
|
+
}
|
|
195
|
+
const app = a.match(/\/([^/]+)\.app\//);
|
|
196
|
+
if (app) return app[1];
|
|
197
|
+
return path.basename(a.split(/\s+/)[0] || `pid ${p.pid}`);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const sized = g => `${g.name} (${gb(g.bytes).replace(/G$/, ' GB')}${g.n > 1 && g.name.startsWith('Safari') ? `, ${g.n} pages` : ''})`;
|
|
201
|
+
|
|
202
|
+
// Every alert the state calls for now: { id, cause, level, title, fix, after?, at? }.
|
|
203
|
+
// level: urgent (a person is held up or dibs is broken), warn, or note.
|
|
204
|
+
export function detect({ s, cfg, hist, m, t, st, users }) {
|
|
205
|
+
const out = [];
|
|
206
|
+
const waiting = (s.queue || []).filter(q => q.pid);
|
|
207
|
+
const verdicts = new Map(waiting.map(q => [q.id, verdict(s, q, cfg, hist, t)]));
|
|
208
|
+
|
|
209
|
+
// A job waiting far longer than its resource usually makes anyone wait.
|
|
210
|
+
for (const q of waiting) {
|
|
211
|
+
const v = verdicts.get(q.id);
|
|
212
|
+
if (v.ok) continue;
|
|
213
|
+
const usual = Math.max(0, ...q.res.map(r => median(st.waits[r] || [])));
|
|
214
|
+
const waited = t - q.enq;
|
|
215
|
+
if (waited < Math.max(WAIT_FLOOR, WAIT_TIMES * usual)) continue;
|
|
216
|
+
out.push({ id: `wait:#${q.id}`, cause: 'wait', level: personWaits(q) ? 'urgent' : 'warn', job: q.id, who: q.who,
|
|
217
|
+
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 ${clock(q.by)}` : q.prio}` : ''}`,
|
|
218
|
+
why: v.why, fix: waitFix(s, q, v, t) });
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Memory holding new jobs back.
|
|
222
|
+
const held = waiting.filter(q => { const v = verdicts.get(q.id); return MEMORY_RULES.has(v.rule) || (v.rule === 'memory' && (v.pressure || v.real)); });
|
|
223
|
+
if (held.length) {
|
|
224
|
+
const swap = held.some(q => /^swap/.test(verdicts.get(q.id).rule));
|
|
225
|
+
const list = users || [];
|
|
226
|
+
const close = list.filter(g => !g.dibs);
|
|
227
|
+
const ours = list.filter(g => g.dibs);
|
|
228
|
+
out.push({ id: 'memory', cause: 'memory', level: 'urgent', after: PRESSURE_AFTER,
|
|
229
|
+
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' : ''})`,
|
|
230
|
+
why: verdicts.get(held[0].id).why,
|
|
231
|
+
detail: list.length ? `Using the most memory: ${list.map(sized).join(', ')}.` : '',
|
|
232
|
+
fix: close.length
|
|
233
|
+
? `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}.` : ''}`
|
|
234
|
+
: ours.length ? `dibs's own jobs use it: dibs stop ${ours[0].id} frees the most.` : 'Close apps you aren\'t using; dibs won\'t close what it didn\'t start.' });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// A slot held by a run that has used no CPU for a long while someone waits for it.
|
|
238
|
+
for (const l of s.leases || []) {
|
|
239
|
+
const idle = stuckFor(l, t);
|
|
240
|
+
if (!idle) continue;
|
|
241
|
+
const behind = waiting.filter(q => q.res.some(r => l.res.includes(r)));
|
|
242
|
+
if (!behind.length) continue;
|
|
243
|
+
out.push({ id: `idle:#${l.id}`, cause: 'idle', level: behind.some(personWaits) ? 'urgent' : 'warn', job: l.id, who: l.who,
|
|
244
|
+
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'}`,
|
|
245
|
+
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.` });
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Jobs that failed, were stopped, or were lost, and dibs's own crashes.
|
|
249
|
+
const failed = new Map();
|
|
250
|
+
for (const x of st.ended) {
|
|
251
|
+
if (x.fixedAt) continue;
|
|
252
|
+
if (x.kind === 'failed') {
|
|
253
|
+
const k = x.key || `${x.who}|${x.cmd}`;
|
|
254
|
+
const g = failed.get(k) || { ...x, n: 0, first: x.at };
|
|
255
|
+
g.n++; g.at = Math.max(g.at, x.at); g.code = x.code;
|
|
256
|
+
failed.set(k, g);
|
|
257
|
+
} else if (x.kind === 'stopped') {
|
|
258
|
+
out.push({ id: `stopped:#${x.id}`, cause: 'ended', level: 'note', at: x.at, job: x.id, who: x.who,
|
|
259
|
+
title: `${job(x)} was stopped${x.by ? ` by ${x.by}` : ''} at ${clock(x.at)}${x.code != null ? ` (exit ${x.code})` : ''}`,
|
|
260
|
+
fix: `If it should finish, ${x.who} runs it again; nothing else waits on it.` });
|
|
261
|
+
} else if (x.kind === 'lost') {
|
|
262
|
+
out.push({ id: `lost:${x.at}`, cause: 'ended', level: 'urgent', at: x.at, who: x.who,
|
|
263
|
+
title: `${x.who}'s job was lost${x.code === 77 ? ' after it started' : ' before it started'} at ${clock(x.at)}: ${x.why || x.cmd}`,
|
|
264
|
+
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.' });
|
|
265
|
+
} else if (x.kind === 'crash') {
|
|
266
|
+
out.push({ id: `crash:${x.at}`, cause: 'dibs', level: 'urgent', at: x.at, who: x.who,
|
|
267
|
+
title: `dibs crashed at ${clock(x.at)} running dibs ${x.verb || ''} for ${x.who}`,
|
|
268
|
+
fix: `It's a bug in dibs. Report it: dibs ask "crash in dibs ${x.verb || ''}"` });
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
for (const [k, g] of failed)
|
|
272
|
+
out.push({ id: `failed:${hash(k)}`, cause: 'ended', level: 'note', at: g.first, who: g.who,
|
|
273
|
+
title: `${g.who}'s ${what(g)} failed${g.n > 1 ? ` ${g.n} times, last` : ''} at ${clock(g.at)} (exit ${g.code})`,
|
|
274
|
+
fix: `${g.who} is the one to fix it; this closes when the same command passes.` });
|
|
275
|
+
|
|
276
|
+
// dibs itself.
|
|
277
|
+
for (const [k, h] of Object.entries(st.svc || {}))
|
|
278
|
+
if (!h.running)
|
|
279
|
+
out.push({ id: `service:${k}`, cause: 'dibs', level: 'urgent',
|
|
280
|
+
title: `dibs's ${k} service isn't running${h.exit ? ` (it last exited with code ${h.exit})` : ''}: ${h.what}`,
|
|
281
|
+
fix: `Start it again: dibs service install ${k}. Why it stopped is in ~/.dibs/${k}.log.` });
|
|
282
|
+
for (const k of new Set((st.restarts || []).map(r => r.k))) {
|
|
283
|
+
const rs = st.restarts.filter(r => r.k === k);
|
|
284
|
+
const last = rs[rs.length - 1];
|
|
285
|
+
out.push({ id: `restart:${k}`, cause: 'dibs', level: 'warn', at: rs[0].at,
|
|
286
|
+
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 ${clock(last.at)}`,
|
|
287
|
+
fix: `Look in ~/.dibs/${k}.log for why, and report it: dibs ask "the ${k} service keeps exiting with ${last.exit}"` });
|
|
288
|
+
}
|
|
289
|
+
if (st.hook?.length) {
|
|
290
|
+
const last = st.hook[st.hook.length - 1];
|
|
291
|
+
out.push({ id: 'hook', cause: 'dibs', level: 'warn', at: st.hook[0].at,
|
|
292
|
+
title: `The Claude Code hook failed ${st.hook.length} time${st.hook.length > 1 ? 's' : ''} in the last hour, last at ${clock(last.at)}: ${last.msg}`,
|
|
293
|
+
fix: `Those tool calls ran without dibs's checks. Report it: dibs ask "hook: ${last.msg.slice(0, 60)}"` });
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Disk under the floor: nothing new starts.
|
|
297
|
+
const floor = bytes(cfg.minDisk || '0');
|
|
298
|
+
if (floor && m.diskFree != null && m.diskFree < floor)
|
|
299
|
+
out.push({ id: 'disk', cause: 'disk', level: 'urgent',
|
|
300
|
+
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`,
|
|
301
|
+
fix: diskFix() });
|
|
302
|
+
return out;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// The one thing that lets a long-waiting job start, by what holds it.
|
|
306
|
+
function waitFix(s, q, v, t) {
|
|
307
|
+
const boost = `dibs boost ${q.id} urgent -m "why"`;
|
|
308
|
+
if (v.rule === 'slot' || v.rule === 'files' || v.rule === 'together') {
|
|
309
|
+
// With one deploy per project (the per-repo lock), the one in the way is this project's.
|
|
310
|
+
const on = (s.leases || []).filter(x => x.res.includes(v.on));
|
|
311
|
+
const l = on.find(x => q.repo && x.repo === q.repo) || on[0] || v.ahead;
|
|
312
|
+
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}.`;
|
|
313
|
+
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.`;
|
|
314
|
+
}
|
|
315
|
+
if (v.rule === 'ahead' && v.ahead) return `${job(v.ahead)} is ahead. If this one matters more: ${boost}.`;
|
|
316
|
+
if (MEMORY_RULES.has(v.rule) || v.rule === 'memory') return 'Free memory: the memory alert says what uses the most.';
|
|
317
|
+
if (v.rule === 'disk' || v.rule === 'drain') return diskFix();
|
|
318
|
+
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".`;
|
|
319
|
+
if (v.rule === 'idle') return `It's idle-priority work, which waits for everything else: dibs boost ${q.id} normal.`;
|
|
320
|
+
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.`;
|
|
321
|
+
return `${v.why}. If it can't wait: ${boost}.`;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function diskFix() {
|
|
325
|
+
return `Free disk: build output, caches and scratch folders${hogHint()}.`;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const median = xs => { if (!xs.length) return 0; const a = [...xs].sort((x, y) => x - y); return a[Math.floor(a.length / 2)]; };
|
|
329
|
+
const hash = k => { let h = 5381; for (const c of String(k)) h = ((h << 5) + h + c.charCodeAt(0)) >>> 0; return h.toString(36); };
|
|
330
|
+
|
|
331
|
+
// Open what's new, keep what's still true, and close the rest with when.
|
|
332
|
+
export function merge(st, found, t) {
|
|
333
|
+
const live = new Set();
|
|
334
|
+
for (const c of found) {
|
|
335
|
+
if (c.after && t - (st.seen[c.id] ??= t) < c.after) continue;
|
|
336
|
+
if (st.dismissed[c.id]) continue;
|
|
337
|
+
live.add(c.id);
|
|
338
|
+
const { after, ...a } = c;
|
|
339
|
+
st.open[c.id] = { ...a, since: st.open[c.id]?.since ?? c.at ?? (c.after ? st.seen[c.id] : t), resolvedAt: null };
|
|
340
|
+
}
|
|
341
|
+
const pending = new Set(found.map(c => c.id));
|
|
342
|
+
for (const id of Object.keys(st.seen)) if (!pending.has(id)) delete st.seen[id];
|
|
343
|
+
for (const [id, a] of Object.entries(st.open)) {
|
|
344
|
+
if (live.has(id)) continue;
|
|
345
|
+
st.resolved.push({ ...a, resolvedAt: t, ...(st.dismissed[id] && { dismissed: true }) });
|
|
346
|
+
delete st.open[id];
|
|
347
|
+
}
|
|
348
|
+
st.resolved = st.resolved.filter(a => t - a.resolvedAt < DAY).slice(-200);
|
|
349
|
+
for (const [id, at] of Object.entries(st.dismissed)) if (t - at > DAY) delete st.dismissed[id];
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// Read what's new and bring alerts.json up to date, unless another process
|
|
353
|
+
// did within SCAN_EVERY. Returns the list to show. Never throws: the board,
|
|
354
|
+
// the watcher and the page call it, and none of them may fail over an alert.
|
|
355
|
+
export function scan({ s, cfg, hist, m = machine(), t = now(), force = false } = {}) {
|
|
356
|
+
try {
|
|
357
|
+
const was = load();
|
|
358
|
+
if (!force && was.at && t - was.at < SCAN_EVERY) return shown(was, t);
|
|
359
|
+
const st = locked(() => {
|
|
360
|
+
const st = load();
|
|
361
|
+
readEvents(st, t);
|
|
362
|
+
readHook(st, t);
|
|
363
|
+
readServices(st, t);
|
|
364
|
+
let users = st.top && t - st.top.at < TOP_EVERY ? st.top.list : null;
|
|
365
|
+
let found = detect({ s, cfg, hist, m, t, st, users });
|
|
366
|
+
// The machine-wide reading only once memory is what holds jobs back.
|
|
367
|
+
if (!users && found.some(a => a.id === 'memory')) {
|
|
368
|
+
users = memoryUsers(s, processes(), memoryUse());
|
|
369
|
+
st.top = { at: t, list: users };
|
|
370
|
+
found = detect({ s, cfg, hist, m, t, st, users });
|
|
371
|
+
}
|
|
372
|
+
merge(st, found, t);
|
|
373
|
+
st.at = t;
|
|
374
|
+
save(st);
|
|
375
|
+
return st;
|
|
376
|
+
});
|
|
377
|
+
return shown(st || load(), t);
|
|
378
|
+
} catch (e) {
|
|
379
|
+
// The one thing that may not fail quietly is this.
|
|
380
|
+
return [{ id: 'alerts', cause: 'dibs', level: 'urgent', since: t, resolvedAt: null,
|
|
381
|
+
title: `dibs couldn't check for problems: ${String(e?.message || e).split('\n')[0]}`,
|
|
382
|
+
fix: `It's a bug in dibs. Report it: dibs ask "alerts: ${String(e?.message || e).slice(0, 60)}"` }];
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// Open alerts, worst first, then the ones resolved in the last RESOLVED_SHOWN.
|
|
387
|
+
const RANK = { urgent: 0, warn: 1, note: 2 };
|
|
388
|
+
export function shown(st, t = now(), all = false) {
|
|
389
|
+
const open = Object.values(st.open || {}).sort((a, b) => RANK[a.level] - RANK[b.level] || b.since - a.since);
|
|
390
|
+
const gone = (st.resolved || []).filter(a => all || t - a.resolvedAt < RESOLVED_SHOWN).sort((a, b) => b.resolvedAt - a.resolvedAt);
|
|
391
|
+
return [...open, ...gone];
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// Close one alert, or all, for a day; a cause that comes back after that opens it again.
|
|
395
|
+
export function dismiss(which, t = now()) {
|
|
396
|
+
return locked(() => {
|
|
397
|
+
const st = load();
|
|
398
|
+
const ids = which === 'all' ? Object.keys(st.open) : Object.keys(st.open).filter(id => id === which || id === `#${which}` || id.endsWith(`:#${which}`) || id.endsWith(`:${which}`));
|
|
399
|
+
for (const id of ids) st.dismissed[id] = t;
|
|
400
|
+
merge(st, Object.values(st.open).filter(a => !ids.includes(a.id)), t);
|
|
401
|
+
save(st);
|
|
402
|
+
return ids;
|
|
403
|
+
}) || [];
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// The board's lines for the alerts: each open one with its fix, worst first,
|
|
407
|
+
// then the ones resolved lately, with when.
|
|
408
|
+
export function alertLines(list, t = now()) {
|
|
409
|
+
const out = [];
|
|
410
|
+
for (const a of list) {
|
|
411
|
+
if (a.resolvedAt) out.push(dim(`Resolved at ${clock(a.resolvedAt)}${a.dismissed ? ' (dismissed)' : ''}: ${a.title}.`));
|
|
412
|
+
else {
|
|
413
|
+
const paint = a.level === 'urgent' ? red : a.level === 'warn' ? amber : x => x;
|
|
414
|
+
out.push(paint(`${a.level === 'note' ? '' : '! '}${a.title} (since ${clock(a.since)}).`), wrap(` Fix: ${a.fix}`, ' '));
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
return out;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
// dibs alerts [--json] [--all] | dibs alerts dismiss <id|all>
|
|
421
|
+
export function alerts(args, cfg) {
|
|
422
|
+
if (args[0] === 'dismiss') {
|
|
423
|
+
const which = args[1] || die('dismiss which? dibs alerts lists them by id, or: dibs alerts dismiss all');
|
|
424
|
+
const ids = dismiss(which.replace(/^#/, ''));
|
|
425
|
+
return console.log(ids.length ? `Dismissed ${andList(ids)} for a day. If the cause is still there after that, it opens again.`
|
|
426
|
+
: `No open alert matches ${which}. dibs alerts lists them.`);
|
|
427
|
+
}
|
|
428
|
+
const t = now();
|
|
429
|
+
const s = withState(s => { markIdle(s); return s; });
|
|
430
|
+
let list = scan({ s, cfg, hist: history(), t, force: true });
|
|
431
|
+
if (args.includes('--all')) list = shown(load(), t, true);
|
|
432
|
+
if (args.includes('--json')) return console.log(JSON.stringify(list, null, 1));
|
|
433
|
+
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.');
|
|
434
|
+
console.log(alertLines(list, t).join('\n'));
|
|
435
|
+
const open = list.filter(a => !a.resolvedAt);
|
|
436
|
+
if (open.length) console.log(dim(`\nIds, for dibs alerts dismiss <id>: ${open.map(a => a.id).join(', ')}`));
|
|
437
|
+
}
|
package/src/answers.mjs
ADDED
|
@@ -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', ...['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
|
+
// The README'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
|
+
}
|