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.
Files changed (84) hide show
  1. package/package.json +3 -3
  2. package/scripts/measure-shared-reads/daemon.mjs +7 -0
  3. package/scripts/measure-shared-reads/probe.mjs +10 -0
  4. package/scripts/measure-shared-reads.mjs +145 -0
  5. package/scripts/test-on-pi.sh +19 -2
  6. package/src/cli.ts +39 -2
  7. package/src/client.ts +9 -4
  8. package/src/daemon-owner.ts +47 -6
  9. package/src/handshake.ts +8 -7
  10. package/src/lifecycle-config.ts +4 -0
  11. package/src/paths.ts +1 -11
  12. package/src/protocol.ts +5 -0
  13. package/src/registry.ts +2 -1
  14. package/src/runtime/background-history.ts +241 -0
  15. package/src/runtime/background.ts +173 -0
  16. package/src/runtime/cancellation.ts +95 -0
  17. package/src/runtime/client.ts +111 -0
  18. package/src/runtime/domain/assignment-observation.d.mts +1 -0
  19. package/src/runtime/domain/assignment-observation.mjs +103 -0
  20. package/src/runtime/domain/assignment-projection.d.mts +1 -0
  21. package/src/runtime/domain/assignment-projection.mjs +245 -0
  22. package/src/runtime/domain/background/conditions.mjs +93 -0
  23. package/src/runtime/domain/background/process-identity.mjs +110 -0
  24. package/src/runtime/domain/background/process.mjs +511 -0
  25. package/src/runtime/domain/background/registry.mjs +374 -0
  26. package/src/runtime/domain/background/snapshot.mjs +73 -0
  27. package/src/runtime/domain/background/supervisor/identity.mjs +92 -0
  28. package/src/runtime/domain/background/supervisor/invocation.mjs +29 -0
  29. package/src/runtime/domain/background/supervisor/store.mjs +604 -0
  30. package/src/runtime/domain/background/supervisor/supervisor.mjs +720 -0
  31. package/src/runtime/domain/background/supervisor/types.mjs +47 -0
  32. package/src/runtime/domain/background/terminal-publication.mjs +58 -0
  33. package/src/runtime/domain/background/types.mjs +3 -0
  34. package/src/runtime/domain/coordinator/index.mjs +50 -0
  35. package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +160 -0
  36. package/src/runtime/domain/coordinator/src/discovery.mjs +85 -0
  37. package/src/runtime/domain/coordinator/src/errors.mjs +12 -0
  38. package/src/runtime/domain/coordinator/src/operations.mjs +299 -0
  39. package/src/runtime/domain/coordinator/src/outbox.mjs +282 -0
  40. package/src/runtime/domain/coordinator/src/recovery.mjs +51 -0
  41. package/src/runtime/domain/coordinator/src/rows.mjs +277 -0
  42. package/src/runtime/domain/coordinator/src/schema.mjs +351 -0
  43. package/src/runtime/domain/coordinator/src/sqlite.mjs +193 -0
  44. package/src/runtime/domain/coordinator/src/store.mjs +235 -0
  45. package/src/runtime/domain/coordinator/src/task-cancellation.mjs +187 -0
  46. package/src/runtime/domain/coordinator/src/types.mjs +24 -0
  47. package/src/runtime/domain/coordinator/src/validate.mjs +233 -0
  48. package/src/runtime/domain/coordinator/src/waits.mjs +850 -0
  49. package/src/runtime/domain/health-observation.d.mts +3 -0
  50. package/src/runtime/domain/health-observation.mjs +613 -0
  51. package/src/runtime/domain/health-surface.mjs +279 -0
  52. package/src/runtime/domain/log-cursor.mjs +148 -0
  53. package/src/runtime/domain/log-paths.mjs +13 -0
  54. package/src/runtime/domain/parse.d.mts +2 -0
  55. package/src/runtime/domain/parse.mjs +1173 -0
  56. package/src/runtime/domain/process-status.d.mts +1 -0
  57. package/src/runtime/domain/process-status.mjs +25 -0
  58. package/src/runtime/domain/session-store.d.mts +2 -0
  59. package/src/runtime/domain/session-store.mjs +489 -0
  60. package/src/runtime/domain/shared-harness-settings.d.mts +1 -0
  61. package/src/runtime/domain/shared-harness-settings.mjs +126 -0
  62. package/src/runtime/domain/shared-log-utils.mjs +1223 -0
  63. package/src/runtime/domain/shared-stall-detector.mjs +37 -0
  64. package/src/runtime/domain/widget.d.mts +1 -0
  65. package/src/runtime/domain/widget.mjs +250 -0
  66. package/src/runtime/guardian.ts +189 -0
  67. package/src/runtime/health-config.ts +27 -0
  68. package/src/runtime/local-client.ts +34 -0
  69. package/src/runtime/queries.ts +76 -0
  70. package/src/runtime/query-executor.ts +228 -0
  71. package/src/runtime/query-worker.mjs +118 -0
  72. package/src/runtime/read-model.ts +357 -0
  73. package/src/runtime/root.ts +29 -0
  74. package/src/runtime/socket.ts +10 -0
  75. package/src/runtime/status-cli.ts +11 -0
  76. package/src/runtime/work-client.d.mts +13 -0
  77. package/src/runtime/work-client.mjs +88 -0
  78. package/src/server.ts +136 -12
  79. package/src/session-activity.ts +22 -2
  80. package/src/shared-ssh-core/index.ts +30 -1
  81. package/src/startup/activation.ts +32 -5
  82. package/src/startup/ensure.ts +13 -1
  83. package/src/startup/install.ts +2 -0
  84. package/src/version.ts +4 -0
