@botbuddy/cli 1.115.2 → 1.117.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/CHANGELOG.md +8 -0
- package/bin/botbuddy.mjs +10 -0
- package/daemon/bin/darwin-arm64/botbuddy-daemon +0 -0
- package/daemon/bin/linux-x64/botbuddy-daemon +0 -0
- package/daemon-release/darwin-arm64.json +4 -4
- package/daemon-release/linux-x64.json +4 -4
- package/daemon-release/manifest.json +5 -5
- package/package.json +1 -1
- package/src/run-delivery.mjs +5 -3
- package/src/run-markers.mjs +27 -0
- package/src/run-ownership.mjs +738 -0
- package/src/run.mjs +66 -5
- package/src/stack-run-outcome.mjs +31 -12
- package/src/stack.mjs +100 -13
|
@@ -0,0 +1,738 @@
|
|
|
1
|
+
// BOT-3463 — a run started by bb owns every process it launches.
|
|
2
|
+
//
|
|
3
|
+
// `bb stack run`, `bb run` (foreground and detached, so `bb test` and `bb push` too)
|
|
4
|
+
// put a run-scoped marker on their child's environment (run-markers.mjs) and write an
|
|
5
|
+
// ownership record naming the owner process:
|
|
6
|
+
//
|
|
7
|
+
// ~/.botbuddy/owned-runs/<run_id>.json (0600) { run_id, owner_pid, groups, … }
|
|
8
|
+
//
|
|
9
|
+
// When the run ends — a normal exit, a signal, a timeout — the owner stops every process
|
|
10
|
+
// that still carries its marker, then removes the record (`release`). When the owner
|
|
11
|
+
// itself dies (SIGKILL, a crashed or killed session) its record stays behind with a dead
|
|
12
|
+
// owner PID, and the per-machine orphan reaper (`runOrphanReaper`, started by bb) stops
|
|
13
|
+
// that run's tree within one interval. On start the reaper also sweeps leftovers from bb
|
|
14
|
+
// releases before this one by their own run-scoped markers (AC-2).
|
|
15
|
+
//
|
|
16
|
+
// Identification is by marker, never by name: a process a user started by hand carries
|
|
17
|
+
// none and is never touched. On macOS `ps -E` cannot read the environment of Apple
|
|
18
|
+
// platform binaries (`/bin/sh`, `/bin/bash`), so a run's shell is covered by the process
|
|
19
|
+
// group the owner recorded and by its marked descendants.
|
|
20
|
+
//
|
|
21
|
+
// Every reaped process group is recorded (AC-3): one `sensor_events` row
|
|
22
|
+
// (`bb-cli` / `run_process_reaped`) with its run id, PID, PGID and age, kept in a local
|
|
23
|
+
// outbox until sensor-ingest accepts it.
|
|
24
|
+
//
|
|
25
|
+
// Host test children are not handled here: they run as transient systemd units with
|
|
26
|
+
// KillMode=control-group, which the host daemon stops (daemon/test_child_systemd.go).
|
|
27
|
+
|
|
28
|
+
import { execFile, spawn } from "node:child_process";
|
|
29
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
30
|
+
import { appendFile, mkdir, readdir, readFile, rename, stat, unlink, utimes, writeFile } from "node:fs/promises";
|
|
31
|
+
import { homedir, hostname } from "node:os";
|
|
32
|
+
import { basename, dirname, join } from "node:path";
|
|
33
|
+
import { fileURLToPath } from "node:url";
|
|
34
|
+
|
|
35
|
+
import { LEGACY_RUN_MARKERS, RUN_ID_ENV, RUN_REGISTRY_ENV, withoutRunMarkers } from "./run-markers.mjs";
|
|
36
|
+
import { acquireDeliveryLock, pidAlive } from "./run-delivery.mjs";
|
|
37
|
+
import { VERSION } from "./version.mjs";
|
|
38
|
+
|
|
39
|
+
/** SIGTERM first; what is still alive after this is sent SIGKILL. */
|
|
40
|
+
export const REAP_GRACE_MS = 5_000;
|
|
41
|
+
/** The reaper checks every owner this often, so a dead owner's tree stops well inside 60 s. */
|
|
42
|
+
export const REAPER_INTERVAL_MS = 10_000;
|
|
43
|
+
/** A full process-table sweep (records whose owner left survivors, pre-fix orphans) this often. */
|
|
44
|
+
export const FULL_SWEEP_INTERVAL_MS = 5 * 60_000;
|
|
45
|
+
/** A `bb` invocation starts a sweep when none has run for this long (AC-2's "next invocation"). */
|
|
46
|
+
export const SWEEP_STALE_MS = 10 * 60_000;
|
|
47
|
+
export const REAP_EVENT_SOURCE = "bb-cli";
|
|
48
|
+
export const REAP_EVENT_KIND = "run_process_reaped";
|
|
49
|
+
const OUTBOX_MAX_EVENTS = 500;
|
|
50
|
+
const OUTBOX_MAX_ATTEMPTS = 20;
|
|
51
|
+
const DELIVERY_TIMEOUT_MS = 5_000;
|
|
52
|
+
/** How many stop-and-look-again rounds an owner's release makes before leaving the rest to the reaper. */
|
|
53
|
+
const RELEASE_ROUNDS = 3;
|
|
54
|
+
/** The most one reaper flush spends delivering; what is left waits for the next one. */
|
|
55
|
+
const DELIVERY_BUDGET_MS = 30_000;
|
|
56
|
+
const MARKER_VALUE = /^[A-Za-z0-9._:-]{1,200}$/;
|
|
57
|
+
|
|
58
|
+
export function ownedRunsDir(home = homedir()) { return join(home, ".botbuddy", "owned-runs"); }
|
|
59
|
+
/** The marker value naming a record directory: a hash, so a path with spaces never matters. */
|
|
60
|
+
export function registryId(dir) { return createHash("sha256").update(dir).digest("hex").slice(0, 16); }
|
|
61
|
+
const recordPath = (dir, runId) => join(dir, `${runId}.json`);
|
|
62
|
+
const reaperLockPath = (dir) => join(dir, ".reaper.lock");
|
|
63
|
+
const sweepStampPath = (dir) => join(dir, ".last-sweep");
|
|
64
|
+
// The repo binding of the last run claimed here: where a pre-fix orphan's event is sent.
|
|
65
|
+
const defaultDeliveryPath = (dir) => join(dir, ".default-delivery.json");
|
|
66
|
+
export const reapOutboxPath = (dir) => join(dir, "reaped-events.ndjson");
|
|
67
|
+
const validRunId = (value) => typeof value === "string" && MARKER_VALUE.test(value);
|
|
68
|
+
|
|
69
|
+
async function writePrivateJson(path, value) {
|
|
70
|
+
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
71
|
+
await writeFile(tmp, JSON.stringify(value), { mode: 0o600 });
|
|
72
|
+
await rename(tmp, path);
|
|
73
|
+
}
|
|
74
|
+
async function readJsonFile(path) {
|
|
75
|
+
try { return JSON.parse(await readFile(path, "utf8")); } catch { return null; }
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// ── the process table ────────────────────────────────────────────────────────
|
|
79
|
+
|
|
80
|
+
/** `[[dd-]hh:]mm:ss` → seconds. */
|
|
81
|
+
export function parseElapsed(text) {
|
|
82
|
+
const match = /^(?:(\d+)-)?(?:(\d+):)?(\d+):(\d+)$/.exec(String(text).trim());
|
|
83
|
+
if (!match) return null;
|
|
84
|
+
const [, days = 0, hours = 0, minutes, seconds] = match;
|
|
85
|
+
return Number(days) * 86_400 + Number(hours) * 3_600 + Number(minutes) * 60 + Number(seconds);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** The marker values in an environment block (`NAME=value` tokens, last one wins). */
|
|
89
|
+
export function markersFromEnvText(text) {
|
|
90
|
+
const markers = {};
|
|
91
|
+
for (const name of [RUN_ID_ENV, RUN_REGISTRY_ENV, ...LEGACY_RUN_MARKERS]) {
|
|
92
|
+
const re = new RegExp(`(?:^|[\\s\\0])${name}=([^\\s\\0]*)`, "g");
|
|
93
|
+
let value = null;
|
|
94
|
+
for (const match of String(text).matchAll(re)) value = match[1];
|
|
95
|
+
if (value && MARKER_VALUE.test(value)) markers[name] = value;
|
|
96
|
+
}
|
|
97
|
+
return markers;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* macOS: `ps` twice — once for the columns, once with `-E`, whose command column is the
|
|
102
|
+
* same text followed by the environment. A platform binary's environment is not readable
|
|
103
|
+
* (its `-E` text is the bare command): `envHidden`, so it can be neither marked nor ruled out.
|
|
104
|
+
*/
|
|
105
|
+
export function parseDarwinProcesses(columnsText, envText) {
|
|
106
|
+
const withEnv = new Map();
|
|
107
|
+
for (const line of String(envText).split("\n")) {
|
|
108
|
+
const match = /^\s*(\d+) (.*)$/.exec(line);
|
|
109
|
+
if (match) withEnv.set(Number(match[1]), match[2]);
|
|
110
|
+
}
|
|
111
|
+
const rows = [];
|
|
112
|
+
for (const line of String(columnsText).split("\n")) {
|
|
113
|
+
const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+) (.*)$/.exec(line);
|
|
114
|
+
if (!match) continue;
|
|
115
|
+
const pid = Number(match[1]);
|
|
116
|
+
const command = match[6].replace(/\s+$/, "");
|
|
117
|
+
const full = (withEnv.get(pid) ?? "").replace(/\s+$/, "");
|
|
118
|
+
const known = full.startsWith(command);
|
|
119
|
+
const envPart = known ? full.slice(command.length) : "";
|
|
120
|
+
rows.push({
|
|
121
|
+
pid, ppid: Number(match[2]), pgid: Number(match[3]), uid: Number(match[4]),
|
|
122
|
+
ageSeconds: parseElapsed(match[5]), name: commandName(command),
|
|
123
|
+
envHidden: !known || envPart.trim() === "", markers: markersFromEnvText(envPart),
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
return rows;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function commandName(command) {
|
|
130
|
+
const first = String(command).trim().split(/\s+/)[0] ?? "";
|
|
131
|
+
return basename(first).slice(0, 64) || null;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function execText(file, args) {
|
|
135
|
+
return new Promise((resolve, reject) => {
|
|
136
|
+
execFile(file, args, { maxBuffer: 64 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } }, (error, stdout) => {
|
|
137
|
+
if (error) reject(error); else resolve(stdout);
|
|
138
|
+
});
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async function listDarwinProcesses(exec) {
|
|
143
|
+
// Columns first: a process that starts between the two reads has no columns row and is
|
|
144
|
+
// skipped this time; one that ends is simply absent from the second.
|
|
145
|
+
const columns = await exec("ps", ["-axww", "-o", "pid=,ppid=,pgid=,uid=,etime=,command="]);
|
|
146
|
+
const env = await exec("ps", ["-axEww", "-o", "pid=,command="]);
|
|
147
|
+
return parseDarwinProcesses(columns, env);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** Linux: /proc — stat for the tree and age, status for the uid, environ for the markers. */
|
|
151
|
+
async function listLinuxProcesses(procRoot = "/proc") {
|
|
152
|
+
let uptime = 0;
|
|
153
|
+
try { uptime = Number((await readFile(join(procRoot, "uptime"), "utf8")).split(/\s+/)[0]); } catch { /* ages unknown */ }
|
|
154
|
+
const rows = [];
|
|
155
|
+
let entries = [];
|
|
156
|
+
try { entries = await readdir(procRoot); } catch { return rows; }
|
|
157
|
+
await Promise.all(entries.filter((entry) => /^\d+$/.test(entry)).map(async (entry) => {
|
|
158
|
+
try {
|
|
159
|
+
const statText = await readFile(join(procRoot, entry, "stat"), "utf8");
|
|
160
|
+
const close = statText.lastIndexOf(")");
|
|
161
|
+
const name = statText.slice(statText.indexOf("(") + 1, close);
|
|
162
|
+
const fields = statText.slice(close + 2).split(" ");
|
|
163
|
+
// fields[0] = state, [1] = ppid, [2] = pgrp, [19] = starttime (clock ticks since boot).
|
|
164
|
+
const startTicks = Number(fields[19]);
|
|
165
|
+
const status = await readFile(join(procRoot, entry, "status"), "utf8");
|
|
166
|
+
const uid = Number(/^Uid:\s+(\d+)/m.exec(status)?.[1]);
|
|
167
|
+
let envText = "";
|
|
168
|
+
let envHidden = false;
|
|
169
|
+
try { envText = (await readFile(join(procRoot, entry, "environ"))).toString("utf8"); } catch { envHidden = true; }
|
|
170
|
+
rows.push({
|
|
171
|
+
pid: Number(entry), ppid: Number(fields[1]), pgid: Number(fields[2]), uid,
|
|
172
|
+
ageSeconds: uptime && Number.isFinite(startTicks) ? Math.max(0, Math.round(uptime - startTicks / 100)) : null,
|
|
173
|
+
name: name.slice(0, 64) || null, envHidden, markers: markersFromEnvText(envText),
|
|
174
|
+
});
|
|
175
|
+
} catch { /* the process ended while it was read */ }
|
|
176
|
+
}));
|
|
177
|
+
return rows;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export async function listProcesses({ platform = process.platform, exec = execText, procRoot } = {}) {
|
|
181
|
+
if (platform === "darwin") return listDarwinProcesses(exec);
|
|
182
|
+
if (platform === "linux") return listLinuxProcesses(procRoot);
|
|
183
|
+
return [];
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// ── which processes belong to a run ──────────────────────────────────────────
|
|
187
|
+
|
|
188
|
+
function indexProcesses(processes) {
|
|
189
|
+
const byPid = new Map(processes.map((proc) => [proc.pid, proc]));
|
|
190
|
+
const children = new Map();
|
|
191
|
+
for (const proc of processes) {
|
|
192
|
+
if (!children.has(proc.ppid)) children.set(proc.ppid, []);
|
|
193
|
+
children.get(proc.ppid).push(proc);
|
|
194
|
+
}
|
|
195
|
+
return { byPid, children };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** This process and its ancestors: never part of a kill set, whatever they carry. */
|
|
199
|
+
function protectedPids(index, selfPid) {
|
|
200
|
+
const pids = new Set();
|
|
201
|
+
for (let pid = selfPid; pid && pid > 1 && !pids.has(pid); pid = index.byPid.get(pid)?.ppid) pids.add(pid);
|
|
202
|
+
pids.add(1);
|
|
203
|
+
pids.add(0);
|
|
204
|
+
return pids;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function addDescendants(index, pids) {
|
|
208
|
+
const queue = [...pids];
|
|
209
|
+
while (queue.length) {
|
|
210
|
+
const pid = queue.pop();
|
|
211
|
+
for (const child of index.children.get(pid) ?? []) {
|
|
212
|
+
if (!pids.has(child.pid)) { pids.add(child.pid); queue.push(child.pid); }
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return pids;
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* The env-hidden ancestors of a run's marked processes up to the first process that is
|
|
220
|
+
* neither hidden nor part of the run (a live owner, a terminal) or init. They are the run's
|
|
221
|
+
* own shell: a platform-binary `sh`/`bash` the run launched, whose environment `ps` cannot read.
|
|
222
|
+
*/
|
|
223
|
+
function hiddenAncestors(index, pids, owners = new Set()) {
|
|
224
|
+
const found = new Set();
|
|
225
|
+
for (const pid of pids) {
|
|
226
|
+
for (let parent = index.byPid.get(index.byPid.get(pid)?.ppid); parent && parent.pid > 1; parent = index.byPid.get(parent.ppid)) {
|
|
227
|
+
if (pids.has(parent.pid) || found.has(parent.pid)) break;
|
|
228
|
+
if (owners.has(parent.pid) || !parent.envHidden) break;
|
|
229
|
+
found.add(parent.pid);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return found;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* A pre-fix (legacy-marker) run is dead when none of its top marked processes is still
|
|
237
|
+
* under a process outside the run: every one reaches init through only marked or
|
|
238
|
+
* env-hidden processes. A live `bb stack run` owner, or a terminal a user typed in,
|
|
239
|
+
* is a visible unmarked ancestor and keeps the run alive.
|
|
240
|
+
*/
|
|
241
|
+
function legacyRunOrphaned(index, members) {
|
|
242
|
+
const memberPids = new Set(members.map((proc) => proc.pid));
|
|
243
|
+
const roots = members.filter((proc) => !memberPids.has(proc.ppid));
|
|
244
|
+
return roots.length > 0 && roots.every((root) => {
|
|
245
|
+
for (let parent = index.byPid.get(root.ppid); ; parent = index.byPid.get(parent.ppid)) {
|
|
246
|
+
if (!parent || parent.pid === 1) return true;
|
|
247
|
+
if (!parent.envHidden && !memberPids.has(parent.pid)) return false;
|
|
248
|
+
}
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function groupedRun({ index, members, runId, marker, reason, record = null, selfPid, uid }) {
|
|
253
|
+
const guard = protectedPids(index, selfPid);
|
|
254
|
+
const pids = new Set(members.map((proc) => proc.pid));
|
|
255
|
+
// The process groups the owner recorded (the child it spawned leads one): a member of
|
|
256
|
+
// the run even when `ps` cannot read its environment. A PGID is not reused while its
|
|
257
|
+
// group exists, so a recorded group is still the run's unless it is led by a process
|
|
258
|
+
// younger than the run (the whole group ended and its number went to a new leader).
|
|
259
|
+
const runAge = record?.created_at ? (Date.now() - Date.parse(record.created_at)) / 1000 : null;
|
|
260
|
+
for (const pgid of record?.groups ?? []) {
|
|
261
|
+
const inGroup = [...index.byPid.values()].filter((proc) => proc.pgid === pgid);
|
|
262
|
+
const leader = index.byPid.get(pgid);
|
|
263
|
+
const markedMember = inGroup.some((proc) => proc.markers[RUN_ID_ENV] === runId);
|
|
264
|
+
const reused = leader && runAge != null && leader.ageSeconds != null && leader.ageSeconds + 10 < runAge;
|
|
265
|
+
if (markedMember || !reused) for (const proc of inGroup) pids.add(proc.pid);
|
|
266
|
+
}
|
|
267
|
+
for (const pid of hiddenAncestors(index, pids, new Set(record ? [record.owner_pid] : []))) pids.add(pid);
|
|
268
|
+
addDescendants(index, pids);
|
|
269
|
+
const owned = [...pids].map((pid) => index.byPid.get(pid))
|
|
270
|
+
.filter((proc) => proc && !guard.has(proc.pid) && proc.uid === uid);
|
|
271
|
+
return owned.length ? { runId, marker, reason, record, processes: owned } : null;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* The runs whose processes must stop now: a record whose owner is dead (or a marked
|
|
276
|
+
* process whose record is gone), and pre-fix runs whose top process is orphaned.
|
|
277
|
+
* `onlyRunId` limits it to one run (its owner's own `release`).
|
|
278
|
+
*/
|
|
279
|
+
export function findRunsToReap(processes, {
|
|
280
|
+
registry, records = new Map(), isAlive = pidAlive, selfPid = process.pid, uid = process.getuid?.() ?? 0, onlyRunId = null, legacy = true,
|
|
281
|
+
} = {}) {
|
|
282
|
+
const index = indexProcesses(processes);
|
|
283
|
+
const byRun = new Map();
|
|
284
|
+
const byLegacy = new Map();
|
|
285
|
+
for (const proc of processes) {
|
|
286
|
+
if (proc.uid !== uid) continue;
|
|
287
|
+
const runId = proc.markers[RUN_ID_ENV];
|
|
288
|
+
if (runId) {
|
|
289
|
+
// A run judged by another record directory (another HOME, another user) is not ours to judge.
|
|
290
|
+
if (proc.markers[RUN_REGISTRY_ENV] !== registry) continue;
|
|
291
|
+
if (!byRun.has(runId)) byRun.set(runId, []);
|
|
292
|
+
byRun.get(runId).push(proc);
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
if (!legacy || onlyRunId) continue;
|
|
296
|
+
const name = LEGACY_RUN_MARKERS.find((marker) => proc.markers[marker]);
|
|
297
|
+
if (!name) continue;
|
|
298
|
+
const key = `${name}=${proc.markers[name]}`;
|
|
299
|
+
if (!byLegacy.has(key)) byLegacy.set(key, { name, value: proc.markers[name], members: [] });
|
|
300
|
+
byLegacy.get(key).members.push(proc);
|
|
301
|
+
}
|
|
302
|
+
const runs = [];
|
|
303
|
+
const runIds = onlyRunId ? [onlyRunId] : [...new Set([...byRun.keys(), ...records.keys()])];
|
|
304
|
+
for (const runId of runIds) {
|
|
305
|
+
const record = records.get(runId) ?? null;
|
|
306
|
+
let reason;
|
|
307
|
+
if (onlyRunId) reason = "run_ended";
|
|
308
|
+
else if (!record) reason = "record_missing";
|
|
309
|
+
else if (!isAlive(record.owner_pid)) reason = "owner_gone";
|
|
310
|
+
else continue;
|
|
311
|
+
const run = groupedRun({ index, members: byRun.get(runId) ?? [], runId, marker: RUN_ID_ENV, reason, record, selfPid, uid });
|
|
312
|
+
runs.push(run ?? { runId, marker: RUN_ID_ENV, reason, record, processes: [] });
|
|
313
|
+
}
|
|
314
|
+
for (const { name, value, members } of byLegacy.values()) {
|
|
315
|
+
if (!legacyRunOrphaned(index, members)) continue;
|
|
316
|
+
const run = groupedRun({ index, members, runId: value, marker: name, reason: "legacy_orphan", selfPid, uid });
|
|
317
|
+
if (run) runs.push(run);
|
|
318
|
+
}
|
|
319
|
+
return runs;
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// ── stopping processes ───────────────────────────────────────────────────────
|
|
323
|
+
|
|
324
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
325
|
+
|
|
326
|
+
/** SIGTERM, wait up to the grace for exit, then SIGKILL what remains. */
|
|
327
|
+
export async function stopProcesses(pids, { kill = (pid, signal) => process.kill(pid, signal), isAlive = pidAlive, graceMs = REAP_GRACE_MS, sleep = defaultSleep } = {}) {
|
|
328
|
+
const signalled = new Map();
|
|
329
|
+
for (const pid of pids) {
|
|
330
|
+
try { kill(pid, "SIGTERM"); signalled.set(pid, "SIGTERM"); } catch { /* already gone */ }
|
|
331
|
+
}
|
|
332
|
+
const deadline = Date.now() + graceMs;
|
|
333
|
+
let alive = [...signalled.keys()].filter((pid) => isAlive(pid));
|
|
334
|
+
while (alive.length && Date.now() < deadline) {
|
|
335
|
+
await sleep(100);
|
|
336
|
+
alive = alive.filter((pid) => isAlive(pid));
|
|
337
|
+
}
|
|
338
|
+
for (const pid of alive) {
|
|
339
|
+
try { kill(pid, "SIGKILL"); signalled.set(pid, "SIGKILL"); } catch { /* exited at the last moment */ }
|
|
340
|
+
}
|
|
341
|
+
if (alive.length) {
|
|
342
|
+
const killDeadline = Date.now() + 2_000;
|
|
343
|
+
while (alive.length && Date.now() < killDeadline) { await sleep(50); alive = alive.filter((pid) => isAlive(pid)); }
|
|
344
|
+
}
|
|
345
|
+
return { signalled, survivors: alive };
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** One telemetry event per reaped process group (AC-3). */
|
|
349
|
+
export function reapEvents(run, { signalled = new Map(), delivery = null, host = hostname(), now = new Date() } = {}) {
|
|
350
|
+
const groups = new Map();
|
|
351
|
+
for (const proc of run.processes) {
|
|
352
|
+
if (!groups.has(proc.pgid)) groups.set(proc.pgid, []);
|
|
353
|
+
groups.get(proc.pgid).push(proc);
|
|
354
|
+
}
|
|
355
|
+
return [...groups.entries()].map(([pgid, procs]) => {
|
|
356
|
+
const leader = procs.find((proc) => proc.pid === pgid) ?? [...procs].sort((a, b) => (b.ageSeconds ?? 0) - (a.ageSeconds ?? 0))[0];
|
|
357
|
+
const signals = procs.map((proc) => signalled.get(proc.pid)).filter(Boolean);
|
|
358
|
+
return {
|
|
359
|
+
source: REAP_EVENT_SOURCE,
|
|
360
|
+
kind: REAP_EVENT_KIND,
|
|
361
|
+
dedupe_key: `${REAP_EVENT_SOURCE}:${REAP_EVENT_KIND}:${randomUUID()}`,
|
|
362
|
+
occurred_at: now.toISOString(),
|
|
363
|
+
payload: {
|
|
364
|
+
run_id: run.runId,
|
|
365
|
+
marker: run.marker,
|
|
366
|
+
reason: run.reason,
|
|
367
|
+
pid: leader.pid,
|
|
368
|
+
pgid,
|
|
369
|
+
process_count: procs.length,
|
|
370
|
+
age_seconds: Math.max(...procs.map((proc) => proc.ageSeconds ?? 0)),
|
|
371
|
+
command_name: leader.name ?? null,
|
|
372
|
+
signal: signals.includes("SIGKILL") ? "SIGKILL" : signals.length ? "SIGTERM" : null,
|
|
373
|
+
run_kind: run.record?.kind ?? null,
|
|
374
|
+
host,
|
|
375
|
+
cli_version: VERSION,
|
|
376
|
+
},
|
|
377
|
+
...(delivery ? { delivery } : {}),
|
|
378
|
+
attempts: 0,
|
|
379
|
+
};
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async function appendOutbox(dir, events) {
|
|
384
|
+
if (!events.length) return;
|
|
385
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
386
|
+
await appendFile(reapOutboxPath(dir), events.map((event) => `${JSON.stringify(event)}\n`).join(""), { mode: 0o600 });
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Stop one run's processes and record each process group it stopped. */
|
|
390
|
+
export async function reapRun(run, { dir, stop = stopProcesses, delivery = null, log = () => {} } = {}) {
|
|
391
|
+
delivery ??= await readJsonFile(defaultDeliveryPath(dir));
|
|
392
|
+
if (!run.processes.length) return { run_id: run.runId, groups: 0, processes: 0 };
|
|
393
|
+
const { signalled, survivors } = await stop(run.processes.map((proc) => proc.pid));
|
|
394
|
+
const events = reapEvents(run, { signalled, delivery: run.record?.delivery ?? delivery });
|
|
395
|
+
await appendOutbox(dir, events).catch(() => {});
|
|
396
|
+
log(`bb: stopped ${run.processes.length} process(es) in ${events.length} group(s) left by run ${run.runId} (${run.reason})`);
|
|
397
|
+
return { run_id: run.runId, groups: events.length, processes: run.processes.length, survivors: survivors.length };
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// ── delivering the events ────────────────────────────────────────────────────
|
|
401
|
+
|
|
402
|
+
function sensorIngestUrl(serverUrl) {
|
|
403
|
+
const url = new URL(serverUrl);
|
|
404
|
+
url.pathname = url.pathname.replace(/\/mcp-server\/?$/, "/sensor-ingest");
|
|
405
|
+
return url.toString();
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/**
|
|
409
|
+
* Send the outbox to sensor-ingest with the MCP key the run's repo binding names
|
|
410
|
+
* (`.botbuddy-agent.json` → `mcp_env`), read from the environment only. An event without
|
|
411
|
+
* a usable key, or one the server refused, stays for a later attempt; one that keeps
|
|
412
|
+
* failing is dropped after OUTBOX_MAX_ATTEMPTS. The file is moved aside first, so an event
|
|
413
|
+
* appended meanwhile is never lost to the rewrite.
|
|
414
|
+
*/
|
|
415
|
+
/**
|
|
416
|
+
* A sender killed mid-delivery (Codex #1925 r7 P2) leaves its batch in its own `.sending` file:
|
|
417
|
+
* once that sender is gone, put the batch back in the outbox. A live sender's is left alone.
|
|
418
|
+
*/
|
|
419
|
+
async function recoverStrandedBatches(dir, isAlive) {
|
|
420
|
+
const prefix = `${basename(reapOutboxPath(dir))}.`;
|
|
421
|
+
let names = [];
|
|
422
|
+
try { names = await readdir(dir); } catch { return; }
|
|
423
|
+
for (const name of names) {
|
|
424
|
+
if (!name.startsWith(prefix) || !name.endsWith(".sending")) continue;
|
|
425
|
+
const pid = Number(name.slice(prefix.length).split(".")[0]);
|
|
426
|
+
if (!Number.isInteger(pid) || pid <= 0 || isAlive(pid)) continue;
|
|
427
|
+
const stranded = join(dir, name);
|
|
428
|
+
// Re-owned as this process's own batch: if this flush dies too, the next one recovers it.
|
|
429
|
+
const claimed = join(dir, `${prefix}${process.pid}.${randomUUID()}.sending`);
|
|
430
|
+
try { await rename(stranded, claimed); } catch { continue; } // another flush took it
|
|
431
|
+
try {
|
|
432
|
+
const text = await readFile(claimed, "utf8");
|
|
433
|
+
if (text.trim()) await appendFile(reapOutboxPath(dir), text.endsWith("\n") ? text : `${text}\n`, { mode: 0o600 });
|
|
434
|
+
await unlink(claimed);
|
|
435
|
+
} catch { /* left for the next flush to retry */ }
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
function ingestAccepted(receipt) {
|
|
440
|
+
return Boolean(receipt) && Array.isArray(receipt.errors) && receipt.errors.length === 0 &&
|
|
441
|
+
(Number(receipt.inserted) || 0) + (Number(receipt.skipped) || 0) >= 1;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
export async function flushReapOutbox({
|
|
445
|
+
dir, env = process.env, fetchImpl = fetch, timeoutMs = DELIVERY_TIMEOUT_MS, budgetMs = Infinity, now = Date.now,
|
|
446
|
+
isAlive = pidAlive,
|
|
447
|
+
} = {}) {
|
|
448
|
+
const deadline = now() + budgetMs;
|
|
449
|
+
const path = reapOutboxPath(dir);
|
|
450
|
+
await recoverStrandedBatches(dir, isAlive);
|
|
451
|
+
const sending = `${path}.${process.pid}.${randomUUID()}.sending`;
|
|
452
|
+
try { await rename(path, sending); } catch { return { delivered: 0, pending: 0 }; }
|
|
453
|
+
let lines = [];
|
|
454
|
+
try { lines = (await readFile(sending, "utf8")).split("\n").filter(Boolean); } catch { /* nothing */ }
|
|
455
|
+
const keep = [];
|
|
456
|
+
let delivered = 0;
|
|
457
|
+
for (const line of lines.slice(-OUTBOX_MAX_EVENTS)) {
|
|
458
|
+
let event;
|
|
459
|
+
try { event = JSON.parse(line); } catch { continue; }
|
|
460
|
+
// Past the budget an event is kept as it is, for the next flush: not attempted, not counted.
|
|
461
|
+
if (now() >= deadline) { keep.push(event); continue; }
|
|
462
|
+
const token = event.delivery?.mcp_env ? env[event.delivery.mcp_env] : null;
|
|
463
|
+
let ok = false;
|
|
464
|
+
if (token && event.delivery?.server_url) {
|
|
465
|
+
const ac = new AbortController();
|
|
466
|
+
const timer = setTimeout(() => ac.abort(), timeoutMs);
|
|
467
|
+
try {
|
|
468
|
+
const res = await fetchImpl(sensorIngestUrl(event.delivery.server_url), {
|
|
469
|
+
method: "POST",
|
|
470
|
+
headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
|
|
471
|
+
body: JSON.stringify({
|
|
472
|
+
...(event.delivery.tenant ? { tenant: event.delivery.tenant } : {}),
|
|
473
|
+
source: event.source, kind: event.kind, dedupe_key: event.dedupe_key, occurred_at: event.occurred_at, payload: event.payload,
|
|
474
|
+
}),
|
|
475
|
+
signal: ac.signal,
|
|
476
|
+
});
|
|
477
|
+
// sensor-ingest answers 200 even when the insert failed (Codex #1925 r6 P2): the event is
|
|
478
|
+
// delivered only when the receipt names no error and the event was inserted or was a
|
|
479
|
+
// known duplicate (skipped).
|
|
480
|
+
ok = res.ok && ingestAccepted(await res.json?.().catch(() => null));
|
|
481
|
+
} catch { ok = false; } finally { clearTimeout(timer); }
|
|
482
|
+
}
|
|
483
|
+
if (ok) delivered++;
|
|
484
|
+
else if ((event.attempts ?? 0) + 1 < OUTBOX_MAX_ATTEMPTS) keep.push({ ...event, attempts: (event.attempts ?? 0) + 1 });
|
|
485
|
+
}
|
|
486
|
+
if (keep.length) await appendOutbox(dir, keep).catch(() => {});
|
|
487
|
+
await unlink(sending).catch(() => {});
|
|
488
|
+
return { delivered, pending: keep.length };
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
// ── ownership records ────────────────────────────────────────────────────────
|
|
492
|
+
|
|
493
|
+
export async function readOwnershipRecords(dir) {
|
|
494
|
+
const records = new Map();
|
|
495
|
+
let entries = [];
|
|
496
|
+
try { entries = await readdir(dir); } catch { return records; }
|
|
497
|
+
for (const entry of entries) {
|
|
498
|
+
if (!entry.endsWith(".json") || entry.startsWith(".")) continue;
|
|
499
|
+
const record = await readJsonFile(join(dir, entry));
|
|
500
|
+
if (record && validRunId(record.run_id) && `${record.run_id}.json` === entry && Number.isInteger(record.owner_pid)) records.set(record.run_id, record);
|
|
501
|
+
}
|
|
502
|
+
return records;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
async function deliveryBinding(cwd, serverUrl) {
|
|
506
|
+
try {
|
|
507
|
+
const { readAgentBinding } = await import("./wait-profile.mjs");
|
|
508
|
+
const binding = await readAgentBinding(cwd);
|
|
509
|
+
return binding ? { tenant: binding.tenant ?? null, mcp_env: binding.mcpEnv ?? null, server_url: serverUrl } : { tenant: null, mcp_env: null, server_url: serverUrl };
|
|
510
|
+
} catch { return { tenant: null, mcp_env: null, server_url: serverUrl }; }
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function serverUrlFrom(env) {
|
|
514
|
+
return env.BOTBUDDY_SERVER_URL || "https://api.bot-buddy.ai/functions/v1/mcp-server";
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function ownershipHandle({ dir, runId, record, log }) {
|
|
518
|
+
let released = null;
|
|
519
|
+
const path = recordPath(dir, runId);
|
|
520
|
+
// Record writes are serialized, and release waits for them, so a write never lands after the
|
|
521
|
+
// record is removed (callers do not await recordGroup: it must not add a tick before the
|
|
522
|
+
// caller attaches its child's exit listener).
|
|
523
|
+
let writes = Promise.resolve();
|
|
524
|
+
const persist = () => (writes = writes.catch(() => {}).then(() => writePrivateJson(path, record)));
|
|
525
|
+
return {
|
|
526
|
+
runId,
|
|
527
|
+
env: { [RUN_ID_ENV]: runId, [RUN_REGISTRY_ENV]: registryId(dir) },
|
|
528
|
+
/** The process this run is now owned by (a detached worker takes over from its launcher). */
|
|
529
|
+
async adoptOwner(pid) { record.owner_pid = pid; await persist(); },
|
|
530
|
+
/** A process group the run's child leads: covered even where `ps` cannot read its environment. */
|
|
531
|
+
async recordGroup(pgid) {
|
|
532
|
+
if (!Number.isInteger(pgid) || pgid <= 1 || record.groups.includes(pgid)) return;
|
|
533
|
+
record.groups.push(pgid);
|
|
534
|
+
await persist().catch(() => {});
|
|
535
|
+
},
|
|
536
|
+
/** The run ended: stop whatever it left running, then drop the record. Idempotent. */
|
|
537
|
+
release({ reason = "run_ended" } = {}) {
|
|
538
|
+
released ??= (async () => {
|
|
539
|
+
await writes.catch(() => {});
|
|
540
|
+
const result = { run_id: runId, groups: 0, processes: 0 };
|
|
541
|
+
try {
|
|
542
|
+
// A process the run left may start another while it handles SIGTERM (a supervisor
|
|
543
|
+
// restarting its child): snapshot again after each stop, a bounded number of times,
|
|
544
|
+
// until the run has nothing left (Codex #1925 r9 P2).
|
|
545
|
+
let clear = false;
|
|
546
|
+
for (let round = 0; round <= RELEASE_ROUNDS; round++) {
|
|
547
|
+
const processes = await listProcesses();
|
|
548
|
+
const [run] = findRunsToReap(processes, { registry: registryId(dir), records: new Map([[runId, record]]), onlyRunId: runId });
|
|
549
|
+
if (!run?.processes.length) { clear = true; break; }
|
|
550
|
+
if (round === RELEASE_ROUNDS) break;
|
|
551
|
+
const reaped = await reapRun({ ...run, reason }, { dir, log });
|
|
552
|
+
result.groups += reaped.groups ?? 0;
|
|
553
|
+
result.processes += reaped.processes ?? 0;
|
|
554
|
+
}
|
|
555
|
+
// Still respawning: the record stays, so the reaper finishes once this owner is gone.
|
|
556
|
+
if (!clear) {
|
|
557
|
+
await ensureOrphanReaper({ home: dirname(dirname(dir)), force: true });
|
|
558
|
+
return { ...result, error: "run_still_respawning" };
|
|
559
|
+
}
|
|
560
|
+
} catch (error) {
|
|
561
|
+
// The record stays: the reaper finishes the job once this owner is gone.
|
|
562
|
+
return { run_id: runId, error: error?.message ?? String(error) };
|
|
563
|
+
}
|
|
564
|
+
await unlink(path).catch(() => {});
|
|
565
|
+
// Something was stopped: the reaper delivers its events (and exits when idle).
|
|
566
|
+
if (result.processes > 0) await ensureOrphanReaper({ home: dirname(dirname(dir)), force: true });
|
|
567
|
+
return result;
|
|
568
|
+
})();
|
|
569
|
+
return released;
|
|
570
|
+
},
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/**
|
|
575
|
+
* Take ownership of a new run before its child is spawned. Pass `env` to the child
|
|
576
|
+
* (merged into its environment); call `recordGroup(child.pid)` once it is spawned (a
|
|
577
|
+
* detached child leads its own group) and `release()` when the run ends.
|
|
578
|
+
*/
|
|
579
|
+
export async function claimRunOwnership({
|
|
580
|
+
runId = randomUUID(), kind, cwd = process.cwd(), ownerPid = process.pid, home = homedir(), env = process.env,
|
|
581
|
+
startReaper = true, log = (line) => process.stderr.write(`${line}\n`),
|
|
582
|
+
} = {}) {
|
|
583
|
+
const dir = ownedRunsDir(home);
|
|
584
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
585
|
+
const record = {
|
|
586
|
+
schema_version: 1, run_id: runId, kind, owner_pid: ownerPid, groups: [], created_at: new Date().toISOString(),
|
|
587
|
+
delivery: await deliveryBinding(cwd, serverUrlFrom(env)),
|
|
588
|
+
};
|
|
589
|
+
await writePrivateJson(recordPath(dir, runId), record);
|
|
590
|
+
if (record.delivery.mcp_env) await writePrivateJson(defaultDeliveryPath(dir), record.delivery).catch(() => {});
|
|
591
|
+
if (startReaper) await ensureOrphanReaper({ home, env, force: true });
|
|
592
|
+
return ownershipHandle({ dir, runId, record, log });
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
/**
|
|
596
|
+
* A detached worker continues the run its launcher claimed: the record names the worker
|
|
597
|
+
* as the owner from now on. Null when this process is not marked with that run.
|
|
598
|
+
*/
|
|
599
|
+
export async function adoptRunOwnership({ runId, ownerPid = process.pid, launcherPid = process.ppid, home = homedir(), log } = {}) {
|
|
600
|
+
if (!validRunId(runId)) return null;
|
|
601
|
+
// The worker carries no run marker (it owns the run, it is not one of its processes), so the
|
|
602
|
+
// record vouches for it (Codex #1925 r4 P1): this HOME's record for this run, owned by the
|
|
603
|
+
// launcher that started this worker or already handed to it. A pre-fix launcher wrote none.
|
|
604
|
+
const dir = ownedRunsDir(home);
|
|
605
|
+
const record = await readJsonFile(recordPath(dir, runId));
|
|
606
|
+
if (!record || record.run_id !== runId) return null;
|
|
607
|
+
if (record.owner_pid !== ownerPid && record.owner_pid !== launcherPid) return null;
|
|
608
|
+
const handle = ownershipHandle({ dir, runId, record, log: log ?? ((line) => process.stderr.write(`${line}\n`)) });
|
|
609
|
+
await handle.adoptOwner(ownerPid);
|
|
610
|
+
return handle;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// ── the per-machine orphan reaper ────────────────────────────────────────────
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* One sweep: every run whose owner is gone (or that a pre-fix release left orphaned) is
|
|
617
|
+
* stopped, and the records of finished runs are removed.
|
|
618
|
+
*/
|
|
619
|
+
export async function sweepOnce({ dir, list = listProcesses, isAlive = pidAlive, stop = stopProcesses, legacy = true, log = () => {} } = {}) {
|
|
620
|
+
// The process snapshot first, then the records (Codex #1925 r2 P1): a run writes its record
|
|
621
|
+
// before it spawns its child, so every run seen in the snapshot already has its record here.
|
|
622
|
+
// Read the other way round, a run claimed in between looked record-less and was reaped live.
|
|
623
|
+
const processes = await list();
|
|
624
|
+
const records = await readOwnershipRecords(dir);
|
|
625
|
+
const runs = findRunsToReap(processes, { registry: registryId(dir), records, isAlive, legacy });
|
|
626
|
+
const results = [];
|
|
627
|
+
for (const run of runs) {
|
|
628
|
+
results.push(await reapRun(run, { dir, stop, log }));
|
|
629
|
+
if (!run.record) continue;
|
|
630
|
+
// A process stopped here may have started another while it handled SIGTERM (Codex #1925
|
|
631
|
+
// r10 P2): the record goes only once a fresh look finds nothing of the run, else it stays
|
|
632
|
+
// and the next owner check (its owner is gone) sweeps the run again.
|
|
633
|
+
const [left] = findRunsToReap(await list(), { registry: registryId(dir), records: new Map([[run.runId, run.record]]), isAlive, onlyRunId: run.runId, legacy: false });
|
|
634
|
+
if (!left?.processes.length) await unlink(recordPath(dir, run.runId)).catch(() => {});
|
|
635
|
+
}
|
|
636
|
+
return results;
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* The reaper process (`bb __reap-orphans`): hold the per-machine lock, sweep once, then
|
|
641
|
+
* check every owner each interval while any run is owned, and exit once none is.
|
|
642
|
+
*/
|
|
643
|
+
export async function runOrphanReaper({
|
|
644
|
+
home = homedir(), env = process.env, intervalMs = Number(env.BOTBUDDY_REAPER_INTERVAL_MS) || REAPER_INTERVAL_MS,
|
|
645
|
+
fullSweepMs = FULL_SWEEP_INTERVAL_MS, sleep = defaultSleep, isAlive = pidAlive, list = listProcesses, fetchImpl = fetch,
|
|
646
|
+
deliveryTimeoutMs = DELIVERY_TIMEOUT_MS, deliveryBudgetMs = DELIVERY_BUDGET_MS,
|
|
647
|
+
restart = () => ensureOrphanReaper({ home, env, force: true }), afterRelease = async () => {},
|
|
648
|
+
} = {}) {
|
|
649
|
+
const dir = ownedRunsDir(home);
|
|
650
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
651
|
+
const lock = await acquireDeliveryLock({ home, lockFile: reaperLockPath(dir) });
|
|
652
|
+
if (!lock.acquired) return { outcome: "held", holder_pid: lock.holderPid };
|
|
653
|
+
const totals = { sweeps: 0, runs: 0, processes: 0 };
|
|
654
|
+
// Telemetry is delivered beside the owner checks, never in their way (Codex #1925 P2): one
|
|
655
|
+
// bounded flush at a time, so an unreachable sensor-ingest never delays a reap.
|
|
656
|
+
let flushing = null;
|
|
657
|
+
const flush = () => {
|
|
658
|
+
flushing ??= flushReapOutbox({ dir, env, fetchImpl, timeoutMs: deliveryTimeoutMs, budgetMs: deliveryBudgetMs })
|
|
659
|
+
.catch(() => {}).finally(() => { flushing = null; });
|
|
660
|
+
};
|
|
661
|
+
const sweep = async () => {
|
|
662
|
+
const results = await sweepOnce({ dir, list, isAlive });
|
|
663
|
+
totals.sweeps++;
|
|
664
|
+
totals.runs += results.filter((result) => result.processes > 0).length;
|
|
665
|
+
totals.processes += results.reduce((sum, result) => sum + (result.processes ?? 0), 0);
|
|
666
|
+
await stampSweep(dir);
|
|
667
|
+
flush();
|
|
668
|
+
};
|
|
669
|
+
let result;
|
|
670
|
+
try {
|
|
671
|
+
await sweep();
|
|
672
|
+
let lastFull = Date.now();
|
|
673
|
+
for (;;) {
|
|
674
|
+
let records = await readOwnershipRecords(dir);
|
|
675
|
+
if (records.size === 0) {
|
|
676
|
+
// Shutdown handshake (Codex #1925 r5 P1): a run claimed while this reaper finishes its
|
|
677
|
+
// delivery saw the lock held and relies on it, so look again once delivery is done.
|
|
678
|
+
// One more bounded flush first (Codex #1925 r8 P2): a run's own release may have queued
|
|
679
|
+
// events since the last one, and found this reaper holding the lock.
|
|
680
|
+
await flushing;
|
|
681
|
+
flush();
|
|
682
|
+
await flushing;
|
|
683
|
+
records = await readOwnershipRecords(dir);
|
|
684
|
+
if (records.size === 0) { result = { outcome: "idle", ...totals }; break; }
|
|
685
|
+
}
|
|
686
|
+
const ownerGone = [...records.values()].some((record) => !isAlive(record.owner_pid));
|
|
687
|
+
if (ownerGone || Date.now() - lastFull >= fullSweepMs) {
|
|
688
|
+
await sweep();
|
|
689
|
+
lastFull = Date.now();
|
|
690
|
+
}
|
|
691
|
+
await sleep(intervalMs);
|
|
692
|
+
}
|
|
693
|
+
} finally {
|
|
694
|
+
await flushing; // bounded by the delivery budget
|
|
695
|
+
await lock.release();
|
|
696
|
+
}
|
|
697
|
+
// A run claimed between that last look and the release found the lock held: it is watched by
|
|
698
|
+
// nobody, so start a replacement (which, holding the lock now, sweeps and watches it).
|
|
699
|
+
await afterRelease();
|
|
700
|
+
if ((await readOwnershipRecords(dir)).size > 0) await restart();
|
|
701
|
+
return result;
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
async function stampSweep(dir) {
|
|
705
|
+
const path = sweepStampPath(dir);
|
|
706
|
+
const now = new Date();
|
|
707
|
+
try { await utimes(path, now, now); } catch { await writeFile(path, "", { mode: 0o600 }).catch(() => {}); }
|
|
708
|
+
}
|
|
709
|
+
|
|
710
|
+
/**
|
|
711
|
+
* Start the reaper unless one is running. Without `force` (a plain `bb` invocation) only
|
|
712
|
+
* when no sweep ran for SWEEP_STALE_MS or a run is still owned. Never throws.
|
|
713
|
+
*/
|
|
714
|
+
export async function ensureOrphanReaper({
|
|
715
|
+
home = homedir(), env = process.env, spawnImpl = spawn, isAlive = pidAlive, force = false, now = Date.now,
|
|
716
|
+
} = {}) {
|
|
717
|
+
try {
|
|
718
|
+
if (env.BOTBUDDY_RUN_REAPER === "off") return { started: false, reason: "disabled" };
|
|
719
|
+
if (process.platform !== "darwin" && process.platform !== "linux") return { started: false, reason: "unsupported_platform" };
|
|
720
|
+
const dir = ownedRunsDir(home);
|
|
721
|
+
const holder = await readJsonFile(reaperLockPath(dir));
|
|
722
|
+
if (Number.isInteger(holder?.pid) && isAlive(holder.pid)) return { started: false, reason: "held" };
|
|
723
|
+
if (!force) {
|
|
724
|
+
let stampAge = Infinity;
|
|
725
|
+
try { stampAge = now() - (await stat(sweepStampPath(dir))).mtimeMs; } catch { /* never swept */ }
|
|
726
|
+
const owned = (await readOwnershipRecords(dir)).size > 0;
|
|
727
|
+
if (stampAge < SWEEP_STALE_MS && !owned) return { started: false, reason: "recent" };
|
|
728
|
+
}
|
|
729
|
+
const bin = join(dirname(fileURLToPath(import.meta.url)), "..", "bin", "botbuddy.mjs");
|
|
730
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
731
|
+
const child = spawnImpl(process.execPath, [bin, "__reap-orphans"], { detached: true, stdio: "ignore", cwd: home, env: withoutRunMarkers(env), windowsHide: true });
|
|
732
|
+
child.on?.("error", () => { /* best effort: the next invocation retries */ });
|
|
733
|
+
child.unref?.();
|
|
734
|
+
return { started: true };
|
|
735
|
+
} catch (error) {
|
|
736
|
+
return { started: false, reason: `error:${error instanceof Error ? error.message : String(error)}` };
|
|
737
|
+
}
|
|
738
|
+
}
|