@dibssoftware/dibs 0.0.179 → 0.0.180

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 (53) hide show
  1. package/CHANGELOG.md +23 -2
  2. package/README.md +4 -2
  3. package/bin/dibs-guard.mjs +10 -1
  4. package/bin/dibs.mjs +28 -9
  5. package/docs/benchmarks.md +1 -1
  6. package/docs/files.md +1 -1
  7. package/docs/guard.md +6 -0
  8. package/docs/questions.md +6 -2
  9. package/docs/reference.md +4 -4
  10. package/docs/relay.md +9 -7
  11. package/docs/releasing.md +4 -3
  12. package/docs/scheduling.md +4 -4
  13. package/docs/windows.md +14 -0
  14. package/package.json +1 -1
  15. package/skills/dibs/SKILL.md +5 -5
  16. package/src/acquire.mjs +91 -26
  17. package/src/agents.mjs +7 -22
  18. package/src/alerts.mjs +59 -21
  19. package/src/board.mjs +1 -2
  20. package/src/broker.mjs +26 -11
  21. package/src/commands.mjs +25 -9
  22. package/src/config.mjs +21 -4
  23. package/src/cool.mjs +104 -9
  24. package/src/diskwarn.mjs +4 -0
  25. package/src/events.mjs +10 -1
  26. package/src/files.mjs +49 -87
  27. package/src/guard.mjs +24 -8
  28. package/src/guardd.mjs +97 -0
  29. package/src/guardw.mjs +19 -0
  30. package/src/later.mjs +20 -25
  31. package/src/lock.mjs +292 -0
  32. package/src/measure.mjs +9 -4
  33. package/src/ondemand.mjs +5 -2
  34. package/src/override.mjs +39 -2
  35. package/src/plain.mjs +2 -2
  36. package/src/platform.mjs +165 -35
  37. package/src/preempt.mjs +51 -3
  38. package/src/primer.mjs +1 -1
  39. package/src/proc.mjs +35 -5
  40. package/src/questions.mjs +8 -22
  41. package/src/relay.mjs +10 -22
  42. package/src/remote.mjs +12 -8
  43. package/src/schedule.mjs +139 -26
  44. package/src/serve.mjs +16 -3
  45. package/src/service.mjs +4 -3
  46. package/src/state.mjs +139 -47
  47. package/src/stats.mjs +3 -2
  48. package/src/talk.mjs +160 -77
  49. package/src/trust.mjs +7 -1
  50. package/src/util.mjs +28 -2
  51. package/src/version.mjs +1 -1
  52. package/src/web.mjs +15 -25
  53. package/src/worker.mjs +2 -1
package/src/state.mjs CHANGED
@@ -1,40 +1,70 @@
1
1
  // The shared state file: who holds what and who's waiting. Every change goes
2
- // through withState, which holds a mkdir lock for a few milliseconds.
2
+ // through withState, which holds the state lock for a few milliseconds.
3
+ //
4
+ // The lock (src/lock.mjs, which says why in full):
5
+ // - One holder: ~/.dibs/lock is renamed into place already holding its owner file, so it's
6
+ // never seen without one, and of two makers one wins.
7
+ // - Stale only when its owner is dead, a zombie or stopped (ps), never for its age: a live
8
+ // holder, however slow, is waited for, and nothing gives up. One holding past a minute is
9
+ // reported once, loudly (stuck below), and plain dibs shows the last state instead of waiting.
10
+ // - Takeover renames the stale owner's file to the taker's own, inside the lock, so of two
11
+ // takers one wins and a fresh lock is never moved or taken by mistake.
12
+ // - A holder checks it still holds the lock just before its rename of state.json.<pid>.tmp;
13
+ // taken over (it was stopped), it writes nothing and makes its change again.
14
+ // - Release removes only its own lock, and never throws.
3
15
  import fs from 'node:fs';
4
16
  import path from 'node:path';
