@dibssoftware/dibs 0.0.180 → 0.0.195

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/CHANGELOG.md +111 -1
  2. package/README.md +10 -8
  3. package/bin/dibs.mjs +379 -74
  4. package/docs/agents.md +303 -0
  5. package/docs/council.md +88 -0
  6. package/docs/files.md +3 -3
  7. package/docs/guard.md +86 -11
  8. package/docs/json.md +211 -0
  9. package/docs/later.md +5 -5
  10. package/docs/machines.md +6 -6
  11. package/docs/questions.md +104 -3
  12. package/docs/reference.md +124 -30
  13. package/docs/relay.md +135 -11
  14. package/docs/releasing.md +7 -1
  15. package/docs/scheduling.md +28 -6
  16. package/docs/secrets.md +53 -0
  17. package/docs/simulators.md +3 -3
  18. package/docs/windows.md +3 -3
  19. package/package.json +1 -1
  20. package/skills/dibs/SKILL.md +79 -149
  21. package/src/about.mjs +341 -0
  22. package/src/acquire.mjs +113 -28
  23. package/src/after.mjs +127 -0
  24. package/src/agents.mjs +2 -1
  25. package/src/alerts.mjs +109 -48
  26. package/src/answers.mjs +2 -2
  27. package/src/board.mjs +21 -16
  28. package/src/broker.mjs +23 -7
  29. package/src/carry.mjs +287 -0
  30. package/src/codex.mjs +132 -0
  31. package/src/commands.mjs +254 -86
  32. package/src/config.mjs +85 -14
  33. package/src/connect.mjs +4 -2
  34. package/src/cool.mjs +28 -12
  35. package/src/council.mjs +482 -0
  36. package/src/cwd.mjs +9 -0
  37. package/src/decisions.mjs +250 -0
  38. package/src/declare.mjs +96 -0
  39. package/src/diskreport.mjs +306 -0
  40. package/src/diskuse.mjs +420 -0
  41. package/src/diskwarn.mjs +68 -13
  42. package/src/doctor.mjs +149 -0
  43. package/src/doors.mjs +547 -0
  44. package/src/durable.mjs +143 -0
  45. package/src/envs.mjs +372 -0
  46. package/src/events.mjs +7 -2
  47. package/src/files.mjs +121 -7
  48. package/src/guard.mjs +288 -105
  49. package/src/guardd.mjs +8 -1
  50. package/src/halt.mjs +63 -0
  51. package/src/handoffs.mjs +362 -0
  52. package/src/history.mjs +34 -4
  53. package/src/hogs.mjs +36 -8
  54. package/src/jobprogress.mjs +283 -0
  55. package/src/later.mjs +21 -10
  56. package/src/lock.mjs +51 -11
  57. package/src/measure.mjs +60 -14
  58. package/src/media.mjs +240 -0
  59. package/src/news.mjs +31 -0
  60. package/src/notes.mjs +49 -8
  61. package/src/notices.mjs +126 -43
  62. package/src/ondemand.mjs +25 -2
  63. package/src/outcome.mjs +163 -0
  64. package/src/overlap.mjs +2 -2
  65. package/src/override.mjs +149 -79
  66. package/src/owner.mjs +15 -2
  67. package/src/people.mjs +236 -0
  68. package/src/pickup.mjs +72 -0
  69. package/src/picture.mjs +321 -0
  70. package/src/plain.mjs +84 -18
  71. package/src/platform.mjs +29 -7
  72. package/src/preempt.mjs +123 -15
  73. package/src/primer.mjs +91 -20
  74. package/src/prints.mjs +99 -0
  75. package/src/proc.mjs +11 -1
  76. package/src/progress.mjs +49 -3
  77. package/src/proof.mjs +102 -0
  78. package/src/push.mjs +271 -0
  79. package/src/questions.mjs +328 -57
  80. package/src/quota.mjs +1 -1
  81. package/src/recap.mjs +205 -0
  82. package/src/relay.mjs +262 -26
  83. package/src/remote.mjs +23 -10
  84. package/src/reviewgate.mjs +268 -0
  85. package/src/reviews.mjs +377 -0
  86. package/src/route.mjs +263 -0
  87. package/src/rules.mjs +216 -0
  88. package/src/schedule.mjs +238 -44
  89. package/src/schema.mjs +62 -0
  90. package/src/scratch.mjs +2 -2
  91. package/src/serve.mjs +3 -2
  92. package/src/service.mjs +5 -1
  93. package/src/signed.mjs +97 -0
  94. package/src/simpool.mjs +46 -1
  95. package/src/spend.mjs +375 -0
  96. package/src/state.mjs +43 -17
  97. package/src/talk.mjs +1082 -134
  98. package/src/thin.sh +2 -0
  99. package/src/trail.mjs +290 -0
  100. package/src/trailnote.mjs +209 -0
  101. package/src/util.mjs +7 -0
  102. package/src/vault.mjs +435 -0
  103. package/src/vendors.mjs +327 -0
  104. package/src/version.mjs +1 -1
  105. package/src/web.mjs +354 -60
  106. package/src/work.mjs +487 -0
  107. package/src/worker.mjs +7 -1
