@dibssoftware/dibs 0.0.178 → 0.0.179

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/diskwarn.mjs CHANGED
@@ -1,10 +1,12 @@
1
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".
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
6
+ // died for every session, and jobs sat silently on "free disk". On 2026-11-03
7
+ // the warnings had gone to every session, 13 of them as the disk fell from 8.2
8
+ // to 4.7 GB, mostly to agents with nothing to free; the person sees the whole
9
+ // machine in dibs alerts.
8
10
  import fs from 'node:fs';
9
11
  import os from 'node:os';
10
12
  import path from 'node:path';
@@ -18,7 +20,10 @@ import { makeAlive } from './proc.mjs';
18
20
  const GB = b => gb(b).replace(/G$/, ' GB');
19
21
  const SAY_FREED = 0.1 * 1024 ** 3; // less than shows as 0.0 GB: not worth a line
20
22
  const LOG = path.join(HOME, 'cool.log');
21
- export const WARN_EVERY = 15 * 6e4;
23
+ // Running jobs that wrote this much (src/measure.mjs, a run's share of the disk's fall) have something to free.
24
+ const ATE_MIN = 1024 ** 3;
25
+ // The bands a session hears about once each, worst last.
26
+ const BANDS = ['low', 'critical'];
22
27
  // Clearing caches again sooner than this frees little: they refill slowly.
23
28
  const CLEAN_EVERY = 30 * 6e4;
24
29
  const STEP_TIMEOUT = 2 * 6e4;
@@ -87,17 +92,17 @@ export async function clean(t = now(), where = HOME) {
87
92
  }
88
93
  export const cleanDue = (was, t, critical) => !(t - (was?.cleaned?.at || 0) < (critical && !was?.cleanedCritical ? 0 : CLEAN_EVERY));
89
94
 
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) {
95
+ // The sessions to tell: those with something of their own to free, a scratch
96
+ // folder hogs.mjs found over its line (was.folders) or running jobs that ate
97
+ // ATE_MIN of disk. Their jobs, for the note.
98
+ function sessions(s, was) {
93
99
  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 {}
100
+ const add = (session, who, agentId) => { if (session && !out.has(session)) out.set(session, { session, who, agentId: agentId || null, running: [], waiting: [], growing: false }); return out.get(session); };
101
+ // Growing: its folder grew since the last reading (hogs.mjs), or its jobs are writing.
102
+ for (const h of was?.folders || []) add(h.session, h.who, h.agentId).growing ||= !!was.grew?.includes(`session ${h.session}'s scratch folder`);
103
+ for (const l of s.leases || []) if (l.kind === 'run' && l.sessionId && (l.ate || 0) >= ATE_MIN) add(l.sessionId, l.who, l.agentId).growing = true;
104
+ for (const l of s.leases || []) if (l.kind === 'run' && out.has(l.sessionId)) out.get(l.sessionId).running.push(l);
105
+ for (const q of s.queue || []) if (q.pid && out.has(q.sessionId)) out.get(q.sessionId).waiting.push(q);
101
106
  return [...out.values()];
102
107
  }
103
108
  const job = x => `#${x.id}${x.purpose ? ` ("${x.purpose}")` : ''}`;
@@ -113,21 +118,11 @@ export function noteText(x, m, floor, hint, cleaned) {
113
118
  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
119
  // Over the floor a waiter is held by something else, not the disk.
115
120
  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)');
121
+ // Files holding still were there before the disk got low: telling their session to free them each time taught agents to skip the note (e4, 2026-11-03).
122
+ if (x.growing) 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
123
  return lines.join('. ') + '.';
118
124
  }
119
125
 
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
126
  // Whether the throttle watcher (src/cool.mjs) is down: its pidfile names no live process.
