@botbuddy/cli 1.85.3 → 1.86.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
@@ -2,6 +2,8 @@
2
2
 
3
3
  ## 1.85.3
4
4
 
5
+ - BOT-3276: `bb stack run --test-child` measures the child's whole process tree, including browsers and servers that move to their own process group or session. `child_resources.method` is now `ps_tree_sample`; the receipt's fields are unchanged.
6
+
5
7
  - Ships the `bb doctor --fix` reused-worktree repair to npm (BOT-3307). A sub-agent working in another worktree keeps that worktree's own identity.
6
8
 
7
9
  ## 1.85.2
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.85.3",
3
- "source_commit": "f50cff97138fdb3acd0b3f65cacdd5fed4fd3281",
4
- "source_sha256": "ea892b69f5b20bb442632b518c1b29c3df3509296847cef4da168f52aec01be4",
2
+ "release_version": "1.86.0",
3
+ "source_commit": "35caa79c6d0ff83a89faac2efcc7cbd98d5bc198",
4
+ "source_sha256": "7b22432ea7ee69e72c29629bca6c6d0de66b3ad5ea1a5beadb15e1b10d1a9207",
5
5
  "target": "darwin-arm64",
6
- "sha256": "34b0c7bf77043626f94db8162888a65ecff5e964b24fcb57131076ae8d9775eb"
6
+ "sha256": "efc9827266c5c700000faddd2020f8e1e59ccc5a3e007c511aa78c8af20e59b7"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.85.3",
3
- "source_commit": "f50cff97138fdb3acd0b3f65cacdd5fed4fd3281",
4
- "source_sha256": "ea892b69f5b20bb442632b518c1b29c3df3509296847cef4da168f52aec01be4",
2
+ "release_version": "1.86.0",
3
+ "source_commit": "35caa79c6d0ff83a89faac2efcc7cbd98d5bc198",
4
+ "source_sha256": "7b22432ea7ee69e72c29629bca6c6d0de66b3ad5ea1a5beadb15e1b10d1a9207",
5
5
  "target": "linux-x64",
6
- "sha256": "8cdad6a23bbf3fecb3a140a7e5f8834ddd29cbca93af3733abe2e67130b10efe"
6
+ "sha256": "de524aa0da29f62069bb844be54557a16b2f3b99c8d449f4328dc800ebfedbf5"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.85.3",
4
- "source_commit": "f50cff97138fdb3acd0b3f65cacdd5fed4fd3281",
5
- "source_sha256": "ea892b69f5b20bb442632b518c1b29c3df3509296847cef4da168f52aec01be4",
3
+ "release_version": "1.86.0",
4
+ "source_commit": "35caa79c6d0ff83a89faac2efcc7cbd98d5bc198",
5
+ "source_sha256": "7b22432ea7ee69e72c29629bca6c6d0de66b3ad5ea1a5beadb15e1b10d1a9207",
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": "34b0c7bf77043626f94db8162888a65ecff5e964b24fcb57131076ae8d9775eb",
11
+ "sha256": "efc9827266c5c700000faddd2020f8e1e59ccc5a3e007c511aa78c8af20e59b7",
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": "8cdad6a23bbf3fecb3a140a7e5f8834ddd29cbca93af3733abe2e67130b10efe",
18
+ "sha256": "de524aa0da29f62069bb844be54557a16b2f3b99c8d449f4328dc800ebfedbf5",
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.85.3",
3
+ "version": "1.86.0",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
package/src/commands.mjs CHANGED
@@ -364,6 +364,8 @@ ${bold("EVIDENCE")} (${cyan("bb help evidence")})
364
364
  status-band read|relay The band's own reads and live wake (run by the mod)
365
365
  evidence require <file> Record an exact-head evidence disposition → botbuddy/ready
366
366
  evidence publish <file> Publish a local evidence statement → botbuddy/ready check-run
367
+ evidence bind <file> Bind a run's receipt to its run, on the requester after the reap
368
+ evidence digest <file> Print the digest of one run record
367
369
 
368
370
  ${bold("HOST + DOCKER")}
369
371
  docker hygiene [options] Dry-run/apply safe stale Supabase cleanup on OrbStack
package/src/evidence.mjs CHANGED
@@ -9,13 +9,59 @@
9
9
  // falling back to the owner/MCP-key ladder like every other `bb` call. Prints
10
10
  // the tool's JSON result on stdout; a refusal exits non-zero.
