@botbuddy/cli 1.95.1 → 1.97.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 CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.97.0
4
+
5
+ - BOT-3397: `bb stack run --test-child --child-artifacts <glob>` (repeatable, at most 16, relative to the checkout) brings a host test child's files back to the requester's worktree. When the child's unit stops (exit, failure, timeout or cancel) its `ExecStopPost` runs the bound `bb child-artifacts pack` as the run's own DynamicUser, inside the sandbox: matching regular files are packed into a gzip tar whose last entry `.bb-artifacts.json` lists each file's size and sha256. Symlinks are never followed or packed, and the files are capped at 200 MiB per run. The daemon uploads the archive to a signed, run-scoped Storage path and reports its sha256, size and typed refusals (`ARTIFACT_GLOB_NO_MATCH`, `ARTIFACT_OVER_CAP`, `ARTIFACT_SYMLINK_REFUSED`, …). The CLI downloads it, checks the archive against the host's sha256 and every file against the manifest, refuses the whole archive on any mismatch or unsafe path, writes the files at their relative paths before the run is seen to end, and records them on the receipt as `host_child.artifacts`. A run with nothing to return says why (`ARTIFACTS_NOT_PACKED`, `ARTIFACTS_UPLOAD_FAILED`, `ARTIFACTS_DIGEST_MISMATCH`, …); the exit code is always the child's. Archives are kept 24 h; `bb stack child-artifacts <run_id>` writes them again.
6
+
3
7
  ## 1.95.1
4
8
 
5
9
  - BOT-3412: a host test child can execute native binaries that live in its own workspace (native npm packages after `pnpm install`, compiled test binaries, downloaded tools). systemd mounts a DynamicUser `StateDirectory` `noexec`; the daemon's unit now carries `ExecPaths=` for exactly that run's state directory. Every other sandbox property is unchanged.
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.95.1",
3
- "source_commit": "c03b6c85d2170e402acd6e937270749ff8e32e96",
4
- "source_sha256": "a3530f22ec199257f95f22058b784673c7b1f90daec707e64231e035620c0b78",
2
+ "release_version": "1.97.0",
3
+ "source_commit": "9624b16c5931a1caa8532d54b5c5bbcbfda7968f",
4
+ "source_sha256": "e3eb890b49b33323cd956f58d69b7211787b86098e940fc6c35e2a71f703adad",
5
5
  "target": "darwin-arm64",
6
- "sha256": "ff7230165e3d6aa6002bb98c3160068d325abccde8d2ccd3c4f6d5e0f7a50a70"
6
+ "sha256": "54c2ae2eb7ad2b829d7e1072ac35c145f1e6cb058032d5ee9083b859b3a93e32"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.95.1",
3
- "source_commit": "c03b6c85d2170e402acd6e937270749ff8e32e96",
4
- "source_sha256": "a3530f22ec199257f95f22058b784673c7b1f90daec707e64231e035620c0b78",
2
+ "release_version": "1.97.0",
3
+ "source_commit": "9624b16c5931a1caa8532d54b5c5bbcbfda7968f",
4
+ "source_sha256": "e3eb890b49b33323cd956f58d69b7211787b86098e940fc6c35e2a71f703adad",
5
5
  "target": "linux-x64",
6
- "sha256": "56fa09c1d4591661ccc0ea8f84569152284e78e952779a7aaf7a225264c75107"
6
+ "sha256": "69d0a5d44faddb8029c99e061a5c1b9ee1134d38e3695f2348e6039a3f5fafa6"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.95.1",
4
- "source_commit": "c03b6c85d2170e402acd6e937270749ff8e32e96",
5
- "source_sha256": "a3530f22ec199257f95f22058b784673c7b1f90daec707e64231e035620c0b78",
3
+ "release_version": "1.97.0",
4
+ "source_commit": "9624b16c5931a1caa8532d54b5c5bbcbfda7968f",
5
+ "source_sha256": "e3eb890b49b33323cd956f58d69b7211787b86098e940fc6c35e2a71f703adad",
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": "ff7230165e3d6aa6002bb98c3160068d325abccde8d2ccd3c4f6d5e0f7a50a70",
11
+ "sha256": "54c2ae2eb7ad2b829d7e1072ac35c145f1e6cb058032d5ee9083b859b3a93e32",
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": "56fa09c1d4591661ccc0ea8f84569152284e78e952779a7aaf7a225264c75107",
18
+ "sha256": "69d0a5d44faddb8029c99e061a5c1b9ee1134d38e3695f2348e6039a3f5fafa6",
19
19
  "mode": "0755"
20
20
  }
