@operad-io/engine 0.1.1 → 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 (81) hide show
  1. package/config.schema.json +2 -1
  2. package/package.json +1 -1
  3. package/src/config/config.ts +74 -45
  4. package/src/flow/types.ts +4 -0
  5. package/src/flow/validate.ts +5 -0
  6. package/src/http/index.ts +2 -0
  7. package/src/http/plugins.ts +68 -0
  8. package/src/http/server.ts +342 -48
  9. package/src/kernel/decide.ts +115 -30
  10. package/src/kernel/state.ts +9 -0
  11. package/src/kernel/types.ts +25 -40
  12. package/src/log/open-log.ts +2 -5
  13. package/src/log/sqlite.ts +127 -85
  14. package/src/log/types.ts +35 -9
  15. package/src/loop/code-watch.ts +108 -2
  16. package/src/loop/older-code.ts +3 -4
  17. package/src/loop/serve.ts +122 -95
  18. package/src/notify/notify.ts +2 -6
  19. package/src/platform/atomic-write.ts +163 -0
  20. package/src/platform/file-lock.ts +43 -21
  21. package/src/platform/git-program.ts +108 -0
  22. package/src/platform/index.ts +3 -0
  23. package/src/platform/kept-workers.ts +290 -0
  24. package/src/platform/process-group.ts +11 -3
  25. package/src/platform/sqlite-open.ts +20 -6
  26. package/src/platform/sqlite-schema.ts +30 -0
  27. package/src/platform/step-reap.ts +33 -18
  28. package/src/platform/watch.ts +1 -11
  29. package/src/plugin/action-schema.ts +59 -1
  30. package/src/plugin/choice-info.ts +133 -0
  31. package/src/plugin/context.ts +279 -0
  32. package/src/plugin/declared-flows.ts +3 -10
  33. package/src/plugin/errors.ts +9 -0
  34. package/src/plugin/freeze.ts +12 -0
  35. package/src/plugin/harness.ts +28 -0
  36. package/src/plugin/index.ts +8 -7
  37. package/src/plugin/install.ts +265 -17
  38. package/src/plugin/keys.ts +2 -12
  39. package/src/plugin/load.ts +47 -23
  40. package/src/plugin/logger.ts +14 -0
  41. package/src/plugin/open-store.ts +0 -6
  42. package/src/plugin/question-form.ts +323 -0
  43. package/src/plugin/registry.ts +519 -76
  44. package/src/plugin/secrets.ts +14 -24
  45. package/src/plugin/semver.ts +52 -0
  46. package/src/plugin/settings.ts +1 -9
  47. package/src/plugin/sqlite-store.ts +94 -64
  48. package/src/plugin/store.ts +5 -0
  49. package/src/plugin/types.ts +575 -21
  50. package/src/plugin/validate.ts +402 -26
  51. package/src/runner/answer.ts +26 -68
  52. package/src/runner/ask.ts +227 -28
  53. package/src/runner/cancel.ts +10 -7
  54. package/src/runner/grants.ts +2 -2
  55. package/src/runner/index.ts +1 -3
  56. package/src/runner/limits.ts +2 -2
  57. package/src/runner/runner.ts +15 -14
  58. package/src/runner/service.ts +52 -19
  59. package/src/runner/step-worker.ts +9 -0
  60. package/src/testing/answer.ts +69 -0
  61. package/src/testing/clock-manual.ts +152 -0
  62. package/src/testing/config.ts +16 -0
  63. package/src/testing/fs.ts +172 -0
  64. package/src/testing/home.ts +43 -0
  65. package/src/testing/index.ts +19 -0
  66. package/src/testing/types.ts +2 -0
  67. package/src/testing/world.ts +9 -2
  68. package/src/trigger/kernel.ts +13 -46
  69. package/src/trigger/rules.ts +22 -12
  70. package/src/trigger/types.ts +2 -6
  71. package/src/util.ts +99 -0
  72. package/src/views/event-line.ts +22 -0
  73. package/src/views/history.ts +36 -19
  74. package/src/views/live-logs.ts +313 -0
  75. package/src/views/pending.ts +23 -5
  76. package/src/views/presentation.ts +629 -81
  77. package/src/views/running.ts +5 -5
  78. package/src/views/settings.ts +205 -66
  79. package/src/views/types.ts +8 -2
  80. package/src/views/uploads.ts +15 -7
  81. package/triggers.schema.json +4 -0
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { dlopen, FFIType } from "bun:ffi";
13
+ import { errorCode, isMissingFile, isRecord } from "../util.ts";
13
14
  import { randomBytes } from "node:crypto";
