@dibssoftware/dibs 0.0.0-stage → 0.0.179
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +594 -0
- package/LICENSE +670 -0
- package/README.md +85 -2
- package/bin/dibs-guard.mjs +7 -0
- package/bin/dibs.mjs +548 -0
- package/docs/benchmarks.md +193 -0
- package/docs/files.md +30 -0
- package/docs/guard.md +91 -0
- package/docs/later.md +43 -0
- package/docs/machines.md +147 -0
- package/docs/questions.md +78 -0
- package/docs/reference.md +157 -0
- package/docs/relay.md +196 -0
- package/docs/releasing.md +27 -0
- package/docs/scheduling.md +163 -0
- package/docs/simulators.md +17 -0
- package/package.json +45 -4
- package/skills/dibs/SKILL.md +183 -0
- package/src/acquire.mjs +700 -0
- package/src/admin.mjs +145 -0
- package/src/agents.mjs +145 -0
- package/src/alerts.mjs +499 -0
- package/src/answers.mjs +65 -0
- package/src/board.mjs +202 -0
- package/src/broker.mjs +369 -0
- package/src/commands.mjs +810 -0
- package/src/config.mjs +324 -0
- package/src/connect.mjs +106 -0
- package/src/cool.mjs +160 -0
- package/src/diskwarn.mjs +154 -0
- package/src/events.mjs +96 -0
- package/src/files.mjs +1123 -0
- package/src/guard.mjs +613 -0
- package/src/history.mjs +247 -0
- package/src/hogs.mjs +227 -0
- package/src/later.mjs +487 -0
- package/src/measure.mjs +262 -0
- package/src/news.mjs +101 -0
- package/src/nodecheck.mjs +17 -0
- package/src/notes.mjs +171 -0
- package/src/notices.mjs +160 -0
- package/src/ondemand.mjs +572 -0
- package/src/overlap.mjs +151 -0
- package/src/override.mjs +360 -0
- package/src/owner.mjs +30 -0
- package/src/plain.mjs +470 -0
- package/src/platform.mjs +357 -0
- package/src/preempt.mjs +438 -0
- package/src/primer.mjs +89 -0
- package/src/proc.mjs +99 -0
- package/src/progress.mjs +187 -0
- package/src/qr.mjs +204 -0
- package/src/questions.mjs +389 -0
- package/src/quota.mjs +81 -0
- package/src/reads.mjs +54 -0
- package/src/relay.mjs +779 -0
- package/src/remote.mjs +584 -0
- package/src/reset.mjs +127 -0
- package/src/schedule.mjs +1020 -0
- package/src/scratch.mjs +61 -0
- package/src/serve.mjs +742 -0
- package/src/service.mjs +221 -0
- package/src/shard.mjs +59 -0
- package/src/simctl.mjs +42 -0
- package/src/simpool.mjs +258 -0
- package/src/state.mjs +201 -0
- package/src/stats.mjs +328 -0
- package/src/style.mjs +44 -0
- package/src/talk.mjs +702 -0
- package/src/thin.sh +130 -0
- package/src/trust.mjs +152 -0
- package/src/util.mjs +184 -0
- package/src/version.mjs +2 -0
- package/src/web.mjs +1119 -0
- package/src/worker.mjs +318 -0
package/src/later.mjs
ADDED
|
@@ -0,0 +1,487 @@
|
|
|
1
|
+
// dibs later: a run scheduled for a time, or for when something else ends.
|
|
2
|
+
// `dibs later` records the command and returns at once. When it's due, a
|
|
3
|
+
// runner starts it as an ordinary `dibs run --wait`, so it waits its turn,
|
|
4
|
+
// gets its lease and is reaped like any other run.
|
|
5
|
+
//
|
|
6
|
+
// The runner is the dibs worker service: it already runs under launchd (or
|
|
7
|
+
// systemd) at Interactive priority, restarts after a crash or reboot, and runs
|
|
8
|
+
// its loop even before the machine joins a coordinator. When no runner is up,
|
|
9
|
+
// scheduling starts one that leaves once nothing is left to run.
|
|
10
|
+
//
|
|
11
|
+
// Jobs keep their own file and lock, not state.json's: the runner looks every
|
|
12
|
+
// second, and nothing here decides who runs next.
|
|
13
|
+
import fs from 'node:fs';
|
|
14
|
+
import os from 'node:os';
|
|
15
|
+
import path from 'node:path';
|
|
16
|
+
import { spawn } from 'node:child_process';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
import { HOME, paths } from './config.mjs';
|
|
19
|
+
import { identity, isMine, makeAlive, pstart, tag, sessionFiles } from './proc.mjs';
|
|
20
|
+
import { AGENT_ENV } from './owner.mjs';
|
|
21
|
+
import { which, OS } from './platform.mjs';
|
|
22
|
+
import { readEvents } from './events.mjs';
|
|
23
|
+
import { short, takeAgent, talkKey } from './files.mjs';
|
|
24
|
+
import { noteAs } from './talk.mjs';
|
|
25
|
+
import { named, about, minutes } from './plain.mjs';
|
|
26
|
+
import { bold, dim, columns } from './style.mjs';
|
|
27
|
+
import { clock, deadline, die, dur, log, ms, now, say, sleep, sleepSync, fakeFull, LEAN } from './util.mjs';
|
|
28
|
+
|
|
29
|
+
const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'dibs.mjs');
|
|
30
|
+
export const DIR = path.join(HOME, 'later');
|
|
31
|
+
const FILE = path.join(DIR, 'jobs.json');
|
|
32
|
+
const LOCK = path.join(DIR, 'jobs.lock');
|
|
33
|
+
const RUNNERS = path.join(DIR, 'runners');
|
|
34
|
+
const logOf = id => path.join(DIR, `${id}.log`);
|
|
35
|
+
const exitOf = id => path.join(DIR, `${id}.exit`);
|
|
36
|
+
|
|
37
|
+
// Further out than a week, the machine, the project and the reason have likely
|
|
38
|
+
// all moved on; a plan that old should be made again, not kept.
|
|
39
|
+
const MAX_AHEAD = 7 * 864e5;
|
|
40
|
+
// How often a runner looks. Due times are to the second, and a look is one small file read.
|
|
41
|
+
const TICK = 1000;
|
|
42
|
+
// Started this long after its time, a job says it ran late (the machine was asleep, or no runner was up).
|
|
43
|
+
const LATE = 60e3;
|
|
44
|
+
// Writes take milliseconds, so a lock this old belongs to a dibs that died holding it.
|
|
45
|
+
const LOCK_STALE = 5000;
|
|
46
|
+
const LOCK_WAIT = 15e3;
|
|
47
|
+
// Finished jobs and their logs stay a week for dibs later list, up to KEEP_DONE of them.
|
|
48
|
+
const KEEP_FOR = 7 * 864e5;
|
|
49
|
+
const KEEP_DONE = 200;
|
|
50
|
+
// What a scheduled command gets from the scheduler's environment. TMPDIR, USER
|
|
51
|
+
// and SHELL too, since Xcode and many scripts break without them. Anything
|
|
52
|
+
// else (a token, say) only with --env, by name.
|
|
53
|
+
const ENV_KEEP = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'USER', 'SHELL', 'TMPDIR'];
|
|
54
|
+
// dibs's own settings reach the run from the runner (DIBS_HOME above all);
|
|
55
|
+
// these say who is calling, and the run sets its own.
|
|
56
|
+
const DIBS_WHO = new Set(['DIBS_AGENT', 'DIBS_AS', 'DIBS_REMOTE_JOB', 'DIBS_LEASE', 'DIBS_OWNER', 'DIBS_LATER_JOB']);
|
|
57
|
+
// Never from --env: dibs's own settings come from the runner, and who is
|
|
58
|
+
// calling is decided when the job is scheduled, not by the job.
|
|
59
|
+
const notEnv = k => k.startsWith('DIBS_') || k.startsWith('CLAUDE_CODE_') || AGENT_ENV.includes(k);
|
|
60
|
+
|
|
61
|
+
const ACTIVE = new Set(['scheduled', 'started']);
|
|
62
|
+
|
|
63
|
+
function locked(fn) {
|
|
64
|
+
fs.mkdirSync(DIR, { recursive: true });
|
|
65
|
+
const t0 = now();
|
|
66
|
+
for (;;) {
|
|
67
|
+
try { fs.mkdirSync(LOCK); break; } catch (e) {
|
|
68
|
+
if (e.code !== 'EEXIST') throw e;
|
|
69
|
+
try { if (now() - fs.statSync(LOCK).mtimeMs > LOCK_STALE) fs.rmSync(LOCK, { recursive: true, force: true }); } catch {}
|
|
70
|
+
if (now() - t0 > LOCK_WAIT) throw Object.assign(new Error(`${LOCK} stayed locked for ${LOCK_WAIT / 1000}s; remove it if no dibs is running. Nothing was changed.`), { exit: 75 });
|
|
71
|
+
sleepSync(5 + Math.random() * 10);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
const s = load();
|
|
76
|
+
const before = JSON.stringify(s);
|
|
77
|
+
reap(s);
|
|
78
|
+
const out = fn(s);
|
|
79
|
+
if (JSON.stringify(s) !== before) {
|
|
80
|
+
// --env values may be tokens: only this user reads the file.
|
|
81
|
+
fakeFull('state');
|
|
82
|
+
fs.writeFileSync(`${FILE}.tmp`, JSON.stringify(s, null, 1), { mode: 0o600 });
|
|
83
|
+
fs.renameSync(`${FILE}.tmp`, FILE);
|
|
84
|
+
}
|
|
85
|
+
return out;
|
|
86
|
+
} finally {
|
|
87
|
+
fs.rmSync(LOCK, { recursive: true, force: true });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function load() {
|
|
92
|
+
let s = {};
|
|
93
|
+
try { s = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) {
|
|
94
|
+
if (e.code !== 'ENOENT') say(`${FILE} was unreadable (${e.message}); starting with no scheduled jobs.`);
|
|
95
|
+
}
|
|
96
|
+
s.seq ||= 0; s.jobs ||= [];
|
|
97
|
+
return s;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// The board and the runner read leases without state.json's lock: writes are
|
|
101
|
+
// renames, so a read sees a whole file. A holder that died counts as gone
|
|
102
|
+
// whether or not anyone has reaped it yet.
|
|
103
|
+
function liveIds(t) {
|
|
104
|
+
let st = {};
|
|
105
|
+
try { st = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
|
|
106
|
+
const leases = st.leases || [], queue = st.queue || [];
|
|
107
|
+
const alive = makeAlive([...leases, ...queue].map(x => x.pid).filter(Boolean));
|
|
108
|
+
const ids = new Map();
|
|
109
|
+
for (const l of leases)
|
|
110
|
+
if (l.kind === 'hold' ? t < l.expires && (!l.pid || alive(l.pid, l.pstart)) : alive(l.pid, l.pstart)) ids.set(l.id, { lease: l });
|
|
111
|
+
for (const q of queue) if (q.pid ? alive(q.pid, q.pstart) : q.keepUntil > t) ids.set(q.id, { waiting: q });
|
|
112
|
+
return { ids, leases };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Whether every lease in ids ended well: a run with exit 0, or a hold.
|
|
116
|
+
// A waiter that left without ever getting its lease didn't.
|
|
117
|
+
function endedOk(ids) {
|
|
118
|
+
const ends = new Map(readEvents().filter(e => e.kind === 'end' && ids.includes(e.id)).map(e => [e.id, e]));
|
|
119
|
+
const bad = ids.find(id => { const e = ends.get(id); return !e || !(e.code === 0 || (e.code == null && e.type === 'hold')); });
|
|
120
|
+
if (bad == null) return null;
|
|
121
|
+
const e = ends.get(bad);
|
|
122
|
+
return !e ? `#${bad} never ran` : e.code == null ? `#${bad} ended without an exit code` : `#${bad} exited ${e.code}`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// Settle what has changed since the last look: runs that ended, triggers
|
|
126
|
+
// that can no longer fire, finished jobs old enough to forget.
|
|
127
|
+
function reap(s, t = now()) {
|
|
128
|
+
const started = s.jobs.filter(j => j.state === 'started');
|
|
129
|
+
const alive = makeAlive(started.flatMap(j => [j.pid, j.runner?.pid]).filter(Boolean));
|
|
130
|
+
for (const j of started) {
|
|
131
|
+
let ex = null;
|
|
132
|
+
try { ex = JSON.parse(fs.readFileSync(exitOf(j.id), 'utf8').trim().split('\n').pop()); } catch {}
|
|
133
|
+
if (ex) end(j, ex.started === false ? 'failed' : 'done', { code: ex.code, why: ex.started === false ? `dibs run exited ${ex.code} before starting it` : null }, t);
|
|
134
|
+
else if (j.pid && !alive(j.pid, j.pstart)) end(j, 'lost', { why: 'its dibs run ended without an exit code (killed, or the machine restarted)' }, t);
|
|
135
|
+
// Never started again: if the runner died between spawning and recording
|
|
136
|
+
// the pid, the command may be running, and a second copy is worse than none.
|
|
137
|
+
else if (!j.pid && !alive(j.runner?.pid, j.runner?.pstart)) end(j, 'lost', { why: 'the runner stopped while starting it' }, t);
|
|
138
|
+
}
|
|
139
|
+
for (const j of s.jobs.filter(j => j.state === 'scheduled' && j.after && t - j.created > MAX_AHEAD))
|
|
140
|
+
end(j, 'skipped', { why: `waited ${dur(MAX_AHEAD)} for ${trigger(j)}` }, t);
|
|
141
|
+
const done = s.jobs.filter(j => !ACTIVE.has(j.state)).sort((a, b) => b.ended - a.ended);
|
|
142
|
+
const drop = new Set(done.filter((j, i) => i >= KEEP_DONE || t - j.ended > KEEP_FOR).map(j => j.id));
|
|
143
|
+
if (!drop.size) return;
|
|
144
|
+
for (const id of drop) for (const f of [logOf(id), exitOf(id)]) fs.rmSync(f, { force: true });
|
|
145
|
+
s.jobs = s.jobs.filter(j => !drop.has(j.id));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function end(j, state, facts, t = now()) {
|
|
149
|
+
Object.assign(j, { state, ended: t }, facts);
|
|
150
|
+
const line = state === 'done' ? `exit ${j.code}` : `${state}${j.why ? `: ${j.why}` : ''}`;
|
|
151
|
+
try { fs.appendFileSync(logOf(j.id), `dibs later ${j.id}: ${line} at ${new Date(t).toISOString()}${j.fired ? `, ${dur(t - j.fired)} after it started` : ''}\n`, { mode: 0o600 }); } catch {}
|
|
152
|
+
told(j);
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// The scheduling agent hears how its job ended, in its own thread, as if it
|
|
156
|
+
// had run dibs say: "l3 (ios snapshot suite) finished: exit 0. Log:
|
|
157
|
+
// ~/.dibs/later/l3.log". Not a cancel: whoever cancelled it knows. Runs once
|
|
158
|
+
// per job, under the jobs lock; a busy messages lock costs the note, not the job.
|
|
159
|
+
const HOMEDIR = os.homedir();
|
|
160
|
+
const shownPath = p => (p.startsWith(HOMEDIR + path.sep) ? `~${p.slice(HOMEDIR.length)}` : p);
|
|
161
|
+
function told(j) {
|
|
162
|
+
if (j.state === 'cancelled') return;
|
|
163
|
+
const how = j.state === 'done' ? `finished: exit ${j.code}` : j.state === 'skipped' ? `was skipped: ${j.why}`
|
|
164
|
+
: j.state === 'failed' ? `didn't start: ${j.why}` : `was lost: ${j.why}`;
|
|
165
|
+
try {
|
|
166
|
+
noteAs({ who: j.who, session: j.session, agentId: j.agentId, label: j.label, spid: j.spid, sstart: j.sstart },
|
|
167
|
+
`${j.id} (${j.purpose || j.cmd.join(' ').slice(0, 40)}) ${how}. Log: ${shownPath(logOf(j.id))}`);
|
|
168
|
+
} catch (e) { log(`dibs later: couldn't tell ${j.agent || j.who} how ${j.id} ended: ${e.message}`); }
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// Whether a scheduled job is due: true, false, or { skip: why }.
|
|
172
|
+
function due(j, t, live) {
|
|
173
|
+
if (j.at != null) return t >= j.at;
|
|
174
|
+
const a = j.after;
|
|
175
|
+
if (a.later) {
|
|
176
|
+
const dep = live.jobs.find(x => x.id === a.later);
|
|
177
|
+
if (!dep) return { skip: `${a.later} is gone from the list` };
|
|
178
|
+
if (ACTIVE.has(dep.state)) return false;
|
|
179
|
+
if (dep.state === 'cancelled' || dep.state === 'skipped') return { skip: `${a.later} was ${dep.state}` };
|
|
180
|
+
if (j.ok && !(dep.state === 'done' && dep.code === 0)) return { skip: `${a.later} ${dep.state === 'done' ? `exited ${dep.code}` : dep.state === 'failed' ? 'failed to start' : 'was lost'}` };
|
|
181
|
+
return true;
|
|
182
|
+
}
|
|
183
|
+
live.leases ??= liveIds(t);
|
|
184
|
+
if (a.ids.some(id => live.leases.ids.has(id))) return false;
|
|
185
|
+
const bad = j.ok && endedOk(a.ids);
|
|
186
|
+
return bad ? { skip: bad } : true;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// One look: claim what's due, then start it outside the lock. Any number of
|
|
190
|
+
// runners can look at once; a job is claimed by exactly one of them.
|
|
191
|
+
export function tick(t = now()) {
|
|
192
|
+
if (!fs.existsSync(FILE)) return 0;
|
|
193
|
+
const me = { pid: process.pid, pstart: pstart(process.pid) };
|
|
194
|
+
const claimed = locked(s => {
|
|
195
|
+
const live = { jobs: s.jobs };
|
|
196
|
+
const out = [];
|
|
197
|
+
for (const j of s.jobs.filter(j => j.state === 'scheduled')) {
|
|
198
|
+
const d = due(j, t, live);
|
|
199
|
+
if (d?.skip) { end(j, 'skipped', { why: d.skip }, t); continue; }
|
|
200
|
+
if (!d) continue;
|
|
201
|
+
Object.assign(j, { state: 'started', fired: t, runner: me });
|
|
202
|
+
if (j.at != null && t - j.at > LATE) j.late = t - j.at;
|
|
203
|
+
out.push({ ...j });
|
|
204
|
+
}
|
|
205
|
+
return out;
|
|
206
|
+
});
|
|
207
|
+
for (const j of claimed) start(j);
|
|
208
|
+
return claimed.length;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function start(j) {
|
|
212
|
+
const fail = why => locked(s => { const x = s.jobs.find(x => x.id === j.id); if (x?.state === 'started' && !x.pid) end(x, 'failed', { why }); });
|
|
213
|
+
if (!fs.existsSync(j.cwd)) return fail(`its folder ${j.cwd} is gone`);
|
|
214
|
+
let fd;
|
|
215
|
+
try {
|
|
216
|
+
fd = fs.openSync(logOf(j.id), 'a', 0o600);
|
|
217
|
+
fs.writeSync(fd, `dibs later ${j.id}: ${j.cmd.join(' ')} in ${j.cwd}, ${trigger(j)}, started ${new Date(j.fired).toISOString()}`
|
|
218
|
+
+ `${j.late ? `; ran late by ${dur(j.late)} (the machine was asleep or no runner was up)` : ''}\n`);
|
|
219
|
+
} catch (e) { return fail(`couldn't write its log: ${e.message}`); }
|
|
220
|
+
const env = {};
|
|
221
|
+
for (const [k, v] of Object.entries(process.env)) if (k.startsWith('DIBS_') && !DIBS_WHO.has(k)) env[k] = v;
|
|
222
|
+
for (const [k, v] of Object.entries(j.env || {})) if (!notEnv(k)) env[k] = v;
|
|
223
|
+
Object.assign(env, { DIBS_AGENT: j.agent || j.who, DIBS_NO_SESSION: '1', DIBS_LATER_JOB: j.id });
|
|
224
|
+
let child;
|
|
225
|
+
try {
|
|
226
|
+
// Detached, with output straight into the log: the run outlives this
|
|
227
|
+
// runner (a service restart, say), and the exit file still records how it ended.
|
|
228
|
+
// Through bin/dibs.mjs's sh lines, so the run waits thin like any other (Node on Windows).
|
|
229
|
+
const argv = OS === 'windows' ? [process.execPath, ...LEAN, BIN] : ['/bin/sh', BIN];
|
|
230
|
+
child = spawn(argv[0], [...argv.slice(1), ...runArgs(j)], { cwd: j.cwd, env, stdio: ['ignore', fd, fd], detached: true, windowsHide: true });
|
|
231
|
+
} catch (e) { fs.closeSync(fd); return fail(`couldn't start dibs run: ${e.message}`); }
|
|
232
|
+
fs.closeSync(fd);
|
|
233
|
+
child.on('error', e => fail(`couldn't start dibs run: ${e.message}`));
|
|
234
|
+
child.unref();
|
|
235
|
+
if (child.pid) locked(s => { const x = s.jobs.find(x => x.id === j.id); if (x) Object.assign(x, { pid: child.pid, pstart: pstart(child.pid) }); });
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// The dibs run a job becomes: the scheduler's flags, waiting as long as it takes.
|
|
239
|
+
export function runArgs(j) {
|
|
240
|
+
const args = ['run', j.res.join(','), '--wait', '--as', j.label ? `${j.label}, later ${j.id}` : `later ${j.id}`, '--notify', exitOf(j.id)];
|
|
241
|
+
if (j.purpose) args.push('-m', j.purpose);
|
|
242
|
+
if (j.prio) args.push('-p', j.prio);
|
|
243
|
+
if (j.est) args.push('--est', `${Math.round(j.est / 1000)}s`);
|
|
244
|
+
if (j.mem) args.push('--mem', String(j.mem));
|
|
245
|
+
if (j.cpu != null) args.push('--cpu', String(j.cpu));
|
|
246
|
+
if (j.disk) args.push('--disk', String(j.disk));
|
|
247
|
+
for (const p of j.ports || []) args.push('--port', p);
|
|
248
|
+
if (j.anywhere) args.push('--anywhere');
|
|
249
|
+
if (j.on) args.push('--on', j.on);
|
|
250
|
+
for (const b of j.bring || []) args.push('--bring', b);
|
|
251
|
+
return [...args, '--', ...j.cmd];
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// The runners up right now, each a file named by its pid holding its start time.
|
|
255
|
+
function runners() {
|
|
256
|
+
let names = [];
|
|
257
|
+
try { names = fs.readdirSync(RUNNERS); } catch { return []; }
|
|
258
|
+
const pids = names.map(Number).filter(Boolean);
|
|
259
|
+
const alive = makeAlive(pids);
|
|
260
|
+
return pids.filter(pid => {
|
|
261
|
+
let st = null;
|
|
262
|
+
try { st = fs.readFileSync(path.join(RUNNERS, String(pid)), 'utf8') || null; } catch {}
|
|
263
|
+
if (alive(pid, st)) return true;
|
|
264
|
+
fs.rmSync(path.join(RUNNERS, String(pid)), { force: true });
|
|
265
|
+
return false;
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// The runner loop, in the worker service or on its own (dibs later run).
|
|
270
|
+
// idleExit: leave once nothing is scheduled or running, or the folder is gone.
|
|
271
|
+
export async function runLater({ idleExit = false } = {}) {
|
|
272
|
+
const mine = path.join(RUNNERS, String(process.pid));
|
|
273
|
+
fs.mkdirSync(RUNNERS, { recursive: true });
|
|
274
|
+
fs.writeFileSync(mine, pstart(process.pid) || '');
|
|
275
|
+
const quit = () => { fs.rmSync(mine, { force: true }); process.exit(0); };
|
|
276
|
+
if (idleExit) for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, quit);
|
|
277
|
+
for (;;) {
|
|
278
|
+
try { tick(); } catch (e) { log(`dibs later: ${e.message}`); }
|
|
279
|
+
if (idleExit && (!fs.existsSync(DIR) || !load().jobs.some(j => ACTIVE.has(j.state)))) quit();
|
|
280
|
+
await sleep(TICK);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function trigger(j) {
|
|
285
|
+
if (j.at != null) {
|
|
286
|
+
const far = new Date(j.at).toDateString() !== new Date(j.created).toDateString();
|
|
287
|
+
return `at ${clock(j.at)}${far ? ` ${new Date(j.at).toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' })}` : ''}`;
|
|
288
|
+
}
|
|
289
|
+
const a = j.after;
|
|
290
|
+
const what = a.later || `${a.who}'s ${a.res.map(r => short(r)).join(',')}${a.ids.length === 1 ? ` (#${a.ids[0]})` : ''}`;
|
|
291
|
+
return `after ${what}${j.ok ? ' succeeds' : ''}`;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// What a job is doing now, for list and the board. A started job is running
|
|
295
|
+
// once its dibs run holds the lease, and waiting in the queue until then.
|
|
296
|
+
function phase(j, leases) {
|
|
297
|
+
if (j.state !== 'started') return j.state;
|
|
298
|
+
// Sent to another machine, it holds no lease here.
|
|
299
|
+
return j.pid && (j.anywhere || j.on || leases.some(l => l.pid === j.pid)) ? 'running' : 'waiting';
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function view(j, leases, t) {
|
|
303
|
+
const p = phase(j, leases);
|
|
304
|
+
return { id: j.id, state: p, res: j.res, who: j.who, agent: j.agent, label: j.label, purpose: j.purpose, cmd: j.cmd.join(' '), cwd: j.cwd,
|
|
305
|
+
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,
|
|
306
|
+
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 };
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
function snapshot(t = now()) {
|
|
310
|
+
if (!fs.existsSync(FILE)) return [];
|
|
311
|
+
const jobs = locked(s => s.jobs);
|
|
312
|
+
const leases = jobs.some(j => j.state === 'started') ? liveIds(t).leases : [];
|
|
313
|
+
return jobs.map(j => view(j, leases, t));
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
const where = v => (v.state === 'scheduled' ? `${v.when}${v.in != null ? ` (in ${dur(v.in)})` : ''}`
|
|
317
|
+
: v.state === 'waiting' ? `${v.when}, waiting in the queue since ${clock(v.fired)}`
|
|
318
|
+
: v.state === 'running' ? `${v.when}, running`
|
|
319
|
+
: `${v.when}, ${v.state === 'done' ? `exit ${v.code}` : v.state}${v.why ? ` (${v.why})` : ''} at ${clock(v.ended)}`)
|
|
320
|
+
+ (v.late ? `, ran late by ${dur(v.late)}` : '');
|
|
321
|
+
const line = v => ` ${v.id.padEnd(4)} ${v.res.map(r => short(r)).join(',').padEnd(11)} ${tag(v).padEnd(20)} ${v.purpose ? `"${v.purpose}" ` : ''}${where(v)} ${v.cmd.slice(0, 40)}`;
|
|
322
|
+
|
|
323
|
+
// The same in the plain board's words: "l3: web-app's "ios snapshot suite"
|
|
324
|
+
// for the simulator", then when: "at 02:00 (in about 5 hr)".
|
|
325
|
+
const ENDED = { done: 'finished', failed: "didn't start", lost: 'was lost', skipped: 'was skipped', cancelled: 'was cancelled' };
|
|
326
|
+
export function laterPlain(v, cfg) {
|
|
327
|
+
const what = `${v.id}: ${tag(v)}'s ${v.purpose ? `"${v.purpose}"` : v.cmd.slice(0, 40)} for ${v.res.map(r => named(cfg, r).the).join(' and ')}`;
|
|
328
|
+
const when = v.state === 'scheduled' ? `${v.when}${v.in != null ? ` (in ${about(v.in)})` : ''}`
|
|
329
|
+
: v.state === 'waiting' ? `${v.when}, waiting in ${named(cfg, v.res[0]).queue} since ${clock(v.fired)}`
|
|
330
|
+
: v.state === 'running' ? `${v.when}, running now`
|
|
331
|
+
: `${v.when}, ${ENDED[v.state]}${v.state === 'done' ? ` with exit ${v.code}` : ''}${v.why ? ` (${v.why})` : ''} at ${clock(v.ended)}`;
|
|
332
|
+
return { what, when: `${when}${v.late ? `, ran late by ${minutes(v.late)}` : ''}.` };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// The board's LATER section: what is scheduled, waiting or running.
|
|
336
|
+
export function laterBoard(t = now()) {
|
|
337
|
+
return snapshot(t).filter(v => ['scheduled', 'waiting', 'running'].includes(v.state))
|
|
338
|
+
.sort((a, b) => (a.at ?? Infinity) - (b.at ?? Infinity) || a.created - b.created);
|
|
339
|
+
}
|
|
340
|
+
export const laterLines = jobs => (jobs.length ? ['', 'LATER', ...jobs.map(line)] : []);
|
|
341
|
+
|
|
342
|
+
// dibs later <res> [--at 2:00 | --in 3h | --after <what> | --after-ok <what>] [--env NAME] [flags] -- <cmd>
|
|
343
|
+
// dibs later list [--json] | cancel <id> | run
|
|
344
|
+
export async function later(argv, cfg, parse) {
|
|
345
|
+
try {
|
|
346
|
+
const [sub, ...rest] = argv;
|
|
347
|
+
if (sub === 'list' || sub === 'ls') return list(parse(rest), cfg);
|
|
348
|
+
if (sub === 'cancel') return cancel(rest);
|
|
349
|
+
if (sub === 'run') return runLater({ idleExit: rest.includes('--idle-exit') });
|
|
350
|
+
return schedule(argv, parse);
|
|
351
|
+
} catch (e) {
|
|
352
|
+
if (e.exit) die(e.message, e.exit);
|
|
353
|
+
throw e;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function schedule(argv, parse) {
|
|
358
|
+
const dd = argv.indexOf('--');
|
|
359
|
+
const own = {}, pass = [];
|
|
360
|
+
for (let i = 0; i < (dd < 0 ? argv.length : dd); i++) {
|
|
361
|
+
const a = argv[i], next = () => argv[++i] ?? die(`${a} needs a value`);
|
|
362
|
+
if (a === '--at') own.at = next();
|
|
363
|
+
else if (a === '--in') own.in = next();
|
|
364
|
+
else if (a === '--after') own.after = next();
|
|
365
|
+
else if (a === '--after-ok') { own.after = next(); own.ok = true; }
|
|
366
|
+
else if (a === '--env') (own.env ||= []).push(next());
|
|
367
|
+
else pass.push(a);
|
|
368
|
+
}
|
|
369
|
+
const o = parse(dd < 0 ? pass : [...pass, ...argv.slice(dd)]);
|
|
370
|
+
if (!o.cmd?.length) die('nothing to run. Use: dibs later <resource> --at 02:00 -- <command>');
|
|
371
|
+
if (!o.res.length) die('name a resource, e.g. dibs later test --in 3h -- npm test');
|
|
372
|
+
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 <...>');
|
|
373
|
+
for (const [f, bad] of [['--by', o.by], ['--max-wait', o.maxWait], ['--notify', o.notify], ['--for', o.for]])
|
|
374
|
+
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`);
|
|
375
|
+
const t = now();
|
|
376
|
+
const job = { res: o.res, cmd: o.cmd, cwd: process.cwd(), created: t, state: 'scheduled', ok: !!own.ok };
|
|
377
|
+
if (own.in != null) {
|
|
378
|
+
const m = String(own.in).match(/^([\d.]+)\s*d$/);
|
|
379
|
+
job.at = t + (m ? parseFloat(m[1]) * 864e5 : ms(own.in));
|
|
380
|
+
} else if (own.at != null) job.at = /\d{4}-\d{2}-\d{2}/.test(own.at) ? Date.parse(own.at) : deadline(own.at, t);
|
|
381
|
+
if (job.at != null) {
|
|
382
|
+
if (Number.isNaN(job.at)) die(`can't read the time "${own.at}" (try 02:00, 9pm or 2026-10-20T02:00)`);
|
|
383
|
+
if (job.at < t - LATE) die(`${new Date(job.at).toLocaleString()} has passed. Nothing was scheduled`);
|
|
384
|
+
if (job.at - t > MAX_AHEAD) die(`that's ${dur(job.at - t)} away; dibs later plans at most ${dur(MAX_AHEAD)} ahead. Nothing was scheduled`);
|
|
385
|
+
}
|
|
386
|
+
if (own.after != null) job.after = target(own.after);
|
|
387
|
+
job.env = {};
|
|
388
|
+
for (const k of ENV_KEEP) if (process.env[k] != null) job.env[k] = process.env[k];
|
|
389
|
+
for (const e of own.env || []) {
|
|
390
|
+
const [k, ...v] = e.split('=');
|
|
391
|
+
if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(k)) die(`--env takes NAME or NAME=value, not ${e}`);
|
|
392
|
+
if (notEnv(k)) die(`--env ${k}: dibs sets its own variables and who is calling for a scheduled run. Nothing was scheduled`);
|
|
393
|
+
if (v.length) job.env[k] = v.join('=');
|
|
394
|
+
else if (process.env[k] != null) job.env[k] = process.env[k];
|
|
395
|
+
else die(`--env ${k}: it isn't set here. Set it, or pass ${k}=value`);
|
|
396
|
+
}
|
|
397
|
+
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);
|
|
398
|
+
const id = identity(o);
|
|
399
|
+
// Which agent of which session asked, so how it ends lands in that agent's thread (told).
|
|
400
|
+
const session = process.env.CLAUDE_CODE_SESSION_ID || sessionFiles().find(f => f.pid === id.spid)?.sessionId;
|
|
401
|
+
const by = session ? takeAgent('later', [], talkKey('later', dd < 0 ? argv : argv.slice(0, dd))) : null;
|
|
402
|
+
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,
|
|
403
|
+
cpu: o.cpu, disk: o.disk, ports: o.ports, anywhere: o.anywhere, on: o.on, bring: o.bring });
|
|
404
|
+
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];
|
|
405
|
+
const saved = locked(s => {
|
|
406
|
+
if (job.after?.later && !s.jobs.some(j => j.id === job.after.later)) return null;
|
|
407
|
+
job.id = `l${++s.seq}`;
|
|
408
|
+
s.jobs.push(job);
|
|
409
|
+
return { ...job };
|
|
410
|
+
});
|
|
411
|
+
if (!saved) die(`there's no ${job.after.later} in dibs later list. Nothing was scheduled`, 1);
|
|
412
|
+
console.log(`${saved.id}: ${saved.cmd.join(' ').slice(0, 60)} ${trigger(saved)}${saved.at != null ? ` (in ${about(saved.at - t)})` : ''}.`
|
|
413
|
+
+ ` Its output goes to ${shownPath(logOf(saved.id))}, and when it ends the person gets a note in your thread saying how. See it: dibs later list. Drop it: dibs later cancel ${saved.id}`);
|
|
414
|
+
ensureRunner();
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// --after <what>: l3 (a scheduled job), 42 or #42 (a lease or waiter on the
|
|
418
|
+
// board), or an agent's name, optionally :resource, meaning everything that
|
|
419
|
+
// agent holds or waits for right now.
|
|
420
|
+
function target(x) {
|
|
421
|
+
if (/^l\d+$/.test(x)) return { later: x };
|
|
422
|
+
const { ids } = liveIds(now());
|
|
423
|
+
const n = x.match(/^#?(\d+)$/);
|
|
424
|
+
if (n) {
|
|
425
|
+
const hit = ids.get(Number(n[1]));
|
|
426
|
+
if (!hit) die(`nothing on the board is #${n[1]} now (dibs shows the ids). Nothing was scheduled`, 1);
|
|
427
|
+
const l = hit.lease || hit.waiting;
|
|
428
|
+
return { ids: [l.id], who: l.agent || l.who, res: l.res };
|
|
429
|
+
}
|
|
430
|
+
const [who, res] = x.split(':');
|
|
431
|
+
const mine = [...ids.values()].map(h => h.lease || h.waiting).filter(l => (l.agent === who || l.who === who) && (!res || l.res.includes(res)));
|
|
432
|
+
if (!mine.length) die(`${who} ${res ? `holds and waits for no ${res}` : 'holds nothing and waits for nothing'} right now, so there's nothing to come after. Nothing was scheduled`, 1);
|
|
433
|
+
return { ids: mine.map(l => l.id), who, res: [...new Set(mine.flatMap(l => l.res))] };
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
// The worker service is the runner that survives a reboot. Without one, start
|
|
437
|
+
// a runner that stays until nothing is left, and say how to make it permanent.
|
|
438
|
+
function ensureRunner() {
|
|
439
|
+
if (runners().length) return;
|
|
440
|
+
fs.mkdirSync(DIR, { recursive: true });
|
|
441
|
+
const out = fs.openSync(path.join(DIR, 'runner.log'), 'a');
|
|
442
|
+
const p = spawn(process.execPath, [...LEAN, BIN, 'later', 'run', '--idle-exit'], { env: process.env, stdio: ['ignore', out, out], detached: true, windowsHide: true });
|
|
443
|
+
fs.closeSync(out);
|
|
444
|
+
p.unref();
|
|
445
|
+
say(`started a runner for scheduled jobs (pid ${p.pid}); it stops when none are left. It won't survive a restart:`
|
|
446
|
+
+ ' for that, the person runs dibs service install worker (it runs scheduled jobs even without other machines)');
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// What `dibs later list --json` prints, for dibs web too.
|
|
450
|
+
export function laterJson(t = now(), all = snapshot(t)) {
|
|
451
|
+
return { jobs: all, runners: runners() };
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function list(o, cfg) {
|
|
455
|
+
const t = now();
|
|
456
|
+
const all = snapshot(t);
|
|
457
|
+
if (o.json) return console.log(JSON.stringify(laterJson(t, all), null, 1));
|
|
458
|
+
if (!all.length) return console.log('Nothing scheduled. To schedule a run: dibs later <resource> --at 02:00 -- <command>');
|
|
459
|
+
const rank = { running: 0, waiting: 1, scheduled: 2 };
|
|
460
|
+
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)));
|
|
461
|
+
const count = st => all.filter(v => st.includes(v.state)).length;
|
|
462
|
+
const head = [[count(['scheduled']), 'scheduled'], [count(['waiting', 'running']), 'started'], [all.length - count(['scheduled', 'waiting', 'running']), 'ended in the last week']]
|
|
463
|
+
.filter(([n]) => n).map(([n, w]) => `${n} ${w}`).join(', ');
|
|
464
|
+
const out = [bold(`${head[0].toUpperCase()}${head.slice(1)}.`), ''];
|
|
465
|
+
out.push(...columns(order.map(v => { const p = laterPlain(v, cfg); return [v.id, p.what.slice(v.id.length + 2), p.when, v.state !== 'scheduled' ? dim(`Output: ${shownPath(v.log)}`) : '']; })));
|
|
466
|
+
if (!runners().length && all.some(v => v.state === 'scheduled')) out.push('', 'No runner is up, so these start when one does. The person can keep one up: dibs service install worker');
|
|
467
|
+
out.push('', dim('Drop one: dibs later cancel <id>. Everything as JSON: dibs later list --json'));
|
|
468
|
+
console.log(out.join('\n'));
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
function cancel(args) {
|
|
472
|
+
const id = args.find(a => !a.startsWith('-'));
|
|
473
|
+
if (!id) die('which? dibs later cancel <id> (dibs later list shows them)');
|
|
474
|
+
const me = identity();
|
|
475
|
+
const r = locked(s => {
|
|
476
|
+
const j = s.jobs.find(x => x.id === id);
|
|
477
|
+
if (!j) return { err: `there's no ${id} in dibs later list`, code: 1 };
|
|
478
|
+
if (!ACTIVE.has(j.state)) return { err: `${id} already ${j.state === 'done' ? `ended (exit ${j.code})` : `ended (${j.state})`}`, code: 1 };
|
|
479
|
+
const was = j.state;
|
|
480
|
+
// dibs run passes SIGTERM to the job's process tree and gives back its lease.
|
|
481
|
+
if (j.pid && makeAlive([j.pid])(j.pid, j.pstart)) process.kill(j.pid, 'SIGTERM');
|
|
482
|
+
end(j, 'cancelled', { why: `by ${me.agent || me.who}` });
|
|
483
|
+
return { was };
|
|
484
|
+
});
|
|
485
|
+
if (r.err) die(r.err, r.code);
|
|
486
|
+
console.log(r.was === 'scheduled' ? `cancelled ${id}; it won't run` : `cancelled ${id} and stopped its run`);
|
|
487
|
+
}
|