21
21
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botbuddy/cli",
3
- "version": "1.95.1",
3
+ "version": "1.97.0",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,15 @@
1
+ {
2
+ "state": "uploaded",
3
+ "archive_sha256": "43df5de99ee28a5f0468f8292d1c208def1a5a1b8e0e0f416e25864d356ef14f",
4
+ "archive_size_bytes": 738,
5
+ "file_count": 3,
6
+ "total_bytes": 141,
7
+ "refusals": [
8
+ {
9
+ "code": "ARTIFACT_GLOB_NO_MATCH",
10
+ "glob": "playwright-report",
11
+ "message": "nothing in the checkout matched this glob"
12
+ }
13
+ ],
14
+ "refusal_count": 1
15
+ }
@@ -0,0 +1,271 @@
1
+ // BOT-3397 — a host test child's declared artifacts come back to the requester's worktree.
2
+ //
3
+ // The host packs the declared files (as the child's own user, inside its sandbox) into a gzip
4
+ // tar whose last entry `.bb-artifacts.json` lists each file's size and sha256, uploads it to a
5
+ // run-scoped Storage path, and reports the archive's sha256 on the run. Here the requester
6
+ // downloads it, checks it against that digest, checks every file against the manifest, and only
7
+ // then writes the files at the same relative paths. Anything off refuses the whole archive:
8
+ // nothing is written. Never a symlink, never a path outside the worktree.
9
+
10
+ import { createHash } from "node:crypto";
11
+ import { lstatSync, mkdirSync, renameSync, writeFileSync, rmSync } from "node:fs";
12
+ import { dirname, join, relative, resolve, sep } from "node:path";
13
+ import { gunzipSync } from "node:zlib";
14
+
15
+ export const HOST_CHILD_ARTIFACT_GLOBS_MAX = 16;
16
+ /** The bucket's object limit; the host caps the files themselves at 200 MiB. */
17
+ export const HOST_CHILD_ARTIFACTS_ARCHIVE_MAX_BYTES = 256 * 1024 * 1024;
18
+ const UNPACKED_MAX_BYTES = 256 * 1024 * 1024;
19
+ const MANIFEST = ".bb-artifacts.json";
20
+ /** The whole download (headers and body) is bounded; a stop cuts it short at once. */
21
+ export const HOST_CHILD_ARTIFACTS_DOWNLOAD_TIMEOUT_MS = 10 * 60_000;
22
+ const RECEIPT_FILES_MAX = 200;
23
+
24
+ /** null when the glob is acceptable, else why not. Mirrors the server's and the daemon's checks. */
25
+ export function validateChildArtifactGlob(glob) {
26
+ if (typeof glob !== "string" || glob.length < 1 || glob.length > 256) return "a glob is 1 to 256 characters";
27
+ if (/^\/|\\|[\n\r\0]|(^|\/)\.{1,2}(\/|$)|\/\/|\/$/.test(glob)) {
28
+ return "a glob is a relative path inside the checkout (no leading /, no .. or . segment, no backslash)";
29
+ }
30
+ return null;
31
+ }
32
+
33
+ /** One glob segment as Go's path.Match reads it: `*`, `?` and `[...]` (`^` negates). */
34
+ function segmentRegex(segment) {
35
+ let out = "";
36
+ for (let i = 0; i < segment.length; i++) {
37
+ const c = segment[i];
38
+ if (c === "*") out += "[^/]*";
39
+ else if (c === "?") out += "[^/]";
40
+ else if (c === "[") {
41
+ const close = segment.indexOf("]", i + 2);
42
+ if (close === -1) return null;
43
+ let body = segment.slice(i + 1, close);
44
+ if (body.startsWith("^")) body = `^${body.slice(1).replace(/[\\\]]/g, "\\$&")}`;
45
+ else body = body.replace(/[\\\]^]/g, "\\$&");
46
+ out += `[${body}]`;
47
+ i = close;
48
+ } else out += c.replace(/[.+^${}()|\\]/g, "\\$&");
49
+ }
50
+ return new RegExp(`^${out}$`);
51
+ }
52
+
53
+ function globSegments(pat, segs) {
54
+ if (!pat.length) return !segs.length;
55
+ if (pat[0] === "**") return globSegments(pat.slice(1), segs) || (segs.length > 0 && globSegments(pat, segs.slice(1)));
56
+ if (!segs.length) return false;
57
+ const re = segmentRegex(pat[0]);
58
+ return Boolean(re?.test(segs[0])) && globSegments(pat.slice(1), segs.slice(1));
59
+ }
60
+
61
+ /**
62
+ * Whether a returned path is one the requester declared: the path itself, or a directory above
63
+ * it, matches a glob (the host packs a matched directory's whole tree).
64
+ */
65
+ export function pathInArtifactGlobs(path, globs) {
66
+ const segs = path.split("/");
67
+ return (globs ?? []).some((g) => {
68
+ const pat = g.split("/");
69
+ for (let n = 1; n <= segs.length; n++) if (globSegments(pat, segs.slice(0, n))) return true;
70
+ return false;
71
+ });
72
+ }
73
+
74
+ function safeRelativePath(p) {
75
+ return typeof p === "string" && p.length > 0 && p.length <= 4096 && !p.startsWith("/") && !/[\\\0\n\r]/.test(p)
76
+ && !p.split("/").some((s) => s === "" || s === "." || s === "..");
77
+ }
78
+
79
+ class ArchiveError extends Error {}
80
+
81
+ function cstr(buf, start, len) {
82
+ const slice = buf.subarray(start, start + len);
83
+ const nul = slice.indexOf(0);
84
+ return slice.subarray(0, nul === -1 ? len : nul).toString("utf8");
85
+ }
86
+
87
+ function octal(buf, start, len) {
88
+ const raw = cstr(buf, start, len).trim();
89
+ if (!/^[0-7]*$/.test(raw)) throw new ArchiveError("a header number is not octal");
90
+ return raw ? parseInt(raw, 8) : 0;
91
+ }
92
+
93
+ function paxRecords(data) {
94
+ const out = {};
95
+ let off = 0;
96
+ while (off < data.length) {
97
+ const space = data.indexOf(0x20, off);
98
+ const len = space === -1 ? NaN : Number(data.subarray(off, space).toString("ascii"));
99
+ if (!Number.isSafeInteger(len) || len <= 0 || off + len > data.length || data[off + len - 1] !== 0x0a) throw new ArchiveError("a PAX record is malformed");
100
+ const record = data.subarray(space + 1, off + len - 1).toString("utf8");
101
+ const eq = record.indexOf("=");
102
+ if (eq === -1) throw new ArchiveError("a PAX record is malformed");
103
+ out[record.slice(0, eq)] = record.slice(eq + 1);
104
+ off += len;
105
+ }
106
+ return out;
107
+ }
108
+
109
+ /**
110
+ * Reads the host's archive: regular files and PAX headers only, the manifest last, and every
111
+ * file exactly as the manifest describes it. Throws on anything else.
112
+ */
113
+ export function readArtifactArchive(gz) {
114
+ let buf;
115
+ try {
116
+ buf = gunzipSync(gz, { maxOutputLength: UNPACKED_MAX_BYTES });
117
+ } catch {
118
+ throw new ArchiveError("the archive is not a readable gzip stream (or unpacks too large)");
119
+ }
120
+ const entries = [];
121
+ let pax = null;
122
+ let off = 0;
123
+ while (off + 512 <= buf.length) {
124
+ const header = buf.subarray(off, off + 512);
125
+ if (header.every((b) => b === 0)) break;
126
+ let sum = 0;
127
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : header[i];
128
+ if (sum !== octal(header, 148, 8)) throw new ArchiveError("a header checksum is wrong");
129
+ const type = header[156] === 0 ? "0" : String.fromCharCode(header[156]);
130
+ let size = octal(header, 124, 12);
131
+ if (pax?.size !== undefined) size = Number(pax.size);
132
+ if (!Number.isSafeInteger(size) || size < 0) throw new ArchiveError("an entry size is invalid");
133
+ off += 512;
134
+ if (off + size > buf.length) throw new ArchiveError("the archive is truncated");
135
+ const data = buf.subarray(off, off + size);
136
+ off += Math.ceil(size / 512) * 512;
137
+ if (type === "x") {
138
+ pax = paxRecords(data);
139
+ continue;
140
+ }
141
+ if (type !== "0") throw new ArchiveError(`entry type ${JSON.stringify(type)} is not a regular file`);
142
+ const prefix = cstr(header, 345, 155);
143
+ const name = pax?.path ?? (prefix ? `${prefix}/${cstr(header, 0, 100)}` : cstr(header, 0, 100));
144
+ pax = null;
145
+ entries.push({ path: name, data });
146
+ }
147
+ const last = entries.pop();
148
+ if (!last || last.path !== MANIFEST) throw new ArchiveError("the archive does not end with its manifest");
149
+ let manifest;
150
+ try { manifest = JSON.parse(last.data.toString("utf8")); } catch { throw new ArchiveError("the manifest is not JSON"); }
151
+ if (!Array.isArray(manifest?.files) || manifest.files.length !== entries.length) throw new ArchiveError("the manifest does not describe every file");
152
+ const seen = new Set();
153
+ entries.forEach((entry, i) => {
154
+ const m = manifest.files[i];
155
+ if (!safeRelativePath(entry.path) || entry.path === MANIFEST) throw new ArchiveError(`the path ${JSON.stringify(entry.path)} leaves the worktree`);
156
+ if (seen.has(entry.path)) throw new ArchiveError(`the path ${entry.path} appears twice`);
157
+ seen.add(entry.path);
158
+ if (m?.path !== entry.path || m.size_bytes !== entry.data.length || m.sha256 !== createHash("sha256").update(entry.data).digest("hex")) {
159
+ throw new ArchiveError(`${entry.path} does not match the manifest`);
160
+ }
161
+ });
162
+ return { files: entries, manifest };
163
+ }
164
+
165
+ function assertDownloadUrl(raw) {
166
+ const url = new URL(raw);
167
+ const local = ["localhost", "127.0.0.1", "host.docker.internal"].includes(url.hostname) || /^(10|192\.168)\./.test(url.hostname);
168
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) throw new Error("the artifact download is not an https storage URL");
169
+ }
170
+
171
+ /** Refuses a destination whose directories (below the worktree root) include a symlink. */
172
+ function checkDestination(root, path) {
173
+ const parts = path.split("/");
174
+ let at = root;
175
+ for (let i = 0; i < parts.length; i++) {
176
+ at = join(at, parts[i]);
177
+ let st;
178
+ try { st = lstatSync(at); } catch { return null; }
179
+ if (st.isSymbolicLink()) return `${relative(root, at)} is a symlink`;
180
+ if (i < parts.length - 1 && !st.isDirectory()) return `${relative(root, at)} is not a directory`;
181
+ if (i === parts.length - 1 && !st.isFile()) return `${path} exists and is not a file`;
182
+ }
183
+ return null;
184
+ }
185
+
186
+ function receiptBase(a) {
187
+ return {
188
+ archive_sha256: a?.archive_sha256 ?? null, archive_size_bytes: a?.archive_size_bytes ?? null,
189
+ refusals: Array.isArray(a?.refusals) ? a.refusals : [], refusal_count: a?.refusal_count ?? (Array.isArray(a?.refusals) ? a.refusals.length : 0),
190
+ ...(a?.dropped_files ? { dropped_files: a.dropped_files, dropped_bytes: a.dropped_bytes ?? null } : {}),
191
+ };
192
+ }
193
+
194
+ /**
195
+ * Downloads a terminal host run's artifacts into the worktree. Answers the receipt's
196
+ * `host_child.artifacts`: `returned` with the files, or `unavailable` with a typed code.
197
+ */
198
+ export async function returnHostChildArtifacts({
199
+ run, worktreeRoot, fetchImpl = fetch, globs = run?.artifact_globs, signal = undefined, timeoutMs = HOST_CHILD_ARTIFACTS_DOWNLOAD_TIMEOUT_MS,
200
+ }) {
201
+ const a = run?.artifacts;
202
+ const unavailable = (code, message) => ({ state: "unavailable", code, message, ...receiptBase(a) });
203
+ if (!a || typeof a !== "object") {
204
+ return unavailable("ARTIFACTS_NOT_REPORTED", `the host reported no artifacts${run?.failure_code ? ` (the run ended ${run.failure_code})` : ""}`);
205
+ }
206
+ if (a.state === "expired") return unavailable("ARTIFACTS_EXPIRED", "the run's artifacts were deleted when their retention ended");
207
+ if (a.state !== "uploaded") return unavailable(a.code ?? "ARTIFACTS_UNAVAILABLE", a.message ?? "the host could not return the artifacts");
208
+ if (typeof run.artifacts_download_url !== "string") {
209
+ return unavailable("ARTIFACTS_DOWNLOAD_UNAVAILABLE", run.artifacts_download_error ?? "no download was signed for the artifacts");
210
+ }
211
+ if (!Array.isArray(globs) || !globs.length) return unavailable("ARTIFACTS_ARCHIVE_INVALID", "the run declares no artifact set to check the archive against");
212
+ let bytes;
213
+ // Codex #1830: the whole download is bounded, and a stop (Ctrl-C, hard TTL) cuts it short.
214
+ // A referenced timer (AbortSignal.timeout's is not): the deadline fires even when nothing
215
+ // else keeps the process alive, and it is cleared once the download settles (Codex #1830 r4).
216
+ const deadlineController = new AbortController();
217
+ const deadlineTimer = setTimeout(() => deadlineController.abort("deadline"), timeoutMs);
218
+ const deadline = deadlineController.signal;
219
+ const abort = signal ? AbortSignal.any([signal, deadline]) : deadline;
220
+ try {
221
+ assertDownloadUrl(run.artifacts_download_url);
222
+ const response = await fetchImpl(run.artifacts_download_url, { signal: abort });
223
+ if (!response?.ok) return unavailable("ARTIFACTS_DOWNLOAD_FAILED", `the artifact download answered HTTP ${response?.status ?? "?"}`);
224
+ bytes = Buffer.from(await response.arrayBuffer());
225
+ } catch (error) {
226
+ if (signal?.aborted) return unavailable("ARTIFACTS_DOWNLOAD_INTERRUPTED", "the run was stopped while its artifacts downloaded; fetch them with bb stack child-artifacts");
227
+ if (deadline.aborted) return unavailable("ARTIFACTS_DOWNLOAD_TIMEOUT", `the artifact download did not finish within ${Math.round(timeoutMs / 1000)} s; fetch them with bb stack child-artifacts`);
228
+ return unavailable("ARTIFACTS_DOWNLOAD_FAILED", String(error?.message ?? error).replace(/token=[^&\s]+/g, "token=…"));
229
+ } finally {
230
+ clearTimeout(deadlineTimer);
231
+ }
232
+ if (bytes.length > HOST_CHILD_ARTIFACTS_ARCHIVE_MAX_BYTES) return unavailable("ARTIFACTS_DOWNLOAD_FAILED", "the archive is larger than any host packs");
233
+ const digest = createHash("sha256").update(bytes).digest("hex");
234
+ if (digest !== a.archive_sha256) {
235
+ return unavailable("ARTIFACTS_DIGEST_MISMATCH", `the downloaded archive's sha256 ${digest.slice(0, 12)} is not the host's ${String(a.archive_sha256).slice(0, 12)}`);
236
+ }
237
+ let files;
238
+ try {
239
+ ({ files } = readArtifactArchive(bytes));
240
+ } catch (error) {
241
+ return unavailable("ARTIFACTS_ARCHIVE_INVALID", error.message);
242
+ }
243
+ // Codex #1830: the archive is the child's to forge, so only files the requester declared are
244
+ // ever written; one path outside the set refuses the whole archive.
245
+ const undeclared = files.find((f) => !pathInArtifactGlobs(f.path, globs));
246
+ if (undeclared) return unavailable("ARTIFACTS_ARCHIVE_INVALID", `${undeclared.path} is not in the declared artifact set; no artifact was written`);
247
+ const root = resolve(worktreeRoot);
248
+ for (const f of files) {
249
+ const dest = resolve(root, f.path);
250
+ if (!dest.startsWith(root + sep)) return unavailable("ARTIFACTS_ARCHIVE_INVALID", `${f.path} leaves the worktree`);
251
+ const why = checkDestination(root, f.path);
252
+ if (why) return unavailable("ARTIFACTS_WRITE_REFUSED", `${why}; no artifact was written`);
253
+ }
254
+ const written = [];
255
+ try {
256
+ for (const f of files) {
257
+ const dest = resolve(root, f.path);
258
+ mkdirSync(dirname(dest), { recursive: true });
259
+ const tmp = `${dest}.bb-partial-${process.pid}`;
260
+ writeFileSync(tmp, f.data, { flag: "wx", mode: 0o644 });
261
+ try { renameSync(tmp, dest); } catch (error) { rmSync(tmp, { force: true }); throw error; }
262
+ written.push({ path: f.path, size_bytes: f.data.length, sha256: createHash("sha256").update(f.data).digest("hex") });
263
+ }
264
+ } catch (error) {
265
+ return { ...unavailable("ARTIFACTS_WRITE_FAILED", String(error?.message ?? error)), files_written: written.length };
266
+ }
267
+ return {
268
+ state: "returned", ...receiptBase(a), file_count: written.length, total_bytes: written.reduce((n, f) => n + f.size_bytes, 0),
269
+ files: written.slice(0, RECEIPT_FILES_MAX), ...(written.length > RECEIPT_FILES_MAX ? { files_truncated: true } : {}),
270
+ };
271
+ }
@@ -15,6 +15,7 @@
15
15
  import { spawn, spawnSync } from "node:child_process";