14
15
  import {
15
16
  closeSync,
@@ -125,6 +126,8 @@ export interface LockFileOptions {
125
126
  readonly onLog?: ((message: string) => void) | undefined;
126
127
  /** Names the lock in log lines; defaults to `lock`. */
127
128
  readonly label?: string | undefined;
129
+ /** How long to wait for a live holder; defaults to `LOCK_TIMEOUT_MS`. */
130
+ readonly timeoutMs?: number | undefined;
128
131
  }
129
132
 
130
133
  /**
@@ -148,12 +151,6 @@ interface LockFile {
148
151
  readonly record: LockRecord | undefined;
149
152
  }
150
153
 
151
- function errorCode(error: unknown): unknown {
152
- return typeof error === "object" && error !== null && "code" in error
153
- ? error.code
154
- : undefined;
155
- }
156
-
157
154
  function newNonce(): string {
158
155
  return randomBytes(16).toString("hex");
159
156
  }
@@ -171,8 +168,8 @@ function readLockFile(path: string): LockFile {
171
168
  } catch {
172
169
  return { raw, record: undefined };
173
170
  }
174
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return { raw, record: undefined };
175
- const fields = parsed as Record<string, unknown>;
171
+ if (!isRecord(parsed)) return { raw, record: undefined };
172
+ const fields = parsed;
176
173
  const pid = fields.pid;
177
174
  const nonce = fields.nonce;
178
175
  if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0) {
@@ -207,15 +204,22 @@ let myStartedAt: number | null | undefined;
207
204
  /** The start time of this process, when the platform will say; best effort. */
208
205
  function myStart(): number | null {
209
206
  if (myStartedAt !== undefined) return myStartedAt;
210
- const pid = process.pid;
207
+ myStartedAt = startOf(process.pid);
208
+ return myStartedAt;
209
+ }
210
+
211
+ /**
212
+ * The start time `ps` or `/proc` reports for a pid, in the same unit as
213
+ * `myStart` on this platform, or null when the platform will not say. It is
214
+ * asked afresh for another pid: a record's pid may belong to a new process by
215
+ * the time a waiter looks at it.
216
+ */
217
+ function startOf(pid: number): number | null {
211
218
  try {
212
219
  const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
213
220
  const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
214
221
  const ticks = Number(fields[19]);
215
- if (Number.isFinite(ticks)) {
216
- myStartedAt = ticks;
217
- return ticks;
218
- }
222
+ if (Number.isFinite(ticks)) return ticks;
219
223
  } catch {
220
224
  // Not Linux.
221
225
  }
@@ -226,11 +230,24 @@ function myStart(): number | null {
226
230
  stderr: "pipe",
227
231
  });
228
232
  const at = Date.parse(result.stdout.toString().trim());
229
- myStartedAt = Number.isFinite(at) ? at : null;
233
+ return Number.isFinite(at) ? at : null;
230
234
  } catch {
231
- myStartedAt = null;
235
+ return null;
232
236
  }
233
- return myStartedAt;
237
+ }
238
+
239
+ /**
240
+ * True when the record's holder is gone: its pid is dead, or the pid now
241
+ * belongs to a process that started at another time. Without the start time a
242
+ * reused pid would look like a live holder until the waiter's deadline, but
243
+ * taking the lock over anyway could enter beside a live holder; waiting is the
244
+ * only safe choice when the platform cannot name the process.
245
+ */
246
+ function holderGone(record: LockRecord): boolean {
247
+ if (!isAlive(record.pid)) return true;
248
+ if (record.startedAt === null) return false;
249
+ const start = startOf(record.pid);
250
+ return start !== null && start !== record.startedAt;
234
251
  }