@@ -0,0 +1,420 @@
1
+ // Who uses the disk, agent session by agent session, and the folders an agent
2
+ // said dibs may delete once its session ends (dibs disk add).
3
+ //
4
+ // While free disk is under ZONE floors, the throttle watcher measures each
5
+ // session's scratch folder in Claude Code's temp folder and the folders it
6
+ // marked disposable, every USE_EVERY, keeps the reading in diskuse.json, and
7
+ // tells a session's agent when it fills more than its share or grows fast. On
8
+ // 2026-11-26 eight agents' jobs sat for hours under the 5 GB floor while one
9
+ // agent's scratch folder grew 2.6 GB in 5 minutes, and that agent heard nothing
10
+ // until the disk was already under.
11
+ //
12
+ // The folders are dibs's only deletes outside its own copies and the caches
13
+ // that rebuild themselves (src/diskwarn.mjs): each was named by the session
14
+ // that made it, is deleted only once every session that named it has ended
15
+ // (END_GRACE later, so a resumed session finds it), and only if it is still
16
+ // the same folder (device and inode) and still passes refusal(). Never in
17
+ // Claude Code's temp folders, a home folder's own, or a repository's checkout.
18
+ import fs from 'node:fs';
19
+ import os from 'node:os';
20
+ import path from 'node:path';
21
+ import { execFile } from 'node:child_process';
22
+ import { HOME, paths, loadConfig, machine } from './config.mjs';
23
+ import { claudeTmp, takeAgent, talkKey } from './files.mjs';
24
+ import { identity, makeAlive, sessionFiles } from './proc.mjs';
25
+ import { sessionFolders, ownerOf } from './hogs.mjs';
26
+ import { underLock, commit } from './lock.mjs';
27
+ import { logChange } from './owner.mjs';
28
+ import { event } from './events.mjs';
29
+ import { bold, dim, columns } from './style.mjs';
30
+ import { gb, bytes, now, die, fakeFull, dur, SCHEMA } from './util.mjs';
31
+ import { readJSON } from './durable.mjs';
32
+
33
+ const FILE = path.join(HOME, 'disposable.json');
34
+ const LOCK = path.join(HOME, 'disposable.lock');
35
+ // The last reading and whom it told: written by the watcher, or by dibs disk when that's stale.
36
+ const USE = path.join(HOME, 'diskuse.json');
37
+ const LOG = path.join(HOME, 'cool.log');
38
+ // Writes take milliseconds: a live holder past this is stuck on something else.
39
+ const LOCK_WAIT = 15e3;
40
+ // How often sessions are measured: 2026-11-26's 2.6 GB took 5 minutes.
41
+ const USE_EVERY = 5 * 6e4;
42
+ // Measured only while free disk is under this many floors (20 GB stock): with more free, nobody's share matters yet.
43
+ const ZONE = 4;
44
+ // What a gigabyte is to the thresholds below. DIBS_DISK_GB stands in for it in tests, whose folders are small.
45
+ const UNIT = Number(process.env.DIBS_DISK_GB) || 1024 ** 3;
46
+ // A share is never smaller than this: under it, deleting wouldn't get anyone's job started.
47
+ const SHARE_MIN = UNIT;
48
+ // Growing this much between two readings is fast: an hour of it empties a Mac with 12 GB free.
49
+ const FAST = UNIT;
50
+ const FAST_AGAIN = 30 * 6e4;
51
+ // A session that ended may be resumed (claude --resume): its folders wait this long first.
52
+ const END_GRACE = 30 * 6e4;
53
+ const DU_TIMEOUT = 120e3;
54
+ // The board of who uses what shows this many, and dibs disk lists this many deletions.
55
+ const ROWS = 12, KEEP_CLEARED = 20;
56
+ // Smaller than this is nobody's problem: it doesn't make the list.
57
+ const SHOW_MIN = UNIT / 20;
58
+
59
+ const GB = b => gb(b).replace(/G$/, ' GB');
60
+ const real = p => { try { return fs.realpathSync(p); } catch { return null; } };
61
+ const inside = (p, dir) => p === dir || p.startsWith(dir.endsWith(path.sep) ? dir : dir + path.sep);
62
+ const table = rows => columns(rows).join('\n');
63
+ const tilde = p => (inside(p, os.homedir()) ? '~' + p.slice(os.homedir().length) : p);
64
+
65
+ // ---- the folders an agent marked disposable ----
66
+
67
+ function load() {
68
+ let s = {};
69
+ try { s = readJSON(FILE); } catch {}
70
+ s.dirs ||= []; s.cleared ||= [];
71
+ return s;
72
+ }
73
+ // quiet: the watcher's call, which throws instead of exiting: dibs never stops its watcher over a lock.
74
+ function locked(fn, quiet = false) {
75
+ const r = underLock(LOCK, h => {
76
+ const s = load();
77
+ const before = JSON.stringify(s);
78
+ const out = fn(s);
79
+ if (JSON.stringify(s) !== before) commit(h, FILE, JSON.stringify(s, null, 1), { fake: () => fakeFull('state') });
80
+ return out;
81
+ }, { wait: LOCK_WAIT, files: [FILE] });
82
+ if (!r && quiet) throw new Error(`${LOCK} stayed locked`);
83
+ if (!r) die(`${LOCK} is held by a dibs that's still running, and stayed held for ${LOCK_WAIT / 1000}s. Nothing was changed: run the same command again.`, 75);
84
+ return r.out;
85
+ }
86
+
87
+ // Folders that are home folders' own on macOS and Linux: never anyone's scratch.
88
+ const PERSONAL = new Set(['Desktop', 'Documents', 'Downloads', 'Movies', 'Music', 'Pictures', 'Public', 'Applications', 'Library', 'Videos', 'snap']);
89
+ // Where a disposable folder may be: the home folder, the temp folders, and the scratch volume (dibs setup scratch).
90
+ function roots() {
91
+ const out = [os.homedir(), os.tmpdir(), '/tmp', '/private/tmp', '/var/tmp', process.env.DIBS_SCRATCH || '/Volumes/DibsScratch'];
92
+ return [...new Set(out.map(real).filter(Boolean))];
93
+ }
94
+
95
+ // Why dibs won't delete folder p (a real path), or null when it may.
96
+ export function refusal(p) {
97
+ let st;
98
+ try { st = fs.lstatSync(p); } catch { return `${p} doesn't exist`; }
99
+ if (!st.isDirectory()) return `${p} isn't a folder`;
100
+ const home = real(os.homedir()) || os.homedir();
101
+ if (roots().includes(p)) return `${p} is a whole ${p === home ? 'home' : 'temp'} folder`;
102
+ if (!roots().some(r => inside(p, r))) return `${p} isn't inside your home folder, a temp folder or the scratch volume`;
103
+ const dibs = real(HOME) || HOME;
104
+ if (inside(p, dibs) || inside(dibs, p)) return `${p} is dibs's own folder`;
105
+ for (const r of claudeTmp().map(real).filter(Boolean))
106
+ if (inside(p, r) || inside(r, p)) return `${p} is in Claude Code's temp folder, where only its own session deletes`;
107
+ if (path.dirname(p) === home && (PERSONAL.has(path.basename(p)) || path.basename(p).startsWith('.'))) return `${p} is one of your home folder's own`;
108
+ const lib = path.join(home, 'Library'), derived = path.join(lib, 'Developer/Xcode/DerivedData');
109
+ if (inside(p, lib) && !(inside(p, derived) && p !== derived)) return `${p} is in ~/Library, where only a project's own DerivedData folder may be`;
110
+ try { if (fs.lstatSync(path.join(p, '.git')).isDirectory()) return `${p} is a git repository's own checkout, where its commits and stashes live (a worktree of it, from git worktree add, may be)`; } catch {}
111
+ try { if (fs.statSync(path.dirname(p)).dev !== st.dev) return `${p} is a volume of its own`; } catch {}
112
+ return null;
113
+ }
114
+
115
+ // Which sessions are still running: a registrant's own process (pid and start), or its Claude Code
116
+ // session under any pid, since a resumed session runs under a new one.
117
+ function liveness(xs) {
118
+ const files = sessionFiles();
119
+ const up = makeAlive([...xs.map(x => x.spid), ...files.map(f => f.pid)].filter(Boolean));
120
+ const live = new Set(files.filter(f => up(f.pid)).map(f => f.sessionId));
121
+ const alive = x => !!((x.spid && up(x.spid, x.sstart)) || (x.session && live.has(x.session)));
122
+ alive.count = live.size;
123
+ return alive;
124
+ }
125
+
126
+ function caller(args) {
127
+ const id = identity();
128
+ const session = process.env.CLAUDE_CODE_SESSION_ID || sessionFiles().find(f => f.pid === id.spid)?.sessionId || null;
129
+ if (!session && !id.spid) return null;
130
+ // Which subagent asked, as the hook saw it (src/files.mjs): its folders are its own.
131
+ const by = session ? takeAgent('disk', [], talkKey('disk', args)) : null;
132
+ return { session, spid: id.spid, sstart: id.sstart, who: id.who, agentId: by?.agentId || 'main' };
133
+ }
134
+
135
+ function add(args) {
136
+ const dirs = args.slice(1).filter(a => !a.startsWith('-'));
137
+ if (!dirs.length) die('which folder? dibs disk add <dir> [<dir>...]: folders your session made, which dibs may delete once your session ends');
138
+ const me = caller(args);
139
+ if (!me) die("dibs disk add ties each folder to the agent session that made it, and dibs can't find one here (it's for Claude Code, Codex and other agents' sessions). Nothing was added.");
140
+ const found = [];
141
+ for (const d of dirs) {
142
+ const p = real(path.resolve(d));
143
+ const why = p ? refusal(p) : `${path.resolve(d)} doesn't exist`;
144
+ if (why) die(`${why}, so dibs won't delete it. Nothing was added.`);
145
+ const st = fs.statSync(p);
146
+ if (olderThan(st, me.sstart)) die(`${tilde(p)} was there before your session started, so it isn't yours to give away. Nothing was added.`);
147
+ // Its birth time too: Linux hands a deleted folder's inode to the next one made, so on a CI runner
148
+ // a folder deleted and made again under the same name read as the one marked (2026-12-06).
149
+ found.push({ path: p, dev: st.dev, ino: st.ino, ...(st.birthtimeMs > 0 && { born: st.birthtimeMs }) });
150
+ }
151
+ locked(s => {
152
+ for (const f of found) {
153
+ s.dirs = s.dirs.filter(x => !(x.path === f.path && sameSession(x, me)));
154
+ s.dirs.push({ ...f, session: me.session, spid: me.spid, sstart: me.sstart, who: me.who, agentId: me.agentId, at: now() });
155
+ }
156
+ });
157
+ for (const f of found) console.log(`dibs deletes ${tilde(f.path)} ${END_GRACE / 6e4} minutes after your session ends. To keep it: dibs disk keep ${tilde(f.path)}`);
158
+ }
159
+ // A folder made before the session started isn't the session's (a folder of projects, each its
160
+ // own repo, passes refusal()). ps gives the start to the second, rounded down, so a folder made
161
+ // after it never reads older; the slack is for clocks. A file system that keeps no birth time
162
+ // (birthtimeMs 0) can't tell, and the other checks stand alone there.
163
+ const BORN_SLACK = 1000;
164
+ function olderThan(st, sstart) {
165
+ const started = Date.parse(sstart || '');
166
+ return st.birthtimeMs > 0 && Number.isFinite(started) && st.birthtimeMs < started - BORN_SLACK;
167
+ }
168
+ const sameSession = (x, me) => (x.session && x.session === me.session) || (!x.session && x.spid === me.spid);
169
+
170
+ function keep(args) {
171
+ const dirs = args.slice(1).filter(a => !a.startsWith('-'));
172
+ if (!dirs.length) die('which folder? dibs disk keep <dir>: dibs won\'t delete it after all');
173
+ const me = caller(args);
174
+ const want = dirs.map(d => real(path.resolve(d)) || path.resolve(d));
175
+ const dropped = locked(s => {
176
+ const out = s.dirs.filter(x => want.includes(x.path));
177
+ s.dirs = s.dirs.filter(x => !want.includes(x.path));
178
+ return out;
179
+ });
180
+ if (!dropped.length) die(`dibs wasn't going to delete ${andOr(want.map(tilde))}. The folders it will: dibs disk list`, 1);
181
+ // Another agent's folder, kept: on the record, as any change to another agent's work is.
182
+ const theirs = dropped.filter(x => !(me && sameSession(x, me)));
183
+ if (theirs.length) logChange('disk keep', { paths: theirs.map(x => x.path), of: [...new Set(theirs.map(x => x.who))] });
184
+ console.log(`dibs won't delete ${andOr([...new Set(dropped.map(x => tilde(x.path)))])}.`);
185
+ }
186
+ const andOr = xs => (xs.length < 2 ? xs.join('') : `${xs.slice(0, -1).join(', ')} and ${xs.at(-1)}`);
187
+
188
+ function list(o) {
189
+ const s = load();
190
+ const alive = liveness(s.dirs);
191
+ if (o.json) return console.log(JSON.stringify({ schema: SCHEMA, dirs: s.dirs.map(x => ({ ...x, live: alive(x) })), cleared: s.cleared }, null, 1));
192
+ if (!s.dirs.length) console.log('No folders are waiting to be deleted. An agent marks its own: dibs disk add <dir>');
193
+ else {
194
+ console.log(bold('Deleted once their session ends'));
195
+ console.log(table(s.dirs.map(x => [tilde(x.path), `${x.who}${x.agentId && x.agentId !== 'main' ? `/${x.agentId}` : ''}: `
196
+ + (alive(x) ? 'its session is running' : x.endedAt ? `its session ended ${dur(now() - x.endedAt)} ago, deleted in ${dur(Math.max(0, x.endedAt + END_GRACE - now()))}` : 'its session ended, deleted soon')])));
197
+ }
198
+ if (s.cleared.length) {
199
+ console.log('\n' + bold('Deleted'));
200
+ console.log(table(s.cleared.slice(-5).reverse().map(x => [tilde(x.path), `${x.who}'s${x.bytes != null ? `, ${GB(x.bytes)}` : ''}, ${dur(now() - x.at)} ago`])));
201
+ }
202
+ }
203
+
204
+ // The folders whose sessions have all ended (END_GRACE ago), deleted, and logged. Run by the
205
+ // watcher on every pass and by dibs disk. Returns what it deleted.
206
+ let reaping = false;
207
+ export async function reapDisposable(t = now()) {
208
+ if (reaping || !fs.existsSync(FILE)) return [];
209
+ reaping = true;
210
+ try {
211
+ let st = {};
212
+ try { st = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
213
+ // A job running or waiting in it keeps it until that ends: its files are in use.
214
+ const used = [...(st.leases || []), ...(st.queue || [])].map(l => l.cwd && real(l.cwd)).filter(Boolean);
215
+ const due = locked(s => {
216
+ const alive = liveness(s.dirs);
217
+ for (const x of s.dirs) {
218
+ if (alive(x)) delete x.endedAt;
219
+ else x.endedAt ??= t;
220
+ }
221
+ const ready = [...new Set(s.dirs.map(x => x.path))].filter(p => {
222
+ const xs = s.dirs.filter(x => x.path === p);
223
+ return xs.every(x => x.endedAt != null && t - x.endedAt >= END_GRACE) && !used.some(c => inside(c, p));
224
+ });
225
+ const out = ready.map(p => s.dirs.find(x => x.path === p));
226
+ s.dirs = s.dirs.filter(x => !ready.includes(x.path));
227
+ return out;
228
+ }, true);
229
+ const done = [];
230
+ for (const x of due) {
231
+ let now_;
232
+ try { now_ = fs.lstatSync(x.path); } catch { continue; } // gone already
233
+ // Not the folder that was named (deleted and made again), or not one dibs may delete now: left alone.
234
+ if (now_.dev !== x.dev || now_.ino !== x.ino || (x.born && now_.birthtimeMs > 0 && now_.birthtimeMs !== x.born) || refusal(x.path)) continue;
235
+ const size = await du([x.path]);
236
+ const gitdir = worktreeOf(x.path);
237
+ try { await fs.promises.rm(x.path, { recursive: true, force: true }); }
238
+ catch (e) { log(`couldn't delete ${x.path}, which ${x.who} marked disposable: ${e.message}`); continue; }
239
+ if (gitdir) await new Promise(r => execFile('git', ['--git-dir', gitdir, 'worktree', 'prune'], { timeout: 30e3 }, () => r()));
240
+ const freed = size[x.path] ?? null;
241
+ done.push({ path: x.path, who: x.who, session: x.session, bytes: freed, at: now() });
242
+ log(`deleted ${x.path}${freed != null ? ` (${GB(freed)})` : ''}, which ${x.who} marked disposable; its session ended ${dur(t - x.endedAt)} ago`);
243
+ event({ kind: 'disposed', path: x.path, who: x.who, sessionId: x.session, bytes: freed });
244
+ }
245
+ if (done.length) locked(s => { s.cleared = [...s.cleared, ...done].slice(-KEEP_CLEARED); }, true);
246
+ return done;
247
+ } catch { return []; } finally { reaping = false; }
248
+ }
249
+ const log = line => { try { fs.appendFileSync(LOG, `${new Date().toISOString()} ${line}\n`); } catch {} };
250
+ // A worktree's repository (its .git file says where), so git forgets it once it's deleted.
251
+ function worktreeOf(p) {
252
+ try {
253
+ const m = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(path.join(p, '.git'), 'utf8'));
254
+ const wt = m && path.resolve(p, m[1].trim());
255
+ return wt && path.basename(path.dirname(wt)) === 'worktrees' ? path.dirname(path.dirname(wt)) : null;
256
+ } catch { return null; }
257
+ }
258
+
259
+ // ---- who uses what ----
260
+
261
+ // { path: bytes } from one du over them all. A folder du can't finish is left out.
262
+ function du(dirs) {
263
+ return new Promise(resolve => {
264
+ if (!dirs.length) return resolve({});
265
+ execFile('du', ['-sk', ...dirs], { timeout: DU_TIMEOUT, maxBuffer: 1 << 22 }, (_, stdout) => {
266
+ const out = {};
267
+ for (const line of String(stdout || '').split('\n')) {
268
+ const m = /^(\d+)\t(.+)$/.exec(line);
269
+ if (m) out[m[2]] = +m[1] * 1024;
270
+ }
271
+ resolve(out);
272
+ });
273
+ });
274
+ }
275
+
276
+ const readUse = () => { try { return JSON.parse(fs.readFileSync(USE, 'utf8')); } catch { return null; } };
277
+ function writeUse(x) {
278
+ const tmp = `${USE}.${process.pid}.tmp`;
279
+ fs.writeFileSync(tmp, JSON.stringify(x));
280
+ fs.renameSync(tmp, USE);
281
+ }
282
+
283
+ // One reading: a row per session with what it fills (its scratch folder, its disposable
284
+ // folders), what it grew since the last reading, and each live session's share.
285
+ export async function measure(cfg, m, was, t = now()) {
286
+ const reg = load().dirs;
287
+ const alive = liveness(reg);
288
+ const folders = sessionFolders();
289
+ // A disposable folder inside another one is counted once, in the outer.
290
+ const own = [...new Set(reg.map(x => x.path))];
291
+ const outer = own.filter(p => !own.some(q => q !== p && inside(p, q)));
292
+ const size = await du([...folders, ...outer]);
293
+ const live = new Set(sessionFiles().filter(f => alive({ session: f.sessionId })).map(f => f.sessionId));
294
+ const rows = new Map();
295
+ const row = k => rows.get(k) || rows.set(k, { key: k, session: null, who: null, live: false, bytes: 0, scratch: 0, dirs: [] }).get(k);
296
+ for (const f of folders) {
297
+ if (!size[f]) continue;
298
+ const r = row(path.basename(f));
299
+ Object.assign(r, { session: path.basename(f), folder: f, scratch: size[f], live: live.has(path.basename(f)) });
300
+ r.bytes += size[f];
301
+ }
302
+ for (const p of outer) {
303
+ if (size[p] == null) continue;
304
+ const x = reg.find(y => y.path === p);
305
+ const r = row(x.session || `pid ${x.spid}`);
306
+ r.session ||= x.session; r.who ||= x.who;
307
+ r.live ||= alive(x);
308
+ r.dirs.push({ path: p, bytes: size[p] });
309
+ r.bytes += size[p];
310
+ }
311
+ const names = new Map(sessionFiles().map(f => [f.sessionId, f.name]));
312
+ for (const r of rows.values()) r.who ||= (r.session && names.get(r.session)) || (r.folder && ownerOf(r.folder, r.session, {}).who) || null;
313
+ const recent = was?.at != null && t - was.at <= 3 * USE_EVERY;
314
+ for (const r of rows.values()) {
315
+ const prev = recent && was.rows?.find(y => y.key === r.key);
316
+ if (prev) Object.assign(r, { grew: r.bytes - prev.bytes, ms: t - was.at });
317
+ }
318
+ const floor = bytes(cfg.minDisk || '0');
319
+ const sessions = [...rows.values()].filter(r => r.live);
320
+ // An even split of what's free above the floor and what the running sessions already fill,
321
+ // among every running session (one that fills nothing still gets its part).
322
+ const count = Math.max(1, new Set([...live, ...sessions.map(r => r.key)]).size);
323
+ const room = Math.max(0, (m.diskFree ?? 0) - floor) + sessions.reduce((a, r) => a + r.bytes, 0);
324
+ const share = cfg.diskShare != null ? bytes(cfg.diskShare) : Math.max(SHARE_MIN, room / count);
325
+ const list = [...rows.values()].filter(r => r.bytes >= SHOW_MIN || r.grew >= FAST).sort((a, b) => b.bytes - a.bytes).slice(0, ROWS);
326
+ return { at: t, free: m.diskFree ?? null, floor, share, sessions: count, rows: list };
327
+ }
328
+
329
+ // What a session's agent hears: what it fills, why that's too much, and what to do.
330
+ export function useNote(r, x) {
331
+ const parts = [...(r.scratch ? [`its scratch folder ${GB(r.scratch)}`] : []), ...r.dirs.slice(0, 3).map(d => `${tilde(d.path)} ${GB(d.bytes)}`)].join(', ');
332
+ const over = r.bytes > x.share;
333
+ const fast = r.grew >= FAST ? `${over ? 'It' : "your session's disk use"} grew ${GB(r.grew)} in the last ${Math.max(1, Math.round(r.ms / 6e4))} min` : '';
334
+ const lines = [];
335
+ if (over) lines.push(`your session fills ${GB(r.bytes)} of disk (${parts}), over its share of ${GB(x.share)}: ${x.sessions} running ${x.sessions === 1 ? 'session shares' : 'sessions share'} what's free above the ${GB(x.floor)} dibs keeps free, and ${GB(x.free)} is free now`, ...(fast ? [fast] : []));
336
+ else lines.push(`${fast}, to ${GB(r.bytes)} (${parts}). ${GB(x.free)} of disk is free, and dibs starts nothing new under ${GB(x.floor)}`);
337
+ lines.push('Delete what you made and no longer need: merged worktrees (git worktree remove <path>), build output, node_modules you can install again. Only exact paths you made: other agents of your session may still use the rest');
338
+ lines.push('Mark folders you make that dibs may delete once your session ends: dibs disk add <dir>');
339
+ return lines.join('. ') + '.';
340
+ }
341
+
342
+ // Tell each running session over its share (once each time it goes over: back under means under
343
+ // UNDER of it, since the share moves with free disk and a session at its line crossed it back and
344
+ // forth) or growing fast (at most every FAST_AGAIN). Quiet: it comes with the agent's next tool
345
+ // call and never wakes a dibs listen, since nothing fails yet. Returns whom it told, to keep.
346
+ const UNDER = 0.75;
347
+ async function tell(x, was, t) {
348
+ const { notify } = await import('./talk.mjs');
349
+ const told = {};
350
+ for (const r of x.rows) {
351
+ const k = { ...(was?.told?.[r.key] || {}) };
352
+ if (!r.live) continue;
353
+ const over = r.bytes > x.share;
354
+ if (r.bytes < UNDER * x.share) delete k.over;
355
+ const say = (over && !k.over) || (r.grew >= FAST && !(t - (k.fast || 0) < FAST_AGAIN));
356
+ if (say && notify({ sessionId: r.session, who: r.who }, `diskuse:${r.key}:${t}`, useNote(r, x), { quiet: true })) {
357
+ if (over) k.over = t;
358
+ if (r.grew >= FAST) k.fast = t;
359
+ }
360
+ if (Object.keys(k).length) told[r.key] = k;
361
+ }
362
+ return told;
363
+ }
364
+
365
+ // One pass, from the throttle watcher: delete what's due, and measure and tell every USE_EVERY
366
+ // while free disk is under ZONE floors. Never throws.
367
+ let busy = false;
368
+ export async function useOnce(cfg, m, t = now()) {
369
+ if (busy) return;
370
+ busy = true;
371
+ try {
372
+ await reapDisposable(t);
373
+ const floor = bytes(cfg.minDisk || '0');
374
+ if (m.diskFree == null || !floor || m.diskFree >= ZONE * floor) return;
375
+ const was = readUse();
376
+ if (t - (was?.at || 0) < USE_EVERY) return;
377
+ const x = await measure(cfg, m, was, t);
378
+ writeUse({ ...x, told: await tell(x, was, t) });
379
+ } catch {} finally { busy = false; }
380
+ }
381
+
382
+ // For the disk alert and a disk wait: who fills the most, as words to add, or ''.
383
+ export function useHint(t = now()) {
384
+ const x = readUse();
385
+ if (!x || t - x.at >= 3 * USE_EVERY) return '';
386
+ const top = x.rows.filter(r => r.live && r.bytes >= SHARE_MIN).slice(0, 3);
387
+ return top.length ? `. Filling the most: ${top.map(r => `${r.who || `session ${String(r.session || r.key).slice(0, 8)}`} ${GB(r.bytes)}`).join(', ')} (dibs disk)` : '';
388
+ }
389
+
390
+ // dibs disk [add|keep|list] [--json] [--fresh]
391
+ export async function disk(args) {
392
+ const sub = args[0];
393
+ if (sub === 'add') return add(args);
394
+ if (sub === 'keep') return keep(args);
395
+ if (sub === 'list') return list({ json: args.includes('--json') });
396
+ if (sub && !sub.startsWith('-')) die(`dibs disk ${sub}? It's dibs disk (the biggest users and who fills what; --fresh measures again), dibs disk add <dir>, dibs disk keep <dir> or dibs disk list`);
397
+ const cfg = loadConfig(), m = machine();
398
+ await reapDisposable();
399
+ let x = readUse();
400
+ // A reading older than the watcher's pace is taken again: the watcher may be down, or the disk roomy.
401
+ if (!x || now() - x.at > 2 * USE_EVERY) {
402
+ x = { ...(await measure(cfg, m, x)), told: x?.told || {} };
403
+ try { writeUse(x); } catch {}
404
+ }
405
+ // The biggest users on the machine, dibs's or not (src/diskreport.mjs): measured again when older than FRESH, or with --fresh.
406
+ const rep = await import('./diskreport.mjs');
407
+ const json = args.includes('--json'), again = args.includes('--fresh');
408
+ if (!json && process.stderr.isTTY) process.stderr.write(dim('Measuring the biggest folders on this machine (a minute at most)...') + '\r');
409
+ const big = await rep.report(m, { fresh: again ? 0 : rep.FRESH });
410
+ if (!json && process.stderr.isTTY) process.stderr.write('\x1b[2K');
411
+ if (json) return console.log(JSON.stringify({ schema: SCHEMA, ...x, rows: x.rows.map(r => ({ agent: r.who ?? null, ...r })), machine: big }, null, 1));
412
+ console.log(`${GB(m.diskFree ?? x.free ?? 0)} of disk free; dibs starts nothing new under ${GB(x.floor)}. Each running session's share: ${GB(x.share)} (${x.sessions} running)`);
413
+ console.log('\n' + rep.lines(big, { dim, bold }).join('\n') + '\n');
414
+ console.log(bold('Agent sessions'));
415
+ if (!x.rows.length) return console.log('No session fills more than a few megabytes.');
416
+ console.log(table(x.rows.map(r => [r.who || `session ${String(r.session || r.key).slice(0, 8)}`,
417
+ [GB(r.bytes), !r.live ? 'session ended' : r.bytes > x.share ? 'over its share' : '', r.grew >= FAST ? `grew ${GB(r.grew)} in ${Math.max(1, Math.round(r.ms / 6e4))} min` : ''].filter(Boolean).join(', '),
418
+ dim([...(r.scratch ? [`scratch folder ${GB(r.scratch)}`] : []), ...r.dirs.map(d => `${tilde(d.path)} ${GB(d.bytes)}`)].join(', '))])));
419
+ console.log(dim(`measured ${dur(now() - x.at)} ago. Folders dibs deletes when their session ends: dibs disk list`));
420
+ }
package/src/diskwarn.mjs CHANGED
@@ -1,8 +1,11 @@
1
1
  // Before the disk runs out: under twice the floor, dibs clears caches that
