@botbuddy/cli 1.116.0 → 1.118.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.mjs +95 -18
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.118.0
|
|
4
|
+
|
|
5
|
+
- BOT-3519: `bb stack run --test-child --child-placement require-host` places the stack lease only on a host that can run the child. The CLI derives the child's whole prerequisite set before the lease (toolchain or the declared tools, `child-layer`, `system-packages-<distro>` for the head's declared system packages, `host-local-callback` for a `--callback-port` run, and `--child-requires`) and sends it as `child_host_prerequisites`. The control plane then weighs only owned hosts in `child_exec_hosts` whose capabilities, reported in the last 15 minutes, provide all of it; a busy one queues the lease as usual. When none qualifies the run ends before any lease or bundle upload with exit 5 and `CHILD_HOST_PREREQUISITES_MISSING` (also for a `--host` pin that lacks one): the receipt's `child_placement.considered[]` names each host with `child_reason` and `missing_prerequisites`, and the run prints one line per host. When the only host that could run it is draining or in maintenance, the code is `CHILD_HOST_UNAVAILABLE` and `child_placement.child_host` names it. `prefer-host` is unchanged. Needs MCP 2.158.0.
|
|
6
|
+
|
|
7
|
+
## 1.117.0
|
|
8
|
+
|
|
9
|
+
- BOT-3463: a run started by `bb stack run`, `bb run` (foreground and detached, so `bb test` and `bb push` too) owns every process its command launches. The child's environment carries a run-scoped marker (`BOTBUDDY_RUN_ID`, `BOTBUDDY_RUN_REGISTRY`) that every descendant inherits, `setsid` daemons included, and the run writes an owner record under `~/.botbuddy/owned-runs/` (0600). When the run ends (exit, signal, timeout, lease loss) its owner stops what is still marked, plus the child's process group and its descendants: SIGTERM, then SIGKILL after 5 s. A detached worker whose command exited lets its output drain for 2 s, then stops what kept the pipes open. When the owner itself dies (SIGKILL), the per-machine reaper (`bb __reap-orphans`, started by bb, one lock per machine) stops that run's tree within one 10 s interval. A `bb` invocation also starts a sweep when none ran for 10 minutes; it stops leftovers of earlier releases by their run-scoped `BOTBUDDY_STACK_LEASE_ID` / `BOTBUDDY_TEST_RUN_ID` marker once the run's top process has only init above it. Processes are never matched by name: one without a marker, such as a dev server started by hand, is never touched. Each stopped process group is one `sensor_events` row (`bb-cli` / `run_process_reaped`: run id, PID, PGID, age), kept in a local outbox until `sensor-ingest` takes it. `BOTBUDDY_RUN_REAPER=off` disables the reaper. Host test children are unchanged: their systemd unit (`KillMode=control-group`) already ends with the run.
|
|
10
|
+
|
|
3
11
|
## 1.116.0
|
|
4
12
|
|
|
5
13
|
- BOT-3536: `bb stack run --ticket <Y>` follows an agent to its next ticket. When the server refuses the run with a session-scope `STALE_AGENT_CONTEXT` (the session is still registered for X), and this checkout's branch names Y, the run sends one ticket-moving `heartbeat` on the worktree's own cached session and one fresh admission, which the unchanged fence judges again. A run for a ticket the branch does not name, an agent-scope refusal, and an env- or flag-supplied token are never rebound, and a run rebinds at most once. The refusal hint no longer offers `bb doctor --fix` (it renews the session in place and keeps its ticket); it names `bb call heartbeat --json '{"ticket_id":"Y"}'`. The receipt carries `context_rebound: {from, to}` and `registered_ticket_id`; the `stack_run_outcome` row carries `registered_ticket_id` (stale-context rows only) and `context_rebound: true`, and an older server's unknown-key refusal drops each newer key in turn. Needs MCP 2.157.2 for the two outcome keys.
|
package/bin/botbuddy.mjs
CHANGED
|
@@ -2,9 +2,15 @@
|
|
|
2
2
|
import { run } from "../src/commands.mjs";
|
|
3
3
|
import { ensureRunDelivery } from "../src/run-delivery.mjs";
|
|
4
4
|
import { feedbackReminder } from "../src/feedback-reminder.mjs";
|
|
5
|
+
import { ensureOrphanReaper, runOrphanReaper } from "../src/run-ownership.mjs";
|
|
5
6
|
import { writeSync } from "node:fs";
|
|
6
7
|
|
|
7
8
|
const argv = process.argv.slice(2);
|
|
9
|
+
|
|
10
|
+
// BOT-3463: the per-machine orphan reaper (started detached by bb, never typed by hand).
|
|
11
|
+
if (argv[0] === "__reap-orphans") {
|
|
12
|
+
runOrphanReaper().then(() => process.exit(0), () => process.exit(1));
|
|
13
|
+
} else {
|
|
8
14
|
// Some commands exit directly; observe the final exit once so those paths
|
|
9
15
|
// receive the same stderr-only guidance without changing their exit status.
|
|
10
16
|
process.once("exit", (code) => {
|
|
@@ -29,6 +35,9 @@ const readOnly = flags.some((flag) => flag === "--help" || flag === "-h")
|
|
|
29
35
|
// Feedback must not start unrelated delivery while an agent reports a blocker.
|
|
30
36
|
const feedbackCommand = argv[0] === "feedback";
|
|
31
37
|
const delivery = deliveryProcessArgs || readOnly || feedbackCommand ? Promise.resolve() : ensureRunDelivery().catch(() => {});
|
|
38
|
+
// BOT-3463 (AC-2): a `bb` invocation sweeps the processes dead runs left behind when no sweep ran
|
|
39
|
+
// for ten minutes. A stat and a small read when nothing is due; it never fails the command.
|
|
40
|
+
if (!deliveryProcessArgs && !readOnly && !feedbackCommand) void ensureOrphanReaper().catch(() => {});
|
|
32
41
|
|
|
33
42
|
delivery.then(() => run(argv)).then((code) => {
|
|
34
43
|
if (typeof code === "number") process.exitCode = code;
|
|
@@ -36,3 +45,4 @@ delivery.then(() => run(argv)).then((code) => {
|
|
|
36
45
|
console.error(`\x1b[31m✗\x1b[0m ${err?.message || err}`);
|
|
37
46
|
process.exit(1);
|
|
38
47
|
});
|
|
48
|
+
}
|
|
Binary file
|
|
Binary file
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
|
-
"release_version": "1.
|
|
3
|
-
"source_commit": "
|
|
4
|
-
"source_sha256": "
|
|
2
|
+
"release_version": "1.118.0",
|
|
3
|
+
"source_commit": "f61949cb5c11c1ab0fd33274a3d69fed41633e4f",
|
|
4
|
+
"source_sha256": "126904b6d3e90b5ce30af5fc7c33feb99efe8023a5b1374f4c8db22a5afbf66e",
|
|
5
5
|
"target": "darwin-arm64",
|
|
6
|
-
"sha256": "
|
|
6
|
+
"sha256": "a58c0dcbf5101515a362023b6e744d49bde8767ced42e68e7579053e3e077073"
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
|
-
"release_version": "1.
|
|
3
|
-
"source_commit": "
|
|
4
|
-
"source_sha256": "
|
|
2
|
+
"release_version": "1.118.0",
|
|
3
|
+
"source_commit": "f61949cb5c11c1ab0fd33274a3d69fed41633e4f",
|
|
4
|
+
"source_sha256": "126904b6d3e90b5ce30af5fc7c33feb99efe8023a5b1374f4c8db22a5afbf66e",
|
|
5
5
|
"target": "linux-x64",
|
|
6
|
-
"sha256": "
|
|
6
|
+
"sha256": "b6fe4938aaebf1ac5f303b2ab7fa466314ab580426159c85de3be5c26e35ff8a"
|
|
7
7
|
}
|
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schema_version": 1,
|
|
3
|
-
"release_version": "1.
|
|
4
|
-
"source_commit": "
|
|
5
|
-
"source_sha256": "
|
|
3
|
+
"release_version": "1.118.0",
|
|
4
|
+
"source_commit": "f61949cb5c11c1ab0fd33274a3d69fed41633e4f",
|
|
5
|
+
"source_sha256": "126904b6d3e90b5ce30af5fc7c33feb99efe8023a5b1374f4c8db22a5afbf66e",
|
|
6
6
|
"targets": {
|
|
7
7
|
"darwin-arm64": {
|
|
8
8
|
"goos": "darwin",
|
|
9
9
|
"goarch": "arm64",
|
|
10
10
|
"binary": "daemon/bin/darwin-arm64/botbuddy-daemon",
|
|
11
|
-
"sha256": "
|
|
11
|
+
"sha256": "a58c0dcbf5101515a362023b6e744d49bde8767ced42e68e7579053e3e077073",
|
|
12
12
|
"mode": "0755"
|
|
13
13
|
},
|
|
14
14
|
"linux-x64": {
|
|
15
15
|
"goos": "linux",
|
|
16
16
|
"goarch": "amd64",
|
|
17
17
|
"binary": "daemon/bin/linux-x64/botbuddy-daemon",
|
|
18
|
-
"sha256": "
|
|
18
|
+
"sha256": "b6fe4938aaebf1ac5f303b2ab7fa466314ab580426159c85de3be5c26e35ff8a",
|
|
19
19
|
"mode": "0755"
|
|
20
20
|
}
|
|
21
21
|
}
|
package/package.json
CHANGED
package/src/run-delivery.mjs
CHANGED
|
@@ -25,6 +25,7 @@
|
|
|
25
25
|
import { createHash, randomUUID } from "node:crypto";
|
|
26
26
|
import { chmod, link, mkdir, readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
|
27
27
|
import { execFile, spawn } from "node:child_process";
|
|
28
|
+
import { withoutRunMarkers } from "./run-markers.mjs";
|
|
28
29
|
import { dirname, join } from "node:path";
|
|
29
30
|
import { homedir } from "node:os";
|
|
30
31
|
import { fileURLToPath } from "node:url";
|
|
@@ -337,8 +338,8 @@ export async function drainOnce({
|
|
|
337
338
|
* Take the per-machine delivery lock. A lock whose holder PID is gone is stale
|
|
338
339
|
* and is taken over.
|
|
339
340
|
*/
|
|
340
|
-
export async function acquireDeliveryLock({ home = homedir(), pid = process.pid, isAlive = pidAlive } = {}) {
|
|
341
|
-
|
|
341
|
+
export async function acquireDeliveryLock({ home = homedir(), pid = process.pid, isAlive = pidAlive, lockFile = deliveryLockPath(home) } = {}) {
|
|
342
|
+
// BOT-3463: the orphan reaper takes its own per-machine lock through the same mechanism.
|
|
342
343
|
await mkdir(dirname(lockFile), { recursive: true });
|
|
343
344
|
const candidate = `${lockFile}.${pid}.${randomUUID()}.tmp`;
|
|
344
345
|
await writeFile(candidate, JSON.stringify({ pid, started_at: new Date().toISOString() }), { mode: 0o600 });
|
|
@@ -487,7 +488,8 @@ export async function ensureRunDelivery({
|
|
|
487
488
|
const holder = await readJson(deliveryLockPath(home));
|
|
488
489
|
if (Number.isInteger(holder?.pid) && isAlive(holder.pid)) return { started: false, reason: "held" };
|
|
489
490
|
const bin = join(dirname(fileURLToPath(import.meta.url)), "..", "bin", "botbuddy.mjs");
|
|
490
|
-
|
|
491
|
+
// BOT-3463: the delivery process outlives the run that started it, so it carries no run marker.
|
|
492
|
+
const child = spawnImpl(process.execPath, [bin, "run", "--deliver"], { detached: true, stdio: "ignore", cwd: home, env: withoutRunMarkers(env), windowsHide: true });
|
|
491
493
|
child.on?.("error", () => { /* best effort: the next invocation retries */ });
|
|
492
494
|
child.unref?.();
|
|
493
495
|
return { started: true, reason: "pending" };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
// BOT-3463 — the run-scoped environment marker every bb run puts on the processes it launches.
|
|
2
|
+
//
|
|
3
|
+
// The marker is what identifies a run's processes later, never a process name: a dev
|
|
4
|
+
// server a user started by hand carries no marker and is never touched.
|
|
5
|
+
|
|
6
|
+
/** The run that launched this process (inherited by every descendant, setsid or not). */
|
|
7
|
+
export const RUN_ID_ENV = "BOTBUDDY_RUN_ID";
|
|
8
|
+
/** Which ownership record directory (a hash of it) judges that run, so another HOME never does. */
|
|
9
|
+
export const RUN_REGISTRY_ENV = "BOTBUDDY_RUN_REGISTRY";
|
|
10
|
+
/**
|
|
11
|
+
* Run-scoped markers that bb releases before BOT-3463 already set on a run's child:
|
|
12
|
+
* `bb stack run` exports the lease, `bb test` the test run. Orphans left by those
|
|
13
|
+
* releases are found by them (AC-2). Order is precedence when a process has both.
|
|
14
|
+
*/
|
|
15
|
+
export const LEGACY_RUN_MARKERS = Object.freeze(["BOTBUDDY_STACK_LEASE_ID", "BOTBUDDY_TEST_RUN_ID"]);
|
|
16
|
+
export const ALL_RUN_MARKERS = Object.freeze([RUN_ID_ENV, RUN_REGISTRY_ENV, ...LEGACY_RUN_MARKERS]);
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* The environment for a long-lived bb helper (the run delivery process, the orphan
|
|
20
|
+
* reaper) that must outlive the run whose process started it: no run marker, so it is
|
|
21
|
+
* never taken for part of that run's tree.
|
|
22
|
+
*/
|
|
23
|
+
export function withoutRunMarkers(env = process.env) {
|
|
24
|
+
const clean = { ...env };
|
|
25
|
+
for (const name of ALL_RUN_MARKERS) delete clean[name];
|
|
26
|
+
return clean;
|
|
27
|
+
}
|
|
@@ -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
|
+
}
|
package/src/run.mjs
CHANGED
|
@@ -6,6 +6,8 @@
|
|
|
6
6
|
// allowed to call update_command_run. A bb-wait is therefore a notification
|
|
7
7
|
// mechanism, never the owner of a child process.
|
|
8
8
|
|
|
9
|
+
import { adoptRunOwnership, claimRunOwnership } from "./run-ownership.mjs";
|
|
10
|
+
import { withoutRunMarkers } from "./run-markers.mjs";
|
|
9
11
|
import { createHash, randomUUID } from "node:crypto";
|
|
10
12
|
import { stackLeaseIdFromEnv, withStackLeaseCorrelation } from "./stack-lease-correlation.mjs";
|
|
11
13
|
import { mkdir, readFile, writeFile, chmod, unlink, stat, rename } from "node:fs/promises";
|
|
@@ -125,6 +127,7 @@ function signalExitCode(signal) {
|
|
|
125
127
|
// event), then returns the child verdict even when terminal delivery degrades.
|
|
126
128
|
export async function launchForegroundRun(argv, {
|
|
127
129
|
cwd = process.cwd(), spawnImpl = spawn, identity = null, outbox = null, signalEmitter = process, env = process.env,
|
|
130
|
+
claimOwnership = spawnImpl === spawn ? claimRunOwnership : null,
|
|
128
131
|
} = {}) {
|
|
129
132
|
const { opts, command, errors } = parseRunArgs(argv);
|
|
130
133
|
if (errors.length) return { exitCode: EXIT.INVALID, receipt: { schema_version: RUN_SCHEMA_VERSION, outcome: "rejected", errors, exit_code: EXIT.INVALID } };
|
|
@@ -179,12 +182,18 @@ export async function launchForegroundRun(argv, {
|
|
|
179
182
|
return { exitCode: EXIT.INTERNAL, receipt: { schema_version: RUN_SCHEMA_VERSION, outcome: "rejected", error: error?.code ?? "telemetry_start_not_durable", exit_code: EXIT.INTERNAL } };
|
|
180
183
|
}
|
|
181
184
|
let child;
|
|
185
|
+
// BOT-3463: this run owns every process its command launches, setsid or not.
|
|
186
|
+
const ownership = await claimOwnershipQuietly(claimOwnership, { runId, kind: `foreground_${opts.kind}`, cwd, env });
|
|
182
187
|
try {
|
|
183
188
|
// A foreground command still needs its own process group: hooks commonly
|
|
184
189
|
// launch package managers or test runners, whose descendants otherwise
|
|
185
190
|
// survive a timeout after their immediate parent exits.
|
|
186
|
-
child = spawnImpl(command[0], command.slice(1), { cwd, detached: process.platform !== "win32", stdio: "inherit", windowsHide: true
|
|
191
|
+
child = spawnImpl(command[0], command.slice(1), { cwd, detached: process.platform !== "win32", stdio: "inherit", windowsHide: true,
|
|
192
|
+
...(ownership ? { env: { ...process.env, ...ownership.env } } : {}) });
|
|
193
|
+
// Not awaited: no tick between spawn and the exit listeners, so a fast exit is never missed.
|
|
194
|
+
void ownership?.recordGroup(child.pid);
|
|
187
195
|
} catch (error) {
|
|
196
|
+
await ownership?.release();
|
|
188
197
|
await telemetry.append({ ...base, action: "terminal", producer_event_id: `${runId}:terminal`, producer_sequence: 1, outcome: "crashed", diagnostic: { code: "spawn_failed", category: "spawn" } }).catch(() => {});
|
|
189
198
|
return { exitCode: EXIT.INTERNAL, receipt: { schema_version: RUN_SCHEMA_VERSION, outcome: "crashed", run_id: runId, telemetry: "degraded", exit_code: EXIT.INTERNAL, ...FOREGROUND_INSPECTION } };
|
|
190
199
|
}
|
|
@@ -197,9 +206,13 @@ export async function launchForegroundRun(argv, {
|
|
|
197
206
|
}, opts.timeout * 1000);
|
|
198
207
|
const forwarded = forwardTerminationSignals(child, signalEmitter);
|
|
199
208
|
const result = await waitForChild(child);
|
|
200
|
-
|
|
209
|
+
// The command has ended: its timeout no longer applies, even while cleanup below takes time
|
|
210
|
+
// (Codex #1925 r2 P2).
|
|
201
211
|
clearTimeout(timeout);
|
|
202
212
|
clearTimeout(killTimer);
|
|
213
|
+
// BOT-3463: whatever the command left running (a backgrounded dev server) stops with the run.
|
|
214
|
+
if (ownership) await ownership.release();
|
|
215
|
+
forwarded.cleanup();
|
|
203
216
|
const terminalSignal = forwarded.signal ?? result.signal;
|
|
204
217
|
const outcome = result.error ? "crashed" : foregroundOutcome({ ...result, signal: terminalSignal, timedOut });
|
|
205
218
|
let telemetryState = "durable";
|
|
@@ -635,6 +648,19 @@ function workerInvocation(context) {
|
|
|
635
648
|
return [process.execPath, [bin, "run", "--worker", context]];
|
|
636
649
|
}
|
|
637
650
|
|
|
651
|
+
// BOT-3463: how long a workload's output may keep flowing after its command exited.
|
|
652
|
+
const WORKLOAD_EXIT_DRAIN_MS = 2_000;
|
|
653
|
+
|
|
654
|
+
// BOT-3463: ownership is the cleanup guarantee, not a precondition — a record that cannot be
|
|
655
|
+
// written (an unwritable HOME) is said once and the run goes ahead unowned.
|
|
656
|
+
async function claimOwnershipQuietly(claim, args) {
|
|
657
|
+
if (!claim) return null;
|
|
658
|
+
try { return await claim(args); } catch (error) {
|
|
659
|
+
process.stderr.write(`bb: run ${args.runId} is not tracked for cleanup (${error?.code ?? error?.message ?? error}); processes it leaves behind are not stopped\n`);
|
|
660
|
+
return null;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
|
|
638
664
|
function sessionFailure(code) { return Object.assign(new Error(code), { code }); }
|
|
639
665
|
|
|
640
666
|
// A selected ID is metadata, not a credential. Require positive private-cache
|
|
@@ -682,6 +708,7 @@ function rejectedSessionReceipt(error, runId) {
|
|
|
682
708
|
export async function launchRun(argv, {
|
|
683
709
|
cwd = process.cwd(), spawnImpl = spawn, call = null, childEnv = null, testRun = null, push = null, beforeSpawn = null,
|
|
684
710
|
resolveCredential = null, renewCredential = selfHealAgentSession, env = process.env, getSourceSha = sourceSha,
|
|
711
|
+
claimOwnership = spawnImpl === spawn ? claimRunOwnership : null,
|
|
685
712
|
} = {}) {
|
|
686
713
|
const parsed = parseRunArgs(argv, env);
|
|
687
714
|
let managedCredential = null;
|
|
@@ -753,11 +780,20 @@ export async function launchRun(argv, {
|
|
|
753
780
|
if (beforeSpawn) await beforeSpawn(runId);
|
|
754
781
|
const [file, args] = workerInvocation(context);
|
|
755
782
|
let workerPid = null;
|
|
783
|
+
// BOT-3463: the run owns its workload's process tree. The launcher claims it; the detached
|
|
784
|
+
// worker it starts becomes the owner, and stops what the workload left when the run ends.
|
|
785
|
+
const ownership = await claimOwnershipQuietly(claimOwnership, { runId, kind: opts.kind ? `detached_${opts.kind}` : "detached", cwd, env });
|
|
756
786
|
try {
|
|
757
|
-
|
|
787
|
+
// The worker owns the run and is never one of its processes (Codex #1925 r3 P1): it carries no
|
|
788
|
+
// run marker, so a sweep after it releases cannot take it while it finalizes. It marks the
|
|
789
|
+
// workload it spawns instead.
|
|
790
|
+
const worker = spawnImpl(file, args, { detached: true, stdio: "ignore", windowsHide: true,
|
|
791
|
+
...(ownership ? { env: withoutRunMarkers(process.env) } : {}) });
|
|
758
792
|
workerPid = Number.isInteger(worker.pid) ? worker.pid : null;
|
|
793
|
+
if (ownership && workerPid) await ownership.adoptOwner(workerPid);
|
|
759
794
|
worker.unref();
|
|
760
795
|
} catch (error) {
|
|
796
|
+
await ownership?.release();
|
|
761
797
|
// BOT-1572 (Codex P2): use effectiveCall — `call` may be null (the token-pinned
|
|
762
798
|
// default path), so calling it here would throw and strand the registered run.
|
|
763
799
|
await effectiveCall("update_command_run", { run_id: runId, run_credential: registration.data.run_credential, status: "owner_lost", invalidated_reason: `launcher_failed:${error instanceof Error ? error.message : String(error)}` });
|
|
@@ -781,9 +817,13 @@ export async function runWorker(contextFile, {
|
|
|
781
817
|
// BOT-2530: worker liveness lease renewal cadence (tests inject a fake timer).
|
|
782
818
|
workerHeartbeatIntervalMs = WORKER_HEARTBEAT_INTERVAL_MS, setIntervalFn = setInterval,
|
|
783
819
|
liveLogIntervalMs = 1_000,
|
|
820
|
+
adoptOwnership = spawnImpl === spawn ? adoptRunOwnership : null,
|
|
784
821
|
} = {}) {
|
|
785
822
|
const retry = { sleep, now, budgetMs: terminalBudgetMs, startDelivery };
|
|
786
823
|
const context = JSON.parse(await readFile(contextFile, "utf8"));
|
|
824
|
+
// BOT-3463: this worker now owns the run its launcher claimed (null for a pre-fix launcher).
|
|
825
|
+
let ownership = null;
|
|
826
|
+
try { ownership = adoptOwnership ? await adoptOwnership({ runId: context.run_id }) : null; } catch { ownership = null; }
|
|
787
827
|
const callbackCall = callWithContextIdentity(context, call);
|
|
788
828
|
const ownerHeartbeat = startOwnerHeartbeat(context, callbackCall);
|
|
789
829
|
const workerLease = startWorkerLease(context, callbackCall, { intervalMs: workerHeartbeatIntervalMs, setIntervalFn });
|
|
@@ -847,7 +887,7 @@ export async function runWorker(contextFile, {
|
|
|
847
887
|
return await preWorkloadCancellationReceipt(context);
|
|
848
888
|
}
|
|
849
889
|
try {
|
|
850
|
-
child = spawnImpl(context.command[0], context.command.slice(1), { cwd: context.cwd, detached: true, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, ...(context.child_env ? { env: { ...process.env, ...context.child_env } } : {}) });
|
|
890
|
+
child = spawnImpl(context.command[0], context.command.slice(1), { cwd: context.cwd, detached: true, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, ...(context.child_env || ownership ? { env: { ...process.env, ...context.child_env, ...ownership?.env } } : {}) });
|
|
851
891
|
} catch (error) {
|
|
852
892
|
const endedAt = new Date().toISOString();
|
|
853
893
|
const receipt = await finalize(context, { status: "owner_lost", startedAt, endedAt, exitCode: null, signal: null, reason: `workload_spawn_failed:${error instanceof Error ? error.message : String(error)}` }, callbackCall, retry);
|
|
@@ -857,6 +897,20 @@ export async function runWorker(contextFile, {
|
|
|
857
897
|
// Subscribe before any filesystem I/O so a busy parallel test run (or a real
|
|
858
898
|
// fast failure) cannot lose the sole terminal event.
|
|
859
899
|
const completion = waitForChild(child);
|
|
900
|
+
// The command's own exit decides whether it beat its deadline, not the later closing of
|
|
901
|
+
// pipes a process it left behind still holds (Codex #1925 r6 P2).
|
|
902
|
+
let workloadExited = false;
|
|
903
|
+
child.once?.("exit", () => { workloadExited = true; });
|
|
904
|
+
// BOT-3463: the run ends when its command exits. A process it backgrounded (a dev server)
|
|
905
|
+
// still holds the output pipes, which would keep the run open until its timeout: after a
|
|
906
|
+
// short drain, stop it, so the pipes close and the run completes. Attached before any await
|
|
907
|
+
// (Codex #1925 P1), like the completion listener, so an immediate exit is never missed.
|
|
908
|
+
if (ownership) {
|
|
909
|
+
child.once?.("exit", () => {
|
|
910
|
+
const drain = setTimeout(() => { void ownership.release(); }, WORKLOAD_EXIT_DRAIN_MS);
|
|
911
|
+
drain.unref?.();
|
|
912
|
+
});
|
|
913
|
+
}
|
|
860
914
|
// Capture pipes before the first await too. A short-lived command can emit
|
|
861
915
|
// all of its output while context persistence yields to the filesystem; if
|
|
862
916
|
// these listeners are attached afterwards, its terminal receipt silently
|
|
@@ -879,6 +933,7 @@ export async function runWorker(contextFile, {
|
|
|
879
933
|
liveLogTimer = setInterval(flushLiveLog, liveLogIntervalMs);
|
|
880
934
|
liveLogTimer.unref?.();
|
|
881
935
|
await persistWorkerContext({ workload_pid: child.pid, worker_state: "running" });
|
|
936
|
+
void ownership?.recordGroup(child.pid);
|
|
882
937
|
// BOT-1510: for a test lane, tail the reporter's NDJSON and flush per-case
|
|
883
938
|
// verdicts while the child runs. The test process never touches the network.
|
|
884
939
|
const lane = context.test_run ? startLaneFlusher(context, callbackCall) : null;
|
|
@@ -886,13 +941,18 @@ export async function runWorker(contextFile, {
|
|
|
886
941
|
const pushMonitor = context.push ? startPushMonitor(context, callbackCall) : null;
|
|
887
942
|
let killTimer;
|
|
888
943
|
const timer = setTimeout(() => {
|
|
889
|
-
|
|
944
|
+
// Past the deadline the group is still stopped, so held pipes close; a command that had
|
|
945
|
+
// already exited is not reported timed out for it.
|
|
946
|
+
if (!workloadExited) timedOut = true;
|
|
890
947
|
terminate(child, "SIGTERM");
|
|
891
948
|
killTimer = setTimeout(() => terminate(child, "SIGKILL"), context.timeout_grace_ms ?? TIMEOUT_GRACE_MS);
|
|
892
949
|
}, context.timeout_seconds * 1000);
|
|
893
950
|
const result = await completion;
|
|
951
|
+
// The workload has ended: its timeout no longer applies while cleanup runs (Codex #1925 r2 P2).
|
|
894
952
|
clearTimeout(timer);
|
|
895
953
|
clearTimeout(killTimer);
|
|
954
|
+
// BOT-3463: the run ends here; nothing the workload started outlives it.
|
|
955
|
+
if (ownership) await ownership.release();
|
|
896
956
|
clearInterval(liveLogTimer);
|
|
897
957
|
flushLiveLog();
|
|
898
958
|
await logWrites;
|
|
@@ -909,6 +969,7 @@ export async function runWorker(contextFile, {
|
|
|
909
969
|
return receipt;
|
|
910
970
|
} finally {
|
|
911
971
|
clearInterval(liveLogTimer);
|
|
972
|
+
if (ownership) await ownership.release();
|
|
912
973
|
if (workerLease) await workerLease.stop();
|
|
913
974
|
if (ownerHeartbeat) await ownerHeartbeat.stop();
|
|
914
975
|
signalEmitter.removeListener("SIGTERM", cancellationHandler);
|
package/src/stack.mjs
CHANGED
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
// labelled fallback for when no Helper is available: it runs `supabase start`/
|
|
28
28
|
// `stop` itself and self-activates/finalizes via the fallback MCP tools.
|
|
29
29
|
|
|
30
|
+
import { claimRunOwnership } from "./run-ownership.mjs";
|
|
30
31
|
import { writeLaneStatus } from "./lane-status.mjs";
|
|
31
32
|
import { markFeedbackGuidanceShown } from "./feedback-reminder.mjs";
|
|
32
33
|
import { spawn, spawnSync } from "child_process";
|
|
@@ -338,7 +339,14 @@ ${bold("run OPTIONS")}
|
|
|
338
339
|
requester pool) is refused before the child starts with CHILD_PLACEMENT_REQUIRED
|
|
339
340
|
(exit 5); the receipt adds child_placement_reason, missing_prerequisites and
|
|
340
341
|
serving_host, and the slot and the lease are released. A full serving-host
|
|
341
|
-
pool still waits for a slot.
|
|
342
|
+
pool still waits for a slot. BOT-3519: require-host also places the LEASE
|
|
343
|
+
only on an owned host whose child capabilities meet the whole prerequisite
|
|
344
|
+
set (toolchain, child-layer, system-packages-<distro>, host-local-callback
|
|
345
|
+
and --child-requires); a busy one is waited for. Refused before any lease
|
|
346
|
+
or upload (exit 5): CHILD_HOST_PREREQUISITES_MISSING (child_placement.
|
|
347
|
+
considered[] names each host and what it lacks; also a --host pin that
|
|
348
|
+
lacks one) or CHILD_HOST_UNAVAILABLE (the only host that could is
|
|
349
|
+
draining or in maintenance; child_placement.child_host names it).
|
|
342
350
|
--child-requires LIST BOT-3030: what the child needs on a host (comma list: node>=24,pnpm,deno,
|
|
343
351
|
curl,git,jq,psql,tar,tar-extract,playwright-chromium-libs, or a name the
|
|
344
352
|
head's system_packages provide, e.g. playwright-webkit-libs). node, pnpm
|
|
@@ -1716,6 +1724,39 @@ export function stackPathRootRefusalNotice(code, message) {
|
|
|
1716
1724
|
return `${yellow("⚠")} stack: ${message || STACK_PATH_ROOT_REFUSED_FALLBACK}`;
|
|
1717
1725
|
}
|
|
1718
1726
|
|
|
1727
|
+
/**
|
|
1728
|
+
* BOT-3240/3407/3396/3470/3399: a --test-child run's whole host prerequisite set — the head's
|
|
1729
|
+
* toolchain (or its declared tools), its dependency layer, its declared system packages and a
|
|
1730
|
+
* host-local callback — plus --child-requires. BOT-3519: computed once before the lease, so a
|
|
1731
|
+
* require-host run's lease is placed only on a host that provides all of it.
|
|
1732
|
+
*/
|
|
1733
|
+
export function childPrerequisiteSet(opts, worktreeRoot, adapters = {}, log = () => {}) {
|
|
1734
|
+
const head = (adapters.headToolchain ?? headToolchain)(worktreeRoot);
|
|
1735
|
+
const toolchain = toolchainPrerequisites(opts.childRequires ?? [], head);
|
|
1736
|
+
if (head.manifest) log(`stack: this head declares its toolchain (mise.toml, mise.lock): placement requires a host with \`toolchain\`${toolchain.provided.length ? `; ${toolchain.provided.join(", ")} come from the manifest` : ""}`);
|
|
1737
|
+
else if (head.lockMissing) log("stack: this head commits mise.toml without mise.lock, so a host builds no toolchain for it; run `mise lock` and commit mise.lock to give host children the repo's own tools");
|
|
1738
|
+
const declaresLayer = (adapters.headDeclaresChildLayer ?? headDeclaresChildLayer)(worktreeRoot);
|
|
1739
|
+
if (declaresLayer) log("stack: this head declares a dependency layer (.botbuddy/child-layer.json): placement requires a host with `child-layer`");
|
|
1740
|
+
const systemPackages = declaresLayer ? (adapters.headSystemPackages ?? headSystemPackages)(worktreeRoot) : null;
|
|
1741
|
+
const system = systemPackagesPrerequisites(childLayerPrerequisites(toolchain.prerequisites, declaresLayer), systemPackages);
|
|
1742
|
+
if (systemPackages) log(`stack: this head declares ${systemPackages.distribution} system packages: placement requires a host with \`${system.prerequisites.at(-1)}\`${system.provided.length ? `; ${system.provided.join(", ")} come from them, proven by the declared probe` : ""}`);
|
|
1743
|
+
const prerequisites = [...system.prerequisites];
|
|
1744
|
+
if (hostLocalCallbackRun(opts) && !prerequisites.includes(HOST_LOCAL_CALLBACK_CAPABILITY)) prerequisites.push(HOST_LOCAL_CALLBACK_CAPABILITY);
|
|
1745
|
+
return prerequisites;
|
|
1746
|
+
}
|
|
1747
|
+
|
|
1748
|
+
/** BOT-3519: the lease refusals that mean no owned host can run this require-host test child. */
|
|
1749
|
+
export const CHILD_HOST_REFUSAL_CODES = Object.freeze(["CHILD_HOST_PREREQUISITES_MISSING", "CHILD_HOST_UNAVAILABLE", CHILD_PLACEMENT_REQUIRED]);
|
|
1750
|
+
|
|
1751
|
+
/** BOT-3519: one line per considered host — what it lacks, or why it cannot take the child. */
|
|
1752
|
+
export function childHostRefusalLines(data) {
|
|
1753
|
+
const name = (c) => (typeof c.display_name === "string" && c.display_name && c.display_name !== c.host_key ? `${c.display_name} (${c.host_key})` : c.host_key);
|
|
1754
|
+
return (Array.isArray(data?.considered) ? data.considered : [])
|
|
1755
|
+
.filter((c) => c && typeof c.host_key === "string" && c.verdict_code === "HOST_CHILD_UNQUALIFIED")
|
|
1756
|
+
.map((c) => ` ${name(c)}: ${c.child_reason === "stack_colocated" ? "this machine's own host (a co-located stack never serves a host child)"
|
|
1757
|
+
: Array.isArray(c.missing_prerequisites) && c.missing_prerequisites.length ? `lacks ${c.missing_prerequisites.join(", ")} (${c.child_reason ?? "unknown"})` : c.child_reason ?? "cannot run the child"}`);
|
|
1758
|
+
}
|
|
1759
|
+
|
|
1719
1760
|
/**
|
|
1720
1761
|
* Exit code for a lease the server REFUSED (`success: false`). A refused root path is a
|
|
1721
1762
|
* bad argument the caller must fix — INVALID (4) — not a backend fault, which automation
|
|
@@ -4555,6 +4596,9 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
4555
4596
|
let leaseId = null;
|
|
4556
4597
|
let child = null;
|
|
4557
4598
|
let childResult = null;
|
|
4599
|
+
// BOT-3463: the run owns every process its child launches (a test double owns its own child).
|
|
4600
|
+
const claimOwnership = adapters.claimOwnership ?? (adapters.startChild ? null : claimRunOwnership);
|
|
4601
|
+
let runOwnership = null;
|
|
4558
4602
|
let connectionFile = null;
|
|
4559
4603
|
let heartbeat = null;
|
|
4560
4604
|
let heartbeatRetry = null;
|
|
@@ -4564,6 +4608,8 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
4564
4608
|
let testChild = null;
|
|
4565
4609
|
let testChildRenew = null;
|
|
4566
4610
|
let testChildWaitAbort = null;
|
|
4611
|
+
// BOT-3519: the test child's whole prerequisite set, derived before the lease is requested.
|
|
4612
|
+
let childPrerequisites = null;
|
|
4567
4613
|
const releaseTestChild = async (resources) => {
|
|
4568
4614
|
if (!testChild?.slotId) return null;
|
|
4569
4615
|
const slotId = testChild.slotId;
|
|
@@ -4972,6 +5018,10 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
4972
5018
|
// BOT-3399: a host-local callback is declared on the host run, never on the lease.
|
|
4973
5019
|
const hostLocalCallback = hostLocalCallbackRun(opts);
|
|
4974
5020
|
const requesterCallbackPort = hostLocalCallback ? null : opts.callbackPort;
|
|
5021
|
+
// BOT-3519: a require-host child's lease goes only to a host that can run it, so the whole
|
|
5022
|
+
// prerequisite set is known (and sent) before the lease exists.
|
|
5023
|
+
const requireHostChild = Boolean(opts.testChild) && opts.childPlacement === "require-host";
|
|
5024
|
+
childPrerequisites = opts.testChild ? childPrerequisiteSet(opts, execution.worktreeRoot, adapters, stderrLine) : null;
|
|
4975
5025
|
const requireNativeCallback = requesterCallbackPort != null && opts.executionRing === "beta" && executionRequest !== "local";
|
|
4976
5026
|
const autoCallbackPolicy = requesterCallbackPort != null && opts.executionRing !== "beta" && executionRequest !== "local" && Boolean(execution.admissionRequestId);
|
|
4977
5027
|
let useNativeCallback = requireNativeCallback;
|
|
@@ -4990,6 +5040,7 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
4990
5040
|
require_stack_digest: true,
|
|
4991
5041
|
// BOT-2269: what the bundle carries beyond the defaults (paths, sha256, key NAMES).
|
|
4992
5042
|
...(bundle?.included?.length ? { bundle_included: bundle.included } : {}),
|
|
5043
|
+
...(requireHostChild ? { child_host_prerequisites: childPrerequisites } : {}),
|
|
4993
5044
|
...(requesterCallbackPort != null ? { callback_port: requesterCallbackPort,
|
|
4994
5045
|
...(requireNativeCallback ? { callback_transport: NATIVE_CALLBACK_TRANSPORT } : autoCallbackPolicy ? { callback_policy: "auto" } : {}) } : {}),
|
|
4995
5046
|
};
|
|
@@ -5323,6 +5374,28 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
5323
5374
|
// an idle mode mismatch) is not proof that its ports are free. Keep the
|
|
5324
5375
|
// claim until owner-safe cleanup is verified; never reap a possibly live batch.
|
|
5325
5376
|
if (request.data?.lease_id) retainBlock = true;
|
|
5377
|
+
// BOT-3519: no owned host can run this require-host child: refused before any lease or upload.
|
|
5378
|
+
// A held lease on a host that cannot run the child is named too (held_lease); its id is kept so
|
|
5379
|
+
// the operator can release it, and its port block stays retained.
|
|
5380
|
+
if (requireHostChild && CHILD_HOST_REFUSAL_CODES.includes(request.data?.code) && (!request.data?.lease_id || request.data.held_lease === true)) {
|
|
5381
|
+
const d = request.data;
|
|
5382
|
+
if (d.lease_id) retainBlock = true;
|
|
5383
|
+
for (const line of childHostRefusalLines(d)) stderrLine(line);
|
|
5384
|
+
return {
|
|
5385
|
+
exitCode: EXIT.BACKEND, outcome: "refused", code: d.code,
|
|
5386
|
+
error: `--child-placement require-host: ${d.message ?? d.code}`,
|
|
5387
|
+
...(d.lease_id ? { leaseId: d.lease_id, state: d.state ?? null } : {}),
|
|
5388
|
+
childHostRefusal: {
|
|
5389
|
+
prerequisites: Array.isArray(d.prerequisites) ? d.prerequisites : childPrerequisites,
|
|
5390
|
+
considered: Array.isArray(d.considered) ? d.considered : [],
|
|
5391
|
+
...(d.child_host ? { child_host: d.child_host } : {}),
|
|
5392
|
+
...(d.host_key ? { host_key: d.host_key } : {}),
|
|
5393
|
+
...(d.child_reason ? { child_reason: d.child_reason } : {}),
|
|
5394
|
+
...(d.child_placement_reason ? { child_placement_reason: d.child_placement_reason } : {}),
|
|
5395
|
+
...(Array.isArray(d.missing_prerequisites) ? { missing_prerequisites: d.missing_prerequisites } : {}),
|
|
5396
|
+
},
|
|
5397
|
+
};
|
|
5398
|
+
}
|
|
5326
5399
|
// BOT-2977: name the re-registration command; the refusal itself is never retried here.
|
|
5327
5400
|
const fenceScope = staleContextFenceScope(request.data);
|
|
5328
5401
|
const branchTicket = request.data?.code === "STALE_AGENT_CONTEXT" ? await (adapters.branchTicket ?? currentBranchTicket)() : undefined;
|
|
@@ -5821,22 +5894,7 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
5821
5894
|
const waitTouch = clock.setInterval(() => { void touchWhileWaiting(); }, waitCadenceMs);
|
|
5822
5895
|
waitTouch?.unref?.();
|
|
5823
5896
|
let placed;
|
|
5824
|
-
|
|
5825
|
-
// placement asks the host for `toolchain` instead of for those tools.
|
|
5826
|
-
const head = (adapters.headToolchain ?? headToolchain)(execution.worktreeRoot);
|
|
5827
|
-
const toolchain = toolchainPrerequisites(opts.childRequires, head);
|
|
5828
|
-
if (head.manifest) stderrLine(`stack: this head declares its toolchain (mise.toml, mise.lock): placement requires a host with \`toolchain\`${toolchain.provided.length ? `; ${toolchain.provided.join(", ")} come from the manifest` : ""}`);
|
|
5829
|
-
else if (head.lockMissing) stderrLine("stack: this head commits mise.toml without mise.lock, so a host builds no toolchain for it; run `mise lock` and commit mise.lock to give host children the repo's own tools");
|
|
5830
|
-
// BOT-3396: a head that commits .botbuddy/child-layer.json needs a host that builds it.
|
|
5831
|
-
const declaresLayer = (adapters.headDeclaresChildLayer ?? headDeclaresChildLayer)(execution.worktreeRoot);
|
|
5832
|
-
if (declaresLayer) stderrLine("stack: this head declares a dependency layer (.botbuddy/child-layer.json): placement requires a host with `child-layer`");
|
|
5833
|
-
// BOT-3470: its declared system packages bring the capabilities they provide with them.
|
|
5834
|
-
const systemPackages = declaresLayer ? (adapters.headSystemPackages ?? headSystemPackages)(execution.worktreeRoot) : null;
|
|
5835
|
-
const system = systemPackagesPrerequisites(childLayerPrerequisites(toolchain.prerequisites, declaresLayer), systemPackages);
|
|
5836
|
-
if (systemPackages) stderrLine(`stack: this head declares ${systemPackages.distribution} system packages: placement requires a host with \`${system.prerequisites.at(-1)}\`${system.provided.length ? `; ${system.provided.join(", ")} come from them, proven by the declared probe` : ""}`);
|
|
5837
|
-
const prerequisites = system.prerequisites;
|
|
5838
|
-
// BOT-3399: a host-local callback child goes only to a host whose daemon serves the route.
|
|
5839
|
-
if (hostLocalCallbackRun(opts) && !prerequisites.includes(HOST_LOCAL_CALLBACK_CAPABILITY)) prerequisites.push(HOST_LOCAL_CALLBACK_CAPABILITY);
|
|
5897
|
+
const prerequisites = childPrerequisites ?? childPrerequisiteSet(opts, execution.worktreeRoot, adapters, stderrLine);
|
|
5840
5898
|
testChildWaitAbort = new AbortController();
|
|
5841
5899
|
try {
|
|
5842
5900
|
placed = await acquireTestChildSlot({
|
|
@@ -5951,7 +6009,13 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
5951
6009
|
child = started.child;
|
|
5952
6010
|
if (hostLocalCallbackRun(opts)) placement.callbackTransport = HOST_LOCAL_CALLBACK_TRANSPORT;
|
|
5953
6011
|
} else {
|
|
5954
|
-
|
|
6012
|
+
try { runOwnership = claimOwnership ? await claimOwnership({ kind: "stack_run", cwd: childCwd ?? process.cwd() }) : null; } catch (error) {
|
|
6013
|
+
stderrLine(`stack: this run is not tracked for cleanup (${error?.code ?? error?.message ?? error}); processes its child leaves behind are not stopped`);
|
|
6014
|
+
}
|
|
6015
|
+
child = startChild(childArgv, runOwnership ? { ...childEnv, ...runOwnership.env } : childEnv, childCwd);
|
|
6016
|
+
// Not awaited: waitForChild attaches its exit listener below with no tick in between, so a
|
|
6017
|
+
// child that exits at once is never missed. The group is recorded in memory synchronously.
|
|
6018
|
+
void runOwnership?.recordGroup(child.pid);
|
|
5955
6019
|
}
|
|
5956
6020
|
if (testChild) {
|
|
5957
6021
|
// A host child is measured by its own cgroup on the host, not sampled here.
|
|
@@ -6071,6 +6135,8 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
6071
6135
|
if (opts.hardTtl) hardTimer = clock.setTimeout(() => stopChild("SIGTERM", EXIT.TIMEOUT), opts.hardTtl * 1000);
|
|
6072
6136
|
hardTimer?.unref?.();
|
|
6073
6137
|
childResult = await waitForChild(child);
|
|
6138
|
+
// BOT-3463: a dev server the child started stops with the run, before the stack is torn down.
|
|
6139
|
+
if (runOwnership) await runOwnership.release();
|
|
6074
6140
|
if (testChildRenew) { clock.clearInterval(testChildRenew); testChildRenew = null; }
|
|
6075
6141
|
if (testChild && child.hostRun) {
|
|
6076
6142
|
// The host already recorded the cgroup cost on the lease; release without overwriting it.
|
|
@@ -6160,6 +6226,8 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
6160
6226
|
const exitCode = cleanup?.ok === false ? EXIT.CLEANUP_FAILED : classifyStackAuthError(error);
|
|
6161
6227
|
return { exitCode, outcome: "error", leaseId, error: String(error?.message ?? error), cleanup };
|
|
6162
6228
|
} finally {
|
|
6229
|
+
// BOT-3463: whichever path ended the run, its processes end with it (idempotent).
|
|
6230
|
+
if (runOwnership) await runOwnership.release();
|
|
6163
6231
|
// BOT-3240: a run that threw still frees its slot now rather than at TTL.
|
|
6164
6232
|
if (testChildRenew) clock.clearInterval(testChildRenew);
|
|
6165
6233
|
if (testChild?.sampler) { try { testChild.resources = testChild.sampler.stop(); } catch { /* best effort */ } testChild.sampler = null; }
|
|
@@ -6240,6 +6308,15 @@ export function runReceiptFields(result) {
|
|
|
6240
6308
|
...(result.requiredPlacement.missing_prerequisites?.length ? { missing_prerequisites: result.requiredPlacement.missing_prerequisites } : {}),
|
|
6241
6309
|
...(result.requiredPlacement.serving_host ? { serving_host: result.requiredPlacement.serving_host } : {}),
|
|
6242
6310
|
} : {}),
|
|
6311
|
+
// BOT-3519: a require-host lease refused before it existed: the child's prerequisite set and
|
|
6312
|
+
// every considered host with what it lacks (or the one host it would wait for).
|
|
6313
|
+
...(result.childHostRefusal ? {
|
|
6314
|
+
child_placement: { prerequisites: result.childHostRefusal.prerequisites, considered: result.childHostRefusal.considered,
|
|
6315
|
+
...(result.childHostRefusal.child_host ? { child_host: result.childHostRefusal.child_host } : {}) },
|
|
6316
|
+
...(result.childHostRefusal.child_placement_reason ? { child_placement_reason: result.childHostRefusal.child_placement_reason } : {}),
|
|
6317
|
+
...(result.childHostRefusal.host_key ? { serving_host: result.childHostRefusal.host_key } : {}),
|
|
6318
|
+
...(result.childHostRefusal.missing_prerequisites?.length ? { missing_prerequisites: result.childHostRefusal.missing_prerequisites } : {}),
|
|
6319
|
+
} : {}),
|
|
6243
6320
|
// BOT-1803: an idle release is `cleanup: { idle: true, idle_since }` (nothing was reaped).
|
|
6244
6321
|
cleanup: result.cleanup?.idle ? { idle: true, idle_since: result.cleanup.idle_since ?? null } : result.cleanup?.ok ?? null,
|
|
6245
6322
|
cleanup_code: result.cleanup?.code ?? null,
|