@@ -0,0 +1,720 @@
1
+ /**
2
+ * Caller-side API for detached local supervision: `start`, `inspect`, `stop`.
3
+ *
4
+ * What this module owns:
5
+ * - the immutable launch record, written before any execution and never edited;
6
+ * - a task id derived from the caller's token, so one token names one execution;
7
+ * - spawning the runner as an independent process group;
8
+ * - reconciliation from durable evidence (claim, result, lost) instead of from
9
+ * the caller's memory.
10
+ *
11
+ * What it deliberately does not own: admission and sandbox confinement. The
12
+ * caller passes an already-admitted executable argv; this module executes it
13
+ * verbatim and never widens permission or bypasses a sandbox wrapper. No
14
+ * environment values are persisted — the runner inherits the launch environment.
15
+ *
16
+ * Every ambiguity resolves towards *not executing again*: a launch with a
17
+ * missing claim is reported and reconciled, never retried, and a runner that
18
+ * disappeared without terminal evidence is `lost`, not successful.
19
+ */
20
+ import { spawn } from "node:child_process";
21
+ import { closeSync, openSync, statSync } from "node:fs";
22
+ import { tmpdir } from "node:os";
23
+ import { join, resolve } from "node:path";
24
+ import { setTimeout as delay } from "node:timers/promises";
25
+ import { validateCondition } from "../conditions.mjs";
26
+ import { stopProcessGroup } from "../process.mjs";
27
+ import { identityAlive, identityAllowsSignals, processGroupAlive, readStartToken, verifyProcessIdentity } from "./identity.mjs";
28
+ import { supervisorRunnerInvocation } from "./invocation.mjs";
29
+ import { appendEvent, ensureSupervisorTaskDir, launchRequestHash, readClaimRecord, readCleanupRecord, readCommandRecord, readLaunchRecord, readLostRecord, readStopRequest, readTerminalRecord, resolveSupervisorDirectory, supervisorPaths, supervisorTaskIdForToken, SupervisorFenceBusyError, withStateFence, writeCleanupRecord, writeLaunchRecord, writeLostRecord, writeStopRequest, writeTerminalRecord, } from "./store.mjs";
30
+ import { DEFAULT_CLAIM_GRACE_MS, DEFAULT_CLAIM_WAIT_MS, DEFAULT_MAX_LOG_BYTES, DEFAULT_STOP_WAIT_MS, DEFAULT_WATCH_INTERVAL_MS, DEFAULT_WATCH_TIMEOUT_MS, SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS, SUPERVISOR_INSPECT_FENCE_WAIT_MS, SUPERVISOR_POLL_MS, SUPERVISOR_RECORD_VERSION, SUPERVISOR_TERMINATION_GRACE_MS, } from "./types.mjs";
31
+ /** Default durable directory: beside this package's runtime task registry, not inside a log sweep. */
32
+ export function defaultSupervisorDirectory() {
33
+ const pool = process.env.VITEST_POOL_ID;
34
+ const root = pool && /^\d+$/.test(pool)
35
+ ? `pi-better-background-tasks-vitest-${pool}`
36
+ : "pi-better-background-tasks";
37
+ return join(tmpdir(), root, "supervisor");
38
+ }
39
+ function tokenProblem(token) {
40
+ if (typeof token !== "string" || token.length === 0)
41
+ return "token must be a non-empty string";
42
+ if (token.length > 512)
43
+ return "token must be at most 512 characters";
44
+ if (/[\0\r\n]/.test(token))
45
+ return "token must not contain NUL or line breaks";
46
+ return undefined;
47
+ }
48
+ function optionalText(value, name, max) {
49
+ if (value === undefined || value === null)
50
+ return undefined;
51
+ if (typeof value !== "string")
52
+ throw new Error(`${name} must be a string`);
53
+ const text = value.trim();
54
+ if (text.length === 0)
55
+ return undefined;
56
+ return text.length > max ? text.slice(0, max) : text;
57
+ }
58
+ /** Seconds to milliseconds; `0` disables an optional whole-task deadline, as in Background tasks. */
59
+ function secondsToMs(value, name, options) {
60
+ if (value === undefined || value === null)
61
+ return undefined;
62
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) {
63
+ throw new Error(`${name} must be a non-negative number of seconds`);
64
+ }
65
+ if (value === 0) {
66
+ if (options.allowZero)
67
+ return undefined;
68
+ throw new Error(`${name} must be greater than 0`);
69
+ }
70
+ return Math.max(1, Math.round(value * 1000));
71
+ }
72
+ function validatedArgv(argv) {
73
+ if (!Array.isArray(argv) || argv.length === 0)
74
+ throw new Error("argv must be a non-empty array");
75
+ return argv.map((entry, index) => {
76
+ if (typeof entry !== "string" || entry.length === 0)
77
+ throw new Error(`argv[${index}] must be a non-empty string`);
78
+ if (entry.includes("\0"))
79
+ throw new Error(`argv[${index}] must not contain a NUL byte`);
80
+ return entry;
81
+ });
82
+ }
83
+ function validatedCwd(cwd) {
84
+ const resolved = resolve(typeof cwd === "string" && cwd.length > 0 ? cwd : process.cwd());
85
+ let isDirectory = false;
86
+ try {
87
+ isDirectory = statSync(resolved).isDirectory();
88
+ }
89
+ catch {
90
+ isDirectory = false;
91
+ }
92
+ if (!isDirectory)
93
+ throw new Error(`cwd does not exist or is not a directory: ${resolved}`);
94
+ return resolved;
95
+ }
96
+ /**
97
+ * Build and validate the immutable launch record. Everything is checked before
98
+ * any record, directory or process exists, so a refused launch leaves nothing
99
+ * behind — the same rule the Background tasks launcher follows.
100
+ */
101
+ function buildLaunchRecord(directory, options) {
102
+ const tokenProblemText = tokenProblem(options.token);
103
+ if (tokenProblemText)
104
+ throw new Error(tokenProblemText);
105
+ const argv = validatedArgv(options.argv);
106
+ const cwd = validatedCwd(options.cwd);
107
+ const kind = options.kind ?? "process";
108
+ if (kind !== "process" && kind !== "watch")
109
+ throw new Error(`kind must be "process" or "watch", not ${JSON.stringify(kind)}`);
110
+ const commandTimeoutMs = secondsToMs(options.commandTimeoutSeconds, "commandTimeoutSeconds", { allowZero: false });
111
+ // A watch keeps the Background tasks default lifetime unless the caller says
112
+ // otherwise; `0` explicitly disables that deadline instead of silently restoring it.
113
+ const taskTimeoutMs = kind === "watch"
114
+ ? (options.timeoutSeconds === undefined
115
+ ? DEFAULT_WATCH_TIMEOUT_MS
116
+ : secondsToMs(options.timeoutSeconds, "timeoutSeconds", { allowZero: true }))
117
+ : secondsToMs(options.timeoutSeconds, "timeoutSeconds", { allowZero: true });
118
+ const intervalMs = kind === "watch"
119
+ ? (secondsToMs(options.intervalSeconds, "intervalSeconds", { allowZero: false }) ?? DEFAULT_WATCH_INTERVAL_MS)
120
+ : undefined;
121
+ if (kind === "process" && options.intervalSeconds !== undefined) {
122
+ throw new Error("intervalSeconds is a watch cadence; a process launch has no poll loop");
123
+ }
124
+ if (kind === "process" && (options.successWhen !== undefined || options.failureWhen !== undefined)) {
125
+ throw new Error("successWhen/failureWhen belong to a watch; a process launch reports its own exit code");
126
+ }
127
+ if (kind === "watch" && options.successWhen === undefined) {
128
+ throw new Error("A watch launch requires successWhen: the condition that ends it as succeeded");
129
+ }
130
+ for (const [name, condition] of [["successWhen", options.successWhen], ["failureWhen", options.failureWhen]]) {
131
+ if (condition === undefined)
132
+ continue;
133
+ const invalid = validateCondition(condition);
134
+ if (invalid)
135
+ throw new Error(`${name}: ${invalid}`);
136
+ }
137
+ const maxLogBytes = options.maxLogBytes === undefined
138
+ ? DEFAULT_MAX_LOG_BYTES
139
+ : options.maxLogBytes;
140
+ if (typeof maxLogBytes !== "number" || !Number.isInteger(maxLogBytes) || maxLogBytes <= 0) {
141
+ throw new Error("maxLogBytes must be a positive integer");
142
+ }
143
+ const request = {
144
+ kind,
145
+ command: { argv, cwd },
146
+ ...(commandTimeoutMs === undefined ? {} : { commandTimeoutMs }),
147
+ ...(taskTimeoutMs === undefined ? {} : { taskTimeoutMs }),
148
+ ...(intervalMs === undefined ? {} : { intervalMs }),
149
+ ...(options.successWhen === undefined ? {} : { successWhen: options.successWhen }),
150
+ ...(options.failureWhen === undefined ? {} : { failureWhen: options.failureWhen }),
151
+ maxLogBytes,
152
+ };
153
+ const taskId = supervisorTaskIdForToken(options.token);
154
+ const name = optionalText(options.name, "name", 200);
155
+ const operationId = optionalText(options.operationId, "operationId", 200);
156
+ const record = {
157
+ version: SUPERVISOR_RECORD_VERSION,
158
+ taskId,
159
+ token: options.token,
160
+ kind,
161
+ command: { argv, cwd },
162
+ requestHash: launchRequestHash(request),
163
+ createdAt: Date.now(),
164
+ ...(commandTimeoutMs === undefined ? {} : { commandTimeoutMs }),
165
+ ...(taskTimeoutMs === undefined ? {} : { taskTimeoutMs }),
166
+ ...(intervalMs === undefined ? {} : { intervalMs }),
167
+ ...(options.successWhen === undefined ? {} : { successWhen: options.successWhen }),
168
+ ...(options.failureWhen === undefined ? {} : { failureWhen: options.failureWhen }),
169
+ maxLogBytes,
170
+ environment: "inherited",
171
+ ...(name === undefined ? {} : { name }),
172
+ ...(operationId === undefined ? {} : { operationId }),
173
+ };
174
+ return record;
175
+ }
176
+ function oneLine(text) {
177
+ return text.replace(/\s+/g, " ").trim();
178
+ }
179
+ function launchSummary(record) {
180
+ return {
181
+ taskId: record.taskId,
182
+ token: record.token,
183
+ kind: record.kind,
184
+ ...(record.name === undefined ? {} : { name: record.name }),
185
+ ...(record.operationId === undefined ? {} : { operationId: record.operationId }),
186
+ createdAt: record.createdAt,
187
+ argv: record.command.argv,
188
+ cwd: record.command.cwd,
189
+ ...(record.commandTimeoutMs === undefined ? {} : { commandTimeoutSeconds: record.commandTimeoutMs / 1000 }),
190
+ ...(record.taskTimeoutMs === undefined ? {} : { timeoutSeconds: record.taskTimeoutMs / 1000 }),
191
+ ...(record.intervalMs === undefined ? {} : { intervalSeconds: record.intervalMs / 1000 }),
192
+ ...(record.successWhen === undefined ? {} : { successWhen: record.successWhen }),
193
+ ...(record.failureWhen === undefined ? {} : { failureWhen: record.failureWhen }),
194
+ requestHash: record.requestHash,
195
+ };
196
+ }
197
+ class Supervisor {
198
+ directory;
199
+ runnerPath;
200
+ claimWaitMs;
201
+ readToken;
202
+ constructor(options) {
203
+ this.directory = resolveSupervisorDirectory(options.directory);
204
+ this.runnerPath = options.runnerPath;
205
+ this.claimWaitMs = options.claimWaitMs ?? DEFAULT_CLAIM_WAIT_MS;
206
+ this.readToken = options.readStartToken ?? readStartToken;
207
+ }
208
+ async start(options) {
209
+ const launch = buildLaunchRecord(this.directory, options);
210
+ const existing = readLaunchRecord(this.directory, launch.taskId);
211
+ if (!existing.missing) {
212
+ if (!existing.value) {
213
+ throw new Error(`The supervisor launch record for ${launch.taskId} is unreadable (${existing.error}); refusing to launch again.`);
214
+ }
215
+ return this.reconcileDuplicate(existing.value, launch);
216
+ }
217
+ if (!writeLaunchRecord(this.directory, launch)) {
218
+ // A concurrent start with the same token won the exclusive create.
219
+ const winner = readLaunchRecord(this.directory, launch.taskId);
220
+ if (!winner.value) {
221
+ throw new Error(`A concurrent launch claimed ${launch.taskId} but its record is unreadable (${winner.error}).`);
222
+ }
223
+ return this.reconcileDuplicate(winner.value, launch);
224
+ }
225
+ return this.spawnRunner(launch, options);
226
+ }
227
+ /**
228
+ * A token can only ever name one request. The same request reports the
229
+ * existing execution; a different request is refused, because executing it
230
+ * would be a second, hidden command under one token.
231
+ */
232
+ reconcileDuplicate(existing, requested) {
233
+ if (existing.requestHash !== requested.requestHash) {
234
+ throw new Error(`Launch token ${JSON.stringify(requested.token)} was already used for a different request (task ${existing.taskId}); `
235
+ + "refusing to execute a second command under one token. Use a new token.");
236
+ }
237
+ const inspection = this.inspect(existing.taskId);
238
+ return {
239
+ taskId: existing.taskId,
240
+ token: existing.token,
241
+ started: false,
242
+ claimed: inspection.claim !== undefined,
243
+ status: inspection.status,
244
+ taskDir: inspection.taskDir,
245
+ inspection,
246
+ };
247
+ }
248
+ async spawnRunner(launch, options) {
249
+ const invocation = supervisorRunnerInvocation(this.directory, launch.taskId, {
250
+ runnerPath: options.runnerPath ?? this.runnerPath,
251
+ });
252
+ const paths = ensureSupervisorTaskDir(this.directory, launch.taskId);
253
+ // The runner's own stdout/stderr land in events.log: a crash before the claim
254
+ // must leave a diagnosable trace, and the runner has no terminal record yet.
255
+ const eventsFd = openSync(paths.events, "a", 0o600);
256
+ let child;
257
+ try {
258
+ child = spawn(invocation.execPath, invocation.args, {
259
+ cwd: launch.command.cwd,
260
+ // Launch environment only: values are inherited, never written to a record.
261
+ env: { ...process.env, ...(options.env ?? {}) },
262
+ detached: true,
263
+ stdio: ["ignore", eventsFd, eventsFd],
264
+ windowsHide: process.platform === "win32",
265
+ });
266
+ }
267
+ finally {
268
+ closeSync(eventsFd);
269
+ }
270
+ child.unref();
271
+ let spawnError;
272
+ let exit;
273
+ child.on("error", (error) => { spawnError = error; });
274
+ child.on("exit", (code, signal) => { exit = { code, signal }; });
275
+ const until = Date.now() + this.claimWaitMs;
276
+ while (Date.now() < until) {
277
+ if (readClaimRecord(this.directory, launch.taskId).value)
278
+ break;
279
+ if (spawnError || exit)
280
+ break;
281
+ await delay(SUPERVISOR_POLL_MS);
282
+ }
283
+ if (spawnError) {
284
+ throw new Error(`The supervisor runner could not start for ${launch.taskId}: ${spawnError.message}. `
285
+ + `The launch record is kept and the token will not execute again. Evidence: ${paths.events}`);
286
+ }
287
+ const inspection = this.inspect(launch.taskId);
288
+ if (!inspection) {
289
+ throw new Error(`The supervisor launch record for ${launch.taskId} disappeared after it was written.`);
290
+ }
291
+ const claimed = inspection.claim !== undefined;
292
+ if (!claimed && exit && !inspection.terminal && exit.code !== 0) {
293
+ throw new Error(`The supervisor runner for ${launch.taskId} exited with code ${exit.code ?? "unknown"} before claiming the launch token; `
294
+ + `no command was executed. The launch record is kept and the token will not execute again. Evidence: ${paths.events}`);
295
+ }
296
+ return {
297
+ taskId: launch.taskId,
298
+ token: launch.token,
299
+ started: true,
300
+ claimed,
301
+ status: inspection.status,
302
+ taskDir: inspection.taskDir,
303
+ inspection,
304
+ };
305
+ }
306
+ inspect(taskId, options = {}) {
307
+ const launchRead = readLaunchRecord(this.directory, taskId);
308
+ if (launchRead.missing)
309
+ return undefined;
310
+ if (!launchRead.value) {
311
+ throw new Error(`Unreadable supervisor launch record for ${taskId}: ${launchRead.error}`);
312
+ }
313
+ const launch = launchRead.value;
314
+ const paths = supervisorPaths(this.directory, taskId);
315
+ const result = readTerminalRecord(this.directory, taskId).value;
316
+ const lostRecord = readLostRecord(this.directory, taskId).value;
317
+ const claim = readClaimRecord(this.directory, taskId).value;
318
+ const command = readCommandRecord(this.directory, taskId).value;
319
+ const stop = readStopRequest(this.directory, taskId);
320
+ const cleanup = readCleanupRecord(this.directory, taskId);
321
+ // Reading a process start token spawns `ps`. A task that already published a
322
+ // terminal/lost record cannot change state again, so its liveness only
323
+ // matters to the one caller that may still act on a surviving command group
324
+ // (`stop`). Every other reader would pay for an answer it does not use, once
325
+ // per task per panel frame. Probe only when that authority is actually needed.
326
+ const needsLiveness = result === undefined && lostRecord === undefined
327
+ ? true
328
+ : result !== undefined && result.groupCleanup === "unproven"
329
+ || lostRecord !== undefined;
330
+ // One identity source per instance: liveness and signalling agree.
331
+ const claimAlive = needsLiveness && claim
332
+ ? identityAlive(claim.pid, claim.pidStartTime, claim.claimedAt, this.readToken)
333
+ : false;
334
+ const commandAlive = needsLiveness && command
335
+ ? identityAlive(command.pid, command.pidStartTime, command.startedAt, this.readToken)
336
+ : false;
337
+ // A published terminal/lost record needs no fence. Anything else is decided
338
+ // under the fence, so a `lost` attestation and a claim cannot both win.
339
+ let state;
340
+ if (result) {
341
+ state = { status: result.status, terminal: true, result };
342
+ }
343
+ else if (lostRecord) {
344
+ state = { status: "lost", terminal: true, lost: lostRecord };
345
+ }
346
+ else {
347
+ state = this.reconcile(launch, options);
348
+ }
349
+ // The reconciliation may observe the terminal record the outer read missed.
350
+ const terminalRecord = result ?? state.result;
351
+ return {
352
+ taskId,
353
+ token: launch.token,
354
+ kind: launch.kind,
355
+ status: state.status,
356
+ terminal: state.terminal,
357
+ launch: launchSummary(launch),
358
+ ...(claim === undefined
359
+ ? {}
360
+ : { claim: { pid: claim.pid, pidStartTime: claim.pidStartTime, claimedAt: claim.claimedAt, alive: claimAlive } }),
361
+ ...(command === undefined
362
+ ? {}
363
+ : {
364
+ command: {
365
+ pid: command.pid,
366
+ pgid: command.pgid,
367
+ pidStartTime: command.pidStartTime,
368
+ startedAt: command.startedAt,
369
+ attempt: command.attempt ?? 1,
370
+ alive: commandAlive,
371
+ },
372
+ }),
373
+ ...(terminalRecord === undefined ? {} : { result: terminalRecord }),
374
+ ...(state.lost === undefined ? {} : { lost: state.lost }),
375
+ ...(cleanup === undefined ? {} : { cleanup }),
376
+ ...(state.fenceBusy === true ? { fenceBusy: true } : {}),
377
+ ...(stop === undefined ? {} : { stopRequestedAt: stop.requestedAt }),
378
+ taskDir: paths.dir,
379
+ logs: { stdout: paths.stdout, stderr: paths.stderr, events: paths.events },
380
+ observedAt: Date.now(),
381
+ };
382
+ }
383
+ /**
384
+ * Read-only projection for rendering: no fence, no lost publication, no `ps`.
385
+ *
386
+ * `inspect` is the authoritative path and pays for that authority — a
387
+ * cross-process SQLite fence and a process-identity probe per recorded pid.
388
+ * A panel asks per task per frame, so it reads what the records already say.
389
+ */
390
+ snapshot(taskId) {
391
+ const launchRead = readLaunchRecord(this.directory, taskId);
392
+ if (launchRead.missing)
393
+ return undefined;
394
+ if (!launchRead.value) {
395
+ throw new Error(`Unreadable supervisor launch record for ${taskId}: ${launchRead.error}`);
396
+ }
397
+ const launch = launchRead.value;
398
+ const paths = supervisorPaths(this.directory, taskId);
399
+ const result = readTerminalRecord(this.directory, taskId).value;
400
+ const lostRecord = readLostRecord(this.directory, taskId).value;
401
+ const claim = readClaimRecord(this.directory, taskId).value;
402
+ const command = readCommandRecord(this.directory, taskId).value;
403
+ const stop = readStopRequest(this.directory, taskId);
404
+ const cleanup = readCleanupRecord(this.directory, taskId);
405
+ const status = result
406
+ ? result.status
407
+ : lostRecord
408
+ ? "lost"
409
+ : claim
410
+ ? "running"
411
+ : "starting";
412
+ return {
413
+ taskId,
414
+ token: launch.token,
415
+ kind: launch.kind,
416
+ status,
417
+ terminal: result !== undefined || lostRecord !== undefined,
418
+ launch: launchSummary(launch),
419
+ // Liveness is deliberately not asserted here: a snapshot never spawns `ps`.
420
+ ...(claim === undefined
421
+ ? {}
422
+ : { claim: { pid: claim.pid, pidStartTime: claim.pidStartTime, claimedAt: claim.claimedAt, alive: false } }),
423
+ ...(command === undefined
424
+ ? {}
425
+ : {
426
+ command: {
427
+ pid: command.pid,
428
+ pgid: command.pgid,
429
+ pidStartTime: command.pidStartTime,
430
+ startedAt: command.startedAt,
431
+ attempt: command.attempt ?? 1,
432
+ alive: false,
433
+ },
434
+ }),
435
+ ...(result === undefined ? {} : { result }),
436
+ ...(lostRecord === undefined ? {} : { lost: lostRecord }),
437
+ ...(cleanup === undefined ? {} : { cleanup }),
438
+ ...(stop === undefined ? {} : { stopRequestedAt: stop.requestedAt }),
439
+ taskDir: paths.dir,
440
+ logs: { stdout: paths.stdout, stderr: paths.stderr, events: paths.events },
441
+ observedAt: Date.now(),
442
+ };
443
+ }
444
+ /**
445
+ * Decide the state of a launch with no terminal result, under the cross-process
446
+ * fence. This is the only place a `lost` record is published, so it can never
447
+ * race a claim into "lost and executed".
448
+ */
449
+ reconcile(launch, options) {
450
+ let transition;
451
+ try {
452
+ transition = this.applyReconciliation(launch, options);
453
+ }
454
+ catch (error) {
455
+ if (!(error instanceof SupervisorFenceBusyError))
456
+ throw error;
457
+ // Never steal a fence to publish a loss. Report the unreconciled state so a
458
+ // later inspection (after the holder releases) can record it.
459
+ const claim = readClaimRecord(this.directory, launch.taskId).value;
460
+ return { status: claim === undefined ? "starting" : "running", terminal: false, fenceBusy: true };
461
+ }
462
+ return transition;
463
+ }
464
+ applyReconciliation(launch, options) {
465
+ return withStateFence(this.directory, launch.taskId, () => {
466
+ const result = readTerminalRecord(this.directory, launch.taskId).value;
467
+ if (result)
468
+ return { status: result.status, terminal: true, result };
469
+ const existingLost = readLostRecord(this.directory, launch.taskId).value;
470
+ if (existingLost)
471
+ return { status: "lost", terminal: true, lost: existingLost };
472
+ const claim = readClaimRecord(this.directory, launch.taskId).value;
473
+ if (claim) {
474
+ if (identityAlive(claim.pid, claim.pidStartTime, claim.claimedAt, this.readToken)) {
475
+ return { status: "running", terminal: false };
476
+ }
477
+ return { status: "lost", terminal: true, lost: this.publishLost(launch, claim, options) };
478
+ }
479
+ const graceMs = options.claimGraceMs ?? DEFAULT_CLAIM_GRACE_MS;
480
+ if (Date.now() - launch.createdAt < graceMs) {
481
+ // A runner may still be starting. Never launch again on this token.
482
+ return { status: "starting", terminal: false };
483
+ }
484
+ return { status: "lost", terminal: true, lost: this.publishLost(launch, undefined, options) };
485
+ }, { waitMs: options.fenceWaitMs ?? SUPERVISOR_INSPECT_FENCE_WAIT_MS });
486
+ }
487
+ /** Caller of {@link reconcile}'s fence; records why the evidence is gone. */
488
+ publishLost(launch, claim, options) {
489
+ const reason = claim === undefined
490
+ ? `no runner claimed the launch token within ${options.claimGraceMs ?? DEFAULT_CLAIM_GRACE_MS}ms of the launch; `
491
+ + "no command execution was witnessed and the launch will not be retried"
492
+ : `the runner (pid ${claim.pid}) exited without recording a terminal result`;
493
+ const record = {
494
+ version: SUPERVISOR_RECORD_VERSION,
495
+ taskId: launch.taskId,
496
+ token: launch.token,
497
+ status: "lost",
498
+ reason,
499
+ recordedAt: Date.now(),
500
+ ...(claim === undefined ? {} : { runner: { pid: claim.pid, pidStartTime: claim.pidStartTime } }),
501
+ };
502
+ if (options.recordLost === false)
503
+ return record;
504
+ writeLostRecord(this.directory, record);
505
+ // Another observer may have recorded the same loss first; return the durable one.
506
+ return readLostRecord(this.directory, launch.taskId).value ?? record;
507
+ }
508
+ async inspectionAfter(taskId, waitMs) {
509
+ const until = Date.now() + waitMs;
510
+ let inspection = this.inspect(taskId);
511
+ while (!inspection.terminal && Date.now() < until) {
512
+ await delay(SUPERVISOR_POLL_MS);
513
+ inspection = this.inspect(taskId);
514
+ }
515
+ return inspection;
516
+ }
517
+ /**
518
+ * Stop a supervised task.
519
+ *
520
+ * The durable stop request is what reaches the runner; nothing is signalled
521
+ * from here on a guess. When the task already ended `lost`, a surviving
522
+ * command is cleaned only if its identity is provable, and the lost evidence
523
+ * is never replaced. Unknown identity is refused rather than signalled.
524
+ */
525
+ async stop(taskId, options = {}) {
526
+ const launchRead = readLaunchRecord(this.directory, taskId);
527
+ if (launchRead.missing)
528
+ return undefined;
529
+ if (!launchRead.value) {
530
+ throw new Error(`Unreadable supervisor launch record for ${taskId}: ${launchRead.error}`);
531
+ }
532
+ const launch = launchRead.value;
533
+ if (options.token !== undefined && options.token !== launch.token) {
534
+ throw new Error(`Refusing to stop ${taskId}: the supplied token does not match the launch token.`);
535
+ }
536
+ let inspection = this.inspect(taskId);
537
+ if (inspection.terminal) {
538
+ // A terminal record whose group cleanup was not proven may still have a
539
+ // live command. An explicit stop may clean it with a verified identity, and
540
+ // the recorded verdict (lost, cancelled, timed_out) is never rewritten.
541
+ const leftoverGroup = inspection.command?.alive === true
542
+ && (inspection.status === "lost" || inspection.result?.groupCleanup === "unproven");
543
+ if (leftoverGroup) {
544
+ const cleanup = await this.cleanupSurvivingCommand(launch, inspection, options);
545
+ inspection = this.inspect(taskId);
546
+ return { taskId, status: inspection.status, terminal: true, stopRequested: false, cleanup, inspection };
547
+ }
548
+ return { taskId, status: inspection.status, terminal: true, stopRequested: false, inspection };
549
+ }
550
+ // A durable request works across processes and survives the caller exiting.
551
+ writeStopRequest(this.directory, {
552
+ version: SUPERVISOR_RECORD_VERSION,
553
+ taskId,
554
+ token: launch.token,
555
+ requestedAt: Date.now(),
556
+ ...(options.reason === undefined ? {} : { reason: options.reason }),
557
+ });
558
+ inspection = await this.inspectionAfter(taskId, options.waitMs ?? DEFAULT_STOP_WAIT_MS);
559
+ if (!inspection.terminal && inspection.command?.alive) {
560
+ // The runner normally acts on the request itself. Only a provable identity
561
+ // may be signalled from here.
562
+ const cleanup = await this.cleanupSurvivingCommand(launch, inspection, options);
563
+ inspection = await this.inspectionAfter(taskId, SUPERVISOR_TERMINATION_GRACE_MS);
564
+ if (!inspection.terminal && (cleanup.outcome === "killed" || cleanup.groupEmpty === true)) {
565
+ inspection = this.publishSupervisorCancellation(launch, inspection, cleanup, options.reason);
566
+ }
567
+ if (inspection.terminal) {
568
+ return { taskId, status: inspection.status, terminal: true, stopRequested: true, cleanup, inspection };
569
+ }
570
+ return { taskId, status: inspection.status, terminal: false, stopRequested: true, cleanup, inspection };
571
+ }
572
+ if (inspection.terminal) {
573
+ return { taskId, status: inspection.status, terminal: true, stopRequested: true, inspection };
574
+ }
575
+ if (inspection.claim === undefined && inspection.command === undefined) {
576
+ // Nothing was witnessed running: cancellation is provable without a signal.
577
+ inspection = this.publishSupervisorCancellation(launch, inspection, undefined, options.reason);
578
+ return { taskId, status: inspection.status, terminal: inspection.terminal, stopRequested: true, inspection };
579
+ }
580
+ // A claimed runner has not spawned yet. The stop request is durable and the
581
+ // runner checks it before executing; report the observation instead of
582
+ // inventing a terminal state.
583
+ return { taskId, status: inspection.status, terminal: false, stopRequested: true, inspection };
584
+ }
585
+ /**
586
+ * Kill a surviving command group from outside the runner, only with a provable
587
+ * identity, and record what happened in `cleanup.json`.
588
+ *
589
+ * The lost/terminal evidence is untouched: this is a cleanup fact, not a new
590
+ * verdict, and it can never turn a `lost` task into a success.
591
+ */
592
+ async cleanupSurvivingCommand(launch, inspection, options) {
593
+ const command = inspection.command;
594
+ const pgid = command.pgid ?? command.pid;
595
+ const verdict = verifyProcessIdentity(command.pid, command.pidStartTime, this.readToken);
596
+ const signals = [];
597
+ let groupEmpty;
598
+ let outcome;
599
+ if (!identityAllowsSignals(verdict)) {
600
+ // Unknown identity cannot authorize an external signal. A recorded process
601
+ // that is gone is only "already gone" when its group is gone too; survivors
602
+ // in a group whose leader died cannot be verified, so they are refused.
603
+ const groupStillAlive = processGroupAlive(pgid);
604
+ outcome = (verdict === "dead" || verdict === "absent") && !groupStillAlive ? "already-gone" : "refused-unknown-identity";
605
+ groupEmpty = outcome === "already-gone" ? true : false;
606
+ }
607
+ else {
608
+ /**
609
+ * Every group signal re-verifies the leader first. Once the leader is gone
610
+ * the pgid is only addressable evidence that *a* group exists, so an
611
+ * external escalation is refused and the cleanup is reported unproven.
612
+ */
613
+ let signalledWhileVerified = false;
614
+ const signalGroup = (signal) => {
615
+ const current = verifyProcessIdentity(command.pid, command.pidStartTime, this.readToken);
616
+ if (!identityAllowsSignals(current))
617
+ return false;
618
+ try {
619
+ stopProcessGroup(command.pid, pgid, signal);
620
+ signals.push(signal);
621
+ signalledWhileVerified = true;
622
+ return true;
623
+ }
624
+ catch {
625
+ return false;
626
+ }
627
+ };
628
+ signalGroup("SIGTERM");
629
+ const termDeadline = Date.now() + SUPERVISOR_TERMINATION_GRACE_MS;
630
+ while (Date.now() < termDeadline && processGroupAlive(pgid)) {
631
+ await delay(25);
632
+ }
633
+ if (processGroupAlive(pgid))
634
+ signalGroup("SIGKILL");
635
+ const killDeadline = Date.now() + SUPERVISOR_GROUP_CLEANUP_DEADLINE_MS;
636
+ while (Date.now() < killDeadline && processGroupAlive(pgid)) {
637
+ await delay(25);
638
+ }
639
+ groupEmpty = !processGroupAlive(pgid);
640
+ outcome = !groupEmpty ? "unproven" : signalledWhileVerified ? "killed" : "already-gone";
641
+ }
642
+ const reason = outcome === "killed"
643
+ ? `stopped the surviving command group ${pgid}`
644
+ : outcome === "already-gone"
645
+ ? "the recorded command and its process group are already gone"
646
+ : outcome === "refused-unknown-identity"
647
+ ? `refused to signal process group ${pgid}: its recorded leader cannot be verified, so its members cannot be proven to be this task's`
648
+ : "cleanup did not prove the process group empty";
649
+ const record = {
650
+ version: SUPERVISOR_RECORD_VERSION,
651
+ taskId: launch.taskId,
652
+ token: launch.token,
653
+ at: Date.now(),
654
+ outcome,
655
+ identity: verdict,
656
+ signals,
657
+ ...(groupEmpty === undefined ? {} : { groupEmpty }),
658
+ pid: command.pid,
659
+ pgid,
660
+ reason: options.reason ? `${reason} (${options.reason})` : reason,
661
+ };
662
+ writeCleanupRecord(this.directory, record);
663
+ appendEvent(inspection.logs.events, `cleanup outcome=${outcome} identity=${verdict} signals=[${signals.join(",")}] group_empty=${groupEmpty ?? "unknown"}`);
664
+ return record;
665
+ }
666
+ /**
667
+ * Publish a cancellation only when nothing is left running: no claim and no
668
+ * command (nothing executed), or a group that a verified cleanup proved empty.
669
+ * A supervisor attestation is never used to replace a lost record.
670
+ */
671
+ publishSupervisorCancellation(launch, inspection, cleanup, reasonOverride) {
672
+ const reason = reasonOverride ?? (inspection.claim === undefined && inspection.command === undefined
673
+ ? "stop requested before a runner claimed the launch token; no command was executed"
674
+ : "stopped by the supervisor after proving the command group empty");
675
+ const published = withStateFence(this.directory, launch.taskId, () => {
676
+ if (readTerminalRecord(this.directory, launch.taskId).value)
677
+ return false;
678
+ if (readLostRecord(this.directory, launch.taskId).value)
679
+ return false;
680
+ const record = {
681
+ version: SUPERVISOR_RECORD_VERSION,
682
+ taskId: launch.taskId,
683
+ token: launch.token,
684
+ kind: launch.kind,
685
+ status: "cancelled",
686
+ attestedBy: "supervisor",
687
+ reason,
688
+ exitCode: null,
689
+ signal: null,
690
+ timedOut: false,
691
+ startedAt: launch.createdAt,
692
+ endedAt: Date.now(),
693
+ ...(cleanup === undefined ? {} : { groupCleanup: cleanup.groupEmpty === true ? "empty" : "unproven" }),
694
+ stdoutBytes: 0,
695
+ stderrBytes: 0,
696
+ stdoutDiscardedBytes: 0,
697
+ stderrDiscardedBytes: 0,
698
+ logs: inspection.logs,
699
+ ...(inspection.claim === undefined
700
+ ? {}
701
+ : { runner: { pid: inspection.claim.pid, pidStartTime: inspection.claim.pidStartTime } }),
702
+ ...(inspection.command === undefined
703
+ ? {}
704
+ : { command: { pid: inspection.command.pid, pgid: inspection.command.pgid, pidStartTime: inspection.command.pidStartTime } }),
705
+ };
706
+ // The event line precedes the authoritative record for the same reason the
707
+ // runner writes it first: a visible terminal record implies a visible trace.
708
+ appendEvent(inspection.logs.events, `terminal status=cancelled attested_by=supervisor reason=${oneLine(reason)}`);
709
+ return writeTerminalRecord(this.directory, record);
710
+ });
711
+ if (published)
712
+ return this.inspect(launch.taskId);
713
+ // Lost or a runner result won the race: report the durable evidence as-is.
714
+ return this.inspect(launch.taskId);
715
+ }
716
+ }
717
+ export function createLocalSupervisor(options) {
718
+ return new Supervisor(options);
719
+ }
720
+ export { supervisorTaskIdForToken, supervisorPaths };