16
16
  import { createHash } from "node:crypto";
17
17
  import { EventEmitter } from "node:events";
18
+ import { returnHostChildArtifacts } from "./host-child-artifacts.mjs";
18
19
 
19
20
  export const HOST_CHILD_BUNDLE_MAX_BYTES = 200 * 1024 * 1024;
20
21
  /** A host run that never reports terminal is given up this long after its own runtime limit. */
@@ -98,14 +99,15 @@ export function hostRunExitCode(run) {
98
99
  export async function startHostChild({
99
100
  api, upload, slotId, argv, env = {}, worktreeRoot, maxRuntimeSeconds = HOST_CHILD_DEFAULT_MAX_RUNTIME_S,
100
101
  bundle: prebuilt = null, wait = defaultHostChildWait, log = () => {}, writeOutput = (s) => process.stdout.write(s), now = Date.now,
101
- signal = undefined,
102
+ signal = undefined, artifactGlobs = [], fetchArtifacts = fetch,
102
103
  }) {
103
104
  const bundle = prebuilt ?? buildHeadBundle(worktreeRoot);
104
105
  if (!bundle.ok) return { ok: false, code: "HOST_CHILD_BUNDLE_FAILED", error: bundle.error };
105
106
  if (bundle.dirty) log(`stack: host child ships HEAD ${bundle.head?.slice(0, 12) ?? ""}; uncommitted changes in the worktree are not shipped`);
106
107
  let created;
107
108
  try {
108
- created = await api.create({ slot_id: slotId, argv, cwd: "", env, bundle_sha256: bundle.sha256, bundle_size_bytes: bundle.sizeBytes, max_runtime_seconds: maxRuntimeSeconds });
109
+ created = await api.create({ slot_id: slotId, argv, cwd: "", env, bundle_sha256: bundle.sha256, bundle_size_bytes: bundle.sizeBytes, max_runtime_seconds: maxRuntimeSeconds,
110
+ ...(artifactGlobs.length ? { artifact_globs: artifactGlobs } : {}) });
109
111
  } catch (error) { created = { ok: false, error: String(error?.message ?? error) }; }
110
112
  const c = created?.data;
111
113
  if (!created?.ok || !c?.success) {
@@ -145,14 +147,16 @@ export async function startHostChild({
145
147
  if (cancelState === "none" && waitIsLong) waitAbort?.abort("cancel_retry");
146
148
  });
147
149
  };
150
+ // Codex #1830: once the run has ended, a stop cuts its artifact download short instead.
151
+ const artifactsAbort = new AbortController();
148
152
  child.stop = () => {
149
- if (child.final) return;
153
+ if (child.final) { artifactsAbort.abort("stopped"); return; }
150
154
  if (!stopWanted) log(`stack: stopping host run ${runId}`);
151
155
  stopWanted = true;
152
156
  requestCancel();
153
157
  };
154
158
  // The caller gave the run up before using it (its slot was lost): stop waiting for it.
155
- child.detach = () => abort.abort("detached");
159
+ child.detach = () => { abort.abort("detached"); artifactsAbort.abort("detached"); };
156
160
  const giveUpAt = now() + (maxRuntimeSeconds * 1000) + HOST_CHILD_WAIT_GRACE_MS;
157
161
  const finish = (run, code) => {
158
162
  if (child.final) return;
@@ -160,9 +164,23 @@ export async function startHostChild({
160
164
  if (typeof run?.output_tail === "string" && run.output_tail) writeOutput(run.output_tail.endsWith("\n") ? run.output_tail : `${run.output_tail}\n`);
161
165
  if (run?.state !== "exited") log(`stack: host run ${runId} ${run?.state ?? "lost"}${run?.failure_code ? ` (${run.failure_code})` : ""}${run?.failure_message ? `: ${run.failure_message}` : ""}`);
162
166
  abort.abort("done");
163
- child.finalCode = code;
164
167
  // Emitted on a later turn: the run loop attaches its listener after startHostChild returns.
165
- setImmediate(() => child.emit("exit", code, null));
168
+ // finalCode is set only now, so a wait never sees the run end before its artifacts land.
169
+ const exit = () => { child.finalCode = code; setImmediate(() => child.emit("exit", code, null)); };
170
+ if (!artifactGlobs.length) return exit();
171
+ // BOT-3397: the declared artifacts are in the worktree before the run is seen to end, so the
172
+ // caller binds and promotes them as it would a local run's. They never change the exit code.
173
+ Promise.resolve().then(() => returnHostChildArtifacts({ run, worktreeRoot, fetchImpl: fetchArtifacts, globs: artifactGlobs, signal: artifactsAbort.signal })).then((artifacts) => {
174
+ child.artifacts = artifacts;
175
+ }, (error) => {
176
+ child.artifacts = { state: "unavailable", code: "ARTIFACTS_RETURN_FAILED", message: String(error?.message ?? error) };
177
+ }).then(() => {
178
+ const a = child.artifacts;
179
+ log(a.state === "returned"
180
+ ? `stack: host run ${runId} returned ${a.file_count} artifact file(s) (${a.total_bytes} bytes)${a.refusal_count ? `, ${a.refusal_count} refused (${[...new Set(a.refusals.map((x) => x.code))].join(", ")})` : ""}`
181
+ : `stack: host run ${runId} artifacts not returned: ${a.code}${a.message ? ` — ${a.message}` : ""}`);
182
+ exit();
183
+ });
166
184
  };
167
185
  (async () => {
168
186
  let since = Number.isSafeInteger(Number(queued.data.signal_cursor)) ? Number(queued.data.signal_cursor) : null;
@@ -213,6 +231,7 @@ export function hostChildReceiptFields(child) {
213
231
  run_id: child.runId, host: child.hostKey, state: run.state ?? null, unit: run.unit_name ?? null,
214
232
  exit_code: run.exit_code ?? null, failure_code: run.failure_code ?? null,
215
233
  started_at: run.started_at ?? null, finished_at: run.finished_at ?? null,
234
+ ...(child.artifacts ? { artifacts: child.artifacts } : {}),
216
235
  },
217
236
  };
218
237
  }
package/src/stack.mjs CHANGED
@@ -63,8 +63,9 @@ import { STACK_RELEASE_INTENT_ENV, classifyStackRunOutcome, observeStackRunSigna
63
63
  import { REQUESTER_NETWORK_CANDIDATE_CODES, REQUESTER_NETWORK_LOST_CODE, createRequesterNetworkWatch, requesterNetworkLostMessage } from "./requester-network.mjs";
64
64
  import { provisionFailureFields, provisionFailureLine } from "./stack-provision-failure.mjs";
65
65
  import { hostChildApi, hostChildReceiptFields, startHostChild, childEnvFrom, HOST_CHILD_DEFAULT_MAX_RUNTIME_S } from "./host-child.mjs";
66
+ import { HOST_CHILD_ARTIFACT_GLOBS_MAX, returnHostChildArtifacts, validateChildArtifactGlob } from "./host-child-artifacts.mjs";
66
67
  import { headToolchain, toolchainConflictError, toolchainPrerequisites } from "./host-toolchain.mjs";
67
- import { acquireTestChildSlot, defaultTestChildWait, readPs, requesterSample, startChildSampler, testChildApi, testChildReceiptFields } from "./test-child.mjs";
68
+ import { acquireTestChildSlot, CHILD_PLACEMENT_REQUIRED, defaultTestChildWait, readPs, requesterSample, startChildSampler, testChildApi, testChildReceiptFields } from "./test-child.mjs";
68
69
 
69
70
  export const STACK_SCHEMA_VERSION = 1;
70
71
 
@@ -180,6 +181,9 @@ ${bold("USAGE")}
180
181
  botbuddy stack cancel <lease_id> Give a queued lease's place up; never reaps a claimed lease (BOT-3094)
181
182
  botbuddy stack run [options] -- <executable> [args...]
182
183
  Own one Helper-backed test/fix batch end-to-end
184
+ botbuddy stack child-artifacts <run_id>
185
+ Write a host test child's artifacts into this worktree again
186
+ (BOT-3397; kept 24 h after the run ends)
183
187
 
184
188
  ${bold("up OPTIONS")}
185
189
  --slot <slot> Stable stack identity (BOT-1186): the shared CLI stack DB port
@@ -301,6 +305,14 @@ ${bold("run OPTIONS")}
301
305
  its own systemd unit with a per-run user, on the host's own ports; its
302
306
  output is printed when it ends, and child_resources is its cgroup peak
303
307
  memory and CPU. The requester keeps the lease, the slot and the reap.
308
+ --child-placement MODE BOT-3398: prefer-host (default) runs the child here when placement does not
309
+ choose the serving host. require-host runs it on the serving host or not at
310
+ all: any other placement (child_placement_disabled, stack_colocated,
311
+ host_child_capabilities_unknown, host_child_prerequisites_missing, a full
312
+ requester pool) is refused before the child starts with CHILD_PLACEMENT_REQUIRED
313
+ (exit 5); the receipt adds child_placement_reason, missing_prerequisites and
314
+ serving_host, and the slot and the lease are released. A full serving-host
315
+ pool still waits for a slot.
304
316
  --child-requires LIST BOT-3030: what the child needs on a host (comma list: node>=24,pnpm,deno,
305
317
  curl,psql,playwright-chromium-libs). node, pnpm and deno count only when
306
318
  they run inside a child's sandbox on that host (BOT-3402). A host lacking
@@ -313,6 +325,17 @@ ${bold("run OPTIONS")}
313
325
  --child-env NAME BOT-3030: pass NAME (this shell's value) to a host child (repeatable).
314
326
  Nothing else is passed; credential-shaped names are refused.
315
327
  --child-max-runtime S BOT-3030: the host stops the child after S seconds (default 3600).
328
+ --child-artifacts GLOB BOT-3397: bring these files back from a host child (repeatable, at most 16;
329
+ relative to the checkout, \`**\` spans directories, a directory brings its
330
+ tree), e.g. .e2e-receipt.json.pending, test-results, playwright-report. When
331
+ the run ends (exited, failed or canceled) the host packs them as the
332
+ child's own user, never following a symlink, up to 200 MiB; they are
333
+ written here at the same paths before the run ends, each checked against
334
+ the host's sha256, and listed on the receipt (host_child.artifacts). A
335
+ glob that matched nothing, a file over the cap, or an archive that could
336
+ not come back is a typed entry there; the exit code stays the child's.
337
+ A local child already writes here, so the flag changes nothing for it.
338
+ Fetch them again within 24 h: bb stack child-artifacts <run_id>.
316
339
  --local-only Require a co-located host (execution "local"); no bundle is built.
317
340
  Default (neither flag): execution "auto" — co-located if it admits now,
318
341
  else a remote host with capacity; the bundle digest is sent up front.
@@ -480,7 +503,7 @@ ${bold("EXAMPLE")}
480
503
  # request a per-worktree stack for this batch, run a lane against it, then reap it
481
504
  botbuddy stack run --repo botbuddy-web --ticket BOT-1346 -- pnpm test:integration`;
482
505
 
483
- const STACK_COMMANDS = new Set(["up", "run", "status", "touch", "done", "cancel"]);
506
+ const STACK_COMMANDS = new Set(["up", "run", "status", "touch", "done", "cancel", "child-artifacts"]);
484
507
  // BOT-2957: a heartbeat touch that goes unanswered is retried this soon, each with its own deadline,
485
508
  // for up to CALLBACK_STALE_PROOF_MAX_MS. Past that the run stops with this code.
486
509
  export const STACK_HEARTBEAT_UNANSWERED_CODE = "LEASE_HEARTBEAT_UNANSWERED";
@@ -496,12 +519,13 @@ export function stackCommandHelp(command) {
496
519
  cancel: ["GLOBAL", "EXIT CODES"],
497
520
  status: ["GLOBAL", "EXIT CODES"],
498
521
  touch: ["GLOBAL", "EXIT CODES", "IDLE LEASES"],
522
+ "child-artifacts": ["GLOBAL", "EXIT CODES"],
499
523
  };
500
524
  // The OPTIONS headings intentionally use lower-case command names.
501
525
  const all = STACK_HELP.split(/\n(?=\u001b\[1m)/);
502
526
  const selected = all.filter((section) => headings[command]?.some((heading) => section.startsWith(bold(heading))));
503
527
  const usage = command === "run" ? "[options] -- <executable> [args...]"
504
- : command === "up" ? "[options]" : "<lease_id> [options]";
528
+ : command === "up" ? "[options]" : command === "child-artifacts" ? "<run_id> [options]" : "<lease_id> [options]";
505
529
  const detail = command === "cancel"
506
530
  ? "\n Cancel gives up a queued (or unclaimed provisioning) lease's place atomically. It never reaps a lease a\n Helper has claimed: release that with `stack done <lease_id> --reap`.\n" : "";
507
531
  return `${bold(`botbuddy stack ${command}`)} ${usage}${detail}\n\n${selected.join("\n")}\n\n${STACK_READINESS_HELP}\n Use bb stack --help for all commands and options.`;
@@ -563,7 +587,7 @@ export function parseStackArgs(argv) {
563
587
  connectionFile: null, noWait: false, claimOnly: false, localExec: false, keepVolumes: false, waitCapacity: null, holdOnTimeout: null,
564
588
  dockerContext: null, dockerEndpoint: null,
565
589
  // BOT-2142: execution placement (null = command default), remote-lease callback + bundle cap.
566
- execution: null, remote: false, localOnly: false, testChild: false, childRequires: [], childEnv: [], childMaxRuntime: null, executionRing: "stable", callbackPort: null, bundleMaxBytes: null,
590
+ execution: null, remote: false, localOnly: false, testChild: false, childPlacement: "prefer-host", childRequires: [], childEnv: [], childMaxRuntime: null, childArtifacts: [], executionRing: "stable", callbackPort: null, bundleMaxBytes: null,
567
591
  // BOT-2269: exact stack-relative files shipped in the remote-lease bundle despite the
568
592
  // default exclusions (`--bundle-include`, repeatable).
569
593
  bundleInclude: [],
@@ -666,6 +690,15 @@ export function parseStackArgs(argv) {
666
690
  case "--remote": opts.remote = true; break;
667
691
  case "--local-only": opts.localOnly = true; break;
668
692
  case "--test-child": opts.testChild = true; break;
693
+ // BOT-3398: require-host runs the child on the serving host or refuses it.
694
+ case "--child-placement": {
695
+ if (need(a, rest[i + 1])) {
696
+ const mode = rest[++i];
697
+ if (!["prefer-host", "require-host"].includes(mode)) errors.push("--child-placement takes prefer-host or require-host");
698
+ else { opts.childPlacement = mode; opts.childPlacementSet = true; }
699
+ }
700
+ break;
701
+ }
669
702
  // BOT-3030: what a host-placed child needs, and the only variables it is given.
670
703
  case "--child-requires": {
671
704
  if (need(a, rest[i + 1])) {
@@ -683,6 +716,15 @@ export function parseStackArgs(argv) {
683
716
  }
684
717
  break;
685
718
  }
719
+ case "--child-artifacts": {
720
+ if (need(a, rest[i + 1])) {
721
+ const glob = rest[++i];
722
+ const why = validateChildArtifactGlob(glob);
723
+ if (why) errors.push(`--child-artifacts ${JSON.stringify(glob)}: ${why}`);
724
+ else if (!opts.childArtifacts.includes(glob)) opts.childArtifacts.push(glob);
725
+ }
726
+ break;
727
+ }
686
728
  case "--child-max-runtime": {
687
729
  if (need(a, rest[i + 1])) {
688
730
  const n = Number(rest[++i]);
@@ -776,8 +818,11 @@ export function parseStackArgs(argv) {
776
818
  if ((opts.callbackPort != null || opts.bundleMaxBytes != null) && command !== "run") {
777
819
  errors.push("--callback-port and --bundle-max-mb are valid only with `stack run`");
778
820
  }
779
- if ((opts.childRequires.length || opts.childEnv.length || opts.childMaxRuntime != null) && !opts.testChild) {
780
- errors.push("--child-requires, --child-env and --child-max-runtime need --test-child");
821
+ if ((opts.childRequires.length || opts.childEnv.length || opts.childMaxRuntime != null || opts.childPlacementSet || opts.childArtifacts.length) && !opts.testChild) {
822
+ errors.push("--child-placement, --child-requires, --child-env, --child-max-runtime and --child-artifacts need --test-child");
823
+ }
824
+ if (opts.childArtifacts.length > HOST_CHILD_ARTIFACT_GLOBS_MAX) {
825
+ errors.push(`--child-artifacts: at most ${HOST_CHILD_ARTIFACT_GLOBS_MAX} globs`);
781
826
  }
782
827
  if (opts.testChild && command !== "run") {
783
828
  errors.push("--test-child is valid only with `stack run` (only run starts a child)");
@@ -816,6 +861,9 @@ export function parseStackArgs(argv) {
816
861
  if (command && ["status", "touch", "done"].includes(command) && !leaseId && !(command === "status" && opts.admissionRequestId)) {
817
862
  errors.push(`${command} needs a <lease_id>`);
818
863
  }
864
+ if (command === "child-artifacts" && !(leaseId && UUID_RE.test(leaseId))) {
865
+ errors.push("child-artifacts needs a <run_id> (the host_child.run_id on a run's receipt)");
866
+ }
819
867
  if (["up", "done"].includes(command) && opts.localExec && Boolean(opts.dockerContext) === Boolean(opts.dockerEndpoint)) {
820
868
  errors.push(`--local-exec ${command} requires exactly one of --docker-context <name> or --docker-endpoint <uri>`);
821
869
  }
@@ -3465,6 +3513,32 @@ async function cmdUpOnce(opts, {
3465
3513
  }), opts, EXIT.OK);
3466
3514
  }
3467
3515
 
3516
+ /**
3517
+ * BOT-3397: `bb stack child-artifacts <run_id>` writes a host run's artifacts into this worktree
3518
+ * again, e.g. after the requester died before its download. Kept 24 h after the run ends.
3519
+ */
3520
+ export async function cmdChildArtifacts(runId, opts, {
3521
+ rpc = retryingStackCall(), emitResult = emit, worktreeRoot = gitWorktreeRoot(), fetchImpl = fetch,
3522
+ } = {}) {
3523
+ const base = { command: "child-artifacts", run_id: runId };
3524
+ const auth = await rpc.init();
3525
+ if (!auth) return emitResult(buildReceipt({ ...base, outcome: "error", error: "not authenticated — run `botbuddy login`" }), opts, EXIT.AUTH);
3526
+ const got = await rpc.call("get_host_test_child_run", { run_id: runId });
3527
+ if (!got.ok) return emitResult(buildReceipt({ ...base, outcome: "error", error: got.error }), opts, got.auth ? EXIT.AUTH : EXIT.BACKEND);
3528
+ const run = got.data ?? {};
3529
+ if (run.success !== true) return emitResult(buildReceipt({ ...base, outcome: "error", code: run.code ?? null, error: run.code ?? "run unreadable" }), opts, EXIT.BACKEND);
3530
+ if (!run.terminal) return emitResult(buildReceipt({ ...base, outcome: "error", code: "TEST_CHILD_RUN_LIVE", error: `the run is ${run.state}; its artifacts come back when it ends` }), opts, EXIT.BACKEND);
3531
+ const artifacts = await returnHostChildArtifacts({ run, worktreeRoot, fetchImpl });
3532
+ const ok = artifacts.state === "returned";
3533
+ return emitResult(buildReceipt({ ...base, outcome: ok ? "returned" : "error", run_state: run.state, ...(ok ? {} : { code: artifacts.code, error: artifacts.message }), artifacts }), opts, ok ? EXIT.OK : EXIT.BACKEND);
3534
+ }
3535
+
3536
+ function gitWorktreeRoot() {
3537
+ // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process -- fixed argv, no shell.
3538
+ const top = spawnSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8" });
3539
+ return top.status === 0 && top.stdout.trim() ? top.stdout.trim() : process.cwd();
3540
+ }
3541
+
3468
3542
  export async function cmdStatus(leaseId, opts, {
3469
3543
  rpc = retryingStackCall(), emitResult = emit, stderr = (line) => process.stderr.write(`${line}\n`),
3470
3544
  forwardSocket = process.env[FORWARD_ATTESTATION_ENV],
@@ -5521,7 +5595,7 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5521
5595
  signal: testChildWaitAbort.signal,
5522
5596
  api: testChildCalls, leaseId, wait: adapters.testChildWait ?? defaultTestChildWait, log: stderrLine, prerequisites: toolchain.prerequisites,
5523
5597
  isStopped: () => Boolean(receivedSignal || tunnelLost || callbackLost || originLost),
5524
- onPark: touchWhileWaiting,
5598
+ onPark: touchWhileWaiting, requireHost: opts.childPlacement === "require-host",
5525
5599
  });
5526
5600
  } finally {
5527
5601
  clock.clearInterval(waitTouch);
@@ -5558,7 +5632,9 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5558
5632
  await closeTunnel();
5559
5633
  const cleanup = await requestCleanup();
5560
5634
  const exitCode = receivedSignal ? SIGNAL_EXIT[receivedSignal] : cleanup.ok ? EXIT.BACKEND : EXIT.CLEANUP_FAILED;
5561
- return { exitCode, outcome: receivedSignal ? "interrupted" : "refused", code: placed.code, leaseId, cleanup, error: placed.error };
5635
+ // BOT-3398: a require-host refusal says where placement went and why.
5636
+ const required = placed.code === CHILD_PLACEMENT_REQUIRED ? { testChild, requiredPlacement: placed.placement ?? null } : {};
5637
+ return { exitCode, outcome: receivedSignal ? "interrupted" : "refused", code: placed.code, leaseId, cleanup, error: placed.error, ...required };
5562
5638
  }
5563
5639
  }
5564
5640
  if (testChild?.placement?.host_kind === "serving_host") {
@@ -5592,7 +5668,8 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5592
5668
  ...(adapters.hostChildBundle ? { bundle: adapters.hostChildBundle } : {}),
5593
5669
  ...(adapters.hostChildWait ? { wait: adapters.hostChildWait } : {}),
5594
5670
  log: stderrLine, ...(adapters.hostChildOutput ? { writeOutput: adapters.hostChildOutput } : {}),
5595
- signal: activeWaitAbort.signal,
5671
+ signal: activeWaitAbort.signal, artifactGlobs: opts.childArtifacts ?? [],
5672
+ ...(adapters.hostChildFetch ? { fetchArtifacts: adapters.hostChildFetch } : {}),
5596
5673
  });
5597
5674
  } finally {
5598
5675
  activeWaitAbort = null;
@@ -5868,6 +5945,13 @@ export function runReceiptFields(result) {
5868
5945
  child_exit_code: result.childExitCode ?? null,
5869
5946
  // BOT-3240: where a --test-child run's child ran, its slot, and what it cost.
5870
5947
  ...testChildReceiptFields(result.testChild),
5948
+ // BOT-3398: a require-host refusal names the child's placement (the lease's own is placement_reason).
5949
+ ...(result.code === CHILD_PLACEMENT_REQUIRED && result.requiredPlacement ? {
5950
+ child_placement: result.requiredPlacement,
5951
+ child_placement_reason: result.requiredPlacement.placement_reason ?? null,
5952
+ ...(result.requiredPlacement.missing_prerequisites?.length ? { missing_prerequisites: result.requiredPlacement.missing_prerequisites } : {}),
5953
+ ...(result.requiredPlacement.serving_host ? { serving_host: result.requiredPlacement.serving_host } : {}),
5954
+ } : {}),
5871
5955
  // BOT-1803: an idle release is `cleanup: { idle: true, idle_since }` (nothing was reaped).
5872
5956
  cleanup: result.cleanup?.idle ? { idle: true, idle_since: result.cleanup.idle_since ?? null } : result.cleanup?.ok ?? null,
5873
5957
  cleanup_code: result.cleanup?.code ?? null,
@@ -6098,6 +6182,7 @@ export async function cmdStack(argv, { report = reportStackRunOutcome, outcomeCh
6098
6182
  case "touch": code = await cmdTouch(leaseId, opts); break;
6099
6183
  case "done": code = await cmdDone(leaseId, opts); break;
6100
6184
  case "run": code = await cmdRun(opts, childArgv, { report }); break;
6185
+ case "child-artifacts": code = await cmdChildArtifacts(leaseId, opts); break;
6101
6186
  default:
6102
6187
  process.stderr.write(`${yellow("⚠")} stack: unknown subcommand "${command}". Try ${bold("botbuddy stack help")}.\n`);
6103
6188
  code = emit(buildReceipt({ command: command || "?", outcome: "error", error: `unknown subcommand: ${command}` }), opts, EXIT.INVALID);
@@ -17,6 +17,7 @@ import { cpus, freemem, loadavg, totalmem } from "node:os";
17
17
 
18
18
  export const TEST_CHILD_CAPACITY = "TEST_CHILD_CAPACITY";
19
19
  export const CHILD_PLACEMENT_UNSUPPORTED = "CHILD_PLACEMENT_UNSUPPORTED";
20
+ export const CHILD_PLACEMENT_REQUIRED = "CHILD_PLACEMENT_REQUIRED";
20
21
  export const TEST_CHILD_UNAVAILABLE = "TEST_CHILD_UNAVAILABLE";
21
22
  /** A full pool with no reported expiry parks at most one default slot TTL. */
22
23
  export const FALLBACK_PARK_MS = 180_000;
@@ -92,9 +93,16 @@ export function defaultTestChildWait(target, { bin = process.execPath, cli = pro
92
93
  * Returns `{ ok: true, slotId, ttlSeconds, placement, waits }` or
93
94
  * `{ ok: false, code, error, placement?, waits }`. Never throws.
94
95
  */
96
+ /** BOT-3398: why a require-host child was refused, in the words of the placement. */
97
+ export function requiredHostError(placement) {
98
+ const missing = Array.isArray(placement?.missing_prerequisites) && placement.missing_prerequisites.length
99
+ ? `; ${placement.serving_host ?? "the serving host"} lacks ${placement.missing_prerequisites.join(", ")}` : "";
100
+ return `--child-placement require-host: placement chose ${placement?.host_kind ?? "no host"} (${placement?.placement_reason ?? "unknown"}), not the serving host${missing}; the child was not started`;
101
+ }
102
+
95
103
  export const RUNNABLE_HOST_KINDS = Object.freeze(["requester", "serving_host"]);
96
104
 
97
- export async function acquireTestChildSlot({ api, leaseId, wait = defaultTestChildWait, log = () => {}, isStopped = () => false, maxWaits = Infinity, onPark = async () => {}, signal = null, sample = placementSample, prerequisites = null }) {
105
+ export async function acquireTestChildSlot({ api, leaseId, wait = defaultTestChildWait, log = () => {}, isStopped = () => false, maxWaits = Infinity, onPark = async () => {}, signal = null, sample = placementSample, prerequisites = null, requireHost = false }) {
98
106
  const waits = [];
99
107
  for (;;) {
100
108
  // A reading that fails never blocks the run: the server then falls back to the host's cap.
@@ -109,12 +117,22 @@ export async function acquireTestChildSlot({ api, leaseId, wait = defaultTestChi
109
117
  return { ok: false, code: CHILD_PLACEMENT_UNSUPPORTED, placement, waits, slotId: data.slot_id,
110
118
  error: `the control plane placed this child on ${placement?.host ?? "another host"} as ${placement?.host_kind ?? "an unknown kind"} (${placement?.placement_reason ?? "unknown"}), which this CLI cannot run` };
111
119
  }
120
+ // BOT-3398: require-host runs on the serving host or not at all; the taken slot is
121
+ // reported so the run releases it before anything starts.
122
+ if (requireHost && placement.host_kind !== "serving_host") {
123
+ return { ok: false, code: CHILD_PLACEMENT_REQUIRED, placement, waits, slotId: data.slot_id, error: requiredHostError(placement) };
124
+ }
112
125
  // BOT-3030 (AC-5): say why a declared child stayed off its serving host.
113
126
  if (Array.isArray(placement.missing_prerequisites) && placement.missing_prerequisites.length) {
114
127
  log(`stack: the child runs on the requester: ${placement.serving_host ?? "the serving host"} lacks ${placement.missing_prerequisites.join(", ")} (${placement.placement_reason})`);
115
128
  }
116
129
  return { ok: true, slotId: data.slot_id, ttlSeconds: data.ttl_seconds ?? 180, expiresAt: data.expires_at ?? null, placement, waits };
117
130
  }
131
+ // BOT-3398: a full pool that is not the serving host's would only ever run the child here.
132
+ if (data?.code === TEST_CHILD_CAPACITY && requireHost && data.host_kind !== "serving_host") {
133
+ const placement = { host: data.run_host ?? null, host_kind: data.host_kind ?? null, placement_reason: data.placement_reason ?? null };
134
+ return { ok: false, code: CHILD_PLACEMENT_REQUIRED, placement, waits, error: requiredHostError(placement) };
135
+ }
118
136
  if (data?.code === TEST_CHILD_CAPACITY) {
119
137
  // The pool's next expiry bounds the park; a missing one falls back to one slot TTL from now.
120
138
  const expiryMs = Date.parse(data.next_expiry_at ?? "");