2
- // rebuild themselves, and tells the sessions with something of their own to
3
- // free (a big scratch folder, or running jobs that wrote a lot) how much is
4
- // free and what to do. Each hears once per band: under twice the floor, then
5
- // under the floor. On 2026-10-20 the Mac hit 210 MB free: writes failed, Bash
2
+ // rebuild themselves, quietly. Only once it's urgent (within URGENT floors, or
3
+ // falling fast enough to reach the floor within FALL_WITHIN) does it tell the
4
+ // sessions with something of their own to free (a big scratch folder, or
5
+ // running jobs that wrote a lot) how much is free and what to do. Each hears
6
+ // once per band and drop: urgent, then under the floor, and again only after
7
+ // free disk was back over twice the floor (src/hogs.mjs clears the bands).
8
+ // On 2026-10-20 the Mac hit 210 MB free: writes failed, Bash
6
9
  // died for every session, and jobs sat silently on "free disk". On 2026-11-03
7
10
  // the warnings had gone to every session, 13 of them as the disk fell from 8.2
8
11
  // to 4.7 GB, mostly to agents with nothing to free; the person sees the whole
@@ -17,6 +20,9 @@ import { event } from './events.mjs';
17
20
  import { gb, bytes, now } from './util.mjs';
18
21
  import { makeAlive } from './proc.mjs';
