@dibssoftware/dibs 0.0.179 → 0.0.181
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -2
- package/README.md +4 -2
- package/bin/dibs-guard.mjs +10 -1
- package/bin/dibs.mjs +37 -10
- package/docs/benchmarks.md +1 -1
- package/docs/files.md +1 -1
- package/docs/guard.md +6 -0
- package/docs/questions.md +6 -2
- package/docs/reference.md +4 -4
- package/docs/relay.md +24 -9
- package/docs/releasing.md +4 -3
- package/docs/scheduling.md +4 -4
- package/docs/windows.md +14 -0
- package/package.json +1 -1
- package/skills/dibs/SKILL.md +6 -6
- package/src/acquire.mjs +93 -27
- package/src/agents.mjs +7 -22
- package/src/alerts.mjs +75 -29
- package/src/board.mjs +1 -2
- package/src/broker.mjs +26 -11
- package/src/commands.mjs +37 -14
- package/src/config.mjs +21 -4
- package/src/cool.mjs +105 -10
- package/src/diskwarn.mjs +4 -0
- package/src/events.mjs +10 -1
- package/src/files.mjs +52 -88
- package/src/guard.mjs +76 -30
- package/src/guardd.mjs +97 -0
- package/src/guardw.mjs +19 -0
- package/src/later.mjs +20 -25
- package/src/lock.mjs +308 -0
- package/src/measure.mjs +27 -7
- package/src/ondemand.mjs +5 -2
- package/src/override.mjs +39 -2
- package/src/plain.mjs +2 -2
- package/src/platform.mjs +175 -42
- package/src/preempt.mjs +51 -3
- package/src/primer.mjs +1 -1
- package/src/proc.mjs +45 -5
- package/src/questions.mjs +8 -22
- package/src/relay.mjs +137 -32
- package/src/remote.mjs +12 -8
- package/src/schedule.mjs +139 -26
- package/src/serve.mjs +16 -3
- package/src/service.mjs +9 -4
- package/src/state.mjs +139 -47
- package/src/stats.mjs +3 -2
- package/src/talk.mjs +169 -83
- package/src/trust.mjs +7 -1
- package/src/util.mjs +28 -2
- package/src/version.mjs +1 -1
- package/src/web.mjs +17 -26
- package/src/worker.mjs +2 -1
package/src/serve.mjs
CHANGED
|
@@ -140,6 +140,18 @@ export function place(workers, need, t = now()) {
|
|
|
140
140
|
// The Tailscale address of this machine. Ask Tailscale itself when its CLI is
|
|
141
141
|
// around; otherwise a 100.64.0.0/10 address on a tunnel interface. That range
|
|
142
142
|
// alone isn't enough: carrier-grade NAT and some hotspots use it too.
|
|
143
|
+
// A log line said once for as long as it stays the same, per key: the Tailscale
|
|
144
|
+
// address is tried every 30 s, and on 2026-11-10 failed all day (EADDRNOTAVAIL),
|
|
145
|
+
// one line each time. null clears the key, so the next failure is said again.
|
|
146
|
+
export function oncePerChange(log) {
|
|
147
|
+
const last = new Map();
|
|
148
|
+
return (key, line) => {
|
|
149
|
+
if (line == null) return last.delete(key);
|
|
150
|
+
if (last.get(key) !== line) log(line);
|
|
151
|
+
last.set(key, line);
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
143
155
|
function tailscaleIp() {
|
|
144
156
|
for (const cli of TS_CLI) {
|
|
145
157
|
try {
|
|
@@ -692,14 +704,15 @@ export async function serve(o) {
|
|
|
692
704
|
const addrs = () => [...listening.keys()].filter(h => h !== '127.0.0.1').map(h => `http://${h}:${port}`);
|
|
693
705
|
try { made = makeServer({ token: rc.token, log, self: rc.name, joinUrl, port, addrs }); } catch (e) { die(e.message); }
|
|
694
706
|
const { server } = made;
|
|
707
|
+
const first = o.bind || '127.0.0.1';
|
|
708
|
+
const failed = oncePerChange(log);
|
|
695
709
|
const listen = host => new Promise(resolve => {
|
|
696
710
|
if (listening.has(host)) return resolve(true);
|
|
697
711
|
const s = server();
|
|
698
|
-
s.once('error', e => {
|
|
699
|
-
s.listen(port, host, () => { listening.set(host, s); resolve(true); });
|
|
712
|
+
s.once('error', e => { failed(host, `can't listen on ${host}:${port}: ${e.message}${host === first ? '' : '. Trying again every 30 s, quietly'}`); resolve(false); });
|
|
713
|
+
s.listen(port, host, () => { failed(host, null); listening.set(host, s); resolve(true); });
|
|
700
714
|
});
|
|
701
715
|
const up = host => log(`listening on http://${host}:${port}`);
|
|
702
|
-
const first = o.bind || '127.0.0.1';
|
|
703
716
|
if (!await listen(first)) die(o.bind ? `can't listen on ${o.bind}:${port}` : `port ${port} is taken. Is a coordinator already running? (dibs machines)`);
|
|
704
717
|
// "listening" comes after remote.json is saved: whatever waits for the line
|
|
705
718
|
// and then reads the file (a test on 2026-10-16) found it missing.
|
package/src/service.mjs
CHANGED
|
@@ -20,16 +20,21 @@ const KINDS = {
|
|
|
20
20
|
throttle: { args: ['throttle', '--watch'], what: 'moves hot work outside dibs to background priority' },
|
|
21
21
|
web: { args: ['web'], what: 'the page and MCP server showing your agents\' work' },
|
|
22
22
|
relay: { args: ['relay'], what: 'reach the page from any browser through the encrypted relay (dibs pair --remote)' },
|
|
23
|
+
guard: { args: ['guard', 'serve'], what: 'answers the Claude Code hook without starting Node for every tool call' },
|
|
23
24
|
};
|
|
24
25
|
// Things started by hand before the service existed; stopped so the service can take over.
|
|
25
|
-
const PIDFILES = { worker: 'worker.pid', throttle: 'cool.pid' };
|
|
26
|
+
const PIDFILES = { worker: 'worker.pid', throttle: 'cool.pid', guard: 'guard.pid' };
|
|
26
27
|
|
|
27
28
|
const label = k => `dev.dibs.${k}`;
|
|
28
29
|
// DIBS_LAUNCH_AGENTS and DIBS_LAUNCHCTL stand in for ~/Library/LaunchAgents and launchctl in tests.
|
|
29
30
|
const plist = k => path.join(process.env.DIBS_LAUNCH_AGENTS || path.join(os.homedir(), 'Library', 'LaunchAgents'), `${label(k)}.plist`);
|
|
30
31
|
const LAUNCHCTL = process.env.DIBS_LAUNCHCTL || 'launchctl';
|
|
31
32
|
const unit = k => path.join(process.env.DIBS_LAUNCH_AGENTS || path.join(os.homedir(), '.config', 'systemd', 'user'), `dibs-${k}.service`);
|
|
32
|
-
|
|
33
|
+
// The guard service's output can't go in guard.log: that's the hook's own error
|
|
34
|
+
// log, which the alerts read as hook failures (src/alerts.mjs readHook).
|
|
35
|
+
const LOGS = { guard: 'guard-service.log' };
|
|
36
|
+
export const logName = k => LOGS[k] || `${k}.log`;
|
|
37
|
+
const logFile = k => path.join(HOME, logName(k));
|
|
33
38
|
const sh = (cmd, args) => { try { return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); } catch (e) { return e.stdout || ''; } };
|
|
34
39
|
const esc = s => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
|
35
40
|
const uid = () => process.getuid?.() ?? 0;
|
|
@@ -88,7 +93,7 @@ function install(k) {
|
|
|
88
93
|
if (PIDFILES[k]) stopManual(k);
|
|
89
94
|
if (OS === 'macos') {
|
|
90
95
|
// Jobs a worker runs inherit its scheduling class, so it can't be Background.
|
|
91
|
-
const type = { serve: 'Standard', worker: 'Interactive', throttle: 'Background', web: 'Standard', relay: 'Standard' }[k];
|
|
96
|
+
const type = { serve: 'Standard', worker: 'Interactive', throttle: 'Background', web: 'Standard', relay: 'Standard', guard: 'Interactive' }[k];
|
|
92
97
|
fs.mkdirSync(path.dirname(plist(k)), { recursive: true });
|
|
93
98
|
fs.writeFileSync(plist(k), `<?xml version="1.0" encoding="UTF-8"?>
|
|
94
99
|
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
@@ -210,7 +215,7 @@ export async function service(args) {
|
|
|
210
215
|
if (kinds.includes('relay')) { const s = await relayStatus(); if (s) console.log(` relay: ${s}`); }
|
|
211
216
|
return;
|
|
212
217
|
}
|
|
213
|
-
if (!kinds.length) die(`which? dibs service ${action} serve|worker|throttle|web|relay (several at once is fine)`);
|
|
218
|
+
if (!kinds.length) die(`which? dibs service ${action} serve|worker|throttle|web|relay|guard (several at once is fine)`);
|
|
214
219
|
// A service runs for weeks and listens on the network: not on a Node with a known hole.
|
|
215
220
|
const hole = action === 'install' && !process.env.DIBS_ALLOW_UNPATCHED && unpatched();
|
|
216
221
|
if (hole) die(`${hole}. The service would run on that Node (${process.execPath}): put a fixed one first on your PATH and run this again.`);
|
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
|
|
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
|
|
17
|
+
import { paths } from './config.mjs';
|
|
6
18
|
import { makeAlive } from './proc.mjs';
|
|
7
|
-
import {
|
|
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,
|
|
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
|
-
|
|
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
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
-
|
|
55
|
-
|
|
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
|
-
|
|
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
|
+
export 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(
|
|
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
|
|
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
|
-
|
|
148
|
-
|
|
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
|
-
|
|
190
|
-
|
|
191
|
-
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
|
|
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
|
|
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;
|