11
11
 
12
+ import { createHash } from "node:crypto";
12
13
  import { readFileSync } from "node:fs";
13
14
  import { CALL_EXIT, callToolJson as defaultCallToolJson, resolveCallAuth } from "./api.mjs";
14
15
 
15
16
  export const EVIDENCE_EXIT = Object.freeze({ ...CALL_EXIT, USAGE: 2, REFUSED: 4 });
16
17
 
18
+ function canonical(value) {
19
+ if (value === null) return "null";
20
+ if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
21
+ if (typeof value === "number") {
22
+ if (!Number.isFinite(value)) throw new Error("a run record number must be finite");
23
+ return JSON.stringify(value);
24
+ }
25
+ if (Array.isArray(value)) return `[${value.map(canonical).join(",")}]`;
26
+ if (typeof value === "object") {
27
+ const entries = Object.entries(value).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
28
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`).join(",")}}`;
29
+ }
30
+ throw new Error("a run record holds only JSON values");
31
+ }
32
+
33
+ /**
34
+ * BOT-3312: sorted-key JSON of one run record. Must stay byte-identical to
35
+ * supabase/functions/_shared/lib/runReceiptBinding.ts; both sides assert one fixed vector.
36
+ */
37
+ export function canonicalRunRecordJson(record) {
38
+ if (!record || typeof record !== "object" || Array.isArray(record)) throw new Error("a run record must be a JSON object");
39
+ return canonical(record);
40
+ }
41
+
42
+ export function runRecordDigest(record) {
43
+ return `sha256:${createHash("sha256").update(canonicalRunRecordJson(record)).digest("hex")}`;
44
+ }
45
+
46
+ const sortedUnique = (values) => [...new Set(values)].sort();
47
+
48
+ /** The first field where the child's record differs from what the requester launched. */
49
+ function claimMismatch({ claim, record, leaseId, testRunId }) {
50
+ if (record.full !== claim.full) return "full";
51
+ const recorded = Array.isArray(record.domains) ? sortedUnique(record.domains) : [];
52
+ const claimed = sortedUnique(claim.domains);
53
+ if (recorded.length !== claimed.length || recorded.some((d, i) => d !== claimed[i])) return "domains";
54
+ if ((record.project ?? null) !== (claim.project ?? null)) return "project";
55
+ if (record.fingerprint !== claim.fingerprint) return "fingerprint";
56
+ if (record.lifecycle?.stackId !== leaseId) return "lifecycle.stackId";
57
+ if (record.runId !== testRunId) return "runId";
58
+ return null;
59
+ }
60
+
17
61
  const USAGE = `Usage: bb evidence require <requirement.json>
18
62
  bb evidence publish <statement.json>
63
+ bb evidence bind <request.json>
64
+ bb evidence digest <run-record.json>
19
65
 
20
66
  require Record the impact producer's decision for one exact PR head. The file
21
67
  is a JSON object with: repo, pr, headSha, disposition
@@ -26,14 +72,44 @@ publish Publish a local evidence statement for a PR head (after an e2e
26
72
  requirement). The statement is a JSON object with:
27
73
  repo, pr, headSha, mainSha, base, fingerprint, requirement, runs[]
28
74
  (each with the BotBuddy runId), verdict ("pass" | "fail"), fixCommand
75
+ bind Bind one run's receipt to its run, after its lease is reaped. Run this
76
+ on the requester, never in the test child. The file is a JSON object
77
+ with: leaseId, testRunId, headSha, childExitCode, record (the run
78
+ record), and claim {full, domains, project, fingerprint}. Build the
79
+ claim from what you launched, not from the child's record. A record
80
+ that differs from the claim is refused and nothing is sent.
81
+ digest Print the digest of one run record. Publish it as runs[i].recordDigest.
29
82
 
30
83
  Exit codes: 0 recorded · 2 usage · 3 auth · 4 refused · 5 unreachable`;
31
84
 
32
85
  const SUBCOMMANDS = Object.freeze({
33
86
  require: { tool: "publish_evidence_requirement", argName: "requirement" },
34
87
  publish: { tool: "publish_evidence", argName: "statement" },
88
+ bind: { tool: "bind_run_receipt" },
89
+ digest: { tool: null },
35
90
  });
36
91
 