19
22
  import { withState } from './state.mjs';
23
+ import { described } from './declare.mjs';
24
+ import { eraseIdle } from './simpool.mjs';
25
+ import { reportHint } from './diskreport.mjs';
20
26
 
21
27
  const GB = b => gb(b).replace(/G$/, ' GB');
22
28
  const SAY_FREED = 0.1 * 1024 ** 3; // less than shows as 0.0 GB: not worth a line
@@ -25,6 +31,15 @@ const LOG = path.join(HOME, 'cool.log');
25
31
  const ATE_MIN = 1024 ** 3;
26
32
  // The bands a session hears about once each, worst last.
27
33
  const BANDS = ['low', 'critical'];
34
+ // Urgent: free disk within this many floors. On 2026-11-28 an agent was told "disk getting low"
35
+ // at 9.8 GB free over a 5 GB floor, with nothing to do about it, and read it as a nag.
36
+ const URGENT = 1.5;
37
+ // Or falling fast enough to reach the floor within this long, measured over the last
38
+ // FALL_SAMPLE to 2 FALL_SAMPLE: a reading every FALL_SAMPLE keeps writes to a nearly full disk few.
39
+ const FALL_WITHIN = 36e5;
40
+ const FALL_SAMPLE = 5 * 6e4;
41
+ // A fall over less than this is the usual churn of a reading, not a rate.
42
+ const FALL_SPAN = 6e4;
28
43
  // Clearing caches again sooner than this frees little: they refill slowly.
