pi-better-server 0.2.2 → 0.3.0
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/package.json +3 -3
- package/scripts/measure-shared-reads/daemon.mjs +7 -0
- package/scripts/measure-shared-reads/probe.mjs +10 -0
- package/scripts/measure-shared-reads.mjs +145 -0
- package/scripts/test-on-pi.sh +19 -2
- package/src/cli.ts +39 -2
- package/src/client.ts +9 -4
- package/src/daemon-owner.ts +47 -6
- package/src/handshake.ts +8 -7
- package/src/lifecycle-config.ts +4 -0
- package/src/paths.ts +1 -11
- package/src/protocol.ts +5 -0
- package/src/registry.ts +2 -1
- package/src/runtime/background-history.ts +241 -0
- package/src/runtime/background.ts +173 -0
- package/src/runtime/cancellation.ts +95 -0
- package/src/runtime/client.ts +111 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -0
- package/src/runtime/domain/assignment-observation.mjs +103 -0
- package/src/runtime/domain/assignment-projection.d.mts +1 -0
- package/src/runtime/domain/assignment-projection.mjs +245 -0
- package/src/runtime/domain/background/conditions.mjs +93 -0
- package/src/runtime/domain/background/process-identity.mjs +110 -0
- package/src/runtime/domain/background/process.mjs +511 -0
- package/src/runtime/domain/background/registry.mjs +374 -0
- package/src/runtime/domain/background/snapshot.mjs +73 -0
- package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
- package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
- package/src/runtime/domain/background/supervisor/store.mjs +604 -0
- package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
- package/src/runtime/domain/background/supervisor/types.mjs +47 -0
- package/src/runtime/domain/background/terminal-publication.mjs +58 -0
- package/src/runtime/domain/background/types.mjs +3 -0
- package/src/runtime/domain/coordinator/index.mjs +50 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
- package/src/runtime/domain/coordinator/src/discovery.mjs +85 -0
- package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
- package/src/runtime/domain/coordinator/src/operations.mjs +299 -0
- package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
- package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +351 -0
- package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
- package/src/runtime/domain/coordinator/src/store.mjs +235 -0
- package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
- package/src/runtime/domain/coordinator/src/types.mjs +24 -0
- package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
- package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
- package/src/runtime/domain/health-observation.d.mts +3 -0
- package/src/runtime/domain/health-observation.mjs +613 -0
- package/src/runtime/domain/health-surface.mjs +279 -0
- package/src/runtime/domain/log-cursor.mjs +148 -0
- package/src/runtime/domain/log-paths.mjs +13 -0
- package/src/runtime/domain/parse.d.mts +2 -0
- package/src/runtime/domain/parse.mjs +1173 -0
- package/src/runtime/domain/process-status.d.mts +1 -0
- package/src/runtime/domain/process-status.mjs +25 -0
- package/src/runtime/domain/session-store.d.mts +2 -0
- package/src/runtime/domain/session-store.mjs +489 -0
- package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
- package/src/runtime/domain/shared-harness-settings.mjs +126 -0
- package/src/runtime/domain/shared-log-utils.mjs +1223 -0
- package/src/runtime/domain/shared-stall-detector.mjs +37 -0
- package/src/runtime/domain/widget.d.mts +1 -0
- package/src/runtime/domain/widget.mjs +250 -0
- package/src/runtime/guardian.ts +189 -0
- package/src/runtime/health-config.ts +27 -0
- package/src/runtime/local-client.ts +34 -0
- package/src/runtime/queries.ts +76 -0
- package/src/runtime/query-executor.ts +228 -0
- package/src/runtime/query-worker.mjs +118 -0
- package/src/runtime/read-model.ts +357 -0
- package/src/runtime/root.ts +29 -0
- package/src/runtime/socket.ts +10 -0
- package/src/runtime/status-cli.ts +11 -0
- package/src/runtime/work-client.d.mts +13 -0
- package/src/runtime/work-client.mjs +88 -0
- package/src/server.ts +136 -12
- package/src/session-activity.ts +22 -2
- package/src/shared-ssh-core/index.ts +30 -1
- package/src/startup/activation.ts +32 -5
- package/src/startup/ensure.ts +13 -1
- package/src/startup/install.ts +2 -0
- package/src/version.ts +4 -0
|
@@ -0,0 +1,604 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable record storage for the detached local supervisor.
|
|
3
|
+
*
|
|
4
|
+
* Layout (all under the caller-configured directory):
|
|
5
|
+
*
|
|
6
|
+
* ```
|
|
7
|
+
* tasks/<taskId>/launch.json written once by the caller, before execution
|
|
8
|
+
* tasks/<taskId>/claim.json created exclusively by the runner before it runs anything
|
|
9
|
+
* tasks/<taskId>/command.json identity of the live command or watch check
|
|
10
|
+
* tasks/<taskId>/stop.json stop request, readable from any process
|
|
11
|
+
* tasks/<taskId>/result.json runner-attested (or stop-attested) terminal evidence
|
|
12
|
+
* tasks/<taskId>/lost.json no terminal evidence exists and none can appear
|
|
13
|
+
* tasks/<taskId>/stdout.log raw stdout bytes
|
|
14
|
+
* tasks/<taskId>/stderr.log raw stderr bytes
|
|
15
|
+
* tasks/<taskId>/events.log runner lifecycle lines plus inherited runner stderr
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* Two rules hold everywhere here:
|
|
19
|
+
*
|
|
20
|
+
* 1. **Claims are exclusive.** `claim.json` is opened with `O_EXCL`, so two
|
|
21
|
+
* runners for one token cannot both execute. Duplicate launches reconcile
|
|
22
|
+
* against the existing record instead of running again.
|
|
23
|
+
* 2. **Terminal evidence is written once.** `result.json`/`lost.json` are
|
|
24
|
+
* exclusive too; the first terminal record wins and a later write cannot
|
|
25
|
+
* rewrite it as success.
|
|
26
|
+
*
|
|
27
|
+
* This module is imported by the runner executable, so it must stay runnable
|
|
28
|
+
* under Node's own TypeScript type stripping: only erasable syntax, and every
|
|
29
|
+
* relative import names the real `.ts` file. `../conditions.ts` qualifies
|
|
30
|
+
* because its only import is type-only.
|
|
31
|
+
*/
|
|
32
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
33
|
+
import { createRequire } from "node:module";
|
|
34
|
+
import { appendFileSync, closeSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeSync, } from "node:fs";
|
|
35
|
+
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
36
|
+
import { validateCondition } from "../conditions.mjs";
|
|
37
|
+
import { SUPERVISOR_FENCE_WAIT_MS, SUPERVISOR_RECORD_VERSION, SUPERVISOR_TASK_ID_PATTERN, SUPERVISOR_TASK_ID_PREFIX, } from "./types.mjs";
|
|
38
|
+
/** The task id is derived from the token, so one token can only ever name one execution. */
|
|
39
|
+
export function supervisorTaskIdForToken(token) {
|
|
40
|
+
const digest = createHash("sha256").update(token, "utf8").digest("hex");
|
|
41
|
+
return `${SUPERVISOR_TASK_ID_PREFIX}${digest.slice(0, 20)}`;
|
|
42
|
+
}
|
|
43
|
+
/** Refuse an id that did not come from {@link supervisorTaskIdForToken}; it is also a path segment. */
|
|
44
|
+
export function assertSupervisorTaskId(taskId) {
|
|
45
|
+
if (!SUPERVISOR_TASK_ID_PATTERN.test(taskId)) {
|
|
46
|
+
throw new Error(`Invalid supervisor task id ${JSON.stringify(taskId)}; expected ${SUPERVISOR_TASK_ID_PREFIX}<20 hex>.`);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
export function resolveSupervisorDirectory(directory) {
|
|
50
|
+
if (typeof directory !== "string" || directory.trim().length === 0) {
|
|
51
|
+
throw new Error("A supervisor directory is required.");
|
|
52
|
+
}
|
|
53
|
+
return resolve(directory);
|
|
54
|
+
}
|
|
55
|
+
export function supervisorPaths(directory, taskId) {
|
|
56
|
+
assertSupervisorTaskId(taskId);
|
|
57
|
+
const dir = join(resolveSupervisorDirectory(directory), "tasks", taskId);
|
|
58
|
+
return {
|
|
59
|
+
dir,
|
|
60
|
+
launch: join(dir, "launch.json"),
|
|
61
|
+
claim: join(dir, "claim.json"),
|
|
62
|
+
command: join(dir, "command.json"),
|
|
63
|
+
stop: join(dir, "stop.json"),
|
|
64
|
+
result: join(dir, "result.json"),
|
|
65
|
+
lost: join(dir, "lost.json"),
|
|
66
|
+
cleanup: join(dir, "cleanup.json"),
|
|
67
|
+
fenceDb: join(dir, "state.db"),
|
|
68
|
+
stdout: join(dir, "stdout.log"),
|
|
69
|
+
stderr: join(dir, "stderr.log"),
|
|
70
|
+
events: join(dir, "events.log"),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
export function ensureSupervisorTaskDir(directory, taskId) {
|
|
74
|
+
const paths = supervisorPaths(directory, taskId);
|
|
75
|
+
mkdirSync(paths.dir, { recursive: true });
|
|
76
|
+
return paths;
|
|
77
|
+
}
|
|
78
|
+
/** Deterministic JSON so a request hash never depends on property order. */
|
|
79
|
+
export function stableStringify(value) {
|
|
80
|
+
if (value === null || typeof value !== "object")
|
|
81
|
+
return JSON.stringify(value) ?? "null";
|
|
82
|
+
if (Array.isArray(value))
|
|
83
|
+
return `[${value.map((entry) => stableStringify(entry)).join(",")}]`;
|
|
84
|
+
const entries = Object.entries(value)
|
|
85
|
+
.filter(([, entry]) => entry !== undefined)
|
|
86
|
+
.sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
|
|
87
|
+
.map(([key, entry]) => `${JSON.stringify(key)}:${stableStringify(entry)}`);
|
|
88
|
+
return `{${entries.join(",")}}`;
|
|
89
|
+
}
|
|
90
|
+
export function launchRequestHash(request) {
|
|
91
|
+
return createHash("sha256").update(stableStringify(request), "utf8").digest("hex");
|
|
92
|
+
}
|
|
93
|
+
// --- low-level durable writes -------------------------------------------------
|
|
94
|
+
function ensureParent(path) {
|
|
95
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
96
|
+
}
|
|
97
|
+
/** Best effort: the rename is what makes the file atomic; the directory fsync only adds durability. */
|
|
98
|
+
function fsyncDirectoryOf(path) {
|
|
99
|
+
try {
|
|
100
|
+
const fd = openSync(dirname(path), "r");
|
|
101
|
+
try {
|
|
102
|
+
fsyncSync(fd);
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
closeSync(fd);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
// Some platforms refuse fsync on a directory fd; atomicity is unaffected.
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
function tempPathFor(path) {
|
|
113
|
+
// `basename`, not `split("/")`: a Windows path has no `/`, so the whole path
|
|
114
|
+
// would become the temp file name.
|
|
115
|
+
return join(dirname(path), `.${basename(path)}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`);
|
|
116
|
+
}
|
|
117
|
+
/** Write a durable temp file; the caller publishes it. */
|
|
118
|
+
function writeDurableTemp(path, text) {
|
|
119
|
+
ensureParent(path);
|
|
120
|
+
const temp = tempPathFor(path);
|
|
121
|
+
const fd = openSync(temp, "wx", 0o600);
|
|
122
|
+
try {
|
|
123
|
+
writeSync(fd, text);
|
|
124
|
+
fsyncSync(fd);
|
|
125
|
+
}
|
|
126
|
+
finally {
|
|
127
|
+
closeSync(fd);
|
|
128
|
+
}
|
|
129
|
+
return temp;
|
|
130
|
+
}
|
|
131
|
+
/** Write a complete file atomically and durably: temp file, fsync, rename. */
|
|
132
|
+
export function writeTextAtomic(path, text) {
|
|
133
|
+
const temp = writeDurableTemp(path, text);
|
|
134
|
+
try {
|
|
135
|
+
renameSync(temp, path);
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
try {
|
|
139
|
+
unlinkSync(temp);
|
|
140
|
+
}
|
|
141
|
+
catch { /* best effort */ }
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
fsyncDirectoryOf(path);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Publish a file only if it does not exist yet, atomically across processes.
|
|
148
|
+
*
|
|
149
|
+
* `open(path, "wx")` is exclusive but publishes an empty file before its bytes
|
|
150
|
+
* arrive, so a concurrent reader can observe a partial record. A hard link from
|
|
151
|
+
* a fully written temp file is atomic in both directions: the target either
|
|
152
|
+
* holds the complete record or does not exist. False means another writer won.
|
|
153
|
+
*
|
|
154
|
+
* A filesystem without hard links fails closed: there is no fallback that would
|
|
155
|
+
* make an exclusive publication atomic, and a known path to a partial record is
|
|
156
|
+
* worse than a refused write.
|
|
157
|
+
*/
|
|
158
|
+
export function writeTextExclusive(path, text) {
|
|
159
|
+
const temp = writeDurableTemp(path, text);
|
|
160
|
+
const cleanupTemp = () => { try {
|
|
161
|
+
unlinkSync(temp);
|
|
162
|
+
}
|
|
163
|
+
catch { /* best effort */ } };
|
|
164
|
+
try {
|
|
165
|
+
linkSync(temp, path);
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
cleanupTemp();
|
|
169
|
+
const code = error.code;
|
|
170
|
+
if (code === "EEXIST")
|
|
171
|
+
return false;
|
|
172
|
+
throw new Error(`Cannot publish ${path} atomically: the filesystem refused a hard link (${code ?? "unknown"}). `
|
|
173
|
+
+ "An exclusive record is never published partially; the write was not applied.", { cause: error });
|
|
174
|
+
}
|
|
175
|
+
cleanupTemp();
|
|
176
|
+
fsyncDirectoryOf(path);
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* A transition could not be applied because the state fence was held longer than
|
|
181
|
+
* the bounded wait (`busy`), or because `node:sqlite` is unavailable
|
|
182
|
+
* (`unavailable`). Callers never take a live holder's lock; they report or retry.
|
|
183
|
+
*/
|
|
184
|
+
export class SupervisorFenceBusyError extends Error {
|
|
185
|
+
taskId;
|
|
186
|
+
verdict;
|
|
187
|
+
constructor(taskId, verdict, detail) {
|
|
188
|
+
super(`The supervisor state fence for ${taskId} was not available (${verdict}); the transition was not applied. ${detail}`);
|
|
189
|
+
this.name = "SupervisorFenceBusyError";
|
|
190
|
+
this.taskId = taskId;
|
|
191
|
+
this.verdict = verdict;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* `node:sqlite` is built into Node 22.5+, but a static import would make this
|
|
196
|
+
* module unloadable on an older runtime. It is therefore resolved on first use;
|
|
197
|
+
* when it is unavailable the fence fails closed and no transition is applied.
|
|
198
|
+
* Loading it adds no permission: SQLite only opens the database under the
|
|
199
|
+
* supervisor directory this module already owns.
|
|
200
|
+
*/
|
|
201
|
+
let sqliteModule;
|
|
202
|
+
function loadSqlite() {
|
|
203
|
+
if (sqliteModule !== undefined)
|
|
204
|
+
return sqliteModule ?? undefined;
|
|
205
|
+
try {
|
|
206
|
+
const requireForModule = createRequire(import.meta.url);
|
|
207
|
+
sqliteModule = requireForModule("node:sqlite");
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
sqliteModule = null;
|
|
211
|
+
}
|
|
212
|
+
return sqliteModule ?? undefined;
|
|
213
|
+
}
|
|
214
|
+
/** SQLite reports lock contention as SQLITE_BUSY (errcode 5) / "database is locked". */
|
|
215
|
+
function isSqliteBusy(error) {
|
|
216
|
+
const candidate = error;
|
|
217
|
+
if (candidate?.errcode === 5)
|
|
218
|
+
return true;
|
|
219
|
+
if (candidate?.code === "SQLITE_BUSY")
|
|
220
|
+
return true;
|
|
221
|
+
return typeof candidate?.message === "string" && /database is locked|SQLITE_BUSY/i.test(candidate.message);
|
|
222
|
+
}
|
|
223
|
+
function fenceFailure(taskId, busyMs, error) {
|
|
224
|
+
if (!isSqliteBusy(error))
|
|
225
|
+
return error;
|
|
226
|
+
return new SupervisorFenceBusyError(taskId, "busy", `Another process held the fence for longer than ${busyMs}ms; it is still alive, so nothing was taken over.`);
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Serialize a state transition across processes (claim vs lost publication, and
|
|
230
|
+
* supervisor-attested terminal writes).
|
|
231
|
+
*
|
|
232
|
+
* The fence is a SQLite `BEGIN IMMEDIATE` transaction on a per-task database.
|
|
233
|
+
* That primitive already provides exactly the two guarantees this needs:
|
|
234
|
+
*
|
|
235
|
+
* - **Exclusion** is decided by the database's write lock, so two contenders can
|
|
236
|
+
* never both be inside the critical section — there is no observation window
|
|
237
|
+
* between "is it held?" and "take it".
|
|
238
|
+
* - **Dead-owner release** is the operating system releasing the file lock when
|
|
239
|
+
* the holder's process ends; SQLite rolls the open transaction back. No age,
|
|
240
|
+
* identity or quarantine heuristic participates, because a live holder is
|
|
241
|
+
* simply waited for (up to `busy_timeout`) and then reported busy.
|
|
242
|
+
*
|
|
243
|
+
* `fn` is synchronous and runs inside the transaction. Any error rolls back and
|
|
244
|
+
* propagates unchanged, so a transition is applied atomically or not at all.
|
|
245
|
+
*/
|
|
246
|
+
export function withStateFence(directory, taskId, fn, options = {}) {
|
|
247
|
+
const paths = supervisorPaths(directory, taskId);
|
|
248
|
+
mkdirSync(paths.dir, { recursive: true });
|
|
249
|
+
const sqlite = loadSqlite();
|
|
250
|
+
if (!sqlite) {
|
|
251
|
+
throw new SupervisorFenceBusyError(taskId, "unavailable", "Node's built-in node:sqlite (Node 22.5+) is unavailable and there is no non-atomic fallback fence.");
|
|
252
|
+
}
|
|
253
|
+
const busyMs = Math.max(1, Math.floor(options.waitMs ?? SUPERVISOR_FENCE_WAIT_MS));
|
|
254
|
+
let db;
|
|
255
|
+
try {
|
|
256
|
+
db = new sqlite.DatabaseSync(paths.fenceDb);
|
|
257
|
+
db.exec(`PRAGMA busy_timeout = ${busyMs}`);
|
|
258
|
+
try {
|
|
259
|
+
db.exec("BEGIN IMMEDIATE");
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
throw fenceFailure(taskId, busyMs, error);
|
|
263
|
+
}
|
|
264
|
+
let result;
|
|
265
|
+
try {
|
|
266
|
+
result = fn();
|
|
267
|
+
}
|
|
268
|
+
catch (error) {
|
|
269
|
+
try {
|
|
270
|
+
db.exec("ROLLBACK");
|
|
271
|
+
}
|
|
272
|
+
catch { /* the transaction may already be gone */ }
|
|
273
|
+
throw error;
|
|
274
|
+
}
|
|
275
|
+
try {
|
|
276
|
+
db.exec("COMMIT");
|
|
277
|
+
}
|
|
278
|
+
catch (error) {
|
|
279
|
+
try {
|
|
280
|
+
db.exec("ROLLBACK");
|
|
281
|
+
}
|
|
282
|
+
catch { /* best effort */ }
|
|
283
|
+
throw fenceFailure(taskId, busyMs, error);
|
|
284
|
+
}
|
|
285
|
+
return result;
|
|
286
|
+
}
|
|
287
|
+
finally {
|
|
288
|
+
try {
|
|
289
|
+
db?.close();
|
|
290
|
+
}
|
|
291
|
+
catch { /* the OS releases the lock with the connection */ }
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* Claim a launch token only if nothing terminal and nothing lost was published.
|
|
296
|
+
*
|
|
297
|
+
* The fence is what removes the check-then-write race: a lost attestation
|
|
298
|
+
* published first makes this claim fail, and a claim published first makes the
|
|
299
|
+
* reconciler see a live execution instead of recording a loss.
|
|
300
|
+
*/
|
|
301
|
+
export function claimLaunch(directory, taskId, claim) {
|
|
302
|
+
return withStateFence(directory, taskId, () => {
|
|
303
|
+
const result = readTerminalRecord(directory, taskId).value;
|
|
304
|
+
if (result)
|
|
305
|
+
return { status: "terminal", result };
|
|
306
|
+
const lost = readLostRecord(directory, taskId).value;
|
|
307
|
+
if (lost)
|
|
308
|
+
return { status: "lost", lost };
|
|
309
|
+
const existing = readClaimRecord(directory, taskId).value;
|
|
310
|
+
if (existing)
|
|
311
|
+
return { status: "already-claimed", claim: existing };
|
|
312
|
+
if (!writeClaimRecord(directory, claim)) {
|
|
313
|
+
const racer = readClaimRecord(directory, taskId).value;
|
|
314
|
+
if (racer)
|
|
315
|
+
return { status: "already-claimed", claim: racer };
|
|
316
|
+
throw new Error(`Could not claim the launch token for ${taskId} under the state fence.`);
|
|
317
|
+
}
|
|
318
|
+
return { status: "claimed", claim };
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
function readText(path) {
|
|
322
|
+
try {
|
|
323
|
+
return { value: readFileSync(path, "utf8"), missing: false };
|
|
324
|
+
}
|
|
325
|
+
catch (error) {
|
|
326
|
+
if (error.code === "ENOENT")
|
|
327
|
+
return { missing: true };
|
|
328
|
+
return { missing: true, error: error instanceof Error ? error.message : String(error) };
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
function readJsonRecord(path, problem) {
|
|
332
|
+
const read = readText(path);
|
|
333
|
+
if (read.missing)
|
|
334
|
+
return { missing: true, error: read.error };
|
|
335
|
+
let parsed;
|
|
336
|
+
try {
|
|
337
|
+
parsed = JSON.parse(read.value);
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
return { missing: false, error: `invalid JSON: ${error instanceof Error ? error.message : String(error)}` };
|
|
341
|
+
}
|
|
342
|
+
const invalid = problem(parsed);
|
|
343
|
+
if (invalid)
|
|
344
|
+
return { missing: false, error: invalid };
|
|
345
|
+
return { value: parsed, missing: false };
|
|
346
|
+
}
|
|
347
|
+
export function appendEvent(eventsPath, message) {
|
|
348
|
+
try {
|
|
349
|
+
ensureParent(eventsPath);
|
|
350
|
+
appendFileSync(eventsPath, `${new Date().toISOString()} ${message}\n`);
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
// A log we cannot write must never decide the verdict; the terminal record carries it.
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
export function appendStreamBytes(path, chunk) {
|
|
357
|
+
if (chunk.length === 0)
|
|
358
|
+
return;
|
|
359
|
+
try {
|
|
360
|
+
ensureParent(path);
|
|
361
|
+
appendFileSync(path, chunk);
|
|
362
|
+
}
|
|
363
|
+
catch {
|
|
364
|
+
// Same rule as appendEvent: losing log detail must not fail the task.
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
// --- shape validation ---------------------------------------------------------
|
|
368
|
+
function isObject(value) {
|
|
369
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
370
|
+
}
|
|
371
|
+
function isFiniteNumber(value) {
|
|
372
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
373
|
+
}
|
|
374
|
+
function isPositiveMs(value) {
|
|
375
|
+
return isFiniteNumber(value) && value > 0;
|
|
376
|
+
}
|
|
377
|
+
function nonEmptyString(value) {
|
|
378
|
+
return typeof value === "string" && value.length > 0;
|
|
379
|
+
}
|
|
380
|
+
function commandProblem(value) {
|
|
381
|
+
if (!isObject(value))
|
|
382
|
+
return "command must be an object";
|
|
383
|
+
if (!Array.isArray(value.argv) || value.argv.length === 0)
|
|
384
|
+
return "command.argv must be a non-empty array";
|
|
385
|
+
for (const [index, entry] of value.argv.entries()) {
|
|
386
|
+
if (!nonEmptyString(entry))
|
|
387
|
+
return `command.argv[${index}] must be a non-empty string`;
|
|
388
|
+
if (entry.includes("\0"))
|
|
389
|
+
return `command.argv[${index}] must not contain a NUL byte`;
|
|
390
|
+
}
|
|
391
|
+
if (!nonEmptyString(value.cwd) || !isAbsolute(value.cwd))
|
|
392
|
+
return "command.cwd must be an absolute path";
|
|
393
|
+
return undefined;
|
|
394
|
+
}
|
|
395
|
+
function conditionProblem(name, value, required) {
|
|
396
|
+
if (value === undefined || value === null) {
|
|
397
|
+
return required ? `${name} is required for a watch` : undefined;
|
|
398
|
+
}
|
|
399
|
+
if (!isObject(value) || !nonEmptyString(value.type))
|
|
400
|
+
return `${name} must be a condition object`;
|
|
401
|
+
const invalid = validateCondition(value);
|
|
402
|
+
return invalid === undefined ? undefined : `${name}: ${invalid}`;
|
|
403
|
+
}
|
|
404
|
+
function launchRecordProblem(taskId) {
|
|
405
|
+
return (value) => {
|
|
406
|
+
if (!isObject(value))
|
|
407
|
+
return "launch record must be an object";
|
|
408
|
+
if (value.version !== SUPERVISOR_RECORD_VERSION) {
|
|
409
|
+
return `unsupported launch record version ${JSON.stringify(value.version)}; this build reads version ${SUPERVISOR_RECORD_VERSION}`;
|
|
410
|
+
}
|
|
411
|
+
if (value.taskId !== taskId)
|
|
412
|
+
return `launch record taskId ${JSON.stringify(value.taskId)} does not match ${JSON.stringify(taskId)}`;
|
|
413
|
+
if (!nonEmptyString(value.token))
|
|
414
|
+
return "launch record token is missing";
|
|
415
|
+
if (supervisorTaskIdForToken(value.token) !== taskId)
|
|
416
|
+
return "launch record token does not derive this task id";
|
|
417
|
+
if (value.kind !== "process" && value.kind !== "watch")
|
|
418
|
+
return "launch record kind must be \"process\" or \"watch\"";
|
|
419
|
+
const command = commandProblem(value.command);
|
|
420
|
+
if (command)
|
|
421
|
+
return command;
|
|
422
|
+
if (!nonEmptyString(value.requestHash))
|
|
423
|
+
return "launch record requestHash is missing";
|
|
424
|
+
if (!isFiniteNumber(value.createdAt))
|
|
425
|
+
return "launch record createdAt is missing";
|
|
426
|
+
if (!isPositiveMs(value.maxLogBytes))
|
|
427
|
+
return "launch record maxLogBytes is missing";
|
|
428
|
+
if (value.environment !== "inherited")
|
|
429
|
+
return "launch record must declare environment: \"inherited\"";
|
|
430
|
+
if (value.commandTimeoutMs !== undefined && !isPositiveMs(value.commandTimeoutMs))
|
|
431
|
+
return "launch record commandTimeoutMs must be positive";
|
|
432
|
+
if (value.taskTimeoutMs !== undefined && !isPositiveMs(value.taskTimeoutMs))
|
|
433
|
+
return "launch record taskTimeoutMs must be positive";
|
|
434
|
+
if (value.intervalMs !== undefined && !isPositiveMs(value.intervalMs))
|
|
435
|
+
return "launch record intervalMs must be positive";
|
|
436
|
+
if (value.kind === "watch") {
|
|
437
|
+
const success = conditionProblem("successWhen", value.successWhen, true);
|
|
438
|
+
if (success)
|
|
439
|
+
return success;
|
|
440
|
+
const failure = conditionProblem("failureWhen", value.failureWhen, false);
|
|
441
|
+
if (failure)
|
|
442
|
+
return failure;
|
|
443
|
+
}
|
|
444
|
+
else if (value.successWhen !== undefined || value.failureWhen !== undefined || value.intervalMs !== undefined) {
|
|
445
|
+
return "a process launch record must not carry watch conditions or a cadence";
|
|
446
|
+
}
|
|
447
|
+
return undefined;
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
export function readLaunchRecord(directory, taskId) {
|
|
451
|
+
return readJsonRecord(supervisorPaths(directory, taskId).launch, launchRecordProblem(taskId));
|
|
452
|
+
}
|
|
453
|
+
/** True when this caller wrote the launch record; false when another launch already owns the token. */
|
|
454
|
+
export function writeLaunchRecord(directory, record) {
|
|
455
|
+
return writeTextExclusive(supervisorPaths(directory, record.taskId).launch, `${JSON.stringify(record, null, 2)}\n`);
|
|
456
|
+
}
|
|
457
|
+
// --- claim --------------------------------------------------------------------
|
|
458
|
+
function claimRecordProblem(taskId) {
|
|
459
|
+
return (value) => {
|
|
460
|
+
if (!isObject(value))
|
|
461
|
+
return "claim record must be an object";
|
|
462
|
+
if (value.version !== SUPERVISOR_RECORD_VERSION)
|
|
463
|
+
return "unsupported claim record version";
|
|
464
|
+
if (value.taskId !== taskId)
|
|
465
|
+
return "claim record taskId mismatch";
|
|
466
|
+
if (!nonEmptyString(value.token))
|
|
467
|
+
return "claim record token is missing";
|
|
468
|
+
if (!Number.isInteger(value.pid) || value.pid <= 0)
|
|
469
|
+
return "claim record runner pid is missing";
|
|
470
|
+
if (!isFiniteNumber(value.claimedAt))
|
|
471
|
+
return "claim record claimedAt is missing";
|
|
472
|
+
return undefined;
|
|
473
|
+
};
|
|
474
|
+
}
|
|
475
|
+
export function readClaimRecord(directory, taskId) {
|
|
476
|
+
return readJsonRecord(supervisorPaths(directory, taskId).claim, claimRecordProblem(taskId));
|
|
477
|
+
}
|
|
478
|
+
/** Durably claim a token before executing. False means another runner already owns it. */
|
|
479
|
+
export function writeClaimRecord(directory, record) {
|
|
480
|
+
return writeTextExclusive(supervisorPaths(directory, record.taskId).claim, `${JSON.stringify(record, null, 2)}\n`);
|
|
481
|
+
}
|
|
482
|
+
// --- live command identity ----------------------------------------------------
|
|
483
|
+
function commandRecordProblem(taskId) {
|
|
484
|
+
return (value) => {
|
|
485
|
+
if (!isObject(value))
|
|
486
|
+
return "command record must be an object";
|
|
487
|
+
if (value.version !== SUPERVISOR_RECORD_VERSION)
|
|
488
|
+
return "unsupported command record version";
|
|
489
|
+
if (value.taskId !== taskId)
|
|
490
|
+
return "command record taskId mismatch";
|
|
491
|
+
if (!nonEmptyString(value.token))
|
|
492
|
+
return "command record token is missing";
|
|
493
|
+
if (!Number.isInteger(value.pid) || value.pid <= 0)
|
|
494
|
+
return "command record pid is missing";
|
|
495
|
+
if (!isFiniteNumber(value.startedAt))
|
|
496
|
+
return "command record startedAt is missing";
|
|
497
|
+
return undefined;
|
|
498
|
+
};
|
|
499
|
+
}
|
|
500
|
+
export function readCommandRecord(directory, taskId) {
|
|
501
|
+
return readJsonRecord(supervisorPaths(directory, taskId).command, commandRecordProblem(taskId));
|
|
502
|
+
}
|
|
503
|
+
/** Overwritten per attempt, so a stop can verify the live command identity. */
|
|
504
|
+
export function writeCommandRecord(directory, record) {
|
|
505
|
+
writeTextAtomic(supervisorPaths(directory, record.taskId).command, `${JSON.stringify(record, null, 2)}\n`);
|
|
506
|
+
}
|
|
507
|
+
// --- stop requests ------------------------------------------------------------
|
|
508
|
+
function stopRequestProblem(taskId) {
|
|
509
|
+
return (value) => {
|
|
510
|
+
if (!isObject(value))
|
|
511
|
+
return "stop request must be an object";
|
|
512
|
+
if (value.version !== SUPERVISOR_RECORD_VERSION)
|
|
513
|
+
return "unsupported stop request version";
|
|
514
|
+
if (value.taskId !== taskId)
|
|
515
|
+
return "stop request taskId mismatch";
|
|
516
|
+
if (!isFiniteNumber(value.requestedAt))
|
|
517
|
+
return "stop request requestedAt is missing";
|
|
518
|
+
return undefined;
|
|
519
|
+
};
|
|
520
|
+
}
|
|
521
|
+
export function readStopRequest(directory, taskId) {
|
|
522
|
+
return readJsonRecord(supervisorPaths(directory, taskId).stop, stopRequestProblem(taskId)).value;
|
|
523
|
+
}
|
|
524
|
+
/** Keep the earliest request time when a stop is repeated. */
|
|
525
|
+
export function writeStopRequest(directory, request) {
|
|
526
|
+
const existing = readStopRequest(directory, request.taskId);
|
|
527
|
+
const effective = existing && existing.requestedAt <= request.requestedAt
|
|
528
|
+
? { ...request, requestedAt: existing.requestedAt, reason: existing.reason ?? request.reason }
|
|
529
|
+
: request;
|
|
530
|
+
writeTextAtomic(supervisorPaths(directory, request.taskId).stop, `${JSON.stringify(effective, null, 2)}\n`);
|
|
531
|
+
return effective;
|
|
532
|
+
}
|
|
533
|
+
// --- terminal and lost evidence ----------------------------------------------
|
|
534
|
+
function terminalRecordProblem(taskId) {
|
|
535
|
+
return (value) => {
|
|
536
|
+
if (!isObject(value))
|
|
537
|
+
return "terminal record must be an object";
|
|
538
|
+
if (value.version !== SUPERVISOR_RECORD_VERSION)
|
|
539
|
+
return "unsupported terminal record version";
|
|
540
|
+
if (value.taskId !== taskId)
|
|
541
|
+
return "terminal record taskId mismatch";
|
|
542
|
+
const status = value.status;
|
|
543
|
+
if (status !== "succeeded" && status !== "failed" && status !== "timed_out" && status !== "cancelled") {
|
|
544
|
+
return "terminal record status is not terminal";
|
|
545
|
+
}
|
|
546
|
+
if (value.attestedBy !== "runner" && value.attestedBy !== "supervisor")
|
|
547
|
+
return "terminal record attestedBy is invalid";
|
|
548
|
+
if (!nonEmptyString(value.reason))
|
|
549
|
+
return "terminal record reason is missing";
|
|
550
|
+
if (!isFiniteNumber(value.startedAt) || !isFiniteNumber(value.endedAt))
|
|
551
|
+
return "terminal record timestamps are missing";
|
|
552
|
+
return undefined;
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
export function readTerminalRecord(directory, taskId) {
|
|
556
|
+
return readJsonRecord(supervisorPaths(directory, taskId).result, terminalRecordProblem(taskId));
|
|
557
|
+
}
|
|
558
|
+
/** First terminal writer wins; a later write can never turn evidence into a different outcome. */
|
|
559
|
+
export function writeTerminalRecord(directory, record) {
|
|
560
|
+
return writeTextExclusive(supervisorPaths(directory, record.taskId).result, `${JSON.stringify(record, null, 2)}\n`);
|
|
561
|
+
}
|
|
562
|
+
function lostRecordProblem(taskId) {
|
|
563
|
+
return (value) => {
|
|
564
|
+
if (!isObject(value))
|
|
565
|
+
return "lost record must be an object";
|
|
566
|
+
if (value.version !== SUPERVISOR_RECORD_VERSION)
|
|
567
|
+
return "unsupported lost record version";
|
|
568
|
+
if (value.taskId !== taskId)
|
|
569
|
+
return "lost record taskId mismatch";
|
|
570
|
+
if (value.status !== "lost")
|
|
571
|
+
return "lost record status must be lost";
|
|
572
|
+
if (!nonEmptyString(value.reason))
|
|
573
|
+
return "lost record reason is missing";
|
|
574
|
+
return undefined;
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
export function readLostRecord(directory, taskId) {
|
|
578
|
+
return readJsonRecord(supervisorPaths(directory, taskId).lost, lostRecordProblem(taskId));
|
|
579
|
+
}
|
|
580
|
+
export function writeLostRecord(directory, record) {
|
|
581
|
+
return writeTextExclusive(supervisorPaths(directory, record.taskId).lost, `${JSON.stringify(record, null, 2)}\n`);
|
|
582
|
+
}
|
|
583
|
+
function cleanupRecordProblem(taskId) {
|
|
584
|
+
return (value) => {
|
|
585
|
+
if (!isObject(value))
|
|
586
|
+
return "cleanup record must be an object";
|
|
587
|
+
if (value.version !== SUPERVISOR_RECORD_VERSION)
|
|
588
|
+
return "unsupported cleanup record version";
|
|
589
|
+
if (value.taskId !== taskId)
|
|
590
|
+
return "cleanup record taskId mismatch";
|
|
591
|
+
if (!isFiniteNumber(value.at))
|
|
592
|
+
return "cleanup record timestamp is missing";
|
|
593
|
+
if (typeof value.outcome !== "string")
|
|
594
|
+
return "cleanup record outcome is missing";
|
|
595
|
+
return undefined;
|
|
596
|
+
};
|
|
597
|
+
}
|
|
598
|
+
export function readCleanupRecord(directory, taskId) {
|
|
599
|
+
return readJsonRecord(supervisorPaths(directory, taskId).cleanup, cleanupRecordProblem(taskId)).value;
|
|
600
|
+
}
|
|
601
|
+
/** Latest explicit-stop cleanup wins; this is evidence about an action, not a verdict. */
|
|
602
|
+
export function writeCleanupRecord(directory, record) {
|
|
603
|
+
writeTextAtomic(supervisorPaths(directory, record.taskId).cleanup, `${JSON.stringify(record, null, 2)}\n`);
|
|
604
|
+
}
|