132
127
  export function watcherDown() {
133
128
  let pid = 0;
@@ -136,7 +131,7 @@ export function watcherDown() {
136
131
  }
137
132
 
138
133
  // 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.
134
+ // each session with something to free, once per band. Returns what to keep in hogs.json.
140
135
  export async function warnOnce(cfg, m, was, hint, t = now()) {
141
136
  const floor = bytes(cfg.minDisk);
142
137
  if (m.diskFree == null || m.diskFree >= 2 * floor) return {};
@@ -148,14 +143,12 @@ export async function warnOnce(cfg, m, was, hint, t = now()) {
148
143
  try { s = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
149
144
  const { notify } = await import('./talk.mjs');
150
145
  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.
146
+ // The worst band each session has heard about; hogs.mjs clears it once there's room again.
152
147
  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;
148
+ for (const x of sessions(s, was)) {
149
+ if (BANDS.indexOf(warned[x.session]?.level) >= BANDS.indexOf(level)) continue;
156
150
  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
151
  }
158
- for (const [k, w] of Object.entries(warned)) if (t - w.at > 4 * WARN_EVERY) delete warned[k];
159
152
  // Kept only when it changed: on a nearly full disk, every write counts.
160
153
  return JSON.stringify(warned) === JSON.stringify(was?.warned || {}) ? keep : { ...keep, warned };
161
154
  }
package/src/events.mjs CHANGED
@@ -85,7 +85,9 @@ export function logChanges(before, paused, s) {
85
85
  const pausedMs = (l.pausedMs || 0) + (paused.get(l.id) ? t - paused.get(l.id) : 0);
86
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
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) }) }) });
88
+ ...(l.kind === 'run' && { key: l.key, cmd: String(l.cmd || '').slice(0, 120), ...(l.purpose && { purpose: String(l.purpose).slice(0, 120) }),
89
+ // A deadline (--by) makes its failure the person's business; an override's by is a name, not that.
90
+ ...(typeof l.by === 'number' && { due: l.by }) }) });
89
91
  }
90
92
  if (!out.length) return;
91
93
  rotate(t);
package/src/files.mjs CHANGED
@@ -106,6 +106,25 @@ function inSession(p) {
106
106
  return null;
107
107
  }
108
108
 
109
+ // Subagents of a session that have stopped (SubagentStop), so the main thread may clear
110
+ // what they left in the scratchpad. A teammate that takes another message starts again
111
+ // and loses the mark. The name can't be a folder's: encodeURIComponent never makes a bare %.
112
+ const stopMark = (session, agent) => path.join(makersDir(session), '%stopped', encodeURIComponent(agent));
113
+ export function subagentState(input) {
114
+ if (typeof input?.session_id !== 'string' || typeof input.agent_id !== 'string' || !input.agent_id) return;
115
+ const f = stopMark(input.session_id, input.agent_id);
116
+ try {
117
+ if (input.hook_event_name === 'SubagentStop') { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, String(Date.now())); }
118
+ else if (input.hook_event_name === 'SubagentStart') fs.rmSync(f, { force: true });
119
+ } catch {}
120
+ }
121
+ const stopped = (session, agent) => fs.existsSync(stopMark(session, agent));
122
+
123
+ // Folders that rebuild themselves: a browser profile's caches, Xcode's and Swift's build
124
+ // output, a bundler's. Any agent of the session may clear them in its own scratchpad
125
+ // (on 2026-11-03 an agent had to ask a teammate to delete Chrome caches in its own session).
126
+ const CACHES = new Set(['Cache', 'Caches', 'Code Cache', 'GPUCache', 'DerivedData', '.build', 'build', 'dist', '.next', '.turbo', '.cache']);
127
+
109
128
  export function maker(session, name) {
110
129
  try { return JSON.parse(fs.readFileSync(path.join(makersDir(session), encodeURIComponent(name)), 'utf8')); } catch { return null; }
111
130
  }