29
44
  const CLEAN_EVERY = 30 * 6e4;
30
45
  const STEP_TIMEOUT = 2 * 6e4;
@@ -71,6 +86,11 @@ async function staleDerived(dir, t) {
71
86
  return was || 0;
72
87
  }
73
88
 
89
+ // Whether the pool has a device no lease holds, read without the lock or a simctl call.
90
+ function poolIdle() {
91
+ try { return (JSON.parse(fs.readFileSync(paths.state, 'utf8')).pool || []).some(d => !d.lease && d.udid); } catch { return false; }
92
+ }
93
+
74
94
  // One clearing: each step in turn, what it freed by free disk before and after, logged under dibs's name.
75
95
  export async function clean(t = now(), where = HOME) {
76
96
  const done = [];
@@ -84,10 +104,15 @@ export async function clean(t = now(), where = HOME) {
84
104
  const by = before != null && after != null ? (st.dir ? before - after : after - before) : 0;
85
105
  done.push({ label: st.label, freed: Math.max(0, by) });
86
106
  }
107
+ // The pool's idle simulators are this dibs's own (src/simpool.mjs), so a test's DIBS_HOME clears its own too.
108
+ try { if (poolIdle()) done.push({ label: 'idle pool simulators', freed: eraseIdle() }); } catch {}
87
109
  const freed = done.reduce((a, d) => a + d.freed, 0);
88
110
  // The room this freed hides what running jobs wrote meanwhile, so their runs don't count
89
- // toward being small (src/schedule.mjs tinyDisk).
90
- try { withState(s => { for (const l of s.leases) if (l.kind === 'run') l.cleaned = true; }); } catch {}
111
+ // toward being small (src/schedule.mjs tinyDisk). A clean that freed next to nothing hides
112
+ // nothing: on 2026-11-27 one ran every 30 minutes all night, freeing 0.0 GB each time, and
113
+ // marked every test run it overlapped, so no run ever counted, no test was ever small, and
114
+ // test runs that write nothing waited an hour or more under the floor.
115
+ if (freed >= SAY_FREED) try { withState(s => { for (const l of s.leases) if (l.kind === 'run') l.cleaned = true; }); } catch {}
91
116
  try {
92
117
  fs.appendFileSync(LOG, `${new Date(t).toISOString()} disk low: dibs cleared ${done.map(d => d.label).join(', ')}, freeing ${GB(freed)}\n`);
93
118
  event({ kind: 'clean', freed, steps: done });
@@ -109,15 +134,40 @@ function sessions(s, was) {
109
134
  for (const q of s.queue || []) if (q.pid && out.has(q.sessionId)) out.get(q.sessionId).waiting.push(q);
110
135
  return [...out.values()];
111
136
  }
112
- const job = x => `#${x.id}${x.purpose ? ` ("${x.purpose}")` : ''}`;
137
+ const job = x => `#${x.id} ("${described(x)}")`;
138
+
139
+ // Free disk readings for the rate of fall: the newest (at, free) and the one before it. Returns
140
+ // the new readings when one is due, else null.
141
+ function sampled(fall, m, t) {
142
+ if (fall && t - fall.at < FALL_SAMPLE) return null;
143
+ return { at: t, free: m.diskFree, ...(fall && t - fall.at <= 2 * FALL_SAMPLE && { prev: { at: fall.at, free: fall.free } }) };
144
+ }
145
+ // How fast free disk is falling now, as { by, ms } over the last readings, or null when it isn't
146
+ // or there's no reading recent enough to say.
147
+ function fallOf(fall, m, t) {
148
+ const p = [fall?.prev, fall].find(x => x && t - x.at <= 3 * FALL_SAMPLE && t - x.at >= FALL_SPAN);
149
+ if (!p || !(p.free > m.diskFree)) return null;
150
+ return { by: p.free - m.diskFree, ms: t - p.at };
151
+ }
152
+ // Whether the agents should hear about the disk now.
153
+ function urgent(m, floor, rate) {
154
+ if (m.diskFree < URGENT * floor) return true;
155
+ return !!rate && (m.diskFree - floor) / (rate.by / rate.ms) < FALL_WITHIN;
156
+ }
113
157
 
114
- // The note itself. hint: what's growing and the biggest folder (hogs.mjs hogHint), cleaned: clean()'s result.
115
- export function noteText(x, m, floor, hint, cleaned) {
158
+ // The note itself. hint: what's growing and the biggest folder (hogs.mjs hogHint), cleaned: clean()'s result,
159
+ // rate: how fast it's falling (fallOf).
160
+ export function noteText(x, m, floor, hint, cleaned, rate) {
116
161
  const critical = m.diskFree < floor;
162
+ const left = rate ? Math.max(1, Math.round((m.diskFree - floor) / (rate.by / rate.ms) / 6e4)) : 0;
117
163
  const lines = [critical
118
164
  ? `free disk is critically low: ${GB(m.diskFree)} left (dibs starts nothing new under ${GB(floor)}). Writes, builds and even Bash will start failing. Save your work now: commit or copy anything in progress.`
119
- : `free disk is getting low: ${GB(m.diskFree)} left (dibs starts nothing new under ${GB(floor)})`];
165
+ : `free disk is getting low: ${GB(m.diskFree)} left (dibs starts nothing new under ${GB(floor)})`
166
+ + (rate ? `, down ${GB(rate.by)} in ${Math.max(1, Math.round(rate.ms / 6e4))} min: at that pace it reaches ${GB(floor)} in about ${left} min` : '')];
120
167
  if (hint) lines.push(hint.replace(/^\. /, ''));
168
+ // The biggest users on the machine, dibs's or not (src/diskreport.mjs), so no agent hunts for them by hand.
169
+ const big = reportHint();
170
+ if (big) lines.push(big.replace(/^\. /, ''));
121
171
  if (cleaned?.freed >= SAY_FREED) lines.push(`dibs cleared caches that rebuild themselves and freed ${GB(cleaned.freed)} (${cleaned.steps.filter(d => d.freed >= SAY_FREED).map(d => `${d.label} ${GB(d.freed)}`).join(', ')})`);
122
172
  if (critical && x.running.length) lines.push(`Your running dibs ${x.running.length === 1 ? 'job' : 'jobs'} ${x.running.map(job).join(', ')} may fail writing: save what it has done if you can`);
123
173
  // Over the floor a waiter is held by something else, not the disk.
@@ -134,8 +184,8 @@ export function watcherDown() {
134
184
  return !(pid && makeAlive([pid])(pid));
135
185
  }
136
186
 
137
- // One pass, from hogs.mjs under twice the floor: clear caches when due, then tell
138
- // each session with something to free, once per band. Returns what to keep in hogs.json.
187
+ // One pass, from hogs.mjs under twice the floor: clear caches when due, then, when it's urgent,
188
+ // tell each session with something to free, once per band. Returns what to keep in hogs.json.
139
189
  export async function warnOnce(cfg, m, was, hint, t = now()) {
140
190
  const floor = bytes(cfg.minDisk);
141
191
  if (m.diskFree == null || m.diskFree >= 2 * floor) return {};
@@ -143,6 +193,10 @@ export async function warnOnce(cfg, m, was, hint, t = now()) {
143
193
  const keep = {};
144
194
  let cleaned = was?.cleaned && t - was.cleaned.at < CLEAN_EVERY ? was.cleaned : null;
145
195
  if (cleanDue(was, t, critical)) { cleaned = await clean(t); Object.assign(keep, { cleaned, cleanedCritical: critical }); }
196
+ const rate = fallOf(was?.fall, m, t);
197
+ const fall = sampled(was?.fall, m, t);
198
+ if (fall) keep.fall = fall;
199
+ if (!urgent(m, floor, rate)) return keep;
146
200
  let s = {};
147
201
  try { s = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
148
202
  const { notify } = await import('./talk.mjs');
@@ -151,7 +205,8 @@ export async function warnOnce(cfg, m, was, hint, t = now()) {
151
205
  const warned = { ...(was?.warned || {}) };
152
206
  for (const x of sessions(s, was)) {
153
207
  if (BANDS.indexOf(warned[x.session]?.level) >= BANDS.indexOf(level)) continue;
154
- if (notify({ sessionId: x.session, who: x.who, agentId: x.agentId }, `disk:${level}:${t}`, noteText(x, m, floor, hint, cleaned))) warned[x.session] = { at: t, level, free: m.diskFree };
208
+ // Under the floor wakes a listening agent: writes are about to fail. Above it, the note comes with its next tool call.
209
+ if (notify({ sessionId: x.session, who: x.who, agentId: x.agentId }, `disk:${level}:${t}`, noteText(x, m, floor, hint, cleaned, rate), { quiet: !critical })) warned[x.session] = { at: t, level, free: m.diskFree };
155
210
  }
156
211
  // Kept only when it changed: on a nearly full disk, every write counts.
157
212
  return JSON.stringify(warned) === JSON.stringify(was?.warned || {}) ? keep : { ...keep, warned };