@botbuddy/cli 1.96.0 → 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.96.0",
3
- "source_commit": "88fafccd1e03e7a0129065aaee14e23e35160660",
4
- "source_sha256": "44663b4b3e7b7335d621e489826f886c2258f5031bfcca23bc82f2af3de94aea",
2
+ "release_version": "1.97.0",
3
+ "source_commit": "9624b16c5931a1caa8532d54b5c5bbcbfda7968f",
4
+ "source_sha256": "e3eb890b49b33323cd956f58d69b7211787b86098e940fc6c35e2a71f703adad",
5
5
  "target": "darwin-arm64",
6
- "sha256": "0e5f1e5fc122f11c8408cb65ec3a355cb41d4ccb48f39588642e2ef2e7beaf8e"
6
+ "sha256": "54c2ae2eb7ad2b829d7e1072ac35c145f1e6cb058032d5ee9083b859b3a93e32"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.96.0",
3
- "source_commit": "88fafccd1e03e7a0129065aaee14e23e35160660",
4
- "source_sha256": "44663b4b3e7b7335d621e489826f886c2258f5031bfcca23bc82f2af3de94aea",
2
+ "release_version": "1.97.0",
3
+ "source_commit": "9624b16c5931a1caa8532d54b5c5bbcbfda7968f",
4
+ "source_sha256": "e3eb890b49b33323cd956f58d69b7211787b86098e940fc6c35e2a71f703adad",
5
5
  "target": "linux-x64",
6
- "sha256": "808be4bfb9a3208b55d3d94699afc5e5f3ec8c2a78e193805df429e4f5dac5c8"
6
+ "sha256": "69d0a5d44faddb8029c99e061a5c1b9ee1134d38e3695f2348e6039a3f5fafa6"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.96.0",
4
- "source_commit": "88fafccd1e03e7a0129065aaee14e23e35160660",
5
- "source_sha256": "44663b4b3e7b7335d621e489826f886c2258f5031bfcca23bc82f2af3de94aea",
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": "0e5f1e5fc122f11c8408cb65ec3a355cb41d4ccb48f39588642e2ef2e7beaf8e",
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": "808be4bfb9a3208b55d3d94699afc5e5f3ec8c2a78e193805df429e4f5dac5c8",
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.96.0",
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,6 +63,7 @@ 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
68
  import { acquireTestChildSlot, CHILD_PLACEMENT_REQUIRED, defaultTestChildWait, readPs, requesterSample, startChildSampler, testChildApi, testChildReceiptFields } from "./test-child.mjs";
68
69
 
@@ -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
@@ -321,6 +325,17 @@ ${bold("run OPTIONS")}
321
325
  --child-env NAME BOT-3030: pass NAME (this shell's value) to a host child (repeatable).
322
326
  Nothing else is passed; credential-shaped names are refused.
323
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>.
324
339
  --local-only Require a co-located host (execution "local"); no bundle is built.
325
340
  Default (neither flag): execution "auto" — co-located if it admits now,
326
341
  else a remote host with capacity; the bundle digest is sent up front.
@@ -488,7 +503,7 @@ ${bold("EXAMPLE")}
488
503
  # request a per-worktree stack for this batch, run a lane against it, then reap it
489
504
  botbuddy stack run --repo botbuddy-web --ticket BOT-1346 -- pnpm test:integration`;
490
505
 
491
- 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"]);
492
507
  // BOT-2957: a heartbeat touch that goes unanswered is retried this soon, each with its own deadline,
493
508
  // for up to CALLBACK_STALE_PROOF_MAX_MS. Past that the run stops with this code.
494
509
  export const STACK_HEARTBEAT_UNANSWERED_CODE = "LEASE_HEARTBEAT_UNANSWERED";
@@ -504,12 +519,13 @@ export function stackCommandHelp(command) {
504
519
  cancel: ["GLOBAL", "EXIT CODES"],
505
520
  status: ["GLOBAL", "EXIT CODES"],
506
521
  touch: ["GLOBAL", "EXIT CODES", "IDLE LEASES"],
522
+ "child-artifacts": ["GLOBAL", "EXIT CODES"],
507
523
  };
508
524
  // The OPTIONS headings intentionally use lower-case command names.
509
525
  const all = STACK_HELP.split(/\n(?=\u001b\[1m)/);
510
526
  const selected = all.filter((section) => headings[command]?.some((heading) => section.startsWith(bold(heading))));
511
527
  const usage = command === "run" ? "[options] -- <executable> [args...]"
512
- : command === "up" ? "[options]" : "<lease_id> [options]";
528
+ : command === "up" ? "[options]" : command === "child-artifacts" ? "<run_id> [options]" : "<lease_id> [options]";
513
529
  const detail = command === "cancel"
514
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" : "";
515
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.`;
@@ -571,7 +587,7 @@ export function parseStackArgs(argv) {
571
587
  connectionFile: null, noWait: false, claimOnly: false, localExec: false, keepVolumes: false, waitCapacity: null, holdOnTimeout: null,
572
588
  dockerContext: null, dockerEndpoint: null,
573
589
  // BOT-2142: execution placement (null = command default), remote-lease callback + bundle cap.
574
- execution: null, remote: false, localOnly: false, testChild: false, childPlacement: "prefer-host", 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,
575
591
  // BOT-2269: exact stack-relative files shipped in the remote-lease bundle despite the
576
592
  // default exclusions (`--bundle-include`, repeatable).
577
593
  bundleInclude: [],
@@ -700,6 +716,15 @@ export function parseStackArgs(argv) {
700
716
  }
701
717
  break;
702
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
+ }
703
728
  case "--child-max-runtime": {
704
729
  if (need(a, rest[i + 1])) {
705
730
  const n = Number(rest[++i]);
@@ -793,8 +818,11 @@ export function parseStackArgs(argv) {
793
818
  if ((opts.callbackPort != null || opts.bundleMaxBytes != null) && command !== "run") {
794
819
  errors.push("--callback-port and --bundle-max-mb are valid only with `stack run`");
795
820
  }
796
- if ((opts.childRequires.length || opts.childEnv.length || opts.childMaxRuntime != null || opts.childPlacementSet) && !opts.testChild) {
797
- errors.push("--child-placement, --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`);
798
826
  }
799
827
  if (opts.testChild && command !== "run") {
800
828
  errors.push("--test-child is valid only with `stack run` (only run starts a child)");
@@ -833,6 +861,9 @@ export function parseStackArgs(argv) {
833
861
  if (command && ["status", "touch", "done"].includes(command) && !leaseId && !(command === "status" && opts.admissionRequestId)) {
834
862
  errors.push(`${command} needs a <lease_id>`);
835
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
+ }
836
867
  if (["up", "done"].includes(command) && opts.localExec && Boolean(opts.dockerContext) === Boolean(opts.dockerEndpoint)) {
837
868
  errors.push(`--local-exec ${command} requires exactly one of --docker-context <name> or --docker-endpoint <uri>`);
838
869
  }
@@ -3482,6 +3513,32 @@ async function cmdUpOnce(opts, {
3482
3513
  }), opts, EXIT.OK);
3483
3514
  }
3484
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
+
3485
3542
  export async function cmdStatus(leaseId, opts, {
3486
3543
  rpc = retryingStackCall(), emitResult = emit, stderr = (line) => process.stderr.write(`${line}\n`),
3487
3544
  forwardSocket = process.env[FORWARD_ATTESTATION_ENV],
@@ -5611,7 +5668,8 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5611
5668
  ...(adapters.hostChildBundle ? { bundle: adapters.hostChildBundle } : {}),
5612
5669
  ...(adapters.hostChildWait ? { wait: adapters.hostChildWait } : {}),
5613
5670
  log: stderrLine, ...(adapters.hostChildOutput ? { writeOutput: adapters.hostChildOutput } : {}),
5614
- signal: activeWaitAbort.signal,
5671
+ signal: activeWaitAbort.signal, artifactGlobs: opts.childArtifacts ?? [],
5672
+ ...(adapters.hostChildFetch ? { fetchArtifacts: adapters.hostChildFetch } : {}),
5615
5673
  });
5616
5674
  } finally {
5617
5675
  activeWaitAbort = null;
@@ -6124,6 +6182,7 @@ export async function cmdStack(argv, { report = reportStackRunOutcome, outcomeCh
6124
6182
  case "touch": code = await cmdTouch(leaseId, opts); break;
6125
6183
  case "done": code = await cmdDone(leaseId, opts); break;
6126
6184
  case "run": code = await cmdRun(opts, childArgv, { report }); break;
6185
+ case "child-artifacts": code = await cmdChildArtifacts(leaseId, opts); break;
6127
6186
  default:
6128
6187
  process.stderr.write(`${yellow("⚠")} stack: unknown subcommand "${command}". Try ${bold("botbuddy stack help")}.\n`);
6129
6188
  code = emit(buildReceipt({ command: command || "?", outcome: "error", error: `unknown subcommand: ${command}` }), opts, EXIT.INVALID);