@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/platform.mjs
CHANGED
|
@@ -12,33 +12,56 @@ export const OS = process.platform === 'win32' ? 'windows' : process.platform ==
|
|
|
12
12
|
const WIN = OS === 'windows';
|
|
13
13
|
|
|
14
14
|
// Output of a command, or null when it couldn't run at all (spawn failed under
|
|
15
|
-
// memory pressure, killed by a signal). Callers must not read null as "nothing".
|
|
16
|
-
|
|
17
|
-
|
|
15
|
+
// memory pressure, killed by a signal, or no answer in RUN_LIMIT). Callers must not read null as "nothing".
|
|
16
|
+
// Some of these run under the state lock (killLease reaping a dead job), where a ps that never
|
|
17
|
+
// returns would stop every dibs command: no process-table read gets longer than this.
|
|
18
|
+
const RUN_LIMIT = 15e3;
|
|
19
|
+
function tryRun(cmd, args, timeout = RUN_LIMIT) {
|
|
20
|
+
try { return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, timeout }); }
|
|
18
21
|
catch (e) { return typeof e.status === 'number' ? e.stdout || '' : null; } // ps exits 1 when any pid is gone
|
|
19
22
|
}
|
|
20
23
|
const run = (cmd, args) => tryRun(cmd, args) ?? '';
|
|
21
|
-
|
|
24
|
+
// A PowerShell that stalls (rebuilding its module cache, say) is "can't tell", not a hung dibs.
|
|
25
|
+
const ps = script => tryRun('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], 30e3);
|
|
22
26
|
|
|
23
27
|
// pid -> start time string. Comparing start times keeps a recycled pid from
|
|
24
28
|
// passing as a live holder. null when the process table couldn't be read.
|
|
25
29
|
// The highest pid each system hands out (macOS's PID_MAX, Linux's PID_MAX_LIMIT).
|
|
26
30
|
// ps refuses a list with anything past it and prints nothing for the rest.
|
|
27
31
|
const PID_MAX = OS === 'macos' ? 99999 : OS === 'linux' ? 4194304 : Infinity;
|
|
32
|
+
const START_TTL = 30e3, winStarts = new Map();
|
|
33
|
+
const exists = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
28
34
|
export function starts(pids) {
|
|
29
35
|
const out = new Map();
|
|
30
36
|
// One bad number in the state file mustn't make every holder look dead.
|
|
31
37
|
pids = [...new Set(pids.filter(p => Number.isInteger(p) && p > 0 && p <= PID_MAX))];
|
|
32
38
|
if (!pids.length) return out;
|
|
33
39
|
if (WIN) {
|
|
34
|
-
|
|
40
|
+
// A start time read in the last START_TTL stands while kill 0 (cheap here)
|
|
41
|
+
// finds the pid alive at every look, and is dropped the first time it doesn't.
|
|
42
|
+
// Each read is a PowerShell, about 0.4 s of CPU: a dozen waiters polling
|
|
43
|
+
// each read fresh kept a CI runner's cores busy and true took 40 s to run.
|
|
44
|
+
// A new process (dibs stop, cancel) starts with nothing kept, so reads fresh.
|
|
45
|
+
const now = Date.now(), need = [];
|
|
46
|
+
for (const pid of pids) {
|
|
47
|
+
const c = winStarts.get(pid);
|
|
48
|
+
if (!c || now - c.at >= START_TTL) need.push(pid);
|
|
49
|
+
else if (exists(pid)) out.set(pid, c.start);
|
|
50
|
+
else winStarts.delete(pid);
|
|
51
|
+
}
|
|
52
|
+
if (!need.length) return out;
|
|
53
|
+
// Get-Process, not a CIM query: 0.3 s against 0.5 s on a CI runner, paid by every dibs call that reads the state.
|
|
54
|
+
const txt = ps(`Get-Process -Id ${need.join(',')} -ErrorAction SilentlyContinue | ForEach-Object { "$($_.Id) $($_.StartTime.ToFileTimeUtc())" }`);
|
|
35
55
|
if (txt == null) return null;
|
|
36
|
-
for (const line of txt.split(/\r?\n/)) {
|
|
56
|
+
for (const line of txt.split(/\r?\n/)) {
|
|
57
|
+
const m = line.trim().match(/^(\d+)\s+(\d+)$/);
|
|
58
|
+
if (m) { out.set(Number(m[1]), m[2]); winStarts.set(Number(m[1]), { start: m[2], at: now }); }
|
|
59
|
+
}
|
|
37
60
|
return out;
|
|
38
61
|
}
|
|
39
62
|
// ps exits 1 with no output when every pid is gone, and also when it refuses
|
|
40
63
|
// the list (it says why on stderr). The second is "can't tell", not "all dead".
|
|
41
|
-
const r = spawnSync('ps', ['-o', 'pid=,lstart=', '-p', pids.join(',')], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
|
|
64
|
+
const r = spawnSync('ps', ['-o', 'pid=,lstart=', '-p', pids.join(',')], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: RUN_LIMIT });
|
|
42
65
|
if (r.status == null || (r.status !== 0 && !r.stdout && r.stderr.trim())) return null;
|
|
43
66
|
const txt = r.stdout;
|
|
44
67
|
for (const line of txt.split('\n')) {
|
|
@@ -48,11 +71,42 @@ export function starts(pids) {
|
|
|
48
71
|
return out;
|
|
49
72
|
}
|
|
50
73
|
|
|
74
|
+
// How long each process has run and the CPU time it has used, in ms, from one ps.
|
|
75
|
+
// Empty on Windows. ps writes both as [[dd-]hh:]mm:ss, CPU time with hundredths.
|
|
76
|
+
export function duration(text) {
|
|
77
|
+
const m = String(text).trim().match(/^(?:(\d+)-)?([\d:]+)(?:\.(\d+))?$/);
|
|
78
|
+
if (!m) return null;
|
|
79
|
+
const parts = m[2].split(':').map(Number).reverse();
|
|
80
|
+
const secs = (parts[0] || 0) + (parts[1] || 0) * 60 + (parts[2] || 0) * 3600 + Number(m[1] || 0) * 86400;
|
|
81
|
+
return secs * 1000 + (m[3] ? Number(`0.${m[3]}`) * 1000 : 0);
|
|
82
|
+
}
|
|
83
|
+
export function runtimes(pids) {
|
|
84
|
+
const out = new Map();
|
|
85
|
+
pids = [...new Set(pids.filter(p => Number.isInteger(p) && p > 0 && p <= PID_MAX))];
|
|
86
|
+
if (WIN || !pids.length) return out;
|
|
87
|
+
for (const line of run('ps', ['-o', 'pid=,etime=,time=', '-p', pids.join(',')]).split('\n')) {
|
|
88
|
+
const [pid, age, cpu] = line.trim().split(/\s+/);
|
|
89
|
+
const a = duration(age), c = duration(cpu);
|
|
90
|
+
if (pid && a != null && c != null) out.set(Number(pid), { age: a, cpu: c });
|
|
91
|
+
}
|
|
92
|
+
return out;
|
|
93
|
+
}
|
|
94
|
+
|
|
51
95
|
// Parent pid and executable name, for walking up to the owning agent.
|
|
96
|
+
// On Windows each PowerShell CIM read costs about half a second, and a walk up
|
|
97
|
+
// to the agent is a dozen levels: one read of the whole table answers them all.
|
|
98
|
+
let parentCache = null;
|
|
52
99
|
export function parent(pid) {
|
|
53
100
|
if (WIN) {
|
|
54
|
-
|
|
55
|
-
|
|
101
|
+
if (!parentCache || Date.now() - parentCache.at > 5000) {
|
|
102
|
+
const table = new Map();
|
|
103
|
+
for (const l of (ps('Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId,Name | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId) $($_.Name)" }') ?? '').split(/\r?\n/)) {
|
|
104
|
+
const m = l.trim().match(/^(\d+)\s+(\d+)\s+(.*)$/);
|
|
105
|
+
if (m) table.set(Number(m[1]), { ppid: Number(m[2]), name: m[3].replace(/\.exe$/i, '') });
|
|
106
|
+
}
|
|
107
|
+
parentCache = { at: Date.now(), table };
|
|
108
|
+
}
|
|
109
|
+
return parentCache.table.get(Number(pid)) ?? null;
|
|
56
110
|
}
|
|
57
111
|
const m = run('ps', ['-o', 'ppid=,comm=', '-p', String(pid)]).trim().match(/^(\d+)\s+(.*)$/);
|
|
58
112
|
if (!m) return null;
|
|
@@ -65,8 +119,8 @@ export function parent(pid) {
|
|
|
65
119
|
}
|
|
66
120
|
|
|
67
121
|
// Every process: pid, parent, process group, % of one core, resident bytes
|
|
68
|
-
// (
|
|
69
|
-
// no process groups.
|
|
122
|
+
// (the working set on Windows), command line. The group is the pid on Windows,
|
|
123
|
+
// which has no process groups.
|
|
70
124
|
let procCache = null;
|
|
71
125
|
export function processes() {
|
|
72
126
|
if (procCache && Date.now() - procCache.at < 5000) return procCache.list;
|
|
@@ -75,12 +129,15 @@ export function processes() {
|
|
|
75
129
|
|
|
76
130
|
function readProcesses() {
|
|
77
131
|
if (WIN) {
|
|
78
|
-
// Two samples of total processor time, a second apart, give a CPU
|
|
132
|
+
// Two samples of total processor time, a second apart, give a CPU %; one WMI query gives
|
|
133
|
+
// parents, working sets and command lines. One PowerShell for all of it, never one per pid.
|
|
134
|
+
// WMI's ProcessId is a UInt32 and Get-Process's Id an Int32: as hashtable keys they never match uncast.
|
|
79
135
|
const txt = ps(`$a = @{}; Get-Process | ForEach-Object { $a[$_.Id] = $_.TotalProcessorTime.TotalMilliseconds }; Start-Sleep -Milliseconds 1000;`
|
|
80
|
-
+ ` Get-
|
|
81
|
-
+ `
|
|
82
|
-
|
|
83
|
-
|
|
136
|
+
+ ` $b = @{}; Get-Process | ForEach-Object { $b[$_.Id] = $_.TotalProcessorTime.TotalMilliseconds };`
|
|
137
|
+
+ ` Get-CimInstance Win32_Process | ForEach-Object { $i = [int]$_.ProcessId;`
|
|
138
|
+
+ ` if ($a[$i] -ne $null -and $b[$i] -ne $null) { "$i\`t$($_.ParentProcessId)\`t$([math]::Round(($b[$i] - $a[$i]) / 10, 1))\`t$($_.WorkingSetSize)\`t$($_.CommandLine)" } }`);
|
|
139
|
+
return (txt ?? '').split(/\r?\n/).map(l => l.split('\t')).filter(f => f.length === 5 && f[4])
|
|
140
|
+
.map(([pid, ppid, cpu, rss, args]) => ({ pid: Number(pid), ppid: Number(ppid), pgid: Number(pid), cpu: Number(cpu), rss: Number(rss) || 0, args }));
|
|
84
141
|
}
|
|
85
142
|
return run('ps', ['-Ao', 'pid=,ppid=,pgid=,pcpu=,rss=,args=']).split('\n')
|
|
86
143
|
.map(l => l.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/)).filter(Boolean)
|
|
@@ -94,6 +151,13 @@ const DIBS_PROC = /^\S*\bnode\s+(?:-\S+\s+)*\S*(?:\/bin\/dibs|\/dibs\.mjs)(?:\s|
|
|
|
94
151
|
export const isDibs = p => DIBS_PROC.test(p.args);
|
|
95
152
|
export const dibsMem = (procs = processes()) => procs.reduce((a, p) => a + (isDibs(p) ? p.rss || 0 : 0), 0);
|
|
96
153
|
|
|
154
|
+
// The process table as it is now, not as the last 5 seconds' cache had it: for joining with another
|
|
155
|
+
// reading by pid, where a pid that ended meanwhile would carry its name onto nothing.
|
|
156
|
+
export function processesNow() {
|
|
157
|
+
procCache = null;
|
|
158
|
+
return processes();
|
|
159
|
+
}
|
|
160
|
+
|
|
97
161
|
// Every process group that has a process in it right now.
|
|
98
162
|
export function liveGroups() {
|
|
99
163
|
procCache = null;
|
|
@@ -125,9 +189,9 @@ export function descendants(pid) {
|
|
|
125
189
|
// smaps_rollup, which splits shared pages between the processes sharing them.
|
|
126
190
|
// Windows: null. DIBS_FAKE_FOOTPRINT names a JSON file of { pid: bytes } for tests.
|
|
127
191
|
const UNITS = { B: 1, K: 1024, M: 1024 ** 2, G: 1024 ** 3, T: 1024 ** 4 };
|
|
128
|
-
// Every process's memory, the way Activity Monitor's Memory column
|
|
129
|
-
//
|
|
130
|
-
//
|
|
192
|
+
// Every process's memory, the way Activity Monitor's Memory column shows it on
|
|
193
|
+
// macOS: its physical footprint, top's MEM, which already counts what the system
|
|
194
|
+
// compressed of it. For telling the person what to close (src/alerts.mjs), so
|
|
131
195
|
// all processes, not only dibs's. Linux: resident memory. DIBS_FAKE_MEMORY,
|
|
132
196
|
// a JSON file of { pid: bytes }, stands in for tests.
|
|
133
197
|
export function memoryUse() {
|
|
@@ -135,12 +199,17 @@ export function memoryUse() {
|
|
|
135
199
|
try { return new Map(Object.entries(JSON.parse(fs.readFileSync(process.env.DIBS_FAKE_MEMORY, 'utf8'))).map(([p, b]) => [Number(p), b])); } catch { return new Map(); }
|
|
136
200
|
}
|
|
137
201
|
if (OS !== 'macos') return new Map(processes().map(p => [p.pid, p.rss || 0]));
|
|
138
|
-
|
|
202
|
+
return topMemory(tryRun('top', ['-l', '1', '-o', 'mem', '-stats', 'pid,mem']));
|
|
203
|
+
}
|
|
204
|
+
// top's MEM by pid. MEM is the footprint, compressed pages included: adding CMPRS on top counted
|
|
205
|
+
// those twice, and under swap, when this is read, most of a process can be compressed. On
|
|
206
|
+
// 2026-11-05 a WebKit page read 813 MB in MEM and 805 MB in CMPRS, and footprint -p said 813 MB.
|
|
207
|
+
export function topMemory(txt) {
|
|
139
208
|
const out = new Map();
|
|
140
209
|
const size = x => { const m = x?.match(/^([\d.]+)([BKMGT])[+-]?$/); return m ? Number(m[1]) * UNITS[m[2]] : 0; };
|
|
141
210
|
for (const line of (txt || '').split('\n')) {
|
|
142
211
|
const f = line.trim().split(/\s+/);
|
|
143
|
-
if (f.length
|
|
212
|
+
if (f.length >= 2 && /^\d+$/.test(f[0])) out.set(Number(f[0]), size(f[1]));
|
|
144
213
|
}
|
|
145
214
|
return out;
|
|
146
215
|
}
|
|
@@ -203,18 +272,28 @@ const winQuote = a => (/^[\w@%+=:,./\\-]+$/.test(a) ? a : `"${a.replace(/(\\*)"/
|
|
|
203
272
|
// process group first, so a caller killed in between leaves nothing untracked.
|
|
204
273
|
// If the caller dies before go(), the pipe closes and the command never starts.
|
|
205
274
|
const GATE = 'IFS= read -r _ <&3 || exit 125; exec 3<&-; exec "$@"';
|
|
275
|
+
// A command line as the system can start it: on Windows a .cmd or .bat (npm's shims,
|
|
276
|
+
// boat's) runs only through cmd.exe. Spawn it with windowsVerbatimArguments when cmd[0] is cmd.exe.
|
|
277
|
+
export function runnable(argv, env = process.env) {
|
|
278
|
+
return WIN && /\.(cmd|bat)$/i.test(which(argv[0], env) || '') ? ['cmd.exe', '/d', '/s', '/c', `"${argv.map(winQuote).join(' ')}"`] : argv;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Windows has no exec, so its gate is a small Node that waits the same way, then
|
|
282
|
+
// runs the command and passes on its exit code. Stopping the gate's tree (taskkill /T)
|
|
283
|
+
// stops the command with it.
|
|
284
|
+
const WIN_GATE = "const fs=require('fs');let n=0;try{n=fs.readSync(3,Buffer.alloc(3),0,3,null)}catch{}if(!n)process.exit(125);fs.closeSync(3);"
|
|
285
|
+
+ "const[c,...a]=JSON.parse(process.argv[1]);const r=require('child_process').spawnSync(c,a,{stdio:'inherit',windowsVerbatimArguments:c==='cmd.exe'});"
|
|
286
|
+
+ "if(r.error){process.stderr.write(r.error.message+'\\n');process.exit(127)}process.exit(r.status??1)";
|
|
206
287
|
export function launch(argv, { env, background = false, gate = false }) {
|
|
207
|
-
let cmd = argv;
|
|
208
|
-
if (WIN
|
|
209
|
-
const
|
|
210
|
-
if (gated) cmd = ['/bin/sh', '-c', GATE, 'dibs', ...cmd];
|
|
211
|
-
const child = spawn(cmd[0], cmd.slice(1), { stdio: gated ? ['inherit', 'inherit', 'inherit', 'pipe'] : 'inherit',
|
|
288
|
+
let cmd = runnable(argv, env);
|
|
289
|
+
if (gate) cmd = WIN ? [process.execPath, '-e', WIN_GATE, JSON.stringify(cmd)] : ['/bin/sh', '-c', GATE, 'dibs', ...cmd];
|
|
290
|
+
const child = spawn(cmd[0], cmd.slice(1), { stdio: gate ? ['inherit', 'inherit', 'inherit', 'pipe'] : 'inherit',
|
|
212
291
|
detached: !WIN, env, windowsHide: false, windowsVerbatimArguments: cmd[0] === 'cmd.exe' });
|
|
213
292
|
// Lowered from outside, as the throttle watcher does, so dibs boost can raise it again: on macOS
|
|
214
293
|
// a process started under `taskpolicy -b` keeps background QoS whatever `taskpolicy -B -p` says.
|
|
215
294
|
// Its children inherit it. Gated, the command doesn't start until it's lowered.
|
|
216
295
|
if (background && child.pid) lower(child.pid);
|
|
217
|
-
child.go = () => { if (
|
|
296
|
+
child.go = () => { if (gate) child.stdio[3].end('go\n'); };
|
|
218
297
|
return child;
|
|
219
298
|
}
|
|
220
299
|
|
|
@@ -287,20 +366,46 @@ export function raise(pid) {
|
|
|
287
366
|
export function freeDisk(dir) {
|
|
288
367
|
try { const st = fs.statfsSync(dir); return st.bavail * st.bsize; } catch { return null; }
|
|
289
368
|
}
|
|
369
|
+
// The volume's whole size: a job that needs more can never start there, however long it waits.
|
|
370
|
+
export function diskSize(dir) {
|
|
371
|
+
try { const st = fs.statfsSync(dir); return st.blocks * st.bsize; } catch { return null; }
|
|
372
|
+
}
|
|
290
373
|
|
|
291
374
|
// Free disk where dibs lives, swap in use, % of memory free, 1-minute load.
|
|
292
375
|
// Windows has no load average, so CPU busy % across all cores stands in for it.
|
|
293
|
-
|
|
294
|
-
|
|
376
|
+
// The CPU's busy and total time so far, summed over every core (ms).
|
|
377
|
+
export function cpuTicks() {
|
|
378
|
+
let busy = 0, total = 0;
|
|
379
|
+
for (const { times: c } of os.cpus()) { busy += c.user + c.nice + c.sys + c.irq; total += c.user + c.nice + c.sys + c.irq + c.idle; }
|
|
380
|
+
return { busy, total };
|
|
381
|
+
}
|
|
382
|
+
// Cores in use from two cpuTicks readings this far apart: closer is noise,
|
|
383
|
+
// further is an average that hides what's happening now.
|
|
384
|
+
const BUSY_GAP_MIN = 1000, BUSY_GAP_MAX = 60e3;
|
|
385
|
+
export function busyBetween(prev, ticks, gap, cores) {
|
|
386
|
+
const dt = ticks.total - (prev?.total ?? NaN);
|
|
387
|
+
if (!(gap >= BUSY_GAP_MIN && gap <= BUSY_GAP_MAX && dt > 0)) return null;
|
|
388
|
+
return Math.max(0, (ticks.busy - prev.busy) / dt) * cores;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// prev: an earlier reading's { at, ticks }, from which the cores in use come
|
|
392
|
+
// without ps (src/config.mjs machine keeps the last one).
|
|
393
|
+
export function pressure(dir, prev = null) {
|
|
394
|
+
const vol = OS === 'macos' ? '/System/Volumes/Data' : dir;
|
|
395
|
+
const diskFree = freeDisk(vol), diskTotal = diskSize(vol);
|
|
295
396
|
let swapUsed = 0, swapFiles = null, memFree = Math.round(100 * os.freemem() / os.totalmem()), memAvail = null;
|
|
397
|
+
let vmPressure;
|
|
296
398
|
if (OS === 'macos') {
|
|
297
|
-
|
|
399
|
+
// One sysctl for all three: under heavy load each spawn costs 100 to 300 ms.
|
|
400
|
+
const [usage = '', level = '', vmLevel = ''] = run('sysctl', ['-n', 'vm.swapusage', 'kern.memorystatus_level', MEM_PRESSURE]).split('\n');
|
|
401
|
+
const sw = usage.match(/used = ([\d.]+)M/);
|
|
298
402
|
if (sw) swapUsed = parseFloat(sw[1]) * 1024 ** 2;
|
|
299
403
|
// The swap files' total size, which is what swap takes from the disk: macOS adds them a gigabyte at a time, ahead of what's used.
|
|
300
|
-
const tot =
|
|
404
|
+
const tot = usage.match(/total = ([\d.]+)M/);
|
|
301
405
|
if (tot) swapFiles = parseFloat(tot[1]) * 1024 ** 2;
|
|
302
|
-
const lvl = Number(
|
|
406
|
+
const lvl = Number(level);
|
|
303
407
|
if (lvl) memFree = lvl; // counts reclaimable cache as free, unlike os.freemem
|
|
408
|
+
vmPressure = PRESSURE_LEVEL[Number(vmLevel)] ?? null;
|
|
304
409
|
memAvail = vmAvail(run('vm_stat', []));
|
|
305
410
|
} else if (OS === 'linux') {
|
|
306
411
|
try {
|
|
@@ -311,22 +416,39 @@ export function pressure(dir) {
|
|
|
311
416
|
swapUsed = (mi.SwapTotal || 0) - (mi.SwapFree || 0);
|
|
312
417
|
} catch {}
|
|
313
418
|
}
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
}
|
|
419
|
+
// Windows has no load average: the cores' busy share over a short window stands in, times
|
|
420
|
+
// the core count. Read from os.cpus() in-process: the CIM processor query it replaces took
|
|
421
|
+
// 1.5 s on a CI runner, and every dibs call reads the machine.
|
|
422
|
+
const load = WIN ? cpuBusy() * os.cpus().length : os.loadavg()[0];
|
|
319
423
|
// Cores actually in use. The load average also counts processes waiting on
|
|
320
424
|
// disk, so heavy swapping can read 20 on a machine that's nearly idle.
|
|
321
425
|
// Just the CPU column (13 ms) unless the full table is fresh anyway: the full one,
|
|
322
426
|
// with every command line, took 60 ms of each dibs run's start on a busy Mac.
|
|
427
|
+
// The CPU's own counters since the last reading cost nothing; ps -Ao pcpu took
|
|
428
|
+
// 0.1 to 1.8 s on 2026-11-11, at load 30 with a thousand processes.
|
|
323
429
|
let busy = null;
|
|
430
|
+
const ticks = cpuTicks(), cores = os.cpus().length;
|
|
324
431
|
if (!WIN) {
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
432
|
+
busy = busyBetween(prev?.ticks, ticks, Date.now() - prev?.at, cores);
|
|
433
|
+
if (busy == null) {
|
|
434
|
+
const cpus = procCache && Date.now() - procCache.at < 5000 ? procCache.list.map(p => p.cpu || 0)
|
|
435
|
+
: run('ps', ['-Ao', 'pcpu=']).split('\n').map(Number).filter(x => !isNaN(x));
|
|
436
|
+
if (cpus.length) busy = cpus.reduce((a, c) => a + c, 0) / 100;
|
|
437
|
+
}
|
|
328
438
|
}
|
|
329
|
-
return { diskFree, swapUsed, ...(swapFiles != null && { swapFiles }), memFree, memAvail, load, busy, cores
|
|
439
|
+
return { diskFree, ...(diskTotal != null && { diskTotal }), swapUsed, ...(swapFiles != null && { swapFiles }), memFree, memAvail, load, busy, cores, os: OS, ticks,
|
|
440
|
+
vmPressure: vmPressure === undefined ? memPressure() : vmPressure };
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// Share of all cores busy over CPU_WINDOW ms (0 to 1), from two os.cpus() readings.
|
|
444
|
+
const CPU_WINDOW = 100;
|
|
445
|
+
function cpuBusy() {
|
|
446
|
+
const total = () => os.cpus().reduce((a, c) => { const t = c.times; a.busy += t.user + t.nice + t.sys + t.irq; a.all += t.user + t.nice + t.sys + t.irq + t.idle; return a; }, { busy: 0, all: 0 });
|
|
447
|
+
const a = total();
|
|
448
|
+
const until = Date.now() + CPU_WINDOW;
|
|
449
|
+
while (Date.now() < until) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, until - Date.now());
|
|
450
|
+
const b = total();
|
|
451
|
+
return b.all > a.all ? Math.min(1, Math.max(0, (b.busy - a.busy) / (b.all - a.all))) : 0;
|
|
330
452
|
}
|
|
331
453
|
|
|
332
454
|
// Memory a new job can take without anything going to swap, from vm_stat: pages
|
|
@@ -343,8 +465,19 @@ export function vmAvail(text) {
|
|
|
343
465
|
// Memory pressure: 0 normal, 1 warning, 2 critical (swapping hard), or null
|
|
344
466
|
// when the OS doesn't say. One sysctl on macOS; PSI on Linux, where a tenth of
|
|
345
467
|
// the last 10s fully stalled on memory counts as critical. Windows: null.
|
|
468
|
+
// When the machine last woke from sleep (dark wakes and Power Nap included), or null:
|
|
469
|
+
// macOS's kern.waketime, which reads 0 until the first sleep after boot. DIBS_FAKE_WAKETIME
|
|
470
|
+
// (ms since 1970) stands in for it in tests.
|
|
471
|
+
export function wokeAt() {
|
|
472
|
+
if (process.env.DIBS_FAKE_WAKETIME) return Number(process.env.DIBS_FAKE_WAKETIME) || null;
|
|
473
|
+
if (OS !== 'macos') return null;
|
|
474
|
+
const m = run('sysctl', ['-n', 'kern.waketime']).match(/sec = (\d+), usec = (\d+)/);
|
|
475
|
+
return m && Number(m[1]) ? Number(m[1]) * 1000 + Math.floor(Number(m[2]) / 1000) : null;
|
|
476
|
+
}
|
|
477
|
+
const MEM_PRESSURE = 'kern.memorystatus_vm_pressure_level';
|
|
478
|
+
const PRESSURE_LEVEL = { 1: 0, 2: 1, 4: 2 };
|
|
346
479
|
export function memPressure() {
|
|
347
|
-
if (OS === 'macos') return
|
|
480
|
+
if (OS === 'macos') return PRESSURE_LEVEL[Number(run('sysctl', ['-n', MEM_PRESSURE]))] ?? null;
|
|
348
481
|
if (OS !== 'linux') return null;
|
|
349
482
|
try {
|
|
350
483
|
const t = fs.readFileSync('/proc/pressure/memory', 'utf8');
|
package/src/preempt.mjs
CHANGED
|
@@ -302,6 +302,32 @@ export function diskStep(track, m, cfg) {
|
|
|
302
302
|
return null;
|
|
303
303
|
}
|
|
304
304
|
|
|
305
|
+
// The hard stop: under HARD_STOP free, a full disk is seconds away and fails every job on the
|
|
306
|
+
// machine, so the dibs run writing fastest is paused whatever its priority or resource (a deploy
|
|
307
|
+
// included, which pausing may time out: that's the lesser harm), one a pass, never the last one
|
|
308
|
+
// running. They resume once
|
|
309
|
+
// there's HARD_RESUME. Writing fastest: the biggest share of the disk's last fall (src/measure.mjs
|
|
310
|
+
// ateLast), then of its fall per minute run.
|
|
311
|
+
export const HARD_STOP = 1024 ** 3, HARD_RESUME = 2 * 1024 ** 3;
|
|
312
|
+
const writing = (l, t) => [l.ateLast || 0, (l.ate || 0) / Math.max(1, t - l.start)];
|
|
313
|
+
export function hardStop(s, t = now(), m = {}) {
|
|
314
|
+
if (m.diskFree == null || m.diskFree >= HARD_STOP || OS === 'windows') return null;
|
|
315
|
+
// Never the last one running: dibs doesn't pause every job (heal would resume one at once).
|
|
316
|
+
if (running(s).length < 2) return null;
|
|
317
|
+
const l = s.leases.filter(x => x.kind === 'run' && x.pgid && !x.pausedAt)
|
|
318
|
+
.sort((a, b) => { const [x, y] = [writing(a, t), writing(b, t)]; return y[0] - x[0] || y[1] - x[1]; })[0];
|
|
319
|
+
if (!l) return null;
|
|
320
|
+
(l.pauses ||= []).push({ watcher: process.pid, wstart: pstart(process.pid), at: t, disk: true, hard: true });
|
|
321
|
+
sync(l);
|
|
322
|
+
return { ...l };
|
|
323
|
+
}
|
|
324
|
+
export function hardResume(s, m = {}) {
|
|
325
|
+
if (m.diskFree == null || m.diskFree < HARD_RESUME) return [];
|
|
326
|
+
const ls = s.leases.filter(l => l.pauses?.some(p => p.hard));
|
|
327
|
+
for (const l of ls) { l.pauses = l.pauses.filter(p => !p.hard); sync(l); }
|
|
328
|
+
return ls.map(l => ({ ...l }));
|
|
329
|
+
}
|
|
330
|
+
|
|
305
331
|
// Pause the next lease while free disk is low and filling: one on top of a full
|
|
306
332
|
// resource first, then idle, low and normal work, newest first (the newest is
|
|
307
333
|
// likeliest to be the one growing). Urgent and high work, holds, and resources
|
|
@@ -350,8 +376,13 @@ export function diskRequeue(s, cfg, t = now(), hist = []) {
|
|
|
350
376
|
&& x.res.every(r => resCfg(cfg, r).rerun === true) && !nearlyDone(x, hist, t))
|
|
351
377
|
.sort((a, b) => (measured(b) || b.mem || 0) - (measured(a) || a.mem || 0))[0];
|
|
352
378
|
if (!l) return null;
|
|
353
|
-
l
|
|
354
|
-
|
|
379
|
+
return stopToRequeue(l, why(l), t);
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// Killed where it stands: SIGKILL ends a stopped process too. Its dibs run sees it end and
|
|
383
|
+
// puts it back in line (src/commands.mjs requeue).
|
|
384
|
+
function stopToRequeue(l, why, t) {
|
|
385
|
+
l.requeue = { at: t, why };
|
|
355
386
|
if (ours(l)) {
|
|
356
387
|
const groups = [...new Set([l.pgid, ...(l.stopped || []), ...(l.groups || [])].filter(Boolean))];
|
|
357
388
|
queued.push(() => { for (const g of groups) stopTree(g, 'SIGKILL'); });
|
|
@@ -359,6 +390,22 @@ export function diskRequeue(s, cfg, t = now(), hist = []) {
|
|
|
359
390
|
return { ...l };
|
|
360
391
|
}
|
|
361
392
|
|
|
393
|
+
// Memory pressure still critical with a job already paused for it: a stopped job keeps every
|
|
394
|
+
// byte it had, and under pressure those go to swap, so pausing more only moves memory to the
|
|
395
|
+
// disk. On 2026-11-10 at 23:48 swap reached 13.7 GB with jobs paused, and the Mac froze. One
|
|
396
|
+
// paused job is stopped instead, the lowest priority first, then the most memory, and its dibs
|
|
397
|
+
// run puts it back at the front of its line, to run again from the start once there's room.
|
|
398
|
+
// Same limits as diskRequeue: jobs dibs can run again (rerun, requeuable), not nearly done, not
|
|
399
|
+
// paused by a person or agent. Returns it, or null when none can go (then the watcher pauses one more).
|
|
400
|
+
const LOWEST = { idle: 0, low: 1, normal: 2 };
|
|
401
|
+
const memPaused = l => !!l.pauses?.some(p => p.watcher && !p.disk);
|
|
402
|
+
export function pressureRequeue(s, cfg, t = now(), hist = []) {
|
|
403
|
+
const l = s.leases.filter(x => memPaused(x) && x.kind === 'run' && x.requeuable && !x.requeue && !x.pauses?.some(p => p.owner)
|
|
404
|
+
&& x.res.every(r => resCfg(cfg, r).rerun === true) && !nearlyDone(x, hist, t))
|
|
405
|
+
.sort((a, b) => (LOWEST[a.prio || 'normal'] ?? 3) - (LOWEST[b.prio || 'normal'] ?? 3) || (measured(b) || b.mem || 0) - (measured(a) || a.mem || 0))[0];
|
|
406
|
+
return l ? stopToRequeue(l, 'memory', t) : null;
|
|
407
|
+
}
|
|
408
|
+
|
|
362
409
|
// Pause the next lease under memory pressure: a job running on top of a full
|
|
363
410
|
// resource first, newest first (src/overlap.mjs), since it's the extra load;
|
|
364
411
|
// then the one furthest over the memory it asked for (it's why the books are
|
|
@@ -379,7 +426,8 @@ export function pressurePause(s, cfg, t = now(), hist = []) {
|
|
|
379
426
|
// memory. With all = true, every one (the watcher is stopping); 'memory', every
|
|
380
427
|
// memory pause and no disk ones. Returns what it resumed.
|
|
381
428
|
export function pressureResume(s, all = false, disk = false) {
|
|
382
|
-
|
|
429
|
+
// A hard stop's pause lifts only at HARD_RESUME (hardResume), or when the watcher hands over.
|
|
430
|
+
const ours = p => p.watcher && !(p.hard && all !== true) && (all === 'memory' ? !p.disk : all || !!p.disk === disk);
|
|
383
431
|
const ls = s.leases.filter(l => l.pauses?.some(ours)).sort((a, b) => !!a.alongside - !!b.alongside || (a.alongside ? a.start - b.start : 0)
|
|
384
432
|
|| (a.prio === 'idle') - (b.prio === 'idle') || a.mem - b.mem);
|
|
385
433
|
const out = all ? ls : ls.slice(0, 1);
|
package/src/primer.mjs
CHANGED
|
@@ -32,7 +32,7 @@ export function rules(res = resources(), more = 'is in dibs.md beside dibs (the
|
|
|
32
32
|
'- No dibs for reads, edits, small commands, or long jobs that mostly wait on the network and use little CPU, memory or disk (crawlers, pollers, HTTP checks). The hook leaves those alone too.',
|
|
33
33
|
'- Start `dibs listen` with run_in_background now, and again each time it exits: it wakes you when the person or dibs has something for you.',
|
|
34
34
|
'- Waiting is normal. A call moved to the background is still waiting: don\'t run it again. A wait on memory, swap or disk protects the machine: keep waiting, and never lower `--mem` or raise `-p` to get past it.',
|
|
35
|
-
'- Exit 75: it gave up waiting and your command never ran; run the same command again. Exit 74:
|
|
35
|
+
'- Exit 75: it gave up waiting and your command never ran; run the same command again. Exit 74: it can\'t fit on this disk, or its wait limit ran out; low disk just means a wait.',
|
|
36
36
|
'- Decide what you can undo yourself. Ask the person only before something you can\'t undo (`dibs question ... --one-way`). Lines starting "Message from the person:" are theirs: act on them.',
|
|
37
37
|
'- Post progress as you work: `dibs progress "what you did or found" --task <name> --eta 30m`, then `--done`.',
|
|
38
38
|
`- The rest (holding across tool calls, file leases, other machines, every exit code, overriding jobs, questions) ${more}.`,
|
package/src/proc.mjs
CHANGED
|
@@ -17,14 +17,19 @@ export const pstart = pid => starts([pid])?.get(pid) || null;
|
|
|
17
17
|
// 30 to 50 ms each time on a busy Mac. A pid can only be reused after its
|
|
18
18
|
// process is gone, which kill(0) sees.
|
|
19
19
|
const STARTS_FOR = 10e3;
|
|
20
|
-
const known = new Map(); // pid -> { start, at }
|
|
20
|
+
const known = new Map(); // pid -> { pid, start, at }
|
|
21
|
+
const KNOWN_MAX = 1000; // a long-lived broker or service sees thousands of pids a day
|
|
22
|
+
// A pid found gone is remembered as gone (start null) for as long: that process
|
|
23
|
+
// can't come back, and a new one given its number isn't the holder recorded.
|
|
21
24
|
const answers = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
|
|
25
|
+
const still = (k, t) => k && t - k.at < STARTS_FOR && (k.start == null || answers(k.pid));
|
|
22
26
|
export function makeAlive(pids) {
|
|
23
27
|
const t = Date.now();
|
|
24
|
-
const need = pids.filter(p => p && !(known.
|
|
28
|
+
const need = pids.filter(p => p && !still(known.get(p), t));
|
|
25
29
|
const st = need.length ? starts(need) : new Map();
|
|
26
30
|
if (!st) return pid => !!pid;
|
|
27
|
-
for (const p of need)
|
|
31
|
+
for (const p of need) known.set(p, { pid: p, start: st.has(p) ? st.get(p) : null, at: t });
|
|
32
|
+
if (known.size > KNOWN_MAX) for (const [p, k] of known) if (t - k.at >= STARTS_FOR) known.delete(p);
|
|
28
33
|
const startOf = pid => (st.has(pid) ? st.get(pid) : known.get(pid)?.start);
|
|
29
34
|
return (pid, started) => !!pid && startOf(pid) != null && (!started || startOf(pid) === started);
|
|
30
35
|
}
|
|
@@ -32,18 +37,28 @@ export function makeAlive(pids) {
|
|
|
32
37
|
// The agent session that owns this call (Claude Code, Codex, Cursor...), found
|
|
33
38
|
// by walking up the process tree. Holds outlive a single tool call, so they
|
|
34
39
|
// hang off this process. For Claude Code, its name is the one SendMessage uses.
|
|
40
|
+
// What other agent programs set (src/owner.mjs AGENT_ENV, less Claude Code's own).
|
|
41
|
+
const OTHER_AGENTS = ['CODEX_SANDBOX', 'CODEX_THREAD_ID', 'CURSOR_AGENT', 'GEMINI_CLI', 'OPENCODE'];
|
|
35
42
|
let cached;
|
|
36
43
|
function session() {
|
|
37
44
|
if (cached !== undefined) return cached;
|
|
38
45
|
cached = null;
|
|
39
46
|
if (process.env.DIBS_NO_SESSION) return cached; // tests act as several agents from one session
|
|
47
|
+
// Inside Claude Code the session names itself: its file in SESSIONS gives the pid without
|
|
48
|
+
// walking up the tree, one ps per level (3 of them, 190 ms of a board at load 60 on
|
|
49
|
+
// 2026-11-11). Not when another agent program runs under it: then the nearest is that one.
|
|
50
|
+
const sid = process.env.CLAUDE_CODE_SESSION_ID;
|
|
51
|
+
if (sid && !OTHER_AGENTS.some(k => process.env[k])) {
|
|
52
|
+
const f = sessionFiles().find(x => x.sessionId === sid && answers(x.pid));
|
|
53
|
+
if (f) return (cached = { pid: f.pid, name: f.name, app: 'claude', start: pstart(f.pid) });
|
|
54
|
+
}
|
|
40
55
|
let pid = callerPid();
|
|
41
56
|
for (let i = 0; i < 25 && pid > 1; i++) {
|
|
42
57
|
const p = parent(pid);
|
|
43
58
|
if (!p) break;
|
|
44
59
|
if (AGENTS.test(p.name)) {
|
|
45
60
|
let name = null;
|
|
46
|
-
try { name =
|
|
61
|
+
try { name = sessionFile(path.join(SESSIONS, `${pid}.json`)).name || null; } catch {}
|
|
47
62
|
cached = { pid, name, app: p.name.toLowerCase(), start: pstart(pid) };
|
|
48
63
|
break;
|
|
49
64
|
}
|
|
@@ -61,6 +76,31 @@ export function identity(o = {}) {
|
|
|
61
76
|
return { who, agent, label, spid: se?.pid || null, sstart: se?.start || null };
|
|
62
77
|
}
|
|
63
78
|
|
|
79
|
+
// One session's record. Claude Code has left one with a stray } after the object (2026-11-10,
|
|
80
|
+
// 43095.json), and a strict parse dropped that session from the board and its messages: the
|
|
81
|
+
// object it starts with is the record.
|
|
82
|
+
export function sessionFile(file) {
|
|
83
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
84
|
+
try { return JSON.parse(text); } catch (e) {
|
|
85
|
+
const end = objectEnd(text);
|
|
86
|
+
if (end < 0) throw e;
|
|
87
|
+
return JSON.parse(text.slice(0, end));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// Where the JSON object a text starts with ends, counting braces outside strings; -1 if it doesn't.
|
|
92
|
+
function objectEnd(text) {
|
|
93
|
+
let depth = 0, str = false;
|
|
94
|
+
for (let i = text.indexOf('{'); i >= 0 && i < text.length; i++) {
|
|
95
|
+
const c = text[i];
|
|
96
|
+
if (str) { if (c === '\\') i++; else if (c === '"') str = false; continue; }
|
|
97
|
+
if (c === '"') str = true;
|
|
98
|
+
else if (c === '{') depth++;
|
|
99
|
+
else if (c === '}' && --depth === 0) return i + 1;
|
|
100
|
+
}
|
|
101
|
+
return -1;
|
|
102
|
+
}
|
|
103
|
+
|
|
64
104
|
// Claude Code's own record of each session it runs: { pid, sessionId, name, status, updated }.
|
|
65
105
|
// The person addresses an agent by the name; hooks know it by sessionId. status is Claude
|
|
66
106
|
// Code's word for what it's doing ("busy", "idle", "shell"), or null from an older one.
|
|
@@ -70,7 +110,7 @@ export function sessionFiles() {
|
|
|
70
110
|
const out = [];
|
|
71
111
|
for (const n of names) {
|
|
72
112
|
try {
|
|
73
|
-
const x =
|
|
113
|
+
const x = sessionFile(path.join(SESSIONS, n));
|
|
74
114
|
if (x.pid && x.sessionId) out.push({ pid: x.pid, sessionId: x.sessionId, name: x.name || null, status: typeof x.status === 'string' ? x.status : null, updated: x.statusUpdatedAt || x.updatedAt || 0 });
|
|
75
115
|
} catch {}
|
|
76
116
|
}
|
package/src/questions.mjs
CHANGED
|
@@ -24,13 +24,13 @@ import { defaultMaxWait } from './acquire.mjs';
|
|
|
24
24
|
import { event } from './events.mjs';
|
|
25
25
|
import { takeAgent, talkKey } from './files.mjs';
|
|
26
26
|
import { messageAsker } from './talk.mjs';
|
|
27
|
-
import {
|
|
27
|
+
import { underLock, commit } from './lock.mjs';
|
|
28
|
+
import { clock, die, dur, ms, now, say, sleep, fakeFull } from './util.mjs';
|
|
28
29
|
import { bold, dim, amber, wrap } from './style.mjs';
|
|
29
30
|
|
|
30
31
|
const FILE = path.join(HOME, 'questions.json');
|
|
31
32
|
const LOCK = path.join(HOME, 'questions.lock');
|
|
32
|
-
// Writes take milliseconds
|
|
33
|
-
const LOCK_STALE = 5000;
|
|
33
|
+
// Writes take milliseconds: a live holder past this is stuck on something else, and the caller hears so.
|
|
34
34
|
const LOCK_WAIT = 15e3;
|
|
35
35
|
// A waiting asker looks for its answer this often. A person reads the answer
|
|
36
36
|
// back slower than this, and each look is one small file read.
|
|
@@ -46,30 +46,16 @@ const OPEN = 'open';
|
|
|
46
46
|
const DECIDED = 'decided';
|
|
47
47
|
|
|
48
48
|
function locked(fn) {
|
|
49
|
-
|
|
50
|
-
const t0 = now();
|
|
51
|
-
for (;;) {
|
|
52
|
-
try { fs.mkdirSync(LOCK); break; } catch (e) {
|
|
53
|
-
if (e.code !== 'EEXIST') throw e;
|
|
54
|
-
try { if (now() - fs.statSync(LOCK).mtimeMs > LOCK_STALE) fs.rmSync(LOCK, { recursive: true, force: true }); } catch {}
|
|
55
|
-
if (now() - t0 > LOCK_WAIT) die(`${LOCK} stayed locked for ${LOCK_WAIT / 1000}s; remove it if no dibs is running. Nothing was changed.`, 75);
|
|
56
|
-
sleepSync(5 + Math.random() * 10);
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
try {
|
|
49
|
+
const r = underLock(LOCK, h => {
|
|
60
50
|
const s = load();
|
|
61
51
|
const before = JSON.stringify(s);
|
|
62
52
|
reap(s);
|
|
63
53
|
const out = fn(s);
|
|
64
|
-
if (JSON.stringify(s) !== before) {
|
|
65
|
-
fakeFull('state');
|
|
66
|
-
fs.writeFileSync(`${FILE}.tmp`, JSON.stringify(s, null, 1));
|
|
67
|
-
fs.renameSync(`${FILE}.tmp`, FILE);
|
|
68
|
-
}
|
|
54
|
+
if (JSON.stringify(s) !== before) commit(h, FILE, JSON.stringify(s, null, 1), { fake: () => fakeFull('state') });
|
|
69
55
|
return out;
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
|
|
56
|
+
}, { wait: LOCK_WAIT, files: [FILE] });
|
|
57
|
+
if (!r) die(`${LOCK} is held by a dibs that's still running, and stayed held for ${LOCK_WAIT / 1000}s. Nothing was changed: run the same command again.`, 75);
|
|
58
|
+
return r.out;
|
|
73
59
|
}
|
|
74
60
|
|
|
75
61
|
// Writes are renames, so reading without the lock always sees a whole file.
|