@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/history.mjs
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
// dibs history: what happened over the last few days, from the event log
|
|
2
|
+
// (src/events.mjs). summarize() is a pure function of the events, so the
|
|
3
|
+
// tests can feed it a made-up week.
|
|
4
|
+
import { withState } from './state.mjs';
|
|
5
|
+
import { readEvents } from './events.mjs';
|
|
6
|
+
import { short } from './files.mjs';
|
|
7
|
+
import { dur, clock, die, now } from './util.mjs';
|
|
8
|
+
import { named } from './plain.mjs';
|
|
9
|
+
import { bold, dim } from './style.mjs';
|
|
10
|
+
|
|
11
|
+
const HOUR = 36e5;
|
|
12
|
+
export const EVENT_CAP = 2000; // the newest events --json carries; the app shows a timeline, not an archive
|
|
13
|
+
// Below this much waiting in all, nothing was a bottleneck worth naming.
|
|
14
|
+
const NOTABLE = 5 * 6e4;
|
|
15
|
+
// A resource is "the bottleneck" when it has at least this share of all the waiting.
|
|
16
|
+
const BOTTLENECK = 0.5;
|
|
17
|
+
// "mostly 18:00-22:00" names the shortest span of the day holding this share of a resource's waiting, if it's a few hours at most.
|
|
18
|
+
const MOSTLY = { share: 0.6, hours: 6 };
|
|
19
|
+
const UNITS = { m: 6e4, h: HOUR, d: 24 * HOUR, w: 168 * HOUR };
|
|
20
|
+
|
|
21
|
+
export function span(s = '7d') {
|
|
22
|
+
const m = String(s).trim().match(/^(\d+(?:\.\d+)?)\s*([mhdw])$/);
|
|
23
|
+
if (!m) die(`can't read --since "${s}" (try 24h, 7d or 30d)`);
|
|
24
|
+
return parseFloat(m[1]) * UNITS[m[2]];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// The most intervals open at once between lo and hi. An interval ending at the
|
|
28
|
+
// moment another starts doesn't overlap it.
|
|
29
|
+
function peak(ivs, lo, hi) {
|
|
30
|
+
const pts = [];
|
|
31
|
+
for (const { a, b } of ivs) {
|
|
32
|
+
const x = Math.max(a, lo), y = Math.min(b, hi);
|
|
33
|
+
if (y > x) pts.push([x, 1], [y, -1]);
|
|
34
|
+
}
|
|
35
|
+
pts.sort((p, q) => p[0] - q[0] || p[1] - q[1]);
|
|
36
|
+
let n = 0, top = 0;
|
|
37
|
+
for (const [, d] of pts) top = Math.max(top, (n += d));
|
|
38
|
+
return top;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Time covered by at least one interval, between lo and hi.
|
|
42
|
+
function union(ivs, lo, hi) {
|
|
43
|
+
const cl = ivs.map(({ a, b }) => [Math.max(a, lo), Math.min(b, hi)]).filter(([x, y]) => y > x).sort((p, q) => p[0] - q[0]);
|
|
44
|
+
let total = 0, end = -Infinity;
|
|
45
|
+
for (const [x, y] of cl) {
|
|
46
|
+
if (y <= end) continue;
|
|
47
|
+
total += y - Math.max(x, end);
|
|
48
|
+
end = y;
|
|
49
|
+
}
|
|
50
|
+
return total;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const clip = (iv, lo, hi) => Math.max(0, Math.min(iv.b, hi) - Math.max(iv.a, lo));
|
|
54
|
+
const pct = (xs, p) => (xs.length ? [...xs].sort((a, b) => a - b)[Math.ceil(p * xs.length) - 1] : 0);
|
|
55
|
+
const mean = xs => (xs.length ? Math.round((xs.reduce((a, b) => a + b, 0) / xs.length) * 100) / 100 : null);
|
|
56
|
+
|
|
57
|
+
// events: from readEvents(). current: what's held and waited for right now
|
|
58
|
+
// ({ leases: [{ id, res, who, start }], queue: [{ id, res, who, enq }] }),
|
|
59
|
+
// so work still going counts up to `until`. Returns the --json shape.
|
|
60
|
+
export function summarize(events, current, since, until) {
|
|
61
|
+
const inWindow = e => e.at >= since && e.at <= until;
|
|
62
|
+
const names = new Map();
|
|
63
|
+
const name = r => (names.has(r) ? names.get(r) : names.set(r, short(r)).get(r));
|
|
64
|
+
const holds = [], waits = new Map();
|
|
65
|
+
const waited = new Set(events.filter(e => e.kind === 'wait').map(e => e.id));
|
|
66
|
+
for (const e of events) {
|
|
67
|
+
if (e.kind === 'end') holds.push({ res: e.res, who: e.who, a: e.at - e.ms, b: e.at });
|
|
68
|
+
// A start that never had to wait isn't a wait. A place kept after a timeout
|
|
69
|
+
// and picked up again is one wait, from when it first joined the line.
|
|
70
|
+
// A waiter that left any other way (a signal, a full disk, the owner, a kill) still waited.
|
|
71
|
+
if (((e.kind === 'start' || e.kind === 'left') && waited.has(e.id)) || e.kind === 'timeout')
|
|
72
|
+
waits.set(e.id, { res: e.res, who: e.who, a: e.at - (e.ms || 0), b: e.at, done: true });
|
|
73
|
+
}
|
|
74
|
+
for (const l of current.leases) holds.push({ res: l.res, who: l.who, a: l.start, b: until });
|
|
75
|
+
for (const q of current.queue) waits.set(q.id, { res: q.res, who: q.who, a: q.enq, b: until, done: false });
|
|
76
|
+
const allWaits = [...waits.values()];
|
|
77
|
+
const timeouts = events.filter(e => e.kind === 'timeout' && inWindow(e));
|
|
78
|
+
const starts = events.filter(e => e.kind === 'start' && inWindow(e));
|
|
79
|
+
|
|
80
|
+
const touched = x => clip(x, since, until) > 0 || (x.b >= since && x.b <= until);
|
|
81
|
+
const resNames = new Set([...holds, ...allWaits].filter(touched).flatMap(x => x.res));
|
|
82
|
+
for (const e of [...timeouts, ...starts]) for (const r of e.res) resNames.add(r);
|
|
83
|
+
const resources = {};
|
|
84
|
+
for (const r of [...resNames].sort()) {
|
|
85
|
+
const on = xs => xs.filter(x => x.res.includes(r));
|
|
86
|
+
const ws = on(allWaits);
|
|
87
|
+
const finished = ws.filter(w => w.done && w.b >= since && w.b <= until).map(w => w.b - w.a);
|
|
88
|
+
resources[name(r)] = {
|
|
89
|
+
busyMs: union(on(holds), since, until), waits: finished.length, waitMs: ws.reduce((t, w) => t + clip(w, since, until), 0),
|
|
90
|
+
p50WaitMs: pct(finished, 0.5), p90WaitMs: pct(finished, 0.9), peakQueue: peak(ws, since, until),
|
|
91
|
+
timeouts: timeouts.filter(e => e.res.includes(r)).length,
|
|
92
|
+
// The hours most of its waiting fell in, [startHour, hours] local, from every wait (the events --json carries are capped).
|
|
93
|
+
mostly: mostly(ws, since, until),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const agents = {};
|
|
98
|
+
const agent = who => (agents[who] ||= { runs: 0, holdMs: 0, waitMs: 0, timeouts: 0 });
|
|
99
|
+
for (const e of starts) agent(e.who).runs++;
|
|
100
|
+
for (const h of holds) if (clip(h, since, until)) agent(h.who).holdMs += clip(h, since, until);
|
|
101
|
+
for (const w of allWaits) if (clip(w, since, until)) agent(w.who).waitMs += clip(w, since, until);
|
|
102
|
+
for (const e of timeouts) agent(e.who).timeouts++;
|
|
103
|
+
|
|
104
|
+
const samples = events.filter(e => e.kind === 'sample');
|
|
105
|
+
const hourly = [];
|
|
106
|
+
for (let h = Math.floor(since / HOUR) * HOUR; h < until; h += HOUR) {
|
|
107
|
+
const lo = Math.max(h, since), hi = Math.min(h + HOUR, until);
|
|
108
|
+
const here = samples.filter(e => e.at >= h && e.at < h + HOUR);
|
|
109
|
+
hourly.push({ hour: h, load: mean(here.map(e => e.load).filter(x => x != null)), waiting: peak(allWaits, lo, hi), held: peak(holds, lo, hi),
|
|
110
|
+
memFree: mean(here.map(e => e.memFree).filter(x => x != null)), diskFree: mean(here.map(e => e.diskFree).filter(x => x != null)) });
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const shown = events.filter(e => e.kind !== 'sample' && inWindow(e)).slice(-EVENT_CAP)
|
|
114
|
+
.map(e => ({ ...e, res: (e.res || []).map(name), who: e.who ?? null, prio: e.prio ?? null, code: e.code ?? null, ms: e.ms ?? null }));
|
|
115
|
+
// The last three are for the plain report; --json leaves them out.
|
|
116
|
+
return { since, until, resources, agents, hourly, events: shown,
|
|
117
|
+
waitIntervals: allWaits.map(w => ({ ...w, res: w.res.map(name) })), started: starts.length, gaveUp: timeouts.length };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// The shortest span of the day (local hours, wrapping past midnight) holding
|
|
121
|
+
// MOSTLY.share of this resource's waiting, as [startHour, hours], or null.
|
|
122
|
+
function mostly(ws, since, until) {
|
|
123
|
+
const by = new Array(24).fill(0);
|
|
124
|
+
for (const w of ws) {
|
|
125
|
+
for (let t = Math.max(w.a, since), end = Math.min(w.b, until); t < end;) {
|
|
126
|
+
const d = new Date(t); d.setMinutes(60, 0, 0);
|
|
127
|
+
const next = Math.min(d.getTime(), end);
|
|
128
|
+
by[new Date(t).getHours()] += next - t;
|
|
129
|
+
t = next;
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
const total = by.reduce((a, b) => a + b, 0);
|
|
133
|
+
if (!total) return null;
|
|
134
|
+
for (let len = 1; len <= MOSTLY.hours; len++)
|
|
135
|
+
for (let s = 0; s < 24; s++) {
|
|
136
|
+
let sum = 0;
|
|
137
|
+
for (let i = 0; i < len; i++) sum += by[(s + i) % 24];
|
|
138
|
+
if (sum >= MOSTLY.share * total) return [s, len];
|
|
139
|
+
}
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const atHour = h => { const d = new Date(); d.setHours(h % 24, 0, 0, 0); return clock(d.getTime()); };
|
|
144
|
+
const day = t => new Date(t).toLocaleDateString([], { month: 'short', day: 'numeric' });
|
|
145
|
+
|
|
146
|
+
// The few sentences at the top: only what the numbers carry.
|
|
147
|
+
export function verdict(h, cfg = { resources: {} }) {
|
|
148
|
+
const res = Object.entries(h.resources);
|
|
149
|
+
const totalWait = res.reduce((t, [, r]) => t + r.waitMs, 0);
|
|
150
|
+
const turns = h.started;
|
|
151
|
+
const label = r => named(cfg, r).label;
|
|
152
|
+
const out = [];
|
|
153
|
+
if (!res.length) return ['Nothing went through dibs in this period.'];
|
|
154
|
+
if (totalWait < NOTABLE) {
|
|
155
|
+
const n = res.reduce((t, [, r]) => t + r.waits, 0);
|
|
156
|
+
out.push(n ? `Nobody had to wait long: ${n} wait${n > 1 ? 's' : ''}, ${dur(totalWait)} in all, across ${turns} turn${turns === 1 ? '' : 's'}.`
|
|
157
|
+
: `Nobody had to wait: ${turns === 1 ? 'the 1 turn' : `all ${turns} turns`} started right away.`);
|
|
158
|
+
} else {
|
|
159
|
+
const [[top, r], ...rest] = res.sort((a, b) => b[1].waitMs - a[1].waitMs);
|
|
160
|
+
if (r.waitMs >= BOTTLENECK * totalWait) {
|
|
161
|
+
const m = mostly(h.waitIntervals.filter(w => w.res.includes(top)), h.since, h.until);
|
|
162
|
+
out.push(`${label(top)} held everyone up: agents waited ${dur(r.waitMs)} for it${m ? `, mostly ${atHour(m[0])}-${atHour(m[0] + m[1])}` : ''}.`);
|
|
163
|
+
} else out.push(`Waiting was spread out: ${[[top, r], ...rest].filter(([, x]) => x.waitMs >= NOTABLE).slice(0, 4).map(([k, x]) => `${label(k)} ${dur(x.waitMs)}`).join(', ')}.`);
|
|
164
|
+
}
|
|
165
|
+
const n = h.gaveUp;
|
|
166
|
+
if (n) out.push(`${n} request${n > 1 ? 's' : ''} gave up waiting (exit 75) before ${n > 1 ? 'their commands' : 'its command'} started.`);
|
|
167
|
+
const loaded = h.hourly.filter(x => x.load != null).sort((a, b) => b.load - a.load)[0];
|
|
168
|
+
if (loaded) out.push(`The machine was busiest in the hour from ${day(loaded.hour)} ${clock(loaded.hour)} (load average ${loaded.load}).`);
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const table = (head, rows) => {
|
|
173
|
+
const w = head.map((c, i) => Math.max(c.length, ...rows.map(r => String(r[i]).length)));
|
|
174
|
+
return [head, ...rows].map(r => r.map((c, i) => (i ? String(c).padStart(w[i]) : String(c).padEnd(w[i]))).join(' ').trimEnd());
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
export function report(h, label, cfg = { resources: {} }) {
|
|
178
|
+
const [lead, ...more] = verdict(h, cfg);
|
|
179
|
+
const out = [bold(lead), ...more, '', dim(`dibs history, last ${label}: ${day(h.since)} ${clock(h.since)} to ${day(h.until)} ${clock(h.until)}`)];
|
|
180
|
+
const res = Object.entries(h.resources).sort((a, b) => b[1].waitMs - a[1].waitMs || b[1].busyMs - a[1].busyMs);
|
|
181
|
+
if (!res.length) return out;
|
|
182
|
+
out.push('', bold('By resource'), ...table(['', 'in use', 'waits', 'waited', 'typical wait', 'worst 1 in 10', 'most in the queue', 'gave up'],
|
|
183
|
+
res.map(([k, r]) => [named(cfg, k).label, dur(r.busyMs), r.waits, dur(r.waitMs), r.waits ? dur(r.p50WaitMs) : '-', r.waits ? dur(r.p90WaitMs) : '-', r.peakQueue, r.timeouts])));
|
|
184
|
+
const ag = Object.entries(h.agents).sort((a, b) => b[1].waitMs - a[1].waitMs || b[1].holdMs - a[1].holdMs);
|
|
185
|
+
out.push('', bold('By agent'), ...table(['', 'turns', 'in use', 'waited', 'gave up'], ag.map(([k, a]) => [k, a.runs, dur(a.holdMs), dur(a.waitMs), a.timeouts])));
|
|
186
|
+
// One waiter at a time is a line nobody stood in; hours with two or more are worth a look.
|
|
187
|
+
const busy = h.hourly.filter(x => x.waiting > 1).sort((a, b) => b.waiting - a.waiting || b.held - a.held).slice(0, 5).sort((a, b) => a.hour - b.hour);
|
|
188
|
+
if (busy.length) {
|
|
189
|
+
out.push('', bold('Longest queues'));
|
|
190
|
+
for (const x of busy)
|
|
191
|
+
out.push(` ${day(x.hour)} ${clock(x.hour).padEnd(8)} ${x.waiting} waiting, ${x.held} running${x.load != null ? `, load average ${x.load}` : ''}`);
|
|
192
|
+
}
|
|
193
|
+
out.push('', dim('Another span: dibs history --since 24h (or 30d). For a program: dibs history --json'));
|
|
194
|
+
return out;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function history(o, cfg) {
|
|
198
|
+
const until = now();
|
|
199
|
+
const since = until - span(o.since);
|
|
200
|
+
// Through withState, so leases whose process died are reaped (and their end recorded) first.
|
|
201
|
+
const current = withState(s => ({
|
|
202
|
+
leases: s.leases.map(l => ({ id: l.id, res: l.res, who: l.who, start: l.start })),
|
|
203
|
+
queue: s.queue.filter(q => q.pid).map(q => ({ id: q.id, res: q.res, who: q.who, enq: q.enq })),
|
|
204
|
+
}));
|
|
205
|
+
const h = summarize(readEvents(until), current, since, until);
|
|
206
|
+
if (o.json) {
|
|
207
|
+
const { waitIntervals, started, gaveUp, ...app } = h;
|
|
208
|
+
return console.log(JSON.stringify(app, null, 1));
|
|
209
|
+
}
|
|
210
|
+
console.log(report(h, o.since || '7d', cfg).join('\n'));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// dibs stats: how long jobs waited before they started, against how long they
|
|
214
|
+
// ran, today and over the last 7 days. The share that waited longer than they
|
|
215
|
+
// ran is the number to watch: a job should wait no longer than its own run
|
|
216
|
+
// time unless the machine is truly full. statsOf() is a pure function of the
|
|
217
|
+
// events (a run's start carries its wait in ms, its end its run time).
|
|
218
|
+
export function statsOf(events, since) {
|
|
219
|
+
const starts = new Map();
|
|
220
|
+
const jobs = [];
|
|
221
|
+
for (const e of events) {
|
|
222
|
+
if (e.type !== 'run' || e.at < since) continue;
|
|
223
|
+
if (e.kind === 'start') starts.set(e.id, e);
|
|
224
|
+
else if (e.kind === 'end' && starts.has(e.id)) jobs.push({ res: e.res[0], wait: starts.get(e.id).ms || 0, run: e.ms || 0 });
|
|
225
|
+
}
|
|
226
|
+
const by = {};
|
|
227
|
+
for (const j of jobs) (by[j.res] ||= []).push(j.wait);
|
|
228
|
+
return {
|
|
229
|
+
jobs: jobs.length,
|
|
230
|
+
waitedLonger: jobs.length ? jobs.filter(j => j.wait > j.run).length / jobs.length : null,
|
|
231
|
+
byRes: Object.entries(by).sort((a, b) => b[1].length - a[1].length).map(([res, ws]) => ({ res, jobs: ws.length, median: pct(ws, 0.5), p90: pct(ws, 0.9) })),
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
export function stats(o, cfg) {
|
|
235
|
+
const t = now(), midnight = new Date(t).setHours(0, 0, 0, 0);
|
|
236
|
+
const events = readEvents(t);
|
|
237
|
+
const today = statsOf(events, midnight), week = statsOf(events, t - 7 * 24 * HOUR);
|
|
238
|
+
if (o.json) return console.log(JSON.stringify({ today, week }, null, 1));
|
|
239
|
+
const out = [];
|
|
240
|
+
for (const [label, s] of [['Today', today], ['Last 7 days', week]]) {
|
|
241
|
+
out.push(bold(label), s.jobs ? ` ${s.jobs} jobs; ${Math.round(100 * s.waitedLonger)}% waited longer than they ran` : ' no jobs');
|
|
242
|
+
for (const r of s.byRes) out.push(` ${named(cfg, r.res).label.padEnd(20)} ${String(r.jobs).padStart(5)} jobs wait: median ${dur(r.median)}, 90% under ${dur(r.p90)}`);
|
|
243
|
+
out.push('');
|
|
244
|
+
}
|
|
245
|
+
out.push(dim('A job should wait no longer than it runs unless the machine is truly full. For a program: dibs stats --json'));
|
|
246
|
+
console.log(out.join('\n'));
|
|
247
|
+
}
|
package/src/hogs.mjs
ADDED
|
@@ -0,0 +1,214 @@
|
|
|
1
|
+
// Who is filling the disk. When free disk is under minDisk, or a waiter is
|
|
2
|
+
// held for disk, the throttle watcher measures the session folders in Claude
|
|
3
|
+
// Code's temp folder (claude-<uid>/<project>/<session>), keeps the biggest in
|
|
4
|
+
// hogs.json, and leaves each one's agent a notice once per time the disk goes
|
|
5
|
+
// under. On 2026-10-19 one session's scratchpad held 58 git worktrees with a
|
|
6
|
+
// node_modules each, 18 GB, the Mac sat under the floor, and every agent
|
|
7
|
+
// waiting saw only "free disk". dibs why and the wait name the biggest, so a
|
|
8
|
+
// waiting agent knows whom to ask: only that session (or the person) may
|
|
9
|
+
// delete there (tmpGuard in src/files.mjs).
|
|
10
|
+
import fs from 'node:fs';
|
|
11
|
+
import os from 'node:os';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { execFile } from 'node:child_process';
|
|
14
|
+
import { HOME, paths } from './config.mjs';
|
|
15
|
+
import { claudeTmp, maker } from './files.mjs';
|
|
16
|
+
import { gb, bytes, now } from './util.mjs';
|
|
17
|
+
import { warnOnce, clean, cleanDue } from './diskwarn.mjs';
|
|
18
|
+
|
|
19
|
+
const FILE = path.join(HOME, 'hogs.json');
|
|
20
|
+
// Folders smaller than this aren't worth a notice: deleting them wouldn't get the disk back over the floor.
|
|
21
|
+
const HOG_MIN = () => Number(process.env.DIBS_HOG_MIN) || 2 * 1024 ** 3;
|
|
22
|
+
const TOP = 3; // how many of the biggest hear about it
|
|
23
|
+
const REMEASURE = 10 * 6e4; // while under, how often the sizes are read again: du over 18 GB takes a while
|
|
24
|
+
const OVER = 1024 ** 3; // free disk must come back this far over the floor before the next drop counts as new
|
|
25
|
+
const DU_TIMEOUT = 120e3;
|
|
26
|
+
// The writer: what grew most between two readings. On 2026-10-20 the Mac kept
|
|
27
|
+
// falling under the floor and no session folder was big, so nobody knew what to
|
|
28
|
+
// free. Readings are taken from twice the floor down, so the first drop has one to compare with.
|
|
29
|
+
const GROW_MIN = 512 * 1024 ** 2; // less than this in 10 minutes is the usual churn
|
|
30
|
+
// Places outside any session that fill a disk. DIBS_HOG_PLACES ({label: path}) stands in for them in tests.
|
|
31
|
+
function places() {
|
|
32
|
+
if (process.env.DIBS_HOG_PLACES) return JSON.parse(process.env.DIBS_HOG_PLACES);
|
|
33
|
+
const h = os.homedir(), work = path.join(HOME, 'work');
|
|
34
|
+
return process.platform === 'darwin'
|
|
35
|
+
? { simulators: path.join(h, 'Library/Developer/CoreSimulator'), 'Xcode build output': path.join(h, 'Library/Developer/Xcode/DerivedData'),
|
|
36
|
+
caches: path.join(h, 'Library/Caches'), "dibs's copies of other machines' jobs": work }
|
|
37
|
+
: { caches: path.join(h, '.cache'), "dibs's copies of other machines' jobs": work };
|
|
38
|
+
}
|
|
39
|
+
const GB = b => gb(b).replace(/G$/, ' GB');
|
|
40
|
+
|
|
41
|
+
const read = () => { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch { return null; } };
|
|
42
|
+
function write(x) {
|
|
43
|
+
const tmp = `${FILE}.${process.pid}.tmp`;
|
|
44
|
+
fs.writeFileSync(tmp, JSON.stringify(x));
|
|
45
|
+
fs.renameSync(tmp, FILE);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// Every session folder under the temp roots, by its real path.
|
|
49
|
+
function sessionFolders() {
|
|
50
|
+
const out = new Set();
|
|
51
|
+
for (const root of claudeTmp()) {
|
|
52
|
+
let projects = [];
|
|
53
|
+
try { projects = fs.readdirSync(root); } catch { continue; }
|
|
54
|
+
for (const p of projects) {
|
|
55
|
+
try { for (const s of fs.readdirSync(path.join(root, p))) out.add(fs.realpathSync(path.join(root, p, s))); } catch {}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return [...out];
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// { path: bytes } for each folder and everything two levels in (its
|
|
62
|
+
// scratchpad's folders), from one du over them all. A folder du can't finish
|
|
63
|
+
// keeps what it printed.
|
|
64
|
+
function sizes(folders) {
|
|
65
|
+
return new Promise(resolve => {
|
|
66
|
+
if (!folders.length) return resolve({});
|
|
67
|
+
execFile('du', ['-k', '-d', '2', ...folders], { timeout: DU_TIMEOUT, maxBuffer: 1 << 22 }, (_, stdout) => {
|
|
68
|
+
const out = {};
|
|
69
|
+
for (const line of String(stdout || '').split('\n')) {
|
|
70
|
+
const m = /^(\d+)\t(.+)$/.exec(line);
|
|
71
|
+
if (m) out[m[2]] = +m[1] * 1024;
|
|
72
|
+
}
|
|
73
|
+
resolve(out);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// What fills a folder, as a few words: git worktrees and node_modules, the usual weight.
|
|
79
|
+
function contents(folder) {
|
|
80
|
+
let worktrees = 0, modules = 0;
|
|
81
|
+
const walk = (dir, depth) => {
|
|
82
|
+
let list;
|
|
83
|
+
try { list = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
84
|
+
if (list.some(e => e.name === '.git' && e.isFile())) worktrees++;
|
|
85
|
+
for (const e of list) {
|
|
86
|
+
if (!e.isDirectory() || e.name === '.git') continue;
|
|
87
|
+
if (e.name === 'node_modules') { modules++; continue; }
|
|
88
|
+
if (depth < 4) walk(path.join(dir, e.name), depth + 1);
|
|
89
|
+
}
|
|
90
|
+
};
|
|
91
|
+
walk(folder, 0);
|
|
92
|
+
if (worktrees > 1) return `${worktrees} git worktrees${modules >= worktrees ? ', node_modules in each' : modules ? `, ${modules} node_modules folders` : ''}`;
|
|
93
|
+
return modules > 1 ? `${modules} node_modules folders` : '';
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Who to tell about a session's folder: the session's name from dibs's own
|
|
97
|
+
// records, and the agent that made its biggest scratchpad folder (src/files.mjs
|
|
98
|
+
// notes it), else the session's main thread.
|
|
99
|
+
function ownerOf(folder, session, size) {
|
|
100
|
+
let who = null;
|
|
101
|
+
for (const f of [paths.state, path.join(HOME, 'messages.json')]) {
|
|
102
|
+
try {
|
|
103
|
+
const s = JSON.parse(fs.readFileSync(f, 'utf8'));
|
|
104
|
+
const x = [...(s.leases || []), ...(s.queue || []), ...(s.threads || [])].find(x => (x.sessionId || x.session) === session && x.who);
|
|
105
|
+
if (x) { who = x.who; break; }
|
|
106
|
+
} catch {}
|
|
107
|
+
}
|
|
108
|
+
const pad = path.join(folder, 'scratchpad') + '/';
|
|
109
|
+
const top = Object.entries(size).filter(([p]) => p.startsWith(pad) && !p.slice(pad.length).includes('/')).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))[0];
|
|
110
|
+
const m = top && maker(session, top[0].slice(pad.length));
|
|
111
|
+
return { who, agentId: m?.agent || 'main', type: m?.type || null };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Whether the disk is short: under the floor, or short for a waiter's own declared need.
|
|
115
|
+
function short(cfg, m, s) {
|
|
116
|
+
if (m.diskFree == null) return false;
|
|
117
|
+
const floor = bytes(cfg.minDisk);
|
|
118
|
+
return m.diskFree < floor || (s.queue || []).some(q => q.pid && q.disk && m.diskFree < q.disk);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// One pass, from the throttle watcher: measure on a new drop (and every
|
|
122
|
+
// REMEASURE while it lasts), and leave the biggest folders' agents a notice
|
|
123
|
+
// once per drop. Never throws.
|
|
124
|
+
let busy = false;
|
|
125
|
+
export async function hogsOnce(cfg, m, t = now()) {
|
|
126
|
+
if (busy) return;
|
|
127
|
+
busy = true;
|
|
128
|
+
try {
|
|
129
|
+
let s = {};
|
|
130
|
+
try { s = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
|
|
131
|
+
let was = read();
|
|
132
|
+
const floor = bytes(cfg.minDisk);
|
|
133
|
+
// The clearing first: measuring the folders can take a minute, and the clearing is what frees space.
|
|
134
|
+
const critical = m.diskFree != null && m.diskFree < floor;
|
|
135
|
+
if (m.diskFree != null && m.diskFree < 2 * floor && cleanDue(was, t, critical)) {
|
|
136
|
+
write(was = { ...was, cleaned: await clean(t), cleanedCritical: critical });
|
|
137
|
+
}
|
|
138
|
+
if (!short(cfg, m, s)) {
|
|
139
|
+
if (was?.under && m.diskFree >= floor + OVER) write({ ...was, under: false, endedAt: t });
|
|
140
|
+
else if (m.diskFree != null && m.diskFree < 2 * floor) {
|
|
141
|
+
let x = was || {};
|
|
142
|
+
if (!(t - (was?.readAt || 0) < REMEASURE)) {
|
|
143
|
+
const folders = sessionFolders();
|
|
144
|
+
write(x = { ...x, under: false, ...readings(folders, await sizes([...folders, ...Object.values(places())]), m, was, t) });
|
|
145
|
+
}
|
|
146
|
+
const keep = await warnOnce(cfg, m, x, hintOf(x), t);
|
|
147
|
+
if (Object.keys(keep).length) write({ ...x, ...keep });
|
|
148
|
+
}
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
const drop = was?.under ? was.drop : t;
|
|
152
|
+
// Between measurements the notes still go out on time, from the last measurement.
|
|
153
|
+
if (was?.under && t - was.at < REMEASURE) {
|
|
154
|
+
const keep = await warnOnce(cfg, m, was, hintOf(was), t);
|
|
155
|
+
if (Object.keys(keep).length) write({ ...was, ...keep });
|
|
156
|
+
return;
|
|
157
|
+
}
|
|
158
|
+
const folders = sessionFolders();
|
|
159
|
+
const size = await sizes([...folders, ...Object.values(places())]);
|
|
160
|
+
const big = Object.entries(size).filter(([p, b]) => folders.includes(p) && b >= HOG_MIN()).sort((a, b) => b[1] - a[1]).slice(0, TOP)
|
|
161
|
+
.map(([folder, b]) => ({ folder, session: path.basename(folder), bytes: b, what: contents(path.join(folder, 'scratchpad')) || contents(folder), ...ownerOf(folder, path.basename(folder), size) }));
|
|
162
|
+
const waiting = (s.queue || []).filter(q => q.pid).length;
|
|
163
|
+
const x = { ...(was?.cleaned && { cleaned: was.cleaned, cleanedCritical: was.cleanedCritical }), ...(was?.warned && { warned: was.warned }), under: true, drop, at: t, free: m.diskFree, floor, waiting, folders: big, ...readings(folders, size, m, was, t) };
|
|
164
|
+
write(x);
|
|
165
|
+
const keep = await warnOnce(cfg, m, x, hintOf(x), t);
|
|
166
|
+
if (Object.keys(keep).length) write({ ...x, ...keep });
|
|
167
|
+
const { notify } = await import('./talk.mjs');
|
|
168
|
+
for (const h of big) {
|
|
169
|
+
notify({ sessionId: h.session, agentId: h.agentId, who: h.who }, `diskhog:${drop}:${h.session}`,
|
|
170
|
+
`your session's scratch folder ${h.folder} holds ${GB(h.bytes)}${h.what ? ` (${h.what})` : ''}. This machine is under its disk floor `
|
|
171
|
+
+ `(${GB(m.diskFree)} free, the floor is ${GB(floor)}) and ${waiting} ${waiting === 1 ? 'job waits' : 'jobs wait'}. `
|
|
172
|
+
+ 'Free what you can: remove merged worktrees (git worktree remove <path>), and symlink node_modules from one install instead of installing in each. '
|
|
173
|
+
+ 'Delete only exact paths your session made: other agents of your session may still use the rest.');
|
|
174
|
+
}
|
|
175
|
+
} catch {} finally { busy = false; }
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// { label: bytes } for each session folder, each of places() and swap, and what grew most
|
|
179
|
+
// since the last reading (no older than 3 REMEASURE, so a stale one can't name anything).
|
|
180
|
+
function readings(folders, size, m, was, t) {
|
|
181
|
+
const now = {};
|
|
182
|
+
for (const f of folders) if (size[f] != null) now[`session ${path.basename(f)}'s scratch folder`] = size[f];
|
|
183
|
+
for (const [label, p] of Object.entries(places())) if (size[p] != null) now[label] = size[p];
|
|
184
|
+
if (m.swapUsed != null) now.swap = m.swapUsed;
|
|
185
|
+
let writer = null;
|
|
186
|
+
if (was?.readings && t - was.readAt <= 3 * REMEASURE) {
|
|
187
|
+
for (const [label, b] of Object.entries(now)) {
|
|
188
|
+
const by = b - (was.readings[label] ?? b);
|
|
189
|
+
if (by >= GROW_MIN && (!writer || by > writer.by)) writer = { label, by, ms: t - was.readAt };
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
return { readings: now, readAt: t, writer };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// For a disk wait: what's growing and the biggest folder and whose it is, as words to add, or ''.
|
|
196
|
+
export function hogHint(t = now()) {
|
|
197
|
+
const x = read();
|
|
198
|
+
if (!x?.under || t - x.at >= 3 * REMEASURE) return '';
|
|
199
|
+
return hintOf(x);
|
|
200
|
+
}
|
|
201
|
+
function hintOf(x) {
|
|
202
|
+
const w = x.writer;
|
|
203
|
+
const grew = w ? `. Growing fastest: ${named(w.label, x)}, up ${GB(w.by)} in ${Math.max(1, Math.round(w.ms / 6e4))} min` : '';
|
|
204
|
+
const h = x.folders?.[0];
|
|
205
|
+
if (!h) return grew;
|
|
206
|
+
const name = h.who || `session ${h.session.slice(0, 8)}`;
|
|
207
|
+
return `${grew}. The most is in ${name}'s scratch folder (${GB(h.bytes)}${h.what ? `, ${h.what}` : ''}): ask ${h.who ? `${h.who} (SendMessage)` : 'that session'} to free it, or the person`;
|
|
208
|
+
}
|
|
209
|
+
// A session's folder by its agent's name when dibs knows it.
|
|
210
|
+
function named(label, x) {
|
|
211
|
+
const m = /^session (.+)'s scratch folder$/.exec(label);
|
|
212
|
+
const h = m && x.folders?.find(f => f.session === m[1]);
|
|
213
|
+
return h?.who ? `${h.who}'s scratch folder` : m ? `session ${m[1].slice(0, 8)}'s scratch folder` : label;
|
|
214
|
+
}
|