@dibssoftware/dibs 0.0.180 → 0.0.195
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 +111 -1
- package/README.md +10 -8
- package/bin/dibs.mjs +379 -74
- package/docs/agents.md +303 -0
- package/docs/council.md +88 -0
- package/docs/files.md +3 -3
- package/docs/guard.md +86 -11
- package/docs/json.md +211 -0
- package/docs/later.md +5 -5
- package/docs/machines.md +6 -6
- package/docs/questions.md +104 -3
- package/docs/reference.md +124 -30
- package/docs/relay.md +135 -11
- package/docs/releasing.md +7 -1
- package/docs/scheduling.md +28 -6
- package/docs/secrets.md +53 -0
- package/docs/simulators.md +3 -3
- package/docs/windows.md +3 -3
- package/package.json +1 -1
- package/skills/dibs/SKILL.md +79 -149
- package/src/about.mjs +341 -0
- package/src/acquire.mjs +113 -28
- package/src/after.mjs +127 -0
- package/src/agents.mjs +2 -1
- package/src/alerts.mjs +109 -48
- package/src/answers.mjs +2 -2
- package/src/board.mjs +21 -16
- package/src/broker.mjs +23 -7
- package/src/carry.mjs +287 -0
- package/src/codex.mjs +132 -0
- package/src/commands.mjs +254 -86
- package/src/config.mjs +85 -14
- package/src/connect.mjs +4 -2
- package/src/cool.mjs +28 -12
- package/src/council.mjs +482 -0
- package/src/cwd.mjs +9 -0
- package/src/decisions.mjs +250 -0
- package/src/declare.mjs +96 -0
- package/src/diskreport.mjs +306 -0
- package/src/diskuse.mjs +420 -0
- package/src/diskwarn.mjs +68 -13
- package/src/doctor.mjs +149 -0
- package/src/doors.mjs +547 -0
- package/src/durable.mjs +143 -0
- package/src/envs.mjs +372 -0
- package/src/events.mjs +7 -2
- package/src/files.mjs +121 -7
- package/src/guard.mjs +288 -105
- package/src/guardd.mjs +8 -1
- package/src/halt.mjs +63 -0
- package/src/handoffs.mjs +362 -0
- package/src/history.mjs +34 -4
- package/src/hogs.mjs +36 -8
- package/src/jobprogress.mjs +283 -0
- package/src/later.mjs +21 -10
- package/src/lock.mjs +51 -11
- package/src/measure.mjs +60 -14
- package/src/media.mjs +240 -0
- package/src/news.mjs +31 -0
- package/src/notes.mjs +49 -8
- package/src/notices.mjs +126 -43
- package/src/ondemand.mjs +25 -2
- package/src/outcome.mjs +163 -0
- package/src/overlap.mjs +2 -2
- package/src/override.mjs +149 -79
- package/src/owner.mjs +15 -2
- package/src/people.mjs +236 -0
- package/src/pickup.mjs +72 -0
- package/src/picture.mjs +321 -0
- package/src/plain.mjs +84 -18
- package/src/platform.mjs +29 -7
- package/src/preempt.mjs +123 -15
- package/src/primer.mjs +91 -20
- package/src/prints.mjs +99 -0
- package/src/proc.mjs +11 -1
- package/src/progress.mjs +49 -3
- package/src/proof.mjs +102 -0
- package/src/push.mjs +271 -0
- package/src/questions.mjs +328 -57
- package/src/quota.mjs +1 -1
- package/src/recap.mjs +205 -0
- package/src/relay.mjs +262 -26
- package/src/remote.mjs +23 -10
- package/src/reviewgate.mjs +268 -0
- package/src/reviews.mjs +377 -0
- package/src/route.mjs +263 -0
- package/src/rules.mjs +216 -0
- package/src/schedule.mjs +238 -44
- package/src/schema.mjs +62 -0
- package/src/scratch.mjs +2 -2
- package/src/serve.mjs +3 -2
- package/src/service.mjs +5 -1
- package/src/signed.mjs +97 -0
- package/src/simpool.mjs +46 -1
- package/src/spend.mjs +375 -0
- package/src/state.mjs +43 -17
- package/src/talk.mjs +1082 -134
- package/src/thin.sh +2 -0
- package/src/trail.mjs +290 -0
- package/src/trailnote.mjs +209 -0
- package/src/util.mjs +7 -0
- package/src/vault.mjs +435 -0
- package/src/vendors.mjs +327 -0
- package/src/version.mjs +1 -1
- package/src/web.mjs +354 -60
- package/src/work.mjs +487 -0
- package/src/worker.mjs +7 -1
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
// How far a running job is, in its own words. On 2026-11-27 a solver run held
|
|
2
|
+
// the machine for 7 hours while a test waited 6 hours behind it, every board
|
|
3
|
+
// said "time left unknown", and nothing knew the run was going at a sixth of
|
|
4
|
+
// its usual speed until an agent asked. A job says how far it is two ways:
|
|
5
|
+
// dibs progress 40%, or dibs progress 1200/9000 "flops solved", from inside
|
|
6
|
+
// the job (dibs run sets DIBS_LEASE there), or from anywhere with --job <id>
|
|
7
|
+
// (src/progress.mjs hands those here)
|
|
8
|
+
// lines in its own output that only a progress display prints: "[ 40%]",
|
|
9
|
+
// "[12/300]", a tqdm bar, "Progress: 40%". Read only when the output goes to
|
|
10
|
+
// a file (Claude Code's tool calls and background tasks), from the file:
|
|
11
|
+
// the job's output never passes through dibs, so nothing about how it runs
|
|
12
|
+
// changes, and dibs keeps the number, never the text.
|
|
13
|
+
// Each reading goes on the lease (progress) with a few earlier ones, so the
|
|
14
|
+
// board can say "40% done, about 2 hr left" from the job's own rate, and see
|
|
15
|
+
// when that rate falls far below where it was, or a job runs several times as
|
|
16
|
+
// long as the same command usually takes (slowness). Nothing is ever stopped
|
|
17
|
+
// for it: the alert and the agent's notice say so, and whoever owns it decides.
|
|
18
|
+
//
|
|
19
|
+
// Pure, apart from outputWatch's reads of the job's output file: the state is
|
|
20
|
+
// written by whoever calls (src/commands.mjs run, src/progress.mjs).
|
|
21
|
+
import fs from 'node:fs';
|
|
22
|
+
import { spawnSync } from 'node:child_process';
|
|
23
|
+
import { now, runsOf } from './util.mjs';
|
|
24
|
+
|
|
25
|
+
const MIN = 6e4;
|
|
26
|
+
// Readings closer together than this replace each other, so a script reporting
|
|
27
|
+
// every item doesn't fill the lease with them.
|
|
28
|
+
const SAMPLE_GAP = 30e3;
|
|
29
|
+
// Readings kept per job: at least 24 minutes of them at SAMPLE_GAP, far more for a job that reports less often.
|
|
30
|
+
const KEEP = 48;
|
|
31
|
+
// A script reporting in a loop writes the state at most this often, unless it reaches 100%.
|
|
32
|
+
export const WRITE_GAP = 2e3;
|
|
33
|
+
// A time left comes from the rate over about this long, so a job that slowed is
|
|
34
|
+
// believed within minutes, and one slow item doesn't swing it.
|
|
35
|
+
const RATE_WINDOW = 20 * MIN;
|
|
36
|
+
// Slowness is judged over at least this long, and over at least STEPS of the
|
|
37
|
+
// job's own reports: a job that reports every 10% isn't stalled between them.
|
|
38
|
+
const SLOW_WINDOW = 30 * MIN;
|
|
39
|
+
const STEPS = 4;
|
|
40
|
+
// Under a quarter of its earlier rate is far below it, not a harder stretch of the same work.
|
|
41
|
+
const SLOW_RATIO = 4;
|
|
42
|
+
// Run this many times the same command's usual time, and at least LONG_OVER past it, is long.
|
|
43
|
+
const LONG_TIMES = 3;
|
|
44
|
+
export const LONG_OVER = 30 * MIN;
|
|
45
|
+
// A usual time needs this many past runs that finished: one or two are no history.
|
|
46
|
+
const LONG_RUNS = 3;
|
|
47
|
+
// A job that usually gets less CPU than this (it mostly waits on the network or a device)
|
|
48
|
+
// can't be judged by what it gets: a quiet stretch is normal for it.
|
|
49
|
+
const CPU_FLOOR = 0.25;
|
|
50
|
+
// Under this many cores is next to nothing: a job getting it looks stuck rather than starved.
|
|
51
|
+
const CPU_NONE = 0.05;
|
|
52
|
+
// CPU readings (src/measure.mjs, every 10 s) closer than this replace each other.
|
|
53
|
+
const CPU_GAP = 60e3;
|
|
54
|
+
// How much of the job's output file one look reads, from its end: the newest progress line is in it.
|
|
55
|
+
const TAIL = 64 * 1024;
|
|
56
|
+
// The words after the number: a short label, not a log line.
|
|
57
|
+
export const MAX_UNIT = 40;
|
|
58
|
+
|
|
59
|
+
// The job's time running, less any time it sat paused (as src/schedule.mjs pausedFor counts it).
|
|
60
|
+
const active = (l, t) => t - l.start - (l.pausedMs || 0) - (l.pausedAt ? t - l.pausedAt : 0);
|
|
61
|
+
|
|
62
|
+
// "40%", "40.5%", "1200/9000": { pct, done?, total? }, or null.
|
|
63
|
+
export const looksLike = w => /^\d+(\.\d+)?%$|^\d+\/\d+$/.test(w || '');
|
|
64
|
+
export function parse(w) {
|
|
65
|
+
let m = /^(\d+(?:\.\d+)?)%$/.exec(w || '');
|
|
66
|
+
if (m) return Number(m[1]) <= 100 ? { pct: Number(m[1]) } : null;
|
|
67
|
+
m = /^(\d+)\/(\d+)$/.exec(w || '');
|
|
68
|
+
return m ? count(m[1], m[2]) : null;
|
|
69
|
+
}
|
|
70
|
+
function count(d, n) {
|
|
71
|
+
const done = Number(d), total = Number(n);
|
|
72
|
+
return total >= 1 && done <= total ? { pct: (100 * done) / total, done, total } : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// Progress lines in output, newest last in the list. Each shape is one only a
|
|
76
|
+
// progress display prints: a bare "40%" or "12/300" mid-line is a coverage
|
|
77
|
+
// figure or a date as often as it's progress, so those don't count.
|
|
78
|
+
const ANSI = /\x1b\[[0-?]*[ -/]*[@-~]/g;
|
|
79
|
+
const SHAPES = [
|
|
80
|
+
// tqdm and bars like it: " 40%|████ | 400/1000 [00:10<00:15, 40.00it/s]"
|
|
81
|
+
[/(\d{1,3}(?:\.\d+)?)%\|/, m => ({ pct: Number(m[1]) })],
|
|
82
|
+
// cmake and make: "[ 40%] Building CXX object ..."; pytest: "tests/test_a.py .... [ 40%]"
|
|
83
|
+
[/^\[\s*(\d{1,3})%\]|\[\s*(\d{1,3})%\]$/, m => ({ pct: Number(m[1] ?? m[2]) })],
|
|
84
|
+
// ninja and other counters: "[12/300] Compiling ...", "(3/10) Fetching ..."
|
|
85
|
+
[/^[[(]\s*(\d+)\s*\/\s*(\d+)\s*[\])]/, m => count(m[1], m[2])],
|
|
86
|
+
// A script's own: "1200/9000 flops solved", "Progress: 40%", "40% done"
|
|
87
|
+
[/^(\d+)\s*\/\s*(\d+)\s+[a-z]/i, m => count(m[1], m[2])],
|
|
88
|
+
[/\bprogress\b\W{0,3}(\d{1,3}(?:\.\d+)?)%|(\d{1,3}(?:\.\d+)?)%\s+(?:done|complete|completed|finished)\b/i, m => ({ pct: Number(m[1] ?? m[2]) })],
|
|
89
|
+
];
|
|
90
|
+
// The newest progress line in a stretch of output, or null. dibs's own lines (dibs: ...) are skipped.
|
|
91
|
+
export function shownIn(text) {
|
|
92
|
+
const lines = text.split(/\r\n|\r|\n/);
|
|
93
|
+
for (let i = lines.length - 1, n = 0; i >= 0 && n < 400; i--, n++) {
|
|
94
|
+
const line = lines[i].replace(ANSI, '').trim();
|
|
95
|
+
if (!line || line.startsWith('dibs: ')) continue;
|
|
96
|
+
for (const [re, make] of SHAPES) {
|
|
97
|
+
const m = re.exec(line);
|
|
98
|
+
const p = m && make(m);
|
|
99
|
+
if (p && p.pct >= 0 && p.pct <= 100) return p;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Put a reading on the lease. src: 'job' (dibs progress) or 'output' (its output).
|
|
106
|
+
// A lower number than the last means the job started a new stretch (a second
|
|
107
|
+
// phase counting from 0): its rate starts over from there. So does a change of
|
|
108
|
+
// source, whose numbers needn't be on the same scale.
|
|
109
|
+
export function note(l, p, t, src) {
|
|
110
|
+
const a = Math.max(0, active(l, t));
|
|
111
|
+
const was = l.progress;
|
|
112
|
+
let seen = Array.isArray(was?.seen) && was.src === src ? was.seen : [[0, 0]];
|
|
113
|
+
if (was?.src === src && p.pct < was.pct) seen = [];
|
|
114
|
+
const last = seen[seen.length - 1];
|
|
115
|
+
if (!last || p.pct !== last[1]) {
|
|
116
|
+
const before = seen[seen.length - 2];
|
|
117
|
+
if (before && seen.length > 2 && a - before[0] < SAMPLE_GAP) seen[seen.length - 1] = [a, p.pct];
|
|
118
|
+
else seen.push([a, p.pct]);
|
|
119
|
+
while (seen.length > KEEP) seen.splice(1, 1);
|
|
120
|
+
}
|
|
121
|
+
// A count's label carries over to the next count without one: 1300/9000 is still "flops solved".
|
|
122
|
+
const unit = p.unit || (p.total != null && was?.src === src && was.total != null ? was.unit : null);
|
|
123
|
+
l.progress = { pct: p.pct, ...(p.total != null && { done: p.done, total: p.total }), ...(unit && { unit }), src, at: t, seen };
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// A CPU reading for the lease, as src/measure.mjs adds up l.cpuMs: [active ms, cpu ms],
|
|
127
|
+
// thinned like progress readings, so the rate it gets now can be set against its earlier one.
|
|
128
|
+
export function noteCpu(l, t) {
|
|
129
|
+
const a = Math.max(0, active(l, t));
|
|
130
|
+
const seen = Array.isArray(l.cpuSeen) ? l.cpuSeen : (l.cpuSeen = []);
|
|
131
|
+
const before = seen[seen.length - 2];
|
|
132
|
+
if (before && a - before[0] < CPU_GAP) seen[seen.length - 1] = [a, l.cpuMs || 0];
|
|
133
|
+
else seen.push([a, l.cpuMs || 0]);
|
|
134
|
+
while (seen.length > KEEP) seen.splice(1, 1);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// The cores a lease has had over its last `back` of running, or null without readings reaching that far.
|
|
138
|
+
function cpuRate(l, back) {
|
|
139
|
+
const seen = Array.isArray(l.cpuSeen) ? l.cpuSeen : [];
|
|
140
|
+
const last = seen[seen.length - 1];
|
|
141
|
+
if (!last) return null;
|
|
142
|
+
let ref = null;
|
|
143
|
+
for (const x of seen) if (x[0] <= last[0] - back) ref = x;
|
|
144
|
+
return ref && last[0] > ref[0] ? (last[1] - ref[1]) / (last[0] - ref[0]) : null;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// What the command's own past runs got of the CPU: { rate (cores: the middle run's CPU
|
|
148
|
+
// time over its run time), cpuMs (the middle run's CPU time) }, once LONG_RUNS of them
|
|
149
|
+
// that finished were measured. Its own runs, never its resource's: a test suite and a
|
|
150
|
+
// one-file test share a resource and nothing else.
|
|
151
|
+
export function usualCpu(hist, key) {
|
|
152
|
+
const runs = runsOf(hist || [], key).filter(h => !h.failed && h.cpuMs > 0 && h.dur > 0).slice(-10);
|
|
153
|
+
return runs.length >= LONG_RUNS ? { rate: middle(runs.map(h => h.cpuMs / h.dur)), cpuMs: middle(runs.map(h => h.cpuMs)) } : null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Time left by work, not clock: the CPU its own runs usually take, less what it has had,
|
|
157
|
+
// at the rate it gets now. A job the machine starves of CPU reads longer, where its clock
|
|
158
|
+
// time alone would read "under a minute left". null without measured history or readings.
|
|
159
|
+
export function cpuLeft(l, hist, t = now()) {
|
|
160
|
+
if (l?.kind !== 'run' || l.cpuMs == null) return null;
|
|
161
|
+
const uc = usualCpu(hist, l.key);
|
|
162
|
+
if (!uc) return null;
|
|
163
|
+
const rate = cpuRate(l, RATE_WINDOW) ?? cpuRate(l, 2 * MIN);
|
|
164
|
+
return rate > CPU_NONE ? Math.max(uc.cpuMs - l.cpuMs, 0) / rate : null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// The newest reading at least `back` before `at`, else the first.
|
|
168
|
+
function before(seen, at, back) {
|
|
169
|
+
let ref = seen[0];
|
|
170
|
+
for (const x of seen) if (x[0] <= at - back) ref = x;
|
|
171
|
+
return ref;
|
|
172
|
+
}
|
|
173
|
+
const middle = xs => { if (!xs.length) return 0; const a = [...xs].sort((x, y) => x - y); return a[Math.floor(a.length / 2)]; };
|
|
174
|
+
|
|
175
|
+
// What a lease's progress says now, or null when its job never reported:
|
|
176
|
+
// { pct, done, total, unit, src, quiet (since it last moved), left (null when
|
|
177
|
+
// there's no rate yet), slow? }. left is the larger of two readings: the rate
|
|
178
|
+
// when it last moved, less the time since, and the rate counting the time
|
|
179
|
+
// since as spent, so a job that stopped moving reads longer and longer.
|
|
180
|
+
export function progressOf(l, t = now()) {
|
|
181
|
+
const p = l?.progress;
|
|
182
|
+
if (!p || typeof p.pct !== 'number' || !Array.isArray(p.seen) || !p.seen.length || l.kind === 'hold') return null;
|
|
183
|
+
const a = active(l, t), seen = p.seen, last = seen[seen.length - 1];
|
|
184
|
+
const out = { pct: p.pct, ...(p.total != null && { done: p.done, total: p.total }), ...(p.unit && { unit: p.unit }), src: p.src, quiet: Math.max(0, a - last[0]), left: null };
|
|
185
|
+
if (p.pct >= 100) return { ...out, left: 0 };
|
|
186
|
+
let ref = before(seen, last[0], RATE_WINDOW);
|
|
187
|
+
if (ref === last || last[1] <= ref[1]) ref = seen[0];
|
|
188
|
+
const moved = last[1] - ref[1];
|
|
189
|
+
if (moved <= 0 || last[0] <= ref[0]) return out;
|
|
190
|
+
const togo = 100 - p.pct;
|
|
191
|
+
out.left = Math.max(togo / (moved / (last[0] - ref[0])) - out.quiet, togo / (moved / Math.max(a - ref[0], 1)));
|
|
192
|
+
return out;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// The usual run time of a lease's command: the middle of its last ten runs that
|
|
196
|
+
// finished, once it has LONG_RUNS of them. Same key as the forecasts (resource and command words).
|
|
197
|
+
export function usualRun(hist, key) {
|
|
198
|
+
const d = runsOf(hist || [], key).filter(h => !h.failed).slice(-10).map(h => h.dur);
|
|
199
|
+
return d.length >= LONG_RUNS ? middle(d) : null;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Whether a running job is far off its own pace, or null. { ran, pct?, stalled
|
|
203
|
+
// (no progress for `quiet`), share (its rate now as a share of before), times
|
|
204
|
+
// and usual (it has run `times` its usual time), cpu and usualCpu (the cores it
|
|
205
|
+
// gets now, and its own runs usually got; starved when it gets some, else it
|
|
206
|
+
// looks stuck) }. Needs real history and a big gap: a job is only slow against
|
|
207
|
+
// its own earlier rate over SLOW_WINDOW and STEPS of its reports, or against
|
|
208
|
+
// at least LONG_RUNS finished runs of the same command.
|
|
209
|
+
export function slowness(l, hist, t = now()) {
|
|
210
|
+
if (l?.kind !== 'run' || !l.start) return null;
|
|
211
|
+
const a = active(l, t);
|
|
212
|
+
const out = { ran: a };
|
|
213
|
+
const p = l.progress;
|
|
214
|
+
if (p && Array.isArray(p.seen) && p.seen.length && p.pct < 100) {
|
|
215
|
+
const seen = p.seen, first = seen[0], last = seen[seen.length - 1];
|
|
216
|
+
const steps = seen.slice(1).map((x, i) => x[0] - seen[i][0]);
|
|
217
|
+
const window = Math.max(SLOW_WINDOW, STEPS * middle(steps));
|
|
218
|
+
const ref = before(seen, a, window);
|
|
219
|
+
const earlier = ref[0] - first[0] >= window && ref[1] > first[1] ? (ref[1] - first[1]) / (ref[0] - first[0]) : null;
|
|
220
|
+
const recent = a - ref[0] >= window ? (last[1] - ref[1]) / (a - ref[0]) : null;
|
|
221
|
+
if (earlier && recent != null && recent * SLOW_RATIO < earlier) {
|
|
222
|
+
out.pct = p.pct;
|
|
223
|
+
if (recent <= 0) { out.stalled = true; out.quiet = a - last[0]; } else out.share = recent / earlier;
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const usual = usualRun(hist, l.key);
|
|
227
|
+
if (usual && a >= LONG_TIMES * usual && a - usual >= LONG_OVER) Object.assign(out, { times: a / usual, usual });
|
|
228
|
+
// Starved or stuck: getting a fraction of the CPU its own runs usually get, over SLOW_WINDOW.
|
|
229
|
+
const uc = usualCpu(hist, l.key);
|
|
230
|
+
const got = uc && uc.rate >= CPU_FLOOR ? cpuRate(l, SLOW_WINDOW) : null;
|
|
231
|
+
if (got != null && got * SLOW_RATIO < uc.rate) Object.assign(out, { cpu: got, usualCpu: uc.rate, starved: got >= CPU_NONE });
|
|
232
|
+
return out.stalled || out.share || out.times || out.cpu != null ? out : null;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// The job's output file, when its output goes to one: a function that returns
|
|
236
|
+
// a new progress reading from what the job has written since the last look,
|
|
237
|
+
// or null. Returns null outright when the output goes to a terminal or a pipe,
|
|
238
|
+
// and on Windows. Call it before the job starts, so dibs's lines before that
|
|
239
|
+
// aren't read as the job's.
|
|
240
|
+
export function outputWatch() {
|
|
241
|
+
if (process.platform === 'win32') return null;
|
|
242
|
+
let fd = null, st;
|
|
243
|
+
for (const n of [1, 2]) {
|
|
244
|
+
try { st = fs.fstatSync(n); } catch { continue; }
|
|
245
|
+
if (st.isFile()) { fd = n; break; }
|
|
246
|
+
}
|
|
247
|
+
if (fd == null) return null;
|
|
248
|
+
let from = st.size, file, last = null, off = false;
|
|
249
|
+
return () => {
|
|
250
|
+
if (off) return null;
|
|
251
|
+
if (file === undefined) file = pathOf(fd, st);
|
|
252
|
+
if (!file) { off = true; return null; }
|
|
253
|
+
let size;
|
|
254
|
+
try { size = fs.fstatSync(fd).size; } catch { off = true; return null; }
|
|
255
|
+
if (size < from) from = 0; // emptied and written again
|
|
256
|
+
if (size === from) return null;
|
|
257
|
+
const start = Math.max(from, size - TAIL);
|
|
258
|
+
let text;
|
|
259
|
+
try {
|
|
260
|
+
const h = fs.openSync(file, 'r');
|
|
261
|
+
try { const buf = Buffer.alloc(size - start); fs.readSync(h, buf, 0, buf.length, start); text = buf.toString('utf8'); } finally { fs.closeSync(h); }
|
|
262
|
+
} catch { off = true; return null; }
|
|
263
|
+
from = size;
|
|
264
|
+
const p = shownIn(text);
|
|
265
|
+
if (!p || (last && p.pct === last.pct)) return null;
|
|
266
|
+
return (last = p);
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Where an open file descriptor points, checked against what it is: Linux says
|
|
271
|
+
// in /proc, macOS through lsof (about 20 ms, once per job). null if neither can.
|
|
272
|
+
function pathOf(fd, st) {
|
|
273
|
+
let p = null;
|
|
274
|
+
try {
|
|
275
|
+
if (process.platform === 'linux') p = fs.readlinkSync(`/proc/self/fd/${fd}`);
|
|
276
|
+
else {
|
|
277
|
+
const r = spawnSync('lsof', ['-a', '-p', String(process.pid), '-d', String(fd), '-Fn', '-w'], { encoding: 'utf8', timeout: 2000 });
|
|
278
|
+
p = (r.stdout || '').split('\n').find(x => x.startsWith('n'))?.slice(1) || null;
|
|
279
|
+
}
|
|
280
|
+
const s = p && fs.statSync(p);
|
|
281
|
+
return s && s.ino === st.ino && s.dev === st.dev ? p : null;
|
|
282
|
+
} catch { return null; }
|
|
283
|
+
}
|
package/src/later.mjs
CHANGED
|
@@ -23,9 +23,11 @@ import { readEvents } from './events.mjs';
|
|
|
23
23
|
import { short, takeAgent, talkKey } from './files.mjs';
|
|
24
24
|
import { noteAs } from './talk.mjs';
|
|
25
25
|
import { named, about, minutes } from './plain.mjs';
|
|
26
|
+
import { requireDeclaration, described, declared } from './declare.mjs';
|
|
26
27
|
import { bold, dim, columns } from './style.mjs';
|
|
27
28
|
import { underLock, commit } from './lock.mjs';
|
|
28
29
|
import { clock, deadline, die, dur, log, ms, now, say, sleep, fakeFull, LEAN } from './util.mjs';
|
|
30
|
+
import { readJSON } from './durable.mjs';
|
|
29
31
|
|
|
30
32
|
const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'dibs.mjs');
|
|
31
33
|
export const DIR = path.join(HOME, 'later');
|
|
@@ -83,7 +85,7 @@ function locked(fn) {
|
|
|
83
85
|
|
|
84
86
|
function load() {
|
|
85
87
|
let s = {};
|
|
86
|
-
try { s =
|
|
88
|
+
try { s = readJSON(FILE); } catch (e) {
|
|
87
89
|
if (e.code !== 'ENOENT') say(`${FILE} was unreadable (${e.message}); starting with no scheduled jobs.`);
|
|
88
90
|
}
|
|
89
91
|
s.seq ||= 0; s.jobs ||= [];
|
|
@@ -157,7 +159,7 @@ function told(j) {
|
|
|
157
159
|
: j.state === 'failed' ? `didn't start: ${j.why}` : `was lost: ${j.why}`;
|
|
158
160
|
try {
|
|
159
161
|
noteAs({ who: j.who, session: j.session, agentId: j.agentId, label: j.label, spid: j.spid, sstart: j.sstart },
|
|
160
|
-
`${j.id} (${j
|
|
162
|
+
`${j.id} (${described(j)}) ${how}. Log: ${shownPath(logOf(j.id))}`);
|
|
161
163
|
} catch (e) { log(`dibs later: couldn't tell ${j.agent || j.who} how ${j.id} ended: ${e.message}`); }
|
|
162
164
|
}
|
|
163
165
|
|
|
@@ -216,6 +218,11 @@ function start(j) {
|
|
|
216
218
|
for (const [k, v] of Object.entries(process.env)) if (k.startsWith('DIBS_') && !DIBS_WHO.has(k)) env[k] = v;
|
|
217
219
|
for (const [k, v] of Object.entries(j.env || {})) if (!notEnv(k)) env[k] = v;
|
|
218
220
|
Object.assign(env, { DIBS_AGENT: j.agent || j.who, DIBS_NO_SESSION: '1', DIBS_LATER_JOB: j.id });
|
|
221
|
+
// A run an agent scheduled is that agent's (src/owner.mjs actor): without a marker, the runner's
|
|
222
|
+
// own environment would make it the person's, and an agent could schedule what only the person
|
|
223
|
+
// may do (answering a spend or one-way question, using a secret without their yes). Jobs from
|
|
224
|
+
// before byAgent was kept go by the session they came from.
|
|
225
|
+
if (j.byAgent || j.spid) env.AI_AGENT = '1';
|
|
219
226
|
let child;
|
|
220
227
|
try {
|
|
221
228
|
// Detached, with output straight into the log: the run outlives this
|
|
@@ -233,7 +240,8 @@ function start(j) {
|
|
|
233
240
|
// The dibs run a job becomes: the scheduler's flags, waiting as long as it takes.
|
|
234
241
|
export function runArgs(j) {
|
|
235
242
|
const args = ['run', j.res.join(','), '--wait', '--as', j.label ? `${j.label}, later ${j.id}` : `later ${j.id}`, '--notify', exitOf(j.id)];
|
|
236
|
-
|
|
243
|
+
// Scheduled by a dibs from before declarations, it gets words made from what's known.
|
|
244
|
+
args.push('-m', described(j));
|
|
237
245
|
if (j.prio) args.push('-p', j.prio);
|
|
238
246
|
if (j.est) args.push('--est', `${Math.round(j.est / 1000)}s`);
|
|
239
247
|
if (j.mem) args.push('--mem', String(j.mem));
|
|
@@ -296,7 +304,7 @@ function phase(j, leases) {
|
|
|
296
304
|
|
|
297
305
|
function view(j, leases, t) {
|
|
298
306
|
const p = phase(j, leases);
|
|
299
|
-
return { id: j.id, state: p, res: j.res, who: j.who, agent: j.agent, label: j.label, purpose: j
|
|
307
|
+
return { id: j.id, state: p, res: j.res, who: j.who, agent: j.agent, label: j.label, purpose: described(j), declared: declared(j), cmd: j.cmd.join(' '), cwd: j.cwd,
|
|
300
308
|
when: trigger(j), at: j.at ?? null, after: j.after ?? null, ok: !!j.ok, created: j.created, fired: j.fired ?? null, late: j.late ?? null,
|
|
301
309
|
ended: j.ended ?? null, code: j.code ?? null, why: j.why ?? null, log: logOf(j.id), in: j.at != null && p === 'scheduled' ? j.at - t : null };
|
|
302
310
|
}
|
|
@@ -313,13 +321,13 @@ const where = v => (v.state === 'scheduled' ? `${v.when}${v.in != null ? ` (in $
|
|
|
313
321
|
: v.state === 'running' ? `${v.when}, running`
|
|
314
322
|
: `${v.when}, ${v.state === 'done' ? `exit ${v.code}` : v.state}${v.why ? ` (${v.why})` : ''} at ${clock(v.ended)}`)
|
|
315
323
|
+ (v.late ? `, ran late by ${dur(v.late)}` : '');
|
|
316
|
-
const line = v => ` ${v.id.padEnd(4)} ${v.res.map(r => short(r)).join(',').padEnd(11)} ${tag(v).padEnd(20)}
|
|
324
|
+
const line = v => ` ${v.id.padEnd(4)} ${v.res.map(r => short(r)).join(',').padEnd(11)} ${tag(v).padEnd(20)} "${v.purpose}" ${where(v)} ${v.cmd.slice(0, 40)}`;
|
|
317
325
|
|
|
318
326
|
// The same in the plain board's words: "l3: web-app's "ios snapshot suite"
|
|
319
327
|
// for the simulator", then when: "at 02:00 (in about 5 hr)".
|
|
320
328
|
const ENDED = { done: 'finished', failed: "didn't start", lost: 'was lost', skipped: 'was skipped', cancelled: 'was cancelled' };
|
|
321
329
|
export function laterPlain(v, cfg) {
|
|
322
|
-
const what = `${v.id}: ${tag(v)}'s
|
|
330
|
+
const what = `${v.id}: ${tag(v)}'s "${v.purpose}" for ${v.res.map(r => named(cfg, r).the).join(' and ')}`;
|
|
323
331
|
const when = v.state === 'scheduled' ? `${v.when}${v.in != null ? ` (in ${about(v.in)})` : ''}`
|
|
324
332
|
: v.state === 'waiting' ? `${v.when}, waiting in ${named(cfg, v.res[0]).queue} since ${clock(v.fired)}`
|
|
325
333
|
: v.state === 'running' ? `${v.when}, running now`
|
|
@@ -362,8 +370,9 @@ function schedule(argv, parse) {
|
|
|
362
370
|
else pass.push(a);
|
|
363
371
|
}
|
|
364
372
|
const o = parse(dd < 0 ? pass : [...pass, ...argv.slice(dd)]);
|
|
365
|
-
if (!o.cmd?.length) die('nothing to run. Use: dibs later <resource> --at 02:00 -- <command>');
|
|
366
|
-
if (!o.res.length) die('name a resource, e.g. dibs later test --in 3h -- npm test');
|
|
373
|
+
if (!o.cmd?.length) die('nothing to run. Use: dibs later <resource> --at 02:00 -m "..." -- <command>');
|
|
374
|
+
if (!o.res.length) die('name a resource, e.g. dibs later test --in 3h -m "run the nightly suite" -- npm test');
|
|
375
|
+
requireDeclaration(o, 'later', ['later', ...argv]);
|
|
367
376
|
if ([own.at, own.in, own.after].filter(x => x != null).length !== 1) die('say when, once: --at 02:00, --in 3h, --after <#id|agent|later id> or --after-ok <...>');
|
|
368
377
|
for (const [f, bad] of [['--by', o.by], ['--max-wait', o.maxWait], ['--notify', o.notify], ['--for', o.for]])
|
|
369
378
|
if (bad != null) die(`${f} doesn't go with dibs later. A scheduled run waits as long as it takes; dibs later list shows how it ended`);
|
|
@@ -391,10 +400,12 @@ function schedule(argv, parse) {
|
|
|
391
400
|
}
|
|
392
401
|
if (!o.anywhere && !o.on && !which(o.cmd[0], job.env)) die(`couldn't find ${o.cmd[0]} on the PATH it would run with. Nothing was scheduled`, 127);
|
|
393
402
|
const id = identity(o);
|
|
403
|
+
// An agent's run stays the agent's when it starts (byAgent, below).
|
|
404
|
+
const byAgent = AGENT_ENV.some(k => process.env[k]) || !!id.spid;
|
|
394
405
|
// Which agent of which session asked, so how it ends lands in that agent's thread (told).
|
|
395
406
|
const session = process.env.CLAUDE_CODE_SESSION_ID || sessionFiles().find(f => f.pid === id.spid)?.sessionId;
|
|
396
407
|
const by = session ? takeAgent('later', [], talkKey('later', dd < 0 ? argv : argv.slice(0, dd))) : null;
|
|
397
|
-
Object.assign(job, { session, agentId: by?.agentId, who: id.who, agent: id.agent, label: id.label || by?.agentType, spid: id.spid, sstart: id.sstart, purpose: o.purpose || '', prio: o.prio, est: o.est, mem: o.mem,
|
|
408
|
+
Object.assign(job, { session, agentId: by?.agentId, who: id.who, agent: id.agent, label: id.label || by?.agentType, spid: id.spid, sstart: id.sstart, byAgent: byAgent || undefined, purpose: o.purpose || '', prio: o.prio, est: o.est, mem: o.mem,
|
|
398
409
|
cpu: o.cpu, disk: o.disk, ports: o.ports, anywhere: o.anywhere, on: o.on, bring: o.bring });
|
|
399
410
|
for (const k of Object.keys(job)) if (job[k] === undefined || (Array.isArray(job[k]) && !job[k].length && k !== 'cmd' && k !== 'res')) delete job[k];
|
|
400
411
|
const saved = locked(s => {
|
|
@@ -450,7 +461,7 @@ function list(o, cfg) {
|
|
|
450
461
|
const t = now();
|
|
451
462
|
const all = snapshot(t);
|
|
452
463
|
if (o.json) return console.log(JSON.stringify(laterJson(t, all), null, 1));
|
|
453
|
-
if (!all.length) return console.log('Nothing scheduled. To schedule a run: dibs later <resource> --at 02:00 -- <command>');
|
|
464
|
+
if (!all.length) return console.log('Nothing scheduled. To schedule a run: dibs later <resource> --at 02:00 -m "..." -- <command>');
|
|
454
465
|
const rank = { running: 0, waiting: 1, scheduled: 2 };
|
|
455
466
|
const order = [...all].sort((a, b) => (rank[a.state] ?? 3) - (rank[b.state] ?? 3) || (a.state === 'scheduled' ? (a.at ?? Infinity) - (b.at ?? Infinity) : (b.ended ?? 0) - (a.ended ?? 0)));
|
|
456
467
|
const count = st => all.filter(v => st.includes(v.state)).length;
|
package/src/lock.mjs
CHANGED
|
@@ -35,7 +35,9 @@
|
|
|
35
35
|
import fs from 'node:fs';
|
|
36
36
|
import path from 'node:path';
|
|
37
37
|
import { spawnSync } from 'node:child_process';
|
|
38
|
+
import { isMainThread, threadId, workerData } from 'node:worker_threads';
|
|
38
39
|
import { sleepSync } from './util.mjs';
|
|
40
|
+
import { writeSynced, keepLast, heal } from './durable.mjs';
|
|
39
41
|
|
|
40
42
|
const WIN = process.platform === 'win32';
|
|
41
43
|
// This process's start, to tell it from a later process given the same pid.
|
|
@@ -57,8 +59,18 @@ const CLAIM_TRIES = 200;
|
|
|
57
59
|
// debugger): waiters keep waiting, but say so once each (onStuck), so the person hears of it.
|
|
58
60
|
export const STUCK_AFTER = 60e3;
|
|
59
61
|
|
|
62
|
+
// The resident guard (src/guardd.mjs) answers hook calls in worker threads of one process, so a pid
|
|
63
|
+
// alone doesn't name a holder there: two calls at once each took the other's lock for its own dead
|
|
64
|
+
// one, and both wrote messages.json.<pid>.tmp (ENOENT on the rename, 2026-11-24). A worker's owner
|
|
65
|
+
// names its thread, and the guard keeps a shared list of the threads still running (THREADS).
|
|
66
|
+
const THREADS = workerData?.threads;
|
|
67
|
+
const TAG = isMainThread ? '' : `t${threadId}-`;
|
|
60
68
|
let made = 0;
|
|
61
|
-
const nonce = () => `${process.pid}.${START}.${(++made).toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
|
69
|
+
const nonce = () => `${process.pid}.${START}.${TAG}${(++made).toString(36)}${Math.random().toString(36).slice(2, 6)}`;
|
|
70
|
+
const threadOf = name => Number(name?.split('.')[3]?.match(/^t(\d+)-/)?.[1]) || 0;
|
|
71
|
+
// Whether the thread of this process that holds a lock is still running. Without the guard's list
|
|
72
|
+
// (a thread nothing keeps a list for), it's taken for gone, as any lock of this pid once was.
|
|
73
|
+
const threadRuns = id => !!THREADS && (id === 0 || THREADS.includes(id));
|
|
62
74
|
|
|
63
75
|
export class LostLock extends Error {
|
|
64
76
|
constructor(lock) { super(`${lock} was taken over while this process held it`); this.code = 'ELOSTLOCK'; }
|
|
@@ -83,12 +95,12 @@ export function acquire(lock, { wait = Infinity, fake, files = [], onStuck } = {
|
|
|
83
95
|
// an empty folder (made, its pid not written yet) would replace it under its writer.
|
|
84
96
|
const o = holder(lock);
|
|
85
97
|
if (!o) {
|
|
86
|
-
if (make(lock, owner, fake)) return
|
|
98
|
+
if (make(lock, owner, fake)) return healed(lock, owner, files);
|
|
87
99
|
continue;
|
|
88
100
|
}
|
|
89
101
|
if (seen?.key !== o.key) seen = { key: o.key, since: Date.now(), asked: 0, gap: ASK_AFTER };
|
|
90
102
|
if (stale(o, seen)) {
|
|
91
|
-
if (claim(lock, o, owner)) { sweep(lock, files); return
|
|
103
|
+
if (claim(lock, o, owner)) { sweep(lock, files); return healed(lock, owner, files); }
|
|
92
104
|
if (++failed >= CLAIM_TRIES) throw new LockBroken(lock);
|
|
93
105
|
} else failed = 0;
|
|
94
106
|
if (Date.now() - t0 >= wait) return null;
|
|
@@ -100,6 +112,17 @@ export function acquire(lock, { wait = Infinity, fake, files = [], onStuck } = {
|
|
|
100
112
|
}
|
|
101
113
|
}
|
|
102
114
|
|
|
115
|
+
// The lock's handle, once every data file under it parses: a broken one is put back from its
|
|
116
|
+
// last good copy before the holder reads it (src/durable.mjs heal), so a reader that takes a
|
|
117
|
+
// broken file for an empty one never writes the empty one over everything. A full disk while
|
|
118
|
+
// putting it back gives the lock up and throws, as any write would.
|
|
119
|
+
function healed(lock, owner, files) {
|
|
120
|
+
const h = handle(lock, owner);
|
|
121
|
+
try { for (const f of files) heal(f); }
|
|
122
|
+
catch (e) { h.release(); throw e; }
|
|
123
|
+
return h;
|
|
124
|
+
}
|
|
125
|
+
|
|
103
126
|
// How long the owner has held it: its owner file dates from when it took the lock (a claim
|
|
104
127
|
// touches the file it renamed in); an older dibs's lock dates from its directory.
|
|
105
128
|
function heldFor(lock, o) {
|
|
@@ -155,7 +178,7 @@ const answers = pid => { try { process.kill(pid, 0); return true; } catch (e) {
|
|
|
155
178
|
|
|
156
179
|
function stale(o, seen) {
|
|
157
180
|
if (!o.pid) return o.age > PIDLESS_STALE;
|
|
158
|
-
if (o.pid === process.pid) return
|
|
181
|
+
if (o.pid === process.pid) return threadOf(o.name) === threadId || !threadRuns(threadOf(o.name));
|
|
159
182
|
if (!answers(o.pid)) return true;
|
|
160
183
|
const t = Date.now();
|
|
161
184
|
if (WIN || t - seen.since < ASK_AFTER || t - seen.asked < seen.gap) return false;
|
|
@@ -168,9 +191,12 @@ function stale(o, seen) {
|
|
|
168
191
|
}
|
|
169
192
|
|
|
170
193
|
// The command line a pid runs, for saying who dibs is stuck behind, or '' when ps can't say.
|
|
194
|
+
// Windows has no ps: the process's command line comes from WMI, as src/platform.mjs reads it.
|
|
171
195
|
export function commandOf(pid) {
|
|
172
|
-
|
|
173
|
-
|
|
196
|
+
const r = WIN
|
|
197
|
+
? spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(pid)}").CommandLine`],
|
|
198
|
+
{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 30e3 })
|
|
199
|
+
: spawnSync('ps', ['-o', 'command=', '-p', String(pid)], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000 });
|
|
174
200
|
return (r.stdout || '').trim().slice(0, 200);
|
|
175
201
|
}
|
|
176
202
|
|
|
@@ -223,7 +249,7 @@ export const sweepLock = (lock, files = []) => sweep(lock, files);
|
|
|
223
249
|
function sweep(lock, files) {
|
|
224
250
|
const dir = path.dirname(lock), base = path.basename(lock);
|
|
225
251
|
const dibsMade = [new RegExp(`^${re(base)}\\.(?:new|gone)\\.(\\d+)\\.`), new RegExp(`^${re(base)}\\.stale-(\\d+)-`),
|
|
226
|
-
...files.filter(f => path.dirname(f) === dir).map(f => new RegExp(`^${re(path.basename(f))}
|
|
252
|
+
...files.filter(f => path.dirname(f) === dir).map(f => new RegExp(`^${re(path.basename(f))}(?:\\.bak)?\\.(\\d+)(?:\\.t\\d+)?\\.tmp$`))];
|
|
227
253
|
let names = [];
|
|
228
254
|
try { names = fs.readdirSync(dir); } catch { return; }
|
|
229
255
|
for (const n of names) {
|
|
@@ -252,7 +278,8 @@ function handle(lock, owner) {
|
|
|
252
278
|
}
|
|
253
279
|
|
|
254
280
|
// The holder's write of a whole file: a temporary copy named for this process (no two writers share
|
|
255
|
-
// one, and a write cut short by a full disk leaves the old file whole),
|
|
281
|
+
// one, and a write cut short by a full disk leaves the old file whole), flushed to disk, the version
|
|
282
|
+
// it replaces kept as <file>.bak (src/durable.mjs), then a rename, only while it
|
|
256
283
|
// still holds the lock (LostLock if not, with nothing written). fake as in acquire.
|
|
257
284
|
// Returns whether it still held the lock just after the rename: false means another writer took it in
|
|
258
285
|
// the moment between the check and the rename (only possible from a holder stopped right there), and
|
|
@@ -268,17 +295,30 @@ export function commitAll(h, files) {
|
|
|
268
295
|
const tmps = [];
|
|
269
296
|
try {
|
|
270
297
|
for (const [file, text, { mode, fake } = {}] of files) {
|
|
271
|
-
const tmp = `${file}.${process.pid}.tmp`;
|
|
298
|
+
const tmp = `${file}.${process.pid}${isMainThread ? '' : `.t${threadId}`}.tmp`;
|
|
272
299
|
tmps.push(tmp);
|
|
273
300
|
fake?.();
|
|
274
|
-
|
|
301
|
+
writeSynced(tmp, text, mode); // on disk before the rename, so a power cut never leaves an empty file
|
|
275
302
|
}
|
|
276
303
|
if (!h.owns()) throw new LostLock(path.dirname(files[0][0]));
|
|
277
304
|
} catch (e) { for (const tmp of tmps) try { fs.rmSync(tmp, { force: true }); } catch {} throw e; }
|
|
278
|
-
files.forEach(([file], i) =>
|
|
305
|
+
files.forEach(([file], i) => { keepLast(file); replace(tmps[i], file); });
|
|
279
306
|
return h.owns();
|
|
280
307
|
}
|
|
281
308
|
|
|
309
|
+
// Windows refuses to rename over a file another process has open (EPERM, EACCES or EBUSY), and
|
|
310
|
+
// readers open the state without the lock, for a few milliseconds each: on 4-core CI runners a
|
|
311
|
+
// writer in the five-writer lock test crashed on it in 3 of 6 runs (2026-11-13). Those clear in a moment, so the
|
|
312
|
+
// rename is tried again for up to REPLACE_FOR; anything else, or past that, throws as before.
|
|
313
|
+
const REPLACE_FOR = 2000, BUSY = new Set(['EPERM', 'EACCES', 'EBUSY']);
|
|
314
|
+
function replace(tmp, file) {
|
|
315
|
+
for (let t0 = Date.now(), gap = 5; ; gap = Math.min(gap * 2, 100)) {
|
|
316
|
+
try { return fs.renameSync(tmp, file); }
|
|
317
|
+
catch (e) { if (!WIN || !BUSY.has(e.code) || Date.now() - t0 > REPLACE_FOR) throw e; }
|
|
318
|
+
sleepSync(gap);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
282
322
|
// fn under the lock, done again from the start if the lock was lost before it wrote.
|
|
283
323
|
// null when wait passes first.
|
|
284
324
|
export function underLock(lock, fn, opts = {}) {
|