@dibssoftware/dibs 0.0.0-stage → 0.0.178

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +577 -0
  2. package/LICENSE +670 -0
  3. package/README.md +234 -2
  4. package/bin/dibs-guard.mjs +7 -0
  5. package/bin/dibs.mjs +526 -0
  6. package/docs/benchmarks.md +193 -0
  7. package/docs/files.md +30 -0
  8. package/docs/guard.md +91 -0
  9. package/docs/later.md +43 -0
  10. package/docs/machines.md +147 -0
  11. package/docs/questions.md +78 -0
  12. package/docs/relay.md +196 -0
  13. package/docs/releasing.md +25 -0
  14. package/docs/scheduling.md +163 -0
  15. package/docs/simulators.md +17 -0
  16. package/package.json +44 -4
  17. package/skills/dibs/SKILL.md +162 -0
  18. package/src/acquire.mjs +697 -0
  19. package/src/admin.mjs +145 -0
  20. package/src/agents.mjs +145 -0
  21. package/src/alerts.mjs +437 -0
  22. package/src/answers.mjs +65 -0
  23. package/src/board.mjs +202 -0
  24. package/src/broker.mjs +369 -0
  25. package/src/commands.mjs +801 -0
  26. package/src/config.mjs +320 -0
  27. package/src/connect.mjs +106 -0
  28. package/src/cool.mjs +160 -0
  29. package/src/diskwarn.mjs +161 -0
  30. package/src/events.mjs +94 -0
  31. package/src/files.mjs +1100 -0
  32. package/src/guard.mjs +583 -0
  33. package/src/history.mjs +247 -0
  34. package/src/hogs.mjs +214 -0
  35. package/src/later.mjs +487 -0
  36. package/src/measure.mjs +262 -0
  37. package/src/nodecheck.mjs +17 -0
  38. package/src/notices.mjs +121 -0
  39. package/src/ondemand.mjs +572 -0
  40. package/src/overlap.mjs +151 -0
  41. package/src/override.mjs +351 -0
  42. package/src/owner.mjs +30 -0
  43. package/src/plain.mjs +467 -0
  44. package/src/platform.mjs +357 -0
  45. package/src/preempt.mjs +438 -0
  46. package/src/primer.mjs +61 -0
  47. package/src/proc.mjs +98 -0
  48. package/src/progress.mjs +158 -0
  49. package/src/qr.mjs +204 -0
  50. package/src/questions.mjs +389 -0
  51. package/src/quota.mjs +81 -0
  52. package/src/reads.mjs +54 -0
  53. package/src/relay.mjs +779 -0
  54. package/src/remote.mjs +584 -0
  55. package/src/reset.mjs +127 -0
  56. package/src/schedule.mjs +995 -0
  57. package/src/scratch.mjs +61 -0
  58. package/src/serve.mjs +736 -0
  59. package/src/service.mjs +221 -0
  60. package/src/shard.mjs +59 -0
  61. package/src/simctl.mjs +42 -0
  62. package/src/simpool.mjs +258 -0
  63. package/src/state.mjs +201 -0
  64. package/src/stats.mjs +328 -0
  65. package/src/style.mjs +44 -0
  66. package/src/talk.mjs +523 -0
  67. package/src/thin.sh +130 -0
  68. package/src/trust.mjs +152 -0
  69. package/src/util.mjs +184 -0
  70. package/src/version.mjs +2 -0
  71. package/src/web.mjs +1117 -0
  72. package/src/worker.mjs +318 -0