@@ -138,15 +157,18 @@ function ownDelete(p, t, input) {
138
157
  if (!rest.length) return whole("your session's temp folder");
139
158
  if (!overlap(path.join(folder, rest[0]), pad)) return null;
140
159
  if (rest.length === 1) return whole("your session's scratchpad");
160
+ if (!GLOB.test(rest.slice(1).join('/')) && rest.slice(1).some(n => CACHES.has(n))) return null;
141
161
  let names = [rest[1]];
142
162
  if (GLOB.test(rest[1])) {
143
163
  try { names = fs.readdirSync(pad).filter(n => overlap(path.join(pad, rest[1]), path.join(pad, n))); } catch { names = []; }
144
164
  }
145
165
  for (const n of names) {
146
166
  const m = maker(input.session_id, n), dir = path.join(pad, n);
147
- if (m && m.agent !== agentOf(input))
167
+ // The main thread may clear what a subagent of its own left, once that subagent has stopped.
168
+ if (m && m.agent !== agentOf(input) && !(agentOf(input) === 'main' && m.agent !== 'main' && stopped(input.session_id, m.agent)))
148
169
  return `${dir} in your session's scratchpad was made by ${agentName(m)}, another agent of your session, so ${t.why} can't delete it.\n`
149
- + `Ask ${m.agent === 'main' ? 'the main thread' : m.type || m.agent} whether it's done with it, or have the person delete it. Deleting single files in it is fine.`;
170
+ + `Ask ${m.agent === 'main' ? 'the main thread' : m.type || m.agent} whether it's done with it, or have the person delete it. Deleting single files in it is fine, `
171
+ + `and so is a cache or build folder in it (${[...CACHES].join(', ')})${agentOf(input) === 'main' ? '. Once that subagent has finished, you may delete the folder' : ''}.`;
150
172
  if (!m && !namedBy(input.session_id, n, agentOf(input)) && bigger(names.length > 1 || rest.length === 2 ? dir : p, UNTRACKED_MAX))
151
173
  return `${dir} in your session's scratchpad holds more than ${UNTRACKED_MAX} files, and dibs can't tell which agent of your session made it (it's older than dibs's record), so ${t.why} can't delete it all.\n`
152
174
  + 'Ask the agents of your session whose it is, or have the person delete it. Deleting single files in it is fine.';
@@ -947,12 +969,13 @@ const READ_VERBS = new Set(['status', 'why', 'mine', 'who', 'when', 'yield']);
947
969
  const ACT_VERBS = new Set(['boost', 'pause', 'resume', 'stop']);
948
970
  const ALIASES = { done: 'release', renew: 'hold', ls: 'status', board: 'status' };
949
971
  // dibs say and dibs question go in the asking agent's own thread (src/talk.mjs),
950
- // and dibs later tells that thread how the job ended (src/later.mjs). Their
972
+ // dibs later tells that thread how the job ended (src/later.mjs), and a dibs
973
+ // progress task belongs to the subagent that posts it (src/progress.mjs). Their
951
974
  // note is keyed by the words, so subagents saying "done" at once each get
952
975
  // their own. A word the hook can't read ($VAR) matches any one word.
953
976
  // Every other call is keyed the same way, by all its words, so two subagents
954
977
  // running `dibs run sim -- ...` at once each claim their own note.
955
- const TALK_VERBS = new Set(['say', 'question', 'later']);
978
+ const TALK_VERBS = new Set(['say', 'question', 'later', 'progress', 'listen']);
956
979
  export const talkKey = (verb, words) => `${verb}|${words.join('\0')}`;
957
980
  // A word the hook can't read ("files:$R/a.ts", $(...)) stands for any one word.
958
981
  const WILD = '\u0001';
package/src/guard.mjs CHANGED
@@ -8,7 +8,7 @@ import fs from 'node:fs';
8
8
  import os from 'node:os';
9
9
  import path from 'node:path';
10
10
  import { fileURLToPath } from 'node:url';
11
- import { tmpGuard, fileGuard, resList } from './files.mjs';
11
+ import { tmpGuard, fileGuard, resList, subagentState } from './files.mjs';
12
12
 
13
13
  const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
14
14
  const HOOK_BIN = path.join(ROOT, 'bin', 'dibs-guard.mjs');
@@ -20,6 +20,11 @@ const LOG = path.join(DIBS_HOME, 'guard.log');
20
20
  // Who has a message from the person waiting: { session_id: [agent ids] }, or
21
21
  // no file at all. src/talk.mjs keeps it; the hook only reads it.
22
22
  const INBOX = path.join(DIBS_HOME, 'inbox.json');
23
+ // dibs listen's list of who listens (src/talk.mjs), and the listeners already reminded about.
24
+ const LISTENERS = path.join(DIBS_HOME, 'listeners.json');
25
+ const REMINDED = path.join(DIBS_HOME, 'listen-reminded.json');
26
+ // Sessions remembered in REMINDED: enough for every session a machine runs in a day or two.
27
+ const REMIND_KEEP = 200;
23
28
  // The threads themselves, which the hook only searches for a subagent's id.
24
29
  const MESSAGES = path.join(DIBS_HOME, 'messages.json');
25
30
  const SETTINGS = process.env.DIBS_CLAUDE_SETTINGS || path.join(os.homedir(), '.claude', 'settings.json');
@@ -429,12 +434,36 @@ function talked(input) {
429
434
  try { return fs.readFileSync(MESSAGES, 'utf8').includes(JSON.stringify(input.agent_id)); } catch { return false; }
430
435
  }
431
436
 
437
+ // A main agent ending its turn after its dibs listen ended (it handed messages over, ran out of
438
+ // time or was killed) is kept going once, for that listener, to start it again: without one, a
439
+ // message sent while it waits sits until its next tool call. Only a session that listened
440
+ // before; one that never did hears about it at its start (src/primer.mjs). One read, and one
441
+ // small write when it reminds.
442
+ function rearm(input) {
443
+ if (input?.hook_event_name !== 'Stop' || input.stop_hook_active || typeof input.session_id !== 'string') return null;
444
+ let l;
445
+ try { l = JSON.parse(fs.readFileSync(LISTENERS, 'utf8'))[`${input.session_id}|main`]; } catch { return null; }
446
+ if (!Number.isInteger(l?.pid)) return null;
447
+ try { process.kill(l.pid, 0); return null; } catch (e) { if (e.code !== 'ESRCH') return null; }
448
+ let told = {};
449
+ try { told = JSON.parse(fs.readFileSync(REMINDED, 'utf8')); } catch {}
450
+ if (told[input.session_id] === l.pid) return null;
451
+ delete told[input.session_id];
452
+ told[input.session_id] = l.pid;
453
+ const keys = Object.keys(told);
454
+ for (const k of keys.slice(0, Math.max(0, keys.length - REMIND_KEEP))) delete told[k];
455
+ fs.writeFileSync(`${REMINDED}.${process.pid}`, JSON.stringify(told));
456
+ fs.renameSync(`${REMINDED}.${process.pid}`, REMINDED);
457
+ return { decision: 'block', reason: 'dibs: re-arm: your dibs listen has ended. Start it again with run_in_background (dibs listen) before you end your turn, so a message sent while you wait wakes you. dibs reminds you once each time it ends.' };
458
+ }
459
+
432
460
  // The hook itself: Claude Code's JSON on stdin, a decision on stdout. Any
433
461
  // failure prints nothing, which leaves the command to the normal permission flow.
434
462
  export async function hook() {
435
463
  let out = null, input = null;
436
464
  try {
437
465
  input = JSON.parse(fs.readFileSync(0, 'utf8'));
466
+ subagentState(input);
438
467
  if (AGENT_EVENT(input)) out = (await import('./agents.mjs')).agentHook(input, dibsConfig());
439
468
  else if (!STOP_EVENT(input) && !START_EVENT(input)) out = respond(input, guardConfig(), dibsCommand());
440
469
  } catch (e) { logError(e, input); }
@@ -444,6 +473,7 @@ export async function hook() {
444
473
  if (queuedFor(input)) out = (await import('./talk.mjs')).deliver(input, out);
445
474
  else if (input?.hook_event_name === 'SubagentStop' && talked(input)) (await import('./talk.mjs')).finished(input);
446
475
  } catch (e) { logError(e, input); }
476
+ try { if (!out) out = rearm(input); } catch (e) { logError(e, input); }
447
477
  if (out) process.stdout.write(JSON.stringify(out) + '\n');
448
478
  }
449
479
 
package/src/hogs.mjs CHANGED
@@ -118,6 +118,12 @@ function short(cfg, m, s) {
118
118
  return m.diskFree < floor || (s.queue || []).some(q => q.pid && q.disk && m.diskFree < q.disk);
119
119
  }
120
120
 
121
+ // The session folders over HOG_MIN, biggest first, with whose they are.
122
+ function bigFolders(folders, size) {
123
+ return Object.entries(size).filter(([p, b]) => folders.includes(p) && b >= HOG_MIN()).sort((a, b) => b[1] - a[1]).slice(0, TOP)
124
+ .map(([folder, b]) => ({ folder, session: path.basename(folder), bytes: b, what: contents(path.join(folder, 'scratchpad')) || contents(folder), ...ownerOf(folder, path.basename(folder), size) }));
125
+ }
126
+
121
127
  // One pass, from the throttle watcher: measure on a new drop (and every
122
128
  // REMEASURE while it lasts), and leave the biggest folders' agents a notice
123
129
  // once per drop. Never throws.
@@ -136,12 +142,17 @@ export async function hogsOnce(cfg, m, t = now()) {
136
142
  write(was = { ...was, cleaned: await clean(t), cleanedCritical: critical });
137
143
  }
138
144
  if (!short(cfg, m, s)) {
139
- if (was?.under && m.diskFree >= floor + OVER) write({ ...was, under: false, endedAt: t });
145
+ // Room again (twice the floor): a later fall is news to each session, band by band (src/diskwarn.mjs).
146
+ const room = m.diskFree != null && m.diskFree >= 2 * floor;
147
+ if (was?.under && m.diskFree >= floor + OVER) { const { warned, ...rest } = was; write({ ...(room ? rest : was), under: false, endedAt: t }); }
148
+ else if (was?.warned && room) { const { warned, ...rest } = was; write(rest); }
140
149
  else if (m.diskFree != null && m.diskFree < 2 * floor) {
141
150
  let x = was || {};
142
151
  if (!(t - (was?.readAt || 0) < REMEASURE)) {
143
152
  const folders = sessionFolders();
144
- write(x = { ...x, under: false, ...readings(folders, await sizes([...folders, ...Object.values(places())]), m, was, t) });
153
+ const size = await sizes([...folders, ...Object.values(places())]);
154
+ // The folders big enough to be worth freeing: their sessions are the ones told.
155
+ write(x = { ...x, under: false, folders: bigFolders(folders, size), ...readings(folders, size, m, was, t) });
145
156
  }
146
157
  const keep = await warnOnce(cfg, m, x, hintOf(x), t);
147
158
  if (Object.keys(keep).length) write({ ...x, ...keep });
@@ -157,8 +168,7 @@ export async function hogsOnce(cfg, m, t = now()) {
157
168
  }
158
169
  const folders = sessionFolders();
159
170
  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) }));