235
252
 
236
253
  function safeUnlink(path: string): void {
@@ -278,7 +295,7 @@ async function acquire(
278
295
  lockPath: string,
279
296
  clock: () => number,
280
297
  wait: (ms: number) => Promise<void>,
281
- log: (message: string) => void,
298
+ timeoutMs: number,
282
299
  ): Promise<LockRecord> {
283
300
  const started = clock();
284
301
  for (;;) {
@@ -313,13 +330,13 @@ async function acquire(
313
330
  const dead =
314
331
  holder.record === undefined
315
332
  ? isStaleUnreadable(lockPath, clock)
316
- : !isAlive(holder.record.pid);
333
+ : holderGone(holder.record);
317
334
  if (dead) {
318
335
  takeOver(lockPath, holder);
319
336
  continue;
320
337
  }
321
338
 
322
- if (clock() - started > LOCK_TIMEOUT_MS) {
339
+ if (clock() - started > timeoutMs) {
323
340
  const who =
324
341
  holder.record === undefined ? "unknown pid" : `pid ${holder.record.pid}`;
325
342
  throw new LockTimeoutError(lockPath, who);
@@ -338,7 +355,7 @@ function release(
338
355
  try {
339
356
  renameSync(lockPath, released);
340
357
  } catch (error) {
341
- if (errorCode(error) === "ENOENT") return;
358
+ if (isMissingFile(error)) return;
342
359
  throw error;
343
360
  }
344
361
 
@@ -376,7 +393,12 @@ export async function withLockFile<T>(
376
393
  const label = options.label ?? "lock";
377
394
  const onLog = options.onLog ?? ((message: string) => console.error(message));
378
395
  const log = (message: string): void => onLog(`${label}: ${message}`);
379
- const mine = await acquire(lockPath, clock, wait, log);
396
+ const mine = await acquire(
397
+ lockPath,
398
+ clock,
399
+ wait,
400
+ options.timeoutMs ?? LOCK_TIMEOUT_MS,
401
+ );
380
402
  try {
381
403
  return await work();
382
404
  } finally {
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Finding the git program without running it where running it could open a
3
+ * dialog. On macOS `/usr/bin/git` is a stub that exists on every Mac; without
4
+ * the command line tools it opens Apple's install dialog. So it is trusted only
5
+ * when `xcode-select -p` names a developer directory that holds a git.
6
+ *
7
+ * The answer is an absolute path, because a PATH that changed after the process
8
+ * started (a `winget install`, a Homebrew install under a GUI-started serve) is
9
+ * not seen by a spawn of the word `git`. Nothing is cached: "not installed" must
10
+ * be looked up again on every call, and a lookup is a few file checks.
11
+ */
12
+
13
+ import { existsSync } from "node:fs";
14
+ import { join } from "node:path";
15
+
16
+ /** What the finder needs from the machine; a test injects each part. */
17
+ export interface GitFinderHost {
18
+ readonly platform: NodeJS.Platform;
19
+ readonly env: Readonly<Record<string, string | undefined>>;
20
+ /** Resolves a command through PATH without running it. */
21
+ which(command: string, path: string | undefined): string | null;
22
+ /** True when a file exists. */
23
+ exists(path: string): boolean;
24
+ /** Runs a program with no shell; returns its exit code and output. */
25
+ run(cmd: readonly string[], env: Readonly<Record<string, string | undefined>>): {
26
+ readonly code: number;
27
+ readonly out: string;
28
+ };
29
+ }
30
+
31
+ /** The message every caller shows when no git program is found. */
32
+ export const GIT_NOT_INSTALLED = "git is not installed";
33
+
34
+ const MACOS_STUB = "/usr/bin/git";
35
+
36
+ function defaultRun(
37
+ cmd: readonly string[],
38
+ env: Readonly<Record<string, string | undefined>>,
39
+ ): { readonly code: number; readonly out: string } {
40
+ try {
41
+ const result = Bun.spawnSync({
42
+ cmd: [...cmd],
43
+ stdin: "ignore",
44
+ stdout: "pipe",
45
+ stderr: "ignore",
46
+ env: { ...env },
47
+ timeout: 10_000,
48
+ killSignal: "SIGKILL",
49
+ });
50
+ return { code: result.exitCode ?? 1, out: result.stdout.toString().trim() };
51
+ } catch {
52
+ return { code: 1, out: "" };
53
+ }
54
+ }
55
+
56
+ /** The machine this process runs on. */
57
+ export function realGitFinderHost(): GitFinderHost {
58
+ return {
59
+ platform: process.platform,
60
+ env: process.env,
61
+ which: (command, path) => Bun.which(command, path === undefined ? {} : { PATH: path }),
62
+ exists: existsSync,
63
+ run: defaultRun,
64
+ };
65
+ }
66
+
67
+ /** True when the selected developer directory on a Mac holds a git. */
68
+ function macToolsInstalled(host: GitFinderHost): boolean {
69
+ const selected = host.run(["/usr/bin/xcode-select", "-p"], host.env);
70
+ if (selected.code !== 0 || selected.out.length === 0) return false;
71
+ return host.exists(join(selected.out, "usr", "bin", "git"));
72
+ }
73
+
74
+ function windowsCandidates(env: GitFinderHost["env"]): string[] {
75
+ const roots = [env.ProgramFiles, env["ProgramFiles(x86)"]].filter(
76
+ (value): value is string => value !== undefined && value.length > 0,
77
+ );
78
+ const found = roots.map((root) => join(root, "Git", "cmd", "git.exe"));
79
+ const local = env.LOCALAPPDATA;
80
+ if (local !== undefined && local.length > 0) {
81
+ found.push(join(local, "Programs", "Git", "cmd", "git.exe"));
82
+ }
83
+ return found;
84
+ }
85
+
86
+ /**
87
+ * The absolute path of a git program that can be run, or undefined when there
88
+ * is none. It never runs git itself and never opens an installer.
89
+ */
90
+ export function findGit(host: GitFinderHost = realGitFinderHost()): string | undefined {
91
+ const onPath = host.which("git", host.env.PATH);
92
+ if (host.platform === "darwin") {
93
+ if (onPath !== null && onPath !== MACOS_STUB) return onPath;
94
+ // A GUI-started process has a short PATH: look where Homebrew installs.
95
+ for (const candidate of ["/opt/homebrew/bin/git", "/usr/local/bin/git"]) {
96
+ if (host.exists(candidate)) return candidate;
97
+ }
98
+ // Only the stub is left: it is real only when the tools are selected.
99
+ return (onPath === MACOS_STUB || host.exists(MACOS_STUB)) && macToolsInstalled(host)
100
+ ? MACOS_STUB
101
+ : undefined;
102
+ }
103
+ if (onPath !== null) return onPath;
104
+ if (host.platform === "win32") {
105
+ return windowsCandidates(host.env).find((path) => host.exists(path));
106
+ }
107
+ return undefined;
108
+ }
@@ -4,6 +4,7 @@
4
4
  * `@operad-io/engine/platform` and never writes its own.
5
5
  */
6
6
 
7
+ export * from "./atomic-write.ts";
7
8
  export * from "./file-lock.ts";
8
9
  export * from "./process-group.ts";
9
10
  export * from "./sqlite-open.ts";
@@ -11,3 +12,5 @@ export * from "./watch.ts";
11
12
  export * from "./step-reap.ts";
12
13
  export * from "./load.ts";
13
14
  export * from "./worker-reports.ts";
15
+ export * from "./kept-workers.ts";
16
+ export * from "./git-program.ts";
@@ -0,0 +1,290 @@
1
+ /**
2
+ * Kept workers: a harness child that may serve more than one reply stays in a
3
+ * directory of its own home and records how another process reaches it.
4
+ *
5
+ * A kept worker has no run marker: the run that started it is over, and the
6
+ * sweep for a step's left-over processes must leave it alone. The record here
7
+ * is how `serve` and its clients tell a kept worker from an ordinary process,
8
+ * find it for the next reply, end it when its owner asks, and never signal a
9
+ * pid that has since been reused by another program. Only the owner may read
10
+ * the directory or open the socket; both are created with owner-only
11
+ * permissions.
12
+ */
13
+
14
+ import { randomBytes } from "node:crypto";
15
+ import {
16
+ chmodSync,
17
+ mkdirSync,
18
+ readFileSync,
19
+ readdirSync,
20
+ rmSync,
21
+ } from "node:fs";
22
+ import { connect } from "node:net";
23
+ import { dirname, join } from "node:path";
24
+ import { writeJsonAtomicSync } from "./atomic-write.ts";
25
+ import { withLockFile } from "./file-lock.ts";
26
+ import { killProcessGroup, systemClock, type Clock } from "./process-group.ts";
27
+ import { readProcessTable } from "./step-reap.ts";
28
+ import { isRecord } from "../util.ts";
29
+
30
+ /** How long a worker is kept after a reply, when nobody asks for another. */
31
+ export const KEPT_WORKER_MS = 10 * 60 * 1000;
32
+
33
+ /** How many workers one home keeps. A fourth ends the one idle longest. */
34
+ export const MAX_KEPT_WORKERS = 3;
35
+
36
+ /** How long a kept worker may take to answer the first line of a new reply. */
37
+ export const KEPT_FIRST_LINE_MS = 5_000;
38
+
39
+ /** How long a kept worker gets to end after the stop request, before SIGKILL. */
40
+ export const KEPT_STOP_GRACE_MS = 500;
41
+
42
+ /** The command-line argument that names a kept worker's record. */
43
+ export const KEPT_WORKER_FLAG = "--operad-kept";
44
+
45
+ /** One kept worker as its owner records it. */
46
+ export interface KeptWorkerRecord {
47
+ readonly pid: number;
48
+ /** The random id that is also on the worker's command line. */
49
+ readonly token: string;
50
+ /** The chat (or other owner) the worker answers. */
51
+ readonly scope: string;
52
+ /** What the worker was started with; a different key means another worker. */
53
+ readonly key: string;
54
+ readonly socket: string;
55
+ /** The record itself; filled in when the record is read. */
56
+ readonly meta: string;
57
+ readonly session: string | null;
58
+ readonly startedAt: number;
59
+ readonly lastUsedAt: number;
60
+ /** True while the worker is answering a reply. */
61
+ readonly busy?: boolean | undefined;
62
+ }
63
+
64
+ export interface KeptWorkerSlot {
65
+ readonly dir: string;
66
+ readonly token: string;
67
+ readonly socket: string;
68
+ readonly meta: string;
69
+ }
70
+
71
+ /** The directory a harness keeps its workers in. */
72
+ export function keptWorkerDirectory(home: string, name: string): string {
73
+ return join(home, "harness", name, "kept");
74
+ }
75
+
76
+ function lockPath(home: string, name: string): string {
77
+ return join(home, "harness", name, "kept.lock");
78
+ }
79
+
80
+ function ownerDirectory(path: string): void {
81
+ mkdirSync(path, { recursive: true, mode: 0o700 });
82
+ chmodSync(path, 0o700);
83
+ }
84
+
85
+ /** A new socket and record path for a worker, with a token that is unique to it. */
86
+ export function newKeptWorkerSlot(home: string, name: string): KeptWorkerSlot {
87
+ const dir = keptWorkerDirectory(home, name);
88
+ ownerDirectory(dir);
89
+ const token = randomBytes(8).toString("hex");
90
+ return {
91
+ dir,
92
+ token,
93
+ socket: join(dir, `${token}.sock`),
94
+ meta: join(dir, `${token}.json`),
95
+ };
96
+ }
97
+
98
+ /** The argument a kept worker carries, so a record's pid can be checked before it is signalled. */
99
+ export function keptWorkerArgument(token: string): string {
100
+ return `${KEPT_WORKER_FLAG}=${token}`;
101
+ }
102
+
103
+ /** Writes a record whole: a reader sees the old one or the new one, never a half. */
104
+ export function writeKeptWorker(record: KeptWorkerRecord): void {
105
+ ownerDirectory(dirname(record.meta));
106
+ writeJsonAtomicSync(record.meta, record, { mode: 0o600 });
107
+ }
108
+
109
+ /** Removes a worker's record and socket; safe when they are already gone. */
110
+ export function removeKeptWorker(record: Pick<KeptWorkerRecord, "meta" | "socket">): void {
111
+ rmSync(record.meta, { force: true });
112
+ rmSync(record.socket, { force: true });
113
+ }
114
+
115
+ function textOf(value: unknown): string | undefined {
116
+ return typeof value === "string" && value.length > 0 ? value : undefined;
117
+ }
118
+
119
+ function recordOf(path: string, value: unknown): KeptWorkerRecord | undefined {
120
+ if (!isRecord(value)) return undefined;
121
+ const fields = value;
122
+ const pid = fields.pid;
123
+ const token = textOf(fields.token);
124
+ const scope = textOf(fields.scope);
125
+ const key = textOf(fields.key);
126
+ const socket = textOf(fields.socket);
127
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 1) return undefined;
128
+ if (token === undefined || scope === undefined || key === undefined || socket === undefined) return undefined;
129
+ const session = fields.session;
130
+ const startedAt = fields.startedAt;
131
+ const lastUsedAt = fields.lastUsedAt;
132
+ return {
133
+ pid,
134
+ token,
135
+ scope,
136
+ key,
137
+ socket,
138
+ meta: path,
139
+ session: typeof session === "string" ? session : null,
140
+ startedAt: typeof startedAt === "number" ? startedAt : 0,
141
+ lastUsedAt: typeof lastUsedAt === "number" ? lastUsedAt : 0,
142
+ ...(fields.busy === true ? { busy: true } : {}),
143
+ };
144
+ }
145
+
146
+ /** One record, or undefined when the file is missing, unreadable or not a record. */
147
+ export function readKeptWorker(path: string): KeptWorkerRecord | undefined {
148
+ try {
149
+ return recordOf(path, JSON.parse(readFileSync(path, "utf8")));
150
+ } catch {
151
+ // A record another process is replacing, or one that is not ours.
152
+ return undefined;
153
+ }
154
+ }
155
+
156
+ /** Every record in one home's kept directory. A record that cannot be read is skipped. */
157
+ export function readKeptWorkers(home: string, name: string): readonly KeptWorkerRecord[] {
158
+ const dir = keptWorkerDirectory(home, name);
159
+ let names: string[];
160
+ try {
161
+ names = readdirSync(dir);
162
+ } catch {
163
+ return [];
164
+ }
165
+ const found: KeptWorkerRecord[] = [];
166
+ for (const entry of names) {
167
+ if (!entry.endsWith(".json")) continue;
168
+ const record = readKeptWorker(join(dir, entry));
169
+ if (record !== undefined) found.push(record);
170
+ }
171
+ return found;
172
+ }
173
+
174
+ /** Every kept worker of every harness in one home. */
175
+ export function readKeptWorkersInHome(home: string): readonly KeptWorkerRecord[] {
176
+ const root = join(home, "harness");
177
+ let names: string[];
178
+ try {
179
+ names = readdirSync(root);
180
+ } catch {
181
+ return [];
182
+ }
183
+ return names.flatMap((name) => readKeptWorkers(home, name));
184
+ }
185
+
186
+ /** True when `pid` is still the kept worker named by `token`, not a reused pid. */
187
+ async function isWorkerProcess(pid: number, token: string): Promise<boolean> {
188
+ const wanted = keptWorkerArgument(token);
189
+ try {
190
+ const rows = await readProcessTable();
191
+ return rows.some((row) => row.pid === pid && row.command.includes(wanted));
192
+ } catch {
193
+ return false;
194
+ }
195
+ }
196
+
197
+ /** Asks a worker to stop over its socket; true when it answered. */
198
+ function requestStop(socketPath: string, timeoutMs: number): Promise<boolean> {
199
+ return new Promise((resolve) => {
200
+ let settled = false;
201
+ const socket = connect(socketPath);
202
+ const finish = (stopped: boolean): void => {
203
+ if (settled) return;
204
+ settled = true;
205
+ socket.destroy();
206
+ resolve(stopped);
207
+ };
208
+ socket.setTimeout(Math.max(1, timeoutMs));
209
+ socket.once("connect", () => {
210
+ socket.write(`${JSON.stringify({ type: "stop" })}\n`);
211
+ socket.end();
212
+ });
213
+ socket.once("close", () => finish(true));
214
+ socket.once("error", () => finish(false));
215
+ socket.once("timeout", () => finish(false));
216
+ });
217
+ }
218
+
219
+ /** Ends one kept worker: ask it over its socket, then signal only its own verified process. */
220
+ export async function stopKeptWorker(
221
+ record: KeptWorkerRecord,
222
+ options: { readonly clock?: Clock | undefined } = {},
223
+ ): Promise<void> {
224
+ const clock = options.clock ?? systemClock;
225
+ const answered = await requestStop(record.socket, KEPT_STOP_GRACE_MS);
226
+ if (answered) {
227
+ // Give the worker its grace to remove the record and leave.
228
+ await clock.sleep(KEPT_STOP_GRACE_MS);
229
+ }
230
+ // A worker that answered may already be gone; a dead one never is signalled.
231
+ if (await isWorkerProcess(record.pid, record.token)) {
232
+ killProcessGroup(record.pid, "SIGTERM");
233
+ await clock.sleep(KEPT_STOP_GRACE_MS);
234
+ if (await isWorkerProcess(record.pid, record.token)) {
235
+ killProcessGroup(record.pid, "SIGKILL");
236
+ }
237
+ }
238
+ removeKeptWorker(record);
239
+ }
240
+
241
+ /** Filters a kept worker; every field that is given must match. */
242
+ export interface KeptWorkerFilter {
243
+ readonly scope?: string | undefined;
244
+ readonly key?: string | undefined;
245
+ /** Keep these records, even when the other fields match. */
246
+ readonly except?: (record: KeptWorkerRecord) => boolean | undefined;
247
+ }
248
+
249
+ /** Ends every kept worker of every harness in one home, oldest first. */
250
+ export async function stopAllKeptWorkers(options: {
251
+ readonly home: string;
252
+ readonly clock?: Clock | undefined;
253
+ }): Promise<readonly KeptWorkerRecord[]> {
254
+ const root = join(options.home, "harness");
255
+ let names: string[];
256
+ try {
257
+ names = readdirSync(root);
258
+ } catch {
259
+ return [];
260
+ }
261
+ const ended: KeptWorkerRecord[] = [];
262
+ for (const name of names) {
263
+ if (readKeptWorkers(options.home, name).length === 0) continue;
264
+ ended.push(...(await stopKeptWorkers({ home: options.home, name, clock: options.clock })));
265
+ }
266
+ return ended;
267
+ }
268
+
269
+ /** Ends the kept workers of one home that match `filter`, oldest first. */
270
+ export async function stopKeptWorkers(options: {
271
+ readonly home: string;
272
+ readonly name: string;
273
+ readonly filter?: KeptWorkerFilter | undefined;
274
+ readonly clock?: Clock | undefined;
275
+ }): Promise<readonly KeptWorkerRecord[]> {
276
+ const filter = options.filter;
277
+ return withLockFile(
278
+ lockPath(options.home, options.name),
279
+ async () => {
280
+ const records = readKeptWorkers(options.home, options.name)
281
+ .filter((record) => filter?.scope === undefined || record.scope === filter.scope)
282
+ .filter((record) => filter?.key === undefined || record.key === filter.key)
283
+ .filter((record) => filter?.except?.(record) !== true)
284
+ .sort((a, b) => a.lastUsedAt - b.lastUsedAt);
285
+ for (const record of records) await stopKeptWorker(record, { clock: options.clock });
286
+ return records;
287
+ },
288
+ { label: `kept ${options.name}` },
289
+ );
290
+ }
@@ -513,14 +513,15 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
513
513
  });
514
514
 
515
515
  let readySeen = false;
516
- const stop = createGroupStop({
516
+ const group: GroupStopOptions = {
517
517
  clock,
518
518
  killGroup: options.killGroup ?? killProcessGroup,
519
519
  pid: () => child.pid,
520
520
  sentinelExited: () => sentinelExited,
521
521
  readySeen: () => readySeen,
522
522
  ready: readyGate,
523
- });
523
+ };
524
+ const stop = createGroupStop(group);
524
525
 
525
526
  let finished = false;
526
527
  let timedOut = false;
@@ -654,7 +655,14 @@ export async function runLine(options: LineRunOptions): Promise<LineOutcome> {
654
655
  // line pay 500 ms. A cancellation or timeout still takes the TERM path.
655
656
  if (ended.kind === "end" && !cancelled && !timedOut && !stalled) {
656
657
  const pid = child.pid;
657
- if (pid !== undefined) (options.killGroup ?? killProcessGroup)(pid, "SIGKILL");
658
+ if (pid !== undefined && (options.killGroup ?? killProcessGroup)(pid, "SIGKILL")) {
659
+ // A child forked as the group was signaled missed the signal, and the
660
+ // sentinel's own `sleep` is forked right about now. The killed leader is
661
+ // a zombie until the event loop reaps it, so its id is still ours: look
662
+ // again, as the TERM path does, before taking the straggler for the
663
+ // step's work to stop later.
664
+ sweep(pid, group);
665
+ }
658
666
  } else {
659
667
  await stop();
660
668
  }
@@ -18,13 +18,27 @@ export function setBusyTimeout(database: Database): void {
18
18
  database.run(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`);
19
19
  }
20
20
 
21
+ /**
22
+ * True for a busy store: SQLITE_BUSY or any extended code of it
23
+ * (SQLITE_BUSY_SNAPSHOT, SQLITE_BUSY_RECOVERY, SQLITE_BUSY_TIMEOUT), whether the
24
+ * error is the one SQLite raised or the `cause` of an error that wrapped it.
25
+ */
21
26
  export function isBusy(error: unknown): boolean {
22
- return (
23
- typeof error === "object" &&
24
- error !== null &&
25
- "code" in error &&
26
- (error as { code?: unknown }).code === "SQLITE_BUSY"
27
- );
27
+ for (let depth = 0; depth < 8; depth += 1) {
28
+ if (typeof error !== "object" || error === null) return false;
29
+ const { code, errno, cause } = error as {
30
+ code?: unknown;
31
+ errno?: unknown;
32
+ cause?: unknown;
33
+ };
34
+ if (code === "SQLITE_BUSY" || (typeof code === "string" && code.startsWith("SQLITE_BUSY_"))) return true;
35
+ // The primary result code is the low byte of an extended one; 5 is BUSY.
36
+ if (typeof errno === "number" && typeof code === "string" && code.startsWith("SQLITE") && (errno & 0xff) === 5) {
37
+ return true;
38
+ }
39
+ error = cause;
40
+ }
41
+ return false;
28
42
  }
29
43
 
30
44
  /**
@@ -0,0 +1,30 @@
1
+ /** Reading a SQLite file's schema version and tables, for both sqlite stores. */
2
+
3
+ import type { Database } from "bun:sqlite";
4
+
5
+ interface VersionRow {
6
+ readonly version: number;
7
+ }
8
+
9
+ /** The recorded version, or undefined when the schema has not been created yet. */
10
+ export function readSchemaVersion(database: Database): number | undefined {
11
+ try {
12
+ const row = database
13
+ .query<VersionRow, []>("SELECT version FROM schema_version WHERE id = 1")
14
+ .get();
15
+ return row !== null && Number.isInteger(row.version) ? row.version : undefined;
16
+ } catch {
17
+ return undefined;
18
+ }
19
+ }
20
+
21
+ /** Whether the database has a table with this name. */
22
+ export function hasTable(database: Database, name: string): boolean {
23
+ return (
24
+ database
25
+ .query<{ name: string }, [string]>(
26
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?",
27
+ )
28
+ .get(name) !== null
29
+ );
30
+ }