@@ -0,0 +1,161 @@
1
+ // Before the disk runs out: under twice the floor, dibs clears caches that
2
+ // rebuild themselves, and tells every active session how much is free, what's
3
+ // growing and whose folder holds the most, at most every WARN_EVERY, again at
4
+ // once when it drops under the floor. Under the floor, each agent with a job
5
+ // running hears to save its work now, and each with a job waiting hears that
6
+ // it waits for disk. On 2026-10-20 the Mac hit 210 MB free: writes failed,
7
+ // Bash died for every session, and jobs sat silently on "free disk".
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { execFile } from 'node:child_process';
12
+ import { HOME, paths } from './config.mjs';
13
+ import { freeDisk, OS } from './platform.mjs';
14
+ import { event } from './events.mjs';
15
+ import { gb, bytes, now } from './util.mjs';
16
+ import { makeAlive } from './proc.mjs';
17
+
18
+ const GB = b => gb(b).replace(/G$/, ' GB');
19
+ const SAY_FREED = 0.1 * 1024 ** 3; // less than shows as 0.0 GB: not worth a line
20
+ const LOG = path.join(HOME, 'cool.log');
21
+ export const WARN_EVERY = 15 * 6e4;
22
+ // Clearing caches again sooner than this frees little: they refill slowly.
23
+ const CLEAN_EVERY = 30 * 6e4;
24
+ const STEP_TIMEOUT = 2 * 6e4;
25
+ const DAY = 24 * 36e5;
26
+
27
+ // The caches dibs may clear on its own: each rebuilds itself when next needed.
28
+ // Never Claude Code's temp folders, a person's own folders, or a booted simulator
29
+ // (simctl's "unavailable" ones have no runtime, so nothing can boot them).
30
+ // DIBS_CLEAN ({label: argv}) and DIBS_DERIVED stand in for them in tests.
31
+ function steps() {
32
+ // A test's own DIBS_HOME never clears the real caches.
33
+ if (!process.env.DIBS_CLEAN && HOME !== path.join(os.homedir(), '.dibs')) return [];
34
+ if (process.env.DIBS_CLEAN) {
35
+ // {label: argv}, or {label: {argv, dir}} to measure a folder.
36
+ return [...Object.entries(JSON.parse(process.env.DIBS_CLEAN)).map(([label, x]) => (Array.isArray(x) ? { label, argv: x } : { label, ...x })),
37
+ ...(process.env.DIBS_DERIVED ? [{ label: 'Xcode build output unused for a day', derived: process.env.DIBS_DERIVED }] : [])];
38
+ }
39
+ const h = os.homedir();
40
+ const out = [{ label: 'npm cache', argv: ['npm', 'cache', 'clean', '--force'], dir: path.join(h, '.npm/_cacache') }];
41
+ if (OS === 'macos') {
42
+ out.push({ label: 'Homebrew cache', argv: ['brew', 'cleanup', '-s'], dir: path.join(h, 'Library/Caches/Homebrew') },
43
+ { label: 'unavailable simulators', argv: ['xcrun', 'simctl', 'delete', 'unavailable'], dir: path.join(h, 'Library/Developer/CoreSimulator/Devices') },
44
+ { label: 'Xcode build output unused for a day', derived: path.join(os.homedir(), 'Library/Developer/Xcode/DerivedData') });
45
+ }
46
+ return out;
47
+ }
48
+ const run = argv => new Promise(resolve => execFile(argv[0], argv.slice(1), { timeout: STEP_TIMEOUT }, () => resolve()));
49
+ // A folder's size in bytes, or null. What a step freed is its folders' shrink,
50
+ // not free disk before and after: on 2026-10-22 swap gave back 3 GB while
51
+ // Homebrew's cleanup ran, and the note said the cleanup freed it.
52
+ const size = dirs => new Promise(resolve => execFile('du', ['-sk', ...dirs], { timeout: STEP_TIMEOUT }, (e, out) => {
53
+ const kb = String(out || '').split('\n').map(l => parseInt(l, 10)).filter(n => n >= 0);
54
+ resolve(kb.length ? kb.reduce((a, n) => a + n, 0) * 1024 : null);
55
+ }));
56
+ // A DerivedData folder no build has touched in a day: Xcode makes it again on the next build.
57
+ // Returns what it removed, in bytes.
58
+ async function staleDerived(dir, t) {
59
+ let list = [];
60
+ try { list = fs.readdirSync(dir, { withFileTypes: true }); } catch { return 0; }
61
+ const stale = list.filter(e => e.isDirectory()).map(e => path.join(dir, e.name)).filter(p => { try { return t - fs.statSync(p).mtimeMs > DAY; } catch { return false; } });
62
+ if (!stale.length) return 0;
63
+ const was = await size(stale);
64
+ for (const p of stale) try { fs.rmSync(p, { recursive: true, force: true }); } catch {}
65
+ return was || 0;
66
+ }
67
+
68
+ // One clearing: each step in turn, what it freed by free disk before and after, logged under dibs's name.
69
+ export async function clean(t = now(), where = HOME) {
70
+ const done = [];
71
+ for (const st of steps()) {
72
+ if (st.derived) { done.push({ label: st.label, freed: await staleDerived(st.derived, t) }); continue; }
73
+ // A step without a folder to measure (DIBS_CLEAN in tests) falls back to free disk.
74
+ const measure = () => (st.dir ? size([st.dir]) : freeDisk(where));
75
+ const before = await measure();
76
+ await run(st.argv);
77
+ const after = await measure();
78
+ const by = before != null && after != null ? (st.dir ? before - after : after - before) : 0;
79
+ done.push({ label: st.label, freed: Math.max(0, by) });
80
+ }
81
+ const freed = done.reduce((a, d) => a + d.freed, 0);
82
+ try {
83
+ fs.appendFileSync(LOG, `${new Date(t).toISOString()} disk low: dibs cleared ${done.map(d => d.label).join(', ')}, freeing ${GB(freed)}\n`);
84
+ event({ kind: 'clean', freed, steps: done });
85
+ } catch {}
86
+ return { at: t, freed, steps: done };
87
+ }
88
+ export const cleanDue = (was, t, critical) => !(t - (was?.cleaned?.at || 0) < (critical && !was?.cleanedCritical ? 0 : CLEAN_EVERY));
89
+
90
+ // The sessions to tell: those with a job running or waiting, and those whose
91
+ // thread with dibs moved in the last hour. Their jobs, for the note.
92
+ function sessions(s, t) {
93
+ const out = new Map();
94
+ const add = (session, who, agentId) => { if (session && !out.has(session)) out.set(session, { session, who, agentId: agentId || null, running: [], waiting: [] }); return out.get(session); };
95
+ for (const l of s.leases || []) if (l.kind === 'run' && l.sessionId) add(l.sessionId, l.who, l.agentId).running.push(l);
96
+ for (const q of s.queue || []) if (q.pid && q.sessionId) add(q.sessionId, q.who, q.agentId).waiting.push(q);
97
+ try {
98
+ for (const th of JSON.parse(fs.readFileSync(path.join(HOME, 'messages.json'), 'utf8')).threads || [])
99
+ if (th.session && t - (th.last || 0) < 36e5) add(th.session, th.who, th.agentId);
100
+ } catch {}
101
+ return [...out.values()];
102
+ }
103
+ const job = x => `#${x.id}${x.purpose ? ` ("${x.purpose}")` : ''}`;
104
+
105
+ // The note itself. hint: what's growing and the biggest folder (hogs.mjs hogHint), cleaned: clean()'s result.
106
+ export function noteText(x, m, floor, hint, cleaned) {
107
+ const critical = m.diskFree < floor;
108
+ const lines = [critical
109
+ ? `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.`
110
+ : `free disk is getting low: ${GB(m.diskFree)} left (dibs starts nothing new under ${GB(floor)})`];
111
+ if (hint) lines.push(hint.replace(/^\. /, ''));
112
+ 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(', ')})`);
113
+ 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`);
114
+ // Over the floor a waiter is held by something else, not the disk.
115
+ if (critical && x.waiting.length) lines.push(`Your waiting ${x.waiting.length === 1 ? 'job' : 'jobs'} ${x.waiting.map(job).join(', ')} won't start until there's room`);
116
+ lines.push('Free what you can of your own: build output, scratch folders and merged worktrees your session made (only exact paths you made; others of your session may still use the rest)');
117
+ return lines.join('. ') + '.';
118
+ }
119
+
120
+ // Whether a session hears again. Under the floor: every WARN_EVERY, and at once on
121
+ // dropping under it. Over it: only once free disk has fallen DROP_AGAIN since its last
122
+ // note, or something grows fast (hogs.mjs writer): a note every 15 minutes at a steady
123
+ // 9.2 GB taught agents to skip it.
124
+ const DROP_AGAIN = 1024 ** 3;
125
+ function again(last, level, m, was, t) {
126
+ if (level === 'critical') return last.level !== 'critical' || t - last.at >= WARN_EVERY;
127
+ if (t - last.at < WARN_EVERY) return false;
128
+ return last.free == null || last.free - m.diskFree >= DROP_AGAIN || !!(was?.writer && t - was.readAt < WARN_EVERY);
129
+ }
130
+
131
+ // Whether the throttle watcher (src/cool.mjs) is down: its pidfile names no live process.
132
+ export function watcherDown() {
133
+ let pid = 0;
134
+ try { pid = Number(fs.readFileSync(path.join(HOME, 'cool.pid'), 'utf8')); } catch {}
135
+ return !(pid && makeAlive([pid])(pid));
136
+ }
137
+
138
+ // One pass, from hogs.mjs under twice the floor: clear caches when due, then tell
139
+ // each active session, once per WARN_EVERY and level. Returns what to keep in hogs.json.
140
+ export async function warnOnce(cfg, m, was, hint, t = now()) {
141
+ const floor = bytes(cfg.minDisk);
142
+ if (m.diskFree == null || m.diskFree >= 2 * floor) return {};
143
+ const critical = m.diskFree < floor;
144
+ const keep = {};
145
+ let cleaned = was?.cleaned && t - was.cleaned.at < CLEAN_EVERY ? was.cleaned : null;
146
+ if (cleanDue(was, t, critical)) { cleaned = await clean(t); Object.assign(keep, { cleaned, cleanedCritical: critical }); }
147
+ let s = {};
148
+ try { s = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
149
+ const { notify } = await import('./talk.mjs');
150
+ const level = critical ? 'critical' : 'low';
151
+ // Each session's last note, so it hears again only WARN_EVERY later, or at once when it turns critical.
152
+ const warned = { ...(was?.warned || {}) };
153
+ for (const x of sessions(s, t)) {
154
+ const last = warned[x.session];
155
+ if (last && !again(last, level, m, was, t)) continue;
156
+ 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 };
157
+ }
158
+ for (const [k, w] of Object.entries(warned)) if (t - w.at > 4 * WARN_EVERY) delete warned[k];
159
+ // Kept only when it changed: on a nearly full disk, every write counts.
160
+ return JSON.stringify(warned) === JSON.stringify(was?.warned || {}) ? keep : { ...keep, warned };
161
+ }
package/src/events.mjs ADDED
@@ -0,0 +1,94 @@
1
+ // What happened, one JSON line per event, for dibs history and the Mac app.
2
+ // Lease starts, ends, pauses and resumes are found by comparing the state
3
+ // before and after each change (logChanges, called by withState), so every
4
+ // way a lease ends is caught: exit, crash, release, a hold running out.
5
+ // Waits and timeouts come from acquire, load samples from the throttle
6
+ // watcher, owner overrides from whoever overrides. Appending never fails a
7
+ // run: an error is written once per process to dibs.log and dropped.
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { HOME } from './config.mjs';
11
+ import { now } from './util.mjs';
12
+
13
+ export const EVENTS = path.join(HOME, 'events.jsonl');
14
+ export const OLDER = path.join(HOME, 'events.1.jsonl');
15
+ const LOG = path.join(HOME, 'dibs.log');
16
+ // Two files, each rotated out at half the limits, keep at most 30 days and 20 MB.
17
+ // A rename never loses an append racing it: the line lands in one file or the other.
18
+ export const KEEP_MS = 30 * 864e5;
19
+ export const KEEP_BYTES = 20 * 1024 ** 2;
20
+
21
+ let complained = false;
22
+ function complain(e) {
23
+ if (complained) return;
24
+ complained = true;
25
+ try { fs.appendFileSync(LOG, `${new Date().toISOString()} couldn't write ${EVENTS}: ${e.message}. History misses events from pid ${process.pid}.\n`); } catch {}
26
+ }
27
+
28
+ // Append one event: { kind, res, who, ... }. `at` is set when missing.
29
+ // Overrides go through here too: event({ kind: 'override', res, who, ... }).
30
+ export function event(e) {
31
+ try { fs.appendFileSync(EVENTS, JSON.stringify({ at: now(), ...e }) + '\n'); } catch (err) { complain(err); }
32
+ }
33
+
34
+ // Move the current file aside once it's past half of either limit. Called
35
+ // under the state lock, so two processes never rotate at once.
36
+ export function rotate(t = now()) {
37
+ try {
38
+ const st = fs.statSync(EVENTS);
39
+ if (st.size < KEEP_BYTES / 2 && t - firstAt() < KEEP_MS / 2) return;
40
+ fs.renameSync(EVENTS, OLDER);
41
+ } catch (e) { if (e.code !== 'ENOENT') complain(e); }
42
+ }
43
+
44
+ // When the current file's first event happened. Only its first bytes are read.
45
+ function firstAt() {
46
+ const fd = fs.openSync(EVENTS, 'r');
47
+ try {
48
+ const buf = Buffer.alloc(64);
49
+ fs.readSync(fd, buf, 0, 64, 0);
50
+ return Number(buf.toString().match(/^\{"at":(\d+)/)?.[1]) || now();
51
+ } finally { fs.closeSync(fd); }
52
+ }
53
+
54
+ // Every event kept, oldest first. A line cut short by a crash is skipped.
55
+ export function readEvents(t = now()) {
56
+ const out = [];
57
+ for (const f of [OLDER, EVENTS]) {
58
+ let text = '';
59
+ try { text = fs.readFileSync(f, 'utf8'); } catch {}
60
+ for (const l of text.split('\n')) {
61
+ if (!l) continue;
62
+ try { const e = JSON.parse(l); if (e.at >= t - KEEP_MS) out.push(e); } catch {}
63
+ }
64
+ }
65
+ return out.sort((a, b) => a.at - b.at);
66
+ }
67
+
68
+ const fields = l => ({ id: l.id, res: l.res, who: l.who, prio: l.prio || 'normal', type: l.kind });
69
+
70
+ // before: the leases as read, before dead ones were reaped. paused: their
71
+ // pausedAt at that point (the lease objects themselves change in place).
72
+ export function logChanges(before, paused, s) {
73
+ try {
74
+ const t = now();
75
+ const after = new Map(s.leases.map(l => [l.id, l]));
76
+ const was = new Set(before.map(l => l.id));
77
+ const out = [];
78
+ for (const l of s.leases) {
79
+ if (!was.has(l.id)) out.push({ at: t, kind: 'start', ...fields(l), ms: l.waited ?? 0, ...(l.held && { held: l.held }) });
80
+ else if (!paused.get(l.id) && l.pausedAt) out.push({ at: t, kind: 'pause', ...fields(l) });
81
+ else if (paused.get(l.id) && !l.pausedAt) out.push({ at: t, kind: 'resume', ...fields(l), ms: t - paused.get(l.id) });
82
+ }
83
+ for (const l of before) {
84
+ if (after.has(l.id)) continue;
85
+ const pausedMs = (l.pausedMs || 0) + (paused.get(l.id) ? t - paused.get(l.id) : 0);
86
+ // What it was, so a failure can be named and a later success of the same command can close it (src/alerts.mjs).
87
+ out.push({ at: t, kind: 'end', ...fields(l), code: l.code ?? null, ms: t - l.start, paused: pausedMs,
88
+ ...(l.kind === 'run' && { key: l.key, cmd: String(l.cmd || '').slice(0, 120), ...(l.purpose && { purpose: String(l.purpose).slice(0, 120) }) }) });
89
+ }
90
+ if (!out.length) return;
91
+ rotate(t);
92
+ for (const e of out) event(e);
93
+ } catch (e) { complain(e); }
94
+ }