171
+ const big = bigFolders(folders, size);
162
172
  const waiting = (s.queue || []).filter(q => q.pid).length;
163
173
  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
174
  write(x);
@@ -183,13 +193,16 @@ function readings(folders, size, m, was, t) {
183
193
  for (const [label, p] of Object.entries(places())) if (size[p] != null) now[label] = size[p];
184
194
  if (m.swapUsed != null) now.swap = m.swapUsed;
185
195
  let writer = null;
196
+ // Every folder that grew, not only the fastest: a session whose files hold still has nothing new to free (src/diskwarn.mjs).
197
+ const grew = [];
186
198
  if (was?.readings && t - was.readAt <= 3 * REMEASURE) {
187
199
  for (const [label, b] of Object.entries(now)) {
188
200
  const by = b - (was.readings[label] ?? b);
201
+ if (by >= GROW_MIN) grew.push(label);
189
202
  if (by >= GROW_MIN && (!writer || by > writer.by)) writer = { label, by, ms: t - was.readAt };
190
203
  }
191
204
  }
192
- return { readings: now, readAt: t, writer };
205
+ return { readings: now, readAt: t, writer, grew };
193
206
  }
194
207
 
195
208
  // For a disk wait: what's growing and the biggest folder and whose it is, as words to add, or ''.