5
- import { paths, HOME } from './config.mjs';
17
+ import { paths } from './config.mjs';
6
18
  import { makeAlive } from './proc.mjs';
7
- import { stopTree, starts, liveGroups, OS } from './platform.mjs';
19
+ import { acquire, commit, commandOf, LostLock } from './lock.mjs';
20
+ import { stopTree, starts, liveGroups, wokeAt, OS } from './platform.mjs';
8
21
  import { settle, flush } from './preempt.mjs';
9
22
  import { reapPool } from './simpool.mjs';
10
23
  import { queueResets, startResets, reapResets } from './reset.mjs';
11
24
  import { logChanges, event } from './events.mjs';
12
- import { die, now, say, sleepSync, noSpace, fakeFull } from './util.mjs';
25
+ import { die, now, say, dur, noSpace, fakeFull, unpolled, GHOST_AFTER, POLLED_EVERY, UNPOLLED } from './util.mjs';
13
26
 
14
27
  export const KEEP_PLACE = 120e3; // a waiter that gave up keeps its place this long
28
+ // A waiter looks at its place every second or so, and a broker for its thin waiters as often:
29
+ // a minute is plenty for one that's alive to see the owner stopped it.
30
+ export const STOP_GRACE = POLLED_EVERY;
31
+ const STOPPED_FOR = 10 * POLLED_EVERY;
32
+ const QUIET_GRACE = 2 * POLLED_EVERY; // two stamps' time, for every waiter to look in again
15
33
 