92
+ /** BOT-3312: the tool arguments for `bind`, or a refusal made before anything is sent. */
93
+ function bindArguments(body) {
94
+ const { leaseId, testRunId, headSha, childExitCode, claim, record } = body ?? {};
95
+ if (!claim || typeof claim !== "object" || !Array.isArray(claim.domains) || !record || typeof record !== "object" || Array.isArray(record)) {
96
+ return { usage: "the request needs a claim {full, domains, project, fingerprint} and the run record" };
97
+ }
98
+ const field = claimMismatch({ claim, record, leaseId, testRunId });
99
+ if (field) {
100
+ return { refusal: { success: false, code: "RECEIPT_BINDING_CLAIM_MISMATCH", field,
101
+ message: `the run record's ${field} differs from what the requester launched; nothing was bound` } };
102
+ }
103
+ return { args: {
104
+ lease_id: leaseId,
105
+ test_run_id: testRunId,
106
+ head_sha: headSha,
107
+ run_record_digest: runRecordDigest(record),
108
+ child_exit_code: childExitCode,
109
+ claim: { full: claim.full, domains: claim.domains, project: claim.project ?? null, fingerprint: claim.fingerprint },
110
+ } };
111
+ }
112
+
37
113
  export async function cmdEvidence(args, {
38
114
  resolveAuth = resolveCallAuth,
39
115
  callToolJson = defaultCallToolJson,
@@ -63,6 +139,31 @@ export async function cmdEvidence(args, {
63
139
  return EVIDENCE_EXIT.USAGE;
64
140
  }
65
141
 
142
+ if (sub === "digest") {
143
+ try {
144
+ log(JSON.stringify({ digest: runRecordDigest(body) }));
145
+ return EVIDENCE_EXIT.OK;
146
+ } catch (error) {
147
+ errorLog(`✗ ${error?.message ?? error}`);
148
+ return EVIDENCE_EXIT.USAGE;
149
+ }
150
+ }
151
+
152
+ let toolArgs = { [spec.argName]: body };
153
+ if (sub === "bind") {
154
+ const bind = bindArguments(body);
155
+ if (bind.usage) {
156
+ errorLog(`✗ ${bind.usage}\n\n${USAGE}`);
157
+ return EVIDENCE_EXIT.USAGE;
158
+ }
159
+ if (bind.refusal) {
160
+ log(JSON.stringify(bind.refusal, null, 2));
161
+ errorLog(`✗ ${bind.refusal.code}: ${bind.refusal.message}`);
162
+ return EVIDENCE_EXIT.REFUSED;
163
+ }
164
+ toolArgs = bind.args;
165
+ }
166
+
66
167
  const resolved = await resolveAuth({ toolName: spec.tool, preferSession: true });
67
168
  if (resolved?.error || !resolved?.auth) {
68
169
  log(JSON.stringify(resolved?.error ?? { ok: false, auth: true, error: "not_authenticated" }, null, 2));
@@ -70,7 +171,7 @@ export async function cmdEvidence(args, {
70
171
  return EVIDENCE_EXIT.AUTH;
71
172
  }
72
173
 
73
- const res = await callToolJson(spec.tool, { [spec.argName]: body }, { auth: resolved.auth });
174
+ const res = await callToolJson(spec.tool, toolArgs, { auth: resolved.auth });
74
175
  if (!res.ok) {
75
176
  log(JSON.stringify(res, null, 2));
76
177
  if (res.auth) {
@@ -86,10 +187,18 @@ export async function cmdEvidence(args, {
86
187
  }
87
188
 
88
189
  log(JSON.stringify(res.data, null, 2));
89
- if (res.isError || res.data?.ok === false) {
90
- errorLog(`✗ ${res.data?.error ?? `${spec.tool} refused`}: ${res.data?.message ?? ""}`.trimEnd());
190
+ if (res.isError || res.data?.ok === false || res.data?.success === false) {
191
+ errorLog(`✗ ${res.data?.code ?? res.data?.error ?? `${spec.tool} refused`}: ${res.data?.message ?? ""}`.trimEnd());
91
192
  return EVIDENCE_EXIT.REFUSED;
92
193
  }
194
+ if (sub === "bind") {
195
+ // Success means a binding id came back; an empty answer is never "bound".
196
+ if (res.data?.success !== true || typeof res.data?.binding_id !== "string") {
197
+ errorLog("✗ BotBuddy returned no binding — nothing is known to be bound; retry.");
198
+ return EVIDENCE_EXIT.ERROR;
199
+ }
200
+ return EVIDENCE_EXIT.OK;
201
+ }
93
202
  if (sub === "require") {
94
203
  // Success means the control plane echoed the recorded disposition — an
95
204
  // outage body that normalises to an empty result is never "recorded".
@@ -3,7 +3,7 @@
3
3
  // Before the child starts, the run asks the control plane where it runs and takes exactly
4
4
  // ONE `test_child` slot on that run host (BOT-3239 R-e: place first, then one slot; a run
5
5
  // that is waiting holds nothing). The slot's TTL is renewed by the run itself, so a killed
6
- // run frees it within one TTL. While the child runs, its process group is sampled for peak
6
+ // run frees it within one TTL. While the child runs, its process tree is sampled for peak
7
7
  // memory and CPU-seconds; at exit the slot is released and the cost recorded on the lease.
8
8
  //
9
9
  // The kill switch and the default-off flag are read by the server on every decision.
@@ -19,7 +19,7 @@ export const TEST_CHILD_UNAVAILABLE = "TEST_CHILD_UNAVAILABLE";
19
19
  /** A full pool with no reported expiry parks at most one default slot TTL. */
20
20
  export const FALLBACK_PARK_MS = 180_000;
21
21
  export const SAMPLE_INTERVAL_MS = 5_000;
22
- export const SAMPLE_METHOD = "ps_pgid_sample";
22
+ export const SAMPLE_METHOD = "ps_tree_sample";
23
23
 
24
24
  /** The three tool calls, over the run's retrying caller. */
25
25
  export function testChildApi(rpc) {
@@ -123,42 +123,88 @@ export function parseCpuTime(raw) {
123
123
  return days * 86_400 + secs;
124
124
  }
125
125
 
126
- /** Rows of `ps -A -o pid=,pgid=,rss=,time=,comm=` (rss in KiB). */
126
+ /** Rows of `ps -A -o pid=,ppid=,pgid=,rss=,time=,lstart=,comm=` (rss in KiB, lstart in the C locale). */
127
127
  export function parsePsRows(text) {
128
128
  const rows = [];
129
129
  for (const line of String(text ?? "").split("\n")) {
130
- const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/);
130
+ const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\S+\s+\S+\s+\d+\s+\S+\s+\d+)\s+(.*)$/);
131
131
  if (!m) continue;
132
- rows.push({ pid: Number(m[1]), pgid: Number(m[2]), rssBytes: Number(m[3]) * 1024, cpuSeconds: parseCpuTime(m[4]), comm: m[5] });
132
+ rows.push({
133
+ pid: Number(m[1]), ppid: Number(m[2]), pgid: Number(m[3]), rssBytes: Number(m[4]) * 1024,
134
+ cpuSeconds: parseCpuTime(m[5]), startedAt: m[6].replace(/\s+/g, " "), comm: m[7],
135
+ });
133
136
  }
134
137
  return rows;
135
138
  }
136
139
 
137
140
  export function readPs({ run = spawnSync } = {}) {
138
141
  // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process -- fixed argv, no shell.
139
- const r = run("ps", ["-A", "-o", "pid=,pgid=,rss=,time=,comm="], { encoding: "utf8", timeout: 5_000 });
142
+ const r = run("ps", ["-A", "-o", "pid=,ppid=,pgid=,rss=,time=,lstart=,comm="], { encoding: "utf8", timeout: 5_000, env: { ...process.env, LC_ALL: "C" } });
140
143
  if (r.status !== 0 || typeof r.stdout !== "string") return null;
141
144
  return parsePsRows(r.stdout);
142
145
  }
143
146
 
147
+ /** A pid is reused over a long run; the pid with its start time names one process. */
148
+ const processKey = (row) => `${row.pid}@${row.startedAt}`;
149
+
150
+ /**
151
+ * Follows one child's process tree across `ps` frames. A process belongs to the tree when it
152
+ * is the child, a child of a member, or in a process group a member leads, so a descendant
153
+ * that calls setsid or setpgid stays in it. A member stays one after its parent dies.
154
+ */
155
+ function childTreeTracker(rootPid) {
156
+ const members = new Set();
157
+ const groups = new Map([[rootPid, null]]); // group id → the identity of its leader
158
+ let rootSeen = false;
159
+ return (rows) => {
160
+ const childrenOf = new Map(); const inGroup = new Map();
161
+ for (const row of rows) {
162
+ childrenOf.set(row.ppid, [...(childrenOf.get(row.ppid) ?? []), row]);
163
+ inGroup.set(row.pgid, [...(inGroup.get(row.pgid) ?? []), row]);
164
+ if (row.pid !== row.pgid || !groups.has(row.pid)) continue;
165
+ const leader = groups.get(row.pid);
166
+ if (leader === null) groups.set(row.pid, processKey(row));
167
+ else if (leader !== processKey(row)) groups.delete(row.pid); // the group id was reused
168
+ }
169
+ if (!rootSeen) {
170
+ const root = rows.find((row) => row.pid === rootPid);
171
+ if (root) { rootSeen = true; members.add(processKey(root)); }
172
+ }
173
+ const tree = new Map();
174
+ const pending = rows.filter((row) => members.has(processKey(row)) || groups.has(row.pgid));
175
+ while (pending.length) {
176
+ const row = pending.pop();
177
+ const key = processKey(row);
178
+ if (tree.has(key)) continue;
179
+ tree.set(key, row);
180
+ members.add(key);
181
+ if (row.pid === row.pgid) { groups.set(row.pid, key); pending.push(...(inGroup.get(row.pid) ?? [])); }
182
+ pending.push(...(childrenOf.get(row.pid) ?? []));
183
+ }
184
+ return tree;
185
+ };
186
+ }
187
+
144
188
  /**
145
- * Samples the child's process group (it is spawned detached, so its pid is the group id).
146
- * Peak memory is the largest summed RSS seen; CPU-seconds sums each process's last seen
147
- * CPU time. Processes that live less than one interval are missed: `method` says so.
189
+ * Samples the child's process tree. Peak memory is the largest summed RSS seen, so memory
190
+ * shared between processes counts once per process; CPU-seconds sums each process's last seen
191
+ * CPU time. Sampling stops when the child exits. A process that lives less than one interval
192
+ * is missed, as is one that leaves the tree (a double fork) before a sample sees it.
148
193
  */
149
- export function startChildSampler(pgid, { ps = readPs, intervalMs = SAMPLE_INTERVAL_MS, setInterval: si = setInterval, clearInterval: ci = clearInterval, now = Date.now } = {}) {
194
+ export function startChildSampler(rootPid, { ps = readPs, intervalMs = SAMPLE_INTERVAL_MS, setInterval: si = setInterval, clearInterval: ci = clearInterval, now = Date.now } = {}) {
150
195
  const startedAt = now();
151
196
  let peakRss = 0; let samples = 0; let failed = 0;
152
- const cpuByPid = new Map();
197
+ const cpuByProcess = new Map();
198
+ const treeOf = childTreeTracker(rootPid);
153
199
  const sample = () => {
154
200
  let rows;
155
201
  try { rows = ps(); } catch { rows = null; }
156
202
  if (!rows) { failed++; return; }
157
- const group = rows.filter((r) => r.pgid === pgid);
158
- if (!group.length) return;
203
+ const tree = treeOf(rows);
204
+ if (!tree.size) return;
159
205
  samples++;
160
- peakRss = Math.max(peakRss, group.reduce((n, r) => n + r.rssBytes, 0));
161
- for (const r of group) if (r.cpuSeconds != null) cpuByPid.set(r.pid, Math.max(cpuByPid.get(r.pid) ?? 0, r.cpuSeconds));
206
+ peakRss = Math.max(peakRss, [...tree.values()].reduce((n, r) => n + r.rssBytes, 0));
207
+ for (const [key, r] of tree) if (r.cpuSeconds != null) cpuByProcess.set(key, Math.max(cpuByProcess.get(key) ?? 0, r.cpuSeconds));
162
208
  };
163
209
  sample();
164
210
  const timer = si(sample, intervalMs);
@@ -166,7 +212,7 @@ export function startChildSampler(pgid, { ps = readPs, intervalMs = SAMPLE_INTER
166
212
  return {
167
213
  stop() {
168
214
  ci(timer);
169
- const cpu = [...cpuByPid.values()].reduce((a, b) => a + b, 0);
215
+ const cpu = [...cpuByProcess.values()].reduce((a, b) => a + b, 0);
170
216
  return {
171
217
  peak_rss_bytes: peakRss, cpu_seconds: Math.round(cpu * 100) / 100,
172
218
  samples, failed_samples: failed, interval_ms: intervalMs,