package/src/news.mjs ADDED
@@ -0,0 +1,101 @@
1
+ // What changed in dibs, for the agents using it: the CHANGELOG's sections, which version each
2
+ // agent last heard about (seen.json, shared with bin/dibs.mjs's what's-new line), the version on
3
+ // disk now (an update lands while a long dibs listen is running), and whether dibs.cc has a
4
+ // newer release (asked at most every 6 hours per machine, never for a git checkout).
5
+ import fs from 'node:fs';
6
+ import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import { HOME, paths, loadConfig } from './config.mjs';
9
+
10
+ export const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
11
+ // DIBS_VERSION_FILE stands in for it in tests, which can't bump the real one.
12
+ const VERSION_FILE = process.env.DIBS_VERSION_FILE || path.join(ROOT, 'src', 'version.mjs');
13
+ // The newest release, as the Mac app reads it. DIBS_UPDATE_URL points a test at its own.
14
+ const LATEST = process.env.DIBS_UPDATE_URL || 'https://dibs.cc/mac/latest.json';
15
+ // How often one machine asks dibs.cc, whoever asks: a release a few hours old can wait.
16
+ export const CHECK_EVERY = 6 * 36e5;
17
+ // An answer slower than this is no answer: the check never holds anything up.
18
+ const CHECK_TIMEOUT = 3000;
19
+ const CHECKED = path.join(HOME, 'update-check.json');
20
+ export const UPGRADE = 'curl -fsSL https://dibs.cc/install.sh | sh';
21
+
22
+ // "0.0.178" against "0.0.99": by number, part by part.
23
+ export function newer(a, b) {
24
+ const x = String(a).split('.').map(Number), y = String(b).split('.').map(Number);
25
+ for (let i = 0; i < Math.max(x.length, y.length); i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) > (y[i] || 0);
26
+ return false;
27
+ }
28
+
29
+ // The changelog's sections, newest first: [{ version, body }].
30
+ export function changelog() {
31
+ try {
32
+ return fs.readFileSync(path.join(ROOT, 'CHANGELOG.md'), 'utf8').split(/^## /m).slice(1)
33
+ .map(sec => ({ version: sec.split(/\s/)[0], body: sec.slice(sec.indexOf('\n') + 1).trim() }));
34
+ } catch { return []; }
35
+ }
36
+
37
+ // The sections after from, up to and including to, oldest first.
38
+ export const since = (from, to) => changelog().filter(c => /^\d/.test(c.version) && newer(c.version, from) && !newer(c.version, to)).reverse();
39
+
40
+ const readSeen = () => { try { return JSON.parse(fs.readFileSync(paths.seen, 'utf8')); } catch { return {}; } };
41
+ export const seenBy = key => readSeen()[key] || null;
42
+ export function markSeen(key, version) {
43
+ const seen = readSeen();
44
+ seen[key] = version;
45
+ try {
46
+ fs.writeFileSync(`${paths.seen}.${process.pid}`, JSON.stringify(seen));
47
+ fs.renameSync(`${paths.seen}.${process.pid}`, paths.seen);
48
+ } catch {}
49
+ }
50
+
51
+ // The version on disk, which is what the next dibs command runs: read again only when the file
52
+ // changed, so a listener can look every few seconds for nothing.
53
+ let onDisk = { mtime: 0, version: null };
54
+ export function diskVersion() {
55
+ try {
56
+ const m = fs.statSync(VERSION_FILE).mtimeMs;
57
+ if (m !== onDisk.mtime) onDisk = { mtime: m, version: /VERSION = '([^']+)'/.exec(fs.readFileSync(VERSION_FILE, 'utf8'))?.[1] || null };
58
+ } catch {}
59
+ return onDisk.version;
60
+ }
61
+
62
+ // A git checkout (this repo, linked from ~/bin) updates by git, not by the install script.
63
+ const checkout = () => !process.env.DIBS_UPDATE_URL && fs.existsSync(path.join(ROOT, '.git'));
64
+ const readChecked = () => { try { return JSON.parse(fs.readFileSync(CHECKED, 'utf8')); } catch { return {}; } };
65
+ function writeChecked(c) {
66
+ try {
67
+ fs.writeFileSync(`${CHECKED}.${process.pid}`, JSON.stringify(c));
68
+ fs.renameSync(`${CHECKED}.${process.pid}`, CHECKED);
69
+ } catch {}
70
+ }
71
+
72
+ // The newest release dibs.cc knows of, as last asked, asking again (in the background) when
73
+ // the machine's last ask is older than CHECK_EVERY. Off with config updateCheck: false.
74
+ export function latest(t = Date.now()) {
75
+ let off = false;
76
+ try { off = loadConfig().updateCheck === false; } catch {}
77
+ if (off || checkout()) return null;
78
+ const c = readChecked();
79
+ if (!(t - (c.at || 0) < CHECK_EVERY)) {
80
+ // Claimed before asking, so a dozen listeners waking together ask once.
81
+ writeChecked({ ...c, at: t });
82
+ fetch(LATEST, { signal: AbortSignal.timeout(CHECK_TIMEOUT) }).then(r => (r.ok ? r.json() : null))
83
+ .then(j => { if (typeof j?.version === 'string' && /^\d+(\.\d+)*$/.test(j.version)) writeChecked({ ...readChecked(), latest: j.version }); })
84
+ .catch(() => {});
85
+ }
86
+ return c.latest || null;
87
+ }
88
+
89
+ // Each thread hears about a release once.
90
+ export const toldOf = key => readChecked().told?.[key] || null;
91
+ // Threads remembered: plenty for a machine's sessions over the weeks between releases.
92
+ const TOLD_KEEP = 500;
93
+ export function tell(key, version) {
94
+ const c = readChecked();
95
+ const told = { ...(c.told || {}) };
96
+ delete told[key];
97
+ told[key] = version;
98
+ const keys = Object.keys(told);
99
+ for (const k of keys.slice(0, Math.max(0, keys.length - TOLD_KEEP))) delete told[k];
100
+ writeChecked({ ...c, told });
101
+ }
package/src/notes.mjs ADDED
@@ -0,0 +1,171 @@
1
+ // dibs init: telling the coding agents on this machine that dibs is here.
2
+ //
3
+ // dibs.md the agent instructions, made from skills/dibs/SKILL.md (one source,
4
+ // no second copy to drift), in the folder dibs is installed in.
5
+ // Rewritten on every install and upgrade, so it matches the version.
6
+ // the block a few marked lines in the agents' own instruction files saying to
7
+ // read dibs.md before builds, tests, simulators or deploys:
8
+ // ~/.claude/CLAUDE.md when ~/.claude exists (made if missing)
9
+ // ~/.codex/AGENTS.md when ~/.codex exists (made if missing)
10
+ // CLAUDE.md and AGENTS.md at the root of the git repo dibs runs in,
11
+ // when that isn't the home folder: only files already there, unless
12
+ // asked with dibs init --repo
13
+ //
14
+ // Only what's between the markers is ever written; the rest of a file stays byte for
15
+ // byte. Each write goes to a temp file beside the real one, with its mode, then is
16
+ // renamed over it: a full disk once emptied a file written in place. A symlinked
17
+ // file is written where the link points, so the link stays a link.
18
+ // DIBS_NO_AGENT_NOTES=1 turns all of it off.
19
+ import fs from 'node:fs';
20
+ import os from 'node:os';
21
+ import path from 'node:path';
22
+ import { execFileSync } from 'node:child_process';
23
+ import { fileURLToPath } from 'node:url';
24
+ import { HOME } from './config.mjs';
25
+ import { VERSION } from './version.mjs';
26
+ import { die } from './util.mjs';
27
+
28
+ export const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
29
+ const START = '<!-- dibs:start -->', END = '<!-- dibs:end -->';
30
+ const BLOCK_RE = /<!-- dibs:start -->[\s\S]*?<!-- dibs:end -->(\r?\n)?/;
31
+ // Which version and folder the notes were last written for (src/notes.mjs stale()).
32
+ const STAMP = path.join(HOME, 'notes.json');
33
+ export const off = () => !!process.env.DIBS_NO_AGENT_NOTES && process.env.DIBS_NO_AGENT_NOTES !== '0';
34
+
35
+ // The agent instructions: SKILL.md without its front matter and title, under a header
36
+ // saying where it came from.
37
+ export function dibsMd(root = ROOT) {
38
+ let skill = '';
39
+ try { skill = fs.readFileSync(path.join(root, 'skills', 'dibs', 'SKILL.md'), 'utf8'); } catch {}
40
+ const body = skill.replace(/^---\n[\s\S]*?\n---\n/, '').replace(/^\s*# dibs\s*\n/, '').replace(/<!-- dibs:rules:(start|end) -->\n/g, '').trim();
41
+ return [
42
+ '# dibs: instructions for coding agents',
43
+ '',
44
+ `Written by dibs ${VERSION} when it was installed here, and rewritten on every install and upgrade, so edits don't last.`,
45
+ `Docs: https://dibs.cc, and ${path.join(root, 'README.md')}. Every command: \`dibs help all\`.`,
46
+ '',
47
+ body || 'Run builds, tests, simulators and deploys through dibs: `dibs run <resource> -m "why" -- <command>`. `dibs help` lists everything.',
48
+ '',
49
+ ].join('\n');
50
+ }
51
+
52
+ export const block = file => [START, '## dibs',
53
+ `This machine runs dibs, the CLI that coding agents use to share simulators, builds, tests and deploys. Read ${file} before running builds, tests, simulators or deploys. Docs: https://dibs.cc`,
54
+ END].join('\n');
55
+
56
+ // Write whole and rename into place, keeping the old file's mode.
57
+ function writeAtomic(file, text) {
58
+ let real = file, mode = 0o644;
59
+ try { real = fs.realpathSync(file); mode = fs.statSync(real).mode & 0o7777; } catch {}
60
+ fs.mkdirSync(path.dirname(real), { recursive: true });
61
+ const tmp = `${real}.dibs-${process.pid}`;
62
+ try {
63
+ fs.writeFileSync(tmp, text, { mode });
64
+ fs.chmodSync(tmp, mode);
65
+ fs.renameSync(tmp, real);
66
+ } catch (e) { try { fs.rmSync(tmp, { force: true }); } catch {} throw e; }
67
+ }
68
+
69
+ // text with the block in it: replaced where the markers are, else added at the end.
70
+ // Line endings follow the file's own.
71
+ export function withBlock(text, b) {
72
+ const nl = /\r\n/.test(text) ? '\r\n' : '\n';
73
+ const mine = b.replace(/\n/g, nl);
74
+ if (BLOCK_RE.test(text)) return text.replace(BLOCK_RE, (m, end) => mine + (end || ''));
75
+ if (!text) return mine + nl;
76
+ const gap = text.endsWith(nl + nl) ? '' : text.endsWith(nl) ? nl : nl + nl;
77
+ return text + gap + mine + nl;
78
+ }
79
+ // text without the block. At the end of the file, the blank line withBlock put in front goes too.
80
+ export function withoutBlock(text) {
81
+ const m = text.match(BLOCK_RE);
82
+ if (!m) return text;
83
+ let before = text.slice(0, m.index);
84
+ const after = text.slice(m.index + m[0].length);
85
+ if (!after) before = before.replace(/(\r?\n)\r?\n$/, '$1');
86
+ return before + after;
87
+ }
88
+
89
+ // The git repo the command runs in, unless it's the home folder itself.
90
+ function repoRoot(cwd) {
91
+ try {
92
+ const top = execFileSync('git', ['rev-parse', '--show-toplevel'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 3000 }).trim();
93
+ return top && path.resolve(top) !== path.resolve(os.homedir()) ? top : null;
94
+ } catch { return null; }
95
+ }
96
+
97
+ // The instruction files the block goes in. made: may be created when missing.
98
+ function targets(cwd, repo) {
99
+ const home = os.homedir(), out = [];
100
+ if (fs.existsSync(path.join(home, '.claude'))) out.push({ file: path.join(home, '.claude', 'CLAUDE.md'), made: true });
101
+ if (fs.existsSync(path.join(home, '.codex'))) out.push({ file: path.join(home, '.codex', 'AGENTS.md'), made: true });
102
+ const top = repoRoot(cwd);
103
+ if (top) {
104
+ const there = ['CLAUDE.md', 'AGENTS.md'].map(n => path.join(top, n)).filter(f => fs.existsSync(f));
105
+ for (const f of there) out.push({ file: f, made: false });
106
+ if (repo && !there.length) out.push({ file: path.join(top, 'CLAUDE.md'), made: true });
107
+ }
108
+ return out;
109
+ }
110
+
111
+ // Where dibs.md goes: the install folder, or ~/.dibs when that can't be written
112
+ // (an npm install owned by root, say).
113
+ function mdPlace(root) {
114
+ const f = path.join(root, 'dibs.md');
115
+ try { fs.accessSync(root, fs.constants.W_OK); return f; } catch { return path.join(HOME, 'dibs.md'); }
116
+ }
117
+
118
+ // Write dibs.md and the blocks. Returns the files that changed.
119
+ export function write({ root = ROOT, cwd = process.cwd(), repo = false } = {}) {
120
+ const changed = [];
121
+ const md = mdPlace(root);
122
+ const text = dibsMd(root);
123
+ let old = null;
124
+ try { old = fs.readFileSync(md, 'utf8'); } catch {}
125
+ if (old !== text) { writeAtomic(md, text); changed.push(md); }
126
+ const b = block(md);
127
+ for (const t of targets(cwd, repo)) {
128
+ let cur = null;
129
+ try { cur = fs.readFileSync(t.file, 'utf8'); } catch (e) { if (e.code !== 'ENOENT') throw e; }
130
+ if (cur == null && !t.made) continue;
131
+ const next = withBlock(cur || '', b);
132
+ if (next !== cur) { writeAtomic(t.file, next); changed.push(t.file); }
133
+ }
134
+ try { fs.mkdirSync(HOME, { recursive: true }); fs.writeFileSync(STAMP, JSON.stringify({ version: VERSION, root })); } catch {}
135
+ return changed;
136
+ }
137
+
138
+ // Take dibs.md and every block back out. Returns the files that changed.
139
+ export function remove({ root = ROOT, cwd = process.cwd() } = {}) {
140
+ const changed = [];
141
+ for (const md of new Set([path.join(root, 'dibs.md'), path.join(HOME, 'dibs.md')])) {
142
+ if (fs.existsSync(md)) { fs.rmSync(md); changed.push(md); }
143
+ }
144
+ for (const t of targets(cwd, false)) {
145
+ let cur;
146
+ try { cur = fs.readFileSync(t.file, 'utf8'); } catch { continue; }
147
+ const next = withoutBlock(cur);
148
+ if (next !== cur) { writeAtomic(t.file, next); changed.push(t.file); }
149
+ }
150
+ try { fs.rmSync(STAMP, { force: true }); } catch {}
151
+ return changed;
152
+ }
153
+
154
+ // Whether the notes are behind this version or this folder: an npm install has no
155
+ // install script to write them (the package runs no scripts, by design), so its
156
+ // first dibs command after an install or upgrade does.
157
+ export function stale(root = ROOT) {
158
+ if (off()) return false;
159
+ try { const s = JSON.parse(fs.readFileSync(STAMP, 'utf8')); return s.version !== VERSION || s.root !== root; } catch { return true; }
160
+ }
161
+
162
+ // dibs init [--repo] [--remove] [--quiet]
163
+ export function init(args) {
164
+ const bad = args.find(a => !['--repo', '--remove', '--quiet'].includes(a));
165
+ if (bad) die(`unknown ${bad}. dibs init [--repo] [--remove]`);
166
+ if (off()) return console.log('DIBS_NO_AGENT_NOTES is set, so dibs leaves the agents\' instruction files alone.');
167
+ const quiet = args.includes('--quiet');
168
+ const changed = args.includes('--remove') ? remove() : write({ repo: args.includes('--repo') });
169
+ for (const f of changed) console.log(`${args.includes('--remove') ? 'cleaned' : 'wrote'} ${f}`);
170
+ if (!changed.length && !quiet) console.log('Nothing to change: dibs.md and the notes are up to date.');
171
+ }