16
- export function withState(fn) {
17
- fs.mkdirSync(HOME, { recursive: true });
18
- const t0 = now();
19
- const owner = path.join(paths.lock, 'pid');
34
+ export function withState(fn, wait = Infinity) {
35
+ warm();
20
36
  for (;;) {
21
- try { fs.mkdirSync(paths.lock); } catch (e) {
22
- if (e.code !== 'EEXIST') throw e;
23
- // Take the lock over only from a writer that died holding it, or one stuck
24
- // for 30s. The age check matters: the pid we read may belong to a writer
25
- // that just finished, while the directory is already someone's fresh lock.
26
- let pid = 0, age = 0;
27
- try { pid = Number(fs.readFileSync(owner, 'utf8')); } catch {}
28
- try { age = now() - fs.statSync(paths.lock).mtimeMs; } catch { continue; }
29
- if (age > 30000 || (age > 3000 && (!pid || !makeAlive([pid])(pid)))) takeOver(pid);
30
- if (now() - t0 > 45000) die(`state lock stuck; remove ${paths.lock} if no dibs is running. Your command did not run.`, 75);
31
- sleepSync(10 + Math.random() * 20);
32
- continue;
33
- }
34
- // A lock with no pid in it (a full disk) would hold everyone up until it looked stale: give it back now.
35
- try { fakeFull('lock'); fs.writeFileSync(owner, String(process.pid)); break; }
36
- catch (e) { fs.rmSync(paths.lock, { recursive: true, force: true }); throw e; }
37
+ const giveUp = deadline != null && wait === Infinity;
38
+ const lock = acquire(paths.lock, { wait: giveUp ? Math.max(deadline - now(), LEAVE_GRACE) : wait, fake: () => fakeFull('lock'), files: [paths.state], onStuck: stuck });
39
+ if (!lock && giveUp) die(`gave up waiting: the state lock stayed held past this wait's limit (dibs is stuck behind another process; dibs alerts says which). Your command did NOT run (exit 75).`, 75);
40
+ if (!lock) return undefined;
41
+ try { return change(fn, lock); }
42
+ catch (e) { if (!(e instanceof LostLock)) throw e; } // taken over while stopped, before it wrote: change again
37
43
  }
44
+ }
45
+
46
+ // A run or hold waiting in line with a limit (--max-wait, or 8m outside Claude Code) gives up with 75
47
+ // at that limit even when what holds it up is the state lock itself. Set by src/acquire.mjs while it
48
+ // waits; LEAVE_GRACE past it is still allowed, for giving its place back.
49
+ let deadline = null;
50
+ const LEAVE_GRACE = 5000;
51
+ export const setLockDeadline = at => { deadline = at; };
52
+
53
+ // A live holder is waited for however long it takes, but one holding past STUCK_AFTER is hung,
54
+ // and with it all of dibs. The first waiter to notice says so, once per holder: an event the
55
+ // alerts make loud (src/alerts.mjs), and a line on its own terminal.
56
+ export const STUCK_DIR = path.join(path.dirname(paths.lock), 'lockstuck');
57
+ function stuck(o, held) {
58
+ fs.mkdirSync(STUCK_DIR, { recursive: true });
59
+ try { fs.writeFileSync(path.join(STUCK_DIR, o.key), '', { flag: 'wx' }); } catch { return; }
60
+ for (const n of fs.readdirSync(STUCK_DIR)) if (n !== o.key) try { fs.rmSync(path.join(STUCK_DIR, n), { force: true }); } catch {}
61
+ const cmd = commandOf(o.pid);
62
+ event({ at: now(), kind: 'lockstuck', key: o.key, pid: o.pid, cmd, held });
63
+ say(`dibs is stuck behind pid ${o.pid}${cmd ? ` (${cmd.slice(0, 80)})` : ''}, which has held the state lock for ${dur(held)}. `
64
+ + `Waiting for it. If it's hung, ending it lets everyone go on: kill ${o.pid}`);
65
+ }
66
+
67
+ function change(fn, lock) {
38
68
  let written = false, moved = false;
39
69
  vanished = [];
40
70
  try {
@@ -42,6 +72,12 @@ export function withState(fn) {
42
72
  const before = [...s.leases];
43
73
  const line = ids(s);
44
74
  const paused = new Map(before.map(l => [l.id, l.pausedAt]));
75
+ // A live waiter stamps its place once a minute, so a state file nobody wrote for longer
76
+ // than UNPOLLED means everyone went quiet at once (the machine slept): every place gets
77
+ // QUIET_GRACE to be looked at again before any counts as one nobody decides for.
78
+ let wrote = null;
79
+ try { wrote = fs.statSync(paths.state).mtimeMs; } catch {}
80
+ if (wrote != null && now() - wrote > UNPOLLED) s.graceUntil = now() + QUIET_GRACE;
45
81
  reap(s);
46
82
  const out = fn(s);
47
83
  settle(s, now(), history); // resume work paused for a lease that has ended, and never leave every job paused
@@ -51,9 +87,8 @@ export function withState(fn) {
51
87
  const text = JSON.stringify(s, null, 1);
52
88
  if (text !== raw) {
53
89
  // A write cut short by a full disk leaves the old state in place, and no half file taking up space.
54
- try { fakeFull('state'); fs.writeFileSync(paths.state + '.tmp', text); }
55
- catch (e) { fs.rmSync(paths.state + '.tmp', { force: true }); throw e; }
56
- fs.renameSync(paths.state + '.tmp', paths.state);
90
+ if (!commit(lock, paths.state, text, { fake: () => fakeFull('state') }))
91
+ event({ at: now(), kind: 'clobbered', pid: process.pid, why: 'the state lock was taken over between the ownership check and the write' });
57
92
  written = true;
58
93
  moved = ids(s) !== line;
59
94
  }
@@ -63,12 +98,24 @@ export function withState(fn) {
63
98
  return out;
64
99
  } finally {
65
100
  flush(false); // a change that failed sends nothing
66
- fs.rmSync(paths.lock, { recursive: true, force: true });
101
+ lock.release();
67
102
  if (moved && kicks) try { kick(); } catch {} // after the lock, which the broker takes next
68
103
  startResets(written);
69
104
  }
70
105
  }
71
106
 
107
+ // Every pid the state names, whose start times reap() checks.
108
+ const pidsOf = s => [...(s.leases || []).map(l => l.pid), ...(s.queue || []).map(q => q.pid || q.keptFor), ...(s.resets || []).flatMap(x => [x.pid, x.cpid])];
109
+
110
+ // Read those start times before taking the lock, so reap() under it finds them in
111
+ // makeAlive's cache instead of running ps: on 2026-11-11 that ps (100 to 700 ms on a
112
+ // Mac at load 30) was most of every first hold, and the lock was held 83% of the time.
113
+ // On Windows each start time is a PowerShell read, about 0.4 s: twelve runs at once queued for the
114
+ // lock past its old 45 s limit on a CI runner.
115
+ function warm() {
116
+ try { makeAlive(pidsOf(JSON.parse(fs.readFileSync(paths.state, 'utf8')))); } catch {}
117
+ }
118
+
72
119
  // The broker (src/broker.mjs) ticks when kicked: one byte down its control
73
120
  // FIFO whenever a change starts or ends a lease or changes the line, so the
74
121
  // next waiter's turn comes at once rather than at the next tick. Never
@@ -90,17 +137,6 @@ export function withStateIfRoom(fn) {
90
137
  try { return withState(fn); } catch (e) { if (noSpace(e)) return undefined; throw e; }
91
138
  }
92
139
 
93
- // Move the stale lock aside atomically, then check it was the one we judged.
94
- // If another waiter replaced it in between, put theirs back.
95
- function takeOver(pid) {
96
- const aside = `${paths.lock}.stale-${process.pid}-${now()}`;
97
- try { fs.renameSync(paths.lock, aside); } catch { return; }
98
- let got = 0;
99
- try { got = Number(fs.readFileSync(path.join(aside, 'pid'), 'utf8')); } catch {}
100
- if (got === pid) fs.rmSync(aside, { recursive: true, force: true });
101
- else try { fs.renameSync(aside, paths.lock); } catch { fs.rmSync(aside, { recursive: true, force: true }); }
102
- }
103
-
104
140
  // The state as last written, without the lock and without reaping: what dibs
105
141
  // web shows. Writes are a rename, so this never sees half a file; a holder that
106
142
  // died shows until the next dibs call reaps it.
@@ -126,14 +162,14 @@ function read() {
126
162
  let vanished = [];
127
163
  function reap(s) {
128
164
  const t = now();
129
- const alive = makeAlive([...s.leases.map(l => l.pid), ...s.queue.map(q => q.pid || q.keptFor), ...(s.resets || []).flatMap(x => [x.pid, x.cpid])]);
165
+ const alive = makeAlive(pidsOf(s));
130
166
  s.leases = s.leases.filter(l => {
131
167
  if (l.kind === 'hold') return t < l.expires && (!l.pid || alive(l.pid, l.pstart));
132
168
  if (alive(l.pid, l.pstart)) return true;
133
169
  killLease(l);
134
170
  // Its dibs was killed, so nobody recorded what it measured. A job big enough
135
171
  // to get its dibs killed is the one the next run most needs to plan for.
136
- if (l.peak?.mem) record(l.key, t - l.start - (l.pausedMs || 0), l.who, l.peak, true);
172
+ if (l.peak?.mem) record(l.key, t - l.start - (l.pausedMs || 0), l.who, peakOf(l), true);
137
173
  return false;
138
174
  });
139
175
  // A waiter whose process is gone leaves the line, however it went: a place
@@ -142,14 +178,42 @@ function reap(s) {
142
178
  // Node (src/broker.mjs keptFor), which only that process can pick up. A place
143
179
  // kept with no process on it (a wait that timed out, exit 75) stays KEEP_PLACE
144
180
  // for the same command to pick up.
181
+ // Two places under one process (pid and start time): it decides for one at most, the one it
182
+ // stamped last (the newer, on a tie). The other is left over and holds the line for nothing.
183
+ const latest = new Map();
184
+ for (const q of s.queue) {
185
+ if (!q.pid) continue;
186
+ const k = `${q.pid} ${q.pstart}`, o = latest.get(k);
187
+ if (!o || (q.polledAt ?? 0) > (o.polledAt ?? 0) || ((q.polledAt ?? 0) === (o.polledAt ?? 0) && q.id > o.id)) latest.set(k, q);
188
+ }
189
+ const twin = q => q.pid && latest.get(`${q.pid} ${q.pstart}`) !== q;
190
+ // The state file can look fresh across a sleep (a dark wake, Power Nap, a worker's write), so a
191
+ // recent wake grants the same grace. Asked only when a place has gone unlooked-at: it's a sysctl.
192
+ if (!(s.graceUntil > t) && s.queue.some(q => unpolled(q, t))) {
193
+ const woke = wokeAt();
194
+ if (woke && t - woke < QUIET_GRACE) s.graceUntil = woke + QUIET_GRACE;
195
+ }
196
+ if (s.graceUntil && t >= s.graceUntil) delete s.graceUntil;
197
+ // A place whose process lives but no longer decides for it (its dibs stopped looking) goes after
198
+ // GHOST_AFTER, and one the owner stopped once its waiter has had STOP_GRACE to see that: both, left
199
+ // in, would sit in line for as long as the process lived.
145
200
  s.queue = s.queue.filter(q => {
146
201
  const owner = q.pid || (q.keptFor && !q.pid ? q.keptFor : null);
147
- if (owner && !alive(owner, q.pstart)) {
148
- vanished.push({ at: t, kind: 'left', id: q.id, res: q.res, who: q.who, prio: q.prio || 'normal', type: q.kind, ms: t - q.enq, why: 'gone' });
202
+ const why = owner && !alive(owner, q.pstart) ? 'gone'
203
+ : q.ownerStop && t - q.ownerStop > STOP_GRACE ? 'owner stop'
204
+ : unpolled(q, t, GHOST_AFTER) && !(s.graceUntil > t) ? 'unpolled'
205
+ : twin(q) ? 'duplicate' : null;
206
+ if (why) {
207
+ vanished.push({ at: t, kind: 'left', id: q.id, res: q.res, who: q.who, prio: q.prio || 'normal', type: q.kind, ms: t - q.enq, why });
149
208
  return false;
150
209
  }
151
210
  return q.pid || (q.keepUntil && t < q.keepUntil);
152
211
  });
212
+ // What the owner stopped, for a waiter that finds its place gone to say why.
213
+ if (s.stopped) {
214
+ for (const id of Object.keys(s.stopped)) if (t - s.stopped[id].at > STOPPED_FOR) delete s.stopped[id];
215
+ if (!Object.keys(s.stopped).length) delete s.stopped;
216
+ }
153
217
  reapPool(s);
154
218
  reapResets(s, alive);
155
219
  }
@@ -185,17 +249,45 @@ function stillOurs(l, g, leader, recorded, live) {
185
249
 
186
250
  // Past run times, newest last. A line cut short (a crash mid-append) is
187
251
  // skipped, not allowed to throw away every other line.
252
+ // Only the end of the file is read: it grows by every run (2 MB, 15,000 lines on
253
+ // 2026-11-11) and every waiter, the broker and the board read it. Just after the
254
+ // file is rotated (src/events.mjs) the rest comes from the end of the one before.
255
+ const HISTORY_KEEP = 1000;
256
+ const HISTORY_CHUNK = 256 * 1024; // about 2,000 lines, so one read nearly always does
188
257
  export function history() {
189
- let text;
190
- try { text = fs.readFileSync(paths.history, 'utf8'); } catch (e) { if (e.code === 'ENOENT') return []; throw e; }
191
- return text.trim().split('\n').slice(-1000).flatMap(l => { try { return [JSON.parse(l)]; } catch { return []; } });
258
+ const lines = tail(paths.history, HISTORY_KEEP);
259
+ if (lines.length < HISTORY_KEEP) lines.unshift(...tail(paths.historyOlder, HISTORY_KEEP - lines.length));
260
+ return lines.slice(-HISTORY_KEEP).flatMap(l => { try { return [JSON.parse(l)]; } catch { return []; } });
261
+ }
262
+
263
+ // The last `need` lines of a file (fewer if it has fewer), none for an empty or missing one.
264
+ function tail(file, need) {
265
+ let fd;
266
+ try { fd = fs.openSync(file, 'r'); } catch (e) { if (e.code === 'ENOENT') return []; throw e; }
267
+ let lines;
268
+ try {
269
+ const size = fs.fstatSync(fd).size;
270
+ for (let want = HISTORY_CHUNK; ; want *= 2) {
271
+ const from = Math.max(0, size - want);
272
+ const buf = Buffer.alloc(size - from);
273
+ fs.readSync(fd, buf, 0, buf.length, from);
274
+ const text = buf.toString('utf8').trim();
275
+ lines = text ? text.split('\n') : [];
276
+ // A read that starts mid-file starts mid-line: that first piece isn't a line.
277
+ if (from > 0) lines.shift();
278
+ if (from === 0 || lines.length >= need) break;
279
+ }
280
+ } finally { fs.closeSync(fd); }
281
+ return lines.slice(-need);
192
282
  }
193
283
 
194
284
  // peak is the most the run was measured using (src/measure.mjs), when it ran long enough to be.
195
285
  // A failed run (nonzero exit, or its dibs killed) is recorded for its size
196
286
  // only: its time says nothing about a run's (schedule.mjs typical skips it).
197
287
  // Run times are worth less than the run: on a full disk this one goes unrecorded.
288
+ // A lease's peak for its history line, marked when the watcher cleared caches during it.
289
+ export const peakOf = l => (l.cleaned && l.peak ? { ...l.peak, cleaned: true } : l.peak);
198
290
  export function record(key, duration, who, peak, failed = false) {
199
- try { fs.appendFileSync(paths.history, JSON.stringify({ key, dur: duration, who, at: now(), ...(peak ? { mem: peak.mem, cpu: peak.cpu, ...(peak.fit && { fit: true }), ...(peak.ate != null && { ate: Math.round(peak.ate) }) } : {}), ...(failed && { failed: true }) }) + '\n'); }
291
+ try { fs.appendFileSync(paths.history, JSON.stringify({ key, dur: duration, who, at: now(), ...(peak ? { mem: peak.mem, cpu: peak.cpu, ...(peak.fit && { fit: true }), ...(peak.in != null && { peakIn: Math.round(peak.in) }), ...(peak.ate != null && { ate: Math.round(peak.ate) }), ...(peak.cleaned && { cleaned: true }) } : {}), ...(failed && { failed: true }) }) + '\n'); }
200
292
  catch (e) { if (!noSpace(e)) throw e; }
201
293
  }
package/src/stats.mjs CHANGED
@@ -40,10 +40,11 @@ const bump = (m, k, ms = 0) => { const x = m.get(k) || { n: 0, ms: 0 }; x.n++; x
40
40
  const resOf = rs => [...new Set((rs || []).map(r => (r.startsWith('files:') ? 'files' : r)))];
41
41
  const cmdOf = key => masked(String(key || '').split('|').slice(1).join('|').split(' / ')[0].replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, ' ').trim()) || null;
42
42
 
43
- // Every history.jsonl line since `since`. history() in state.mjs keeps only the newest 1000.
43
+ // Every run time since `since`, from history.jsonl and the one rotated out before it.
44
+ // history() in state.mjs keeps only the newest 1000.
44
45
  export function readRuns(since) {
45
46
  let text = '';
46
- try { text = fs.readFileSync(paths.history, 'utf8'); } catch {}
47
+ for (const f of [paths.historyOlder, paths.history]) try { text += fs.readFileSync(f, 'utf8') + '\n'; } catch {}
47
48
  const out = [];
48
49
  for (const l of text.split('\n')) {
49
50
  if (!l) continue;