@botbuddy/cli 1.78.0 → 1.78.3

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.
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.78.0",
3
- "source_commit": "d1d71be9cf32932eb09adaca324829bf643c9c3a",
4
- "source_sha256": "d6e8bde1777cdcee29120aac387cf7dc0c0cfcb11495f99c1b6ec22ed457e154",
2
+ "release_version": "1.78.3",
3
+ "source_commit": "016217f2bb60798780bd8de86bd2e0a20585a31a",
4
+ "source_sha256": "a47b7b82b6f2b3b5e2cd7ba4e6a06f4749c9f02b3f83917496a7f875e147927d",
5
5
  "target": "darwin-arm64",
6
- "sha256": "744982a2a08a8d796911eb2cb37229a6a9de5b43ab41848d2d797d31093ac3e7"
6
+ "sha256": "7cc6f65cb8fadc76b5e7a890a94b8dd7ba4249223d13d6b6bde80af5598d908d"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.78.0",
3
- "source_commit": "d1d71be9cf32932eb09adaca324829bf643c9c3a",
4
- "source_sha256": "d6e8bde1777cdcee29120aac387cf7dc0c0cfcb11495f99c1b6ec22ed457e154",
2
+ "release_version": "1.78.3",
3
+ "source_commit": "016217f2bb60798780bd8de86bd2e0a20585a31a",
4
+ "source_sha256": "a47b7b82b6f2b3b5e2cd7ba4e6a06f4749c9f02b3f83917496a7f875e147927d",
5
5
  "target": "linux-x64",
6
- "sha256": "fe36d3e84ca6cf34e4a718356aeb295fc86d04914c5649fc1ddd10ce45ea9ec6"
6
+ "sha256": "4561b9a97f8c3271ad73c1254bc374e75cad40419be82a05ef2d25d29253a8bc"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.78.0",
4
- "source_commit": "d1d71be9cf32932eb09adaca324829bf643c9c3a",
5
- "source_sha256": "d6e8bde1777cdcee29120aac387cf7dc0c0cfcb11495f99c1b6ec22ed457e154",
3
+ "release_version": "1.78.3",
4
+ "source_commit": "016217f2bb60798780bd8de86bd2e0a20585a31a",
5
+ "source_sha256": "a47b7b82b6f2b3b5e2cd7ba4e6a06f4749c9f02b3f83917496a7f875e147927d",
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": "744982a2a08a8d796911eb2cb37229a6a9de5b43ab41848d2d797d31093ac3e7",
11
+ "sha256": "7cc6f65cb8fadc76b5e7a890a94b8dd7ba4249223d13d6b6bde80af5598d908d",
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": "fe36d3e84ca6cf34e4a718356aeb295fc86d04914c5649fc1ddd10ce45ea9ec6",
18
+ "sha256": "4561b9a97f8c3271ad73c1254bc374e75cad40419be82a05ef2d25d29253a8bc",
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.78.0",
3
+ "version": "1.78.3",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
package/src/stack.mjs CHANGED
@@ -62,6 +62,7 @@ import { bold, dim, yellow } from "./utils.mjs";
62
62
  import { STACK_RELEASE_INTENT_ENV, classifyStackRunOutcome, observeStackRunSignal, ownerReleaseHeld, reportStackRunOutcome } from "./stack-run-outcome.mjs";
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
+ import { acquireTestChildSlot, defaultTestChildWait, readPs, requesterSample, startChildSampler, testChildApi, testChildReceiptFields } from "./test-child.mjs";
65
66
 
66
67
  export const STACK_SCHEMA_VERSION = 1;
67
68
 
@@ -285,6 +286,14 @@ ${bold("run OPTIONS")}
285
286
  ssh_target (transport ssh-forward), and gives the child a connection file
286
287
  on the LOCAL ports (same numbers when free and outside the leased
287
288
  serving band 61000-64999, else remapped; see "forwards").
289
+ --test-child BOT-3240: before the child starts, ask the control plane where it runs
290
+ and take exactly one test_child compute slot there (the requester today;
291
+ child-on-host is default-off). A full pool waits with TEST_CHILD_CAPACITY
292
+ holding no slot, parked on the pool's slot-release signal and its next
293
+ expiry; a lost slot stops the child (TEST_CHILD_SLOT_LOST); 0 slots refuses (TEST_CHILD_SLOTS_ZERO). The slot is
294
+ renewed while the child runs and released at exit; the receipt adds
295
+ child_placement {host, slot, placement_reason}, child_resources {peak RSS,
296
+ CPU-seconds} and requester_sample.
288
297
  --local-only Require a co-located host (execution "local"); no bundle is built.
289
298
  Default (neither flag): execution "auto" — co-located if it admits now,
290
299
  else a remote host with capacity; the bundle digest is sent up front.
@@ -523,7 +532,7 @@ export function parseStackArgs(argv) {
523
532
  connectionFile: null, noWait: false, claimOnly: false, localExec: false, keepVolumes: false, waitCapacity: null, holdOnTimeout: null,
524
533
  dockerContext: null, dockerEndpoint: null,
525
534
  // BOT-2142: execution placement (null = command default), remote-lease callback + bundle cap.
526
- execution: null, remote: false, localOnly: false, executionRing: "stable", callbackPort: null, bundleMaxBytes: null,
535
+ execution: null, remote: false, localOnly: false, testChild: false, executionRing: "stable", callbackPort: null, bundleMaxBytes: null,
527
536
  // BOT-2269: exact stack-relative files shipped in the remote-lease bundle despite the
528
537
  // default exclusions (`--bundle-include`, repeatable).
529
538
  bundleInclude: [],
@@ -623,6 +632,7 @@ export function parseStackArgs(argv) {
623
632
  }
624
633
  case "--remote": opts.remote = true; break;
625
634
  case "--local-only": opts.localOnly = true; break;
635
+ case "--test-child": opts.testChild = true; break;
626
636
  case "--execution-ring": {
627
637
  if (need(a, rest[i + 1])) {
628
638
  const ring = rest[++i];
@@ -701,6 +711,9 @@ export function parseStackArgs(argv) {
701
711
  if ((opts.callbackPort != null || opts.bundleMaxBytes != null) && command !== "run") {
702
712
  errors.push("--callback-port and --bundle-max-mb are valid only with `stack run`");
703
713
  }
714
+ if (opts.testChild && command !== "run") {
715
+ errors.push("--test-child is valid only with `stack run` (only run starts a child)");
716
+ }
704
717
  if (opts.bundleInclude.length && command !== "run") {
705
718
  errors.push("--bundle-include is valid only with `stack run` (only run builds a remote-lease bundle)");
706
719
  } else if (opts.bundleInclude.length && opts.localOnly) {
@@ -4006,7 +4019,9 @@ async function runStackLifecycleWatched(opts, childArgv, adapters, firstBox, fre
4006
4019
  if (requeuedFrom && result && typeof result === "object") result = { ...result, requeuedFrom };
4007
4020
  const withIncident = incidentBox.incident && !result?.incident ? { ...result, incident: incidentBox.incident } : result;
4008
4021
  const withExecution = incidentBox.execution && !withIncident?.execution ? { ...withIncident, execution: incidentBox.execution } : withIncident;
4009
- const withIdle = incidentBox.idleLease && !withExecution?.idleLease ? { ...withExecution, idleLease: incidentBox.idleLease } : withExecution;
4022
+ const withIdleOnly = incidentBox.idleLease && !withExecution?.idleLease ? { ...withExecution, idleLease: incidentBox.idleLease } : withExecution;
4023
+ // BOT-3240: the test child's placement and cost ride every result shape, refusals included.
4024
+ const withIdle = incidentBox.testChild && withIdleOnly && !withIdleOnly.testChild ? { ...withIdleOnly, testChild: incidentBox.testChild } : withIdleOnly;
4010
4025
  const withPortBlock = incidentBox.portBlock && !withIdle?.portBlock ? { ...withIdle, portBlock: incidentBox.portBlock } : withIdle;
4011
4026
  const withWebUrl = incidentBox.webUrl && withPortBlock && !withPortBlock.webUrl ? { ...withPortBlock, webUrl: incidentBox.webUrl } : withPortBlock;
4012
4027
  const withStopSignal = incidentBox.stopSignal && withWebUrl ? { ...withWebUrl, stopSignal: incidentBox.stopSignal } : withWebUrl;
@@ -4049,6 +4064,9 @@ export async function applyRequesterNetworkLoss(result, watch, { failedAtMs = nu
4049
4064
  };
4050
4065
  }
4051
4066
 
4067
+ /** BOT-3240: how long a --test-child slot release may take before cleanup goes on without it. */
4068
+ export const TEST_CHILD_RELEASE_DEADLINE_MS = 10_000;
4069
+
4052
4070
  /** BOT-2467: where a lifecycle result carries its outcome-record channel. */
4053
4071
  export const OUTCOME_CHANNEL = Symbol.for("botbuddy.stackRunOutcomeChannel");
4054
4072
 
@@ -4165,6 +4183,26 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
4165
4183
  let heartbeat = null;
4166
4184
  let heartbeatRetry = null;
4167
4185
  let heartbeatUnanswered = false;
4186
+ // BOT-3240: the --test-child slot (null unless the flag is set).
4187
+ const testChildCalls = adapters.testChild ?? testChildApi(rpc);
4188
+ let testChild = null;
4189
+ let testChildRenew = null;
4190
+ let testChildWaitAbort = null;
4191
+ const releaseTestChild = async (resources) => {
4192
+ if (!testChild?.slotId) return null;
4193
+ const slotId = testChild.slotId;
4194
+ testChild.slotId = null; // released at most once
4195
+ // Codex #1691 r5: release is bounded, so an unanswered call never blocks lease cleanup or the
4196
+ // receipt; the slot then frees at its TTL, and the receipt says it was not confirmed.
4197
+ const deadlineMs = adapters.testChildReleaseDeadlineMs ?? TEST_CHILD_RELEASE_DEADLINE_MS;
4198
+ let timer = null;
4199
+ // Not unref'd: the run must outlive an unanswered release until the deadline (CI caught it).
4200
+ const deadline = new Promise((resolveDeadline) => { timer = setTimeout(() => resolveDeadline(null), deadlineMs); });
4201
+ try {
4202
+ const r = await Promise.race([Promise.resolve(testChildCalls.release(slotId, resources)).catch(() => null), deadline]);
4203
+ return Boolean(r?.ok && r.data?.success);
4204
+ } catch { return false; } finally { clearTimeout(timer); }
4205
+ };
4168
4206
  let retention = null;
4169
4207
  let hardTimer = null;
4170
4208
  let cleanupResult = null;
@@ -4370,14 +4408,18 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
4370
4408
  return cleanupPromise;
4371
4409
  };
4372
4410
 
4411
+ // Test seam: a fake child's pid is never a real process group.
4412
+ const signalGroup = adapters.signalChildGroup ?? childGroupSignal;
4373
4413
  const stopChild = (signal = "SIGTERM", forcedCode = null) => {
4374
4414
  void closeOrigin();
4415
+ // BOT-3240 (Codex #1691 r4): a loss before the child exists ends a pending slot wait now.
4416
+ testChildWaitAbort?.abort("stopped");
4375
4417
  if (!child || childResult) return;
4376
4418
  // BOT-3109: when a loss stopped the child, so the requester probe weighs the network then, not after cleanup.
4377
4419
  if (forcedCode != null && forcedStopCode == null) incidentBox.lossAtMs ??= Date.now();
4378
4420
  forcedStopCode ??= forcedCode;
4379
- childGroupSignal(child, signal);
4380
- const kill = clock.setTimeout(() => childGroupSignal(child, "SIGKILL"), 10_000);
4421
+ signalGroup(child, signal);
4422
+ const kill = clock.setTimeout(() => signalGroup(child, "SIGKILL"), 10_000);
4381
4423
  kill.unref?.();
4382
4424
  };
4383
4425
 
@@ -4390,6 +4432,7 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
4390
4432
  incidentBox.stopSignal = { signal, source: "unknown", parent: null };
4391
4433
  }
4392
4434
  activeWaitAbort?.abort("interrupted");
4435
+ testChildWaitAbort?.abort("interrupted");
4393
4436
  stopChild(signal);
4394
4437
  // If capacity is still queued/provisioning there is no child to hold open;
4395
4438
  // release immediately so an interrupted invocation cannot later provision.
@@ -5341,7 +5384,90 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5341
5384
  const cleanup = await requestCleanup();
5342
5385
  return tunnelLostResult(tunnelLost, { leaseId, cleanup, childExitCode: null, ...(callbackCleanupError ? { callbackCleanupUncertain: true } : {}) });
5343
5386
  }
5387
+ if (opts.testChild) {
5388
+ // BOT-3240 (R-e): place first, then exactly one slot; a full pool waits holding nothing.
5389
+ // Codex #1691 r3: keep the active lease touched while the run waits for a child slot — once
5390
+ // before each park and on the lease's own cadence — or a long queue loses its stack.
5391
+ const touchWhileWaiting = () => Promise.resolve(api.touch(leaseId, undefined)).catch(() => null);
5392
+ const waitCadenceMs = Math.max(1_000, Math.floor((current.data.idle_ttl_secs ?? opts.idleTtl ?? 1800) * 1000 / 3));
5393
+ const waitTouch = clock.setInterval(() => { void touchWhileWaiting(); }, waitCadenceMs);
5394
+ waitTouch?.unref?.();
5395
+ let placed;
5396
+ testChildWaitAbort = new AbortController();
5397
+ try {
5398
+ placed = await acquireTestChildSlot({
5399
+ signal: testChildWaitAbort.signal,
5400
+ api: testChildCalls, leaseId, wait: adapters.testChildWait ?? defaultTestChildWait, log: stderrLine,
5401
+ isStopped: () => Boolean(receivedSignal || tunnelLost || callbackLost || originLost),
5402
+ onPark: touchWhileWaiting,
5403
+ });
5404
+ } finally {
5405
+ clock.clearInterval(waitTouch);
5406
+ testChildWaitAbort = null;
5407
+ }
5408
+ testChild = { placement: placed.placement ?? null, waits: placed.waits, slotId: placed.slotId ?? null, ttlSeconds: placed.ttlSeconds ?? null,
5409
+ confirmedUntilMs: Date.parse(placed.expiresAt ?? "") || null };
5410
+ incidentBox.testChild = testChild;
5411
+ // Codex #1691 P2: a stop that landed while the slot was being taken wins — release it, start nothing.
5412
+ const stoppedWhilePlacing = placed.ok && (receivedSignal || tunnelLost || callbackLost || originLost);
5413
+ if (stoppedWhilePlacing) {
5414
+ testChild.released = await releaseTestChild(null);
5415
+ await closeTunnel();
5416
+ const cleanup = await requestCleanup();
5417
+ return { exitCode: receivedSignal ? SIGNAL_EXIT[receivedSignal] : cleanup.ok ? EXIT.LEASE_FAILED : EXIT.CLEANUP_FAILED,
5418
+ outcome: receivedSignal ? "interrupted" : "error", code: receivedSignal ? null : (tunnelLost?.code ?? callbackLost?.code ?? originLost?.code ?? null),
5419
+ leaseId, cleanup, error: "the run was stopped while its test_child slot was being taken; the slot was released and the child never started" };
5420
+ }
5421
+ // Codex #1691 r8: a slot already past its expiry (a late answer, a suspended requester) is
5422
+ // renewed before the child starts; one that cannot be renewed is refused, never run.
5423
+ if (placed.ok && testChild.confirmedUntilMs != null && (adapters.now ?? Date.now)() >= testChild.confirmedUntilMs) {
5424
+ let renewed = null;
5425
+ try { renewed = await testChildCalls.renew(testChild.slotId); } catch { renewed = null; }
5426
+ if (renewed?.ok && renewed.data?.success) {
5427
+ testChild.confirmedUntilMs = Date.parse(renewed.data.expires_at ?? "") || null;
5428
+ } else {
5429
+ placed.ok = false;
5430
+ placed.code = renewed?.data?.code ?? "TEST_CHILD_SLOT_LOST";
5431
+ placed.error = "the test_child slot expired before the child could start and could not be renewed; the child was not started";
5432
+ }
5433
+ }
5434
+ if (!placed.ok) {
5435
+ if (placed.slotId) testChild.released = await releaseTestChild(null);
5436
+ await closeTunnel();
5437
+ const cleanup = await requestCleanup();
5438
+ const exitCode = receivedSignal ? SIGNAL_EXIT[receivedSignal] : cleanup.ok ? EXIT.BACKEND : EXIT.CLEANUP_FAILED;
5439
+ return { exitCode, outcome: receivedSignal ? "interrupted" : "refused", code: placed.code, leaseId, cleanup, error: placed.error };
5440
+ }
5441
+ }
5344
5442
  child = startChild(childArgv, childEnv, childCwd);
5443
+ if (testChild) {
5444
+ testChild.sampler = (adapters.testChildSampler ?? startChildSampler)(child.pid);
5445
+ // Renew at a third of the slot TTL, independent of the lease touch cadence.
5446
+ const renewMs = Math.max(10_000, Math.floor((testChild.ttlSeconds ?? 180) * 1000 / 3));
5447
+ // Codex #1691 P1: a child whose slot is lost is stopped — a definitive TEST_CHILD_SLOT_LOST at
5448
+ // once, unanswered renewals once the last confirmed expiry has passed (the server may then
5449
+ // hand the slot to another run). Never a successful receipt past the concurrency bound.
5450
+ const fenceSlotLost = (code) => {
5451
+ if (testChild.renewLost) return;
5452
+ testChild.renewLost = code;
5453
+ stderrLine(`stack: ${code}: this run's test_child slot was lost; stopping the child`);
5454
+ stopChild("SIGTERM", EXIT.LEASE_FAILED);
5455
+ };
5456
+ const renewNow = adapters.now ?? Date.now;
5457
+ testChildRenew = clock.setInterval(async () => {
5458
+ if (!testChild.slotId || childResult) return;
5459
+ let r;
5460
+ try { r = await testChildCalls.renew(testChild.slotId); } catch { r = null; }
5461
+ if (r?.ok && r.data?.success) {
5462
+ testChild.confirmedUntilMs = Date.parse(r.data.expires_at ?? "") || testChild.confirmedUntilMs;
5463
+ } else if (r?.ok && r.data?.success === false) {
5464
+ fenceSlotLost(r.data.code ?? "TEST_CHILD_SLOT_LOST");
5465
+ } else if (testChild.confirmedUntilMs != null && renewNow() >= testChild.confirmedUntilMs) {
5466
+ fenceSlotLost("TEST_CHILD_SLOT_LOST");
5467
+ }
5468
+ }, renewMs);
5469
+ testChildRenew?.unref?.();
5470
+ }
5345
5471
  leaseIdleTtlSecs = current.data.idle_ttl_secs ?? opts.idleTtl ?? 1800;
5346
5472
  const cadenceMs = Math.max(1_000, Math.floor(leaseIdleTtlSecs * 1000 / 3));
5347
5473
  // BOT-1798 (Codex #928 R8 P2): the directory's retention tracks the LEASE's
@@ -5427,6 +5553,13 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5427
5553
  if (opts.hardTtl) hardTimer = clock.setTimeout(() => stopChild("SIGTERM", EXIT.TIMEOUT), opts.hardTtl * 1000);
5428
5554
  hardTimer?.unref?.();
5429
5555
  childResult = await waitForChild(child);
5556
+ if (testChildRenew) { clock.clearInterval(testChildRenew); testChildRenew = null; }
5557
+ if (testChild?.sampler) {
5558
+ testChild.resources = testChild.sampler.stop();
5559
+ testChild.sampler = null;
5560
+ try { testChild.requesterSample = (adapters.testChildRequesterSample ?? (() => requesterSample({ rows: readPs() })))(); } catch { testChild.requesterSample = null; }
5561
+ testChild.released = await releaseTestChild({ ...testChild.resources, ...(testChild.requesterSample ? { requester_sample: testChild.requesterSample } : {}) });
5562
+ }
5430
5563
  if (heartbeat) clock.clearInterval(heartbeat);
5431
5564
  if (heartbeatRetry) clock.clearTimeout(heartbeatRetry);
5432
5565
  if (retention) { clock.clearInterval(retention); retention = null; }
@@ -5467,6 +5600,10 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5467
5600
  };
5468
5601
  }
5469
5602
  const exitCode = receivedSignal ? SIGNAL_EXIT[receivedSignal] : callbackCleanupError ? EXIT.CLEANUP_FAILED : forcedStopCode ?? (childResult.code !== 0 ? childResult.code : callbackCleanupError || !cleanup.ok ? EXIT.CLEANUP_FAILED : 0);
5603
+ if (testChild?.renewLost && !receivedSignal) {
5604
+ return { exitCode: EXIT.LEASE_FAILED, outcome: "failed", code: testChild.renewLost, leaseId, childExitCode: childResult.code, cleanup, fenced: true,
5605
+ error: "this run's test_child slot was lost while the child ran, so the child was stopped (no result past the slot bound)" };
5606
+ }
5470
5607
  return { exitCode, outcome: exitCode === 0 ? "completed" : "failed", leaseId, childExitCode: childResult.code, cleanup, ...(callbackCleanupError ? { code: callbackCleanupError } : heartbeatUnanswered ? { code: STACK_HEARTBEAT_UNANSWERED_CODE } : {}), fenced: fencing, ...(parkIncident ? { incident: parkIncident } : {}) };
5471
5608
  } catch (error) {
5472
5609
  const cleanup = await requestCleanup();
@@ -5477,6 +5614,10 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5477
5614
  const exitCode = cleanup?.ok === false ? EXIT.CLEANUP_FAILED : classifyStackAuthError(error);
5478
5615
  return { exitCode, outcome: "error", leaseId, error: String(error?.message ?? error), cleanup };
5479
5616
  } finally {
5617
+ // BOT-3240: a run that threw still frees its slot now rather than at TTL.
5618
+ if (testChildRenew) clock.clearInterval(testChildRenew);
5619
+ if (testChild?.sampler) { try { testChild.resources = testChild.sampler.stop(); } catch { /* best effort */ } testChild.sampler = null; }
5620
+ if (testChild?.slotId) testChild.released = await releaseTestChild(testChild.resources ?? null);
5480
5621
  if (heartbeat) clock.clearInterval(heartbeat);
5481
5622
  if (retention) clock.clearInterval(retention);
5482
5623
  if (hardTimer) clock.clearTimeout(hardTimer);
@@ -5544,6 +5685,8 @@ export function runReceiptFields(result) {
5544
5685
  ...capacityStaleReceiptFields(result),
5545
5686
  ...(result.wait_exit_code != null ? { wait_exit_code: result.wait_exit_code, wait_receipt: result.wait_receipt ?? null } : {}),
5546
5687
  child_exit_code: result.childExitCode ?? null,
5688
+ // BOT-3240: where a --test-child run's child ran, its slot, and what it cost.
5689
+ ...testChildReceiptFields(result.testChild),
5547
5690
  // BOT-1803: an idle release is `cleanup: { idle: true, idle_since }` (nothing was reaped).
5548
5691
  cleanup: result.cleanup?.idle ? { idle: true, idle_since: result.cleanup.idle_since ?? null } : result.cleanup?.ok ?? null,
5549
5692
  cleanup_code: result.cleanup?.code ?? null,
@@ -0,0 +1,214 @@
1
+ // BOT-3240 — `bb stack run --test-child`: the child-placement straw man (P-BOT-42 PR 2).
2
+ //
3
+ // Before the child starts, the run asks the control plane where it runs and takes exactly
4
+ // ONE `test_child` slot on that run host (BOT-3239 R-e: place first, then one slot; a run
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
7
+ // memory and CPU-seconds; at exit the slot is released and the cost recorded on the lease.
8
+ //
9
+ // The kill switch and the default-off flag are read by the server on every decision.
10
+ // A placement on a serving host (child-on-host) is BOT-3030 and is not built here: the CLI
11
+ // refuses one it cannot execute (CHILD_PLACEMENT_UNSUPPORTED), never running it elsewhere.
12
+
13
+ import { spawn, spawnSync } from "node:child_process";
14
+ import { cpus, freemem, loadavg, totalmem } from "node:os";
15
+
16
+ export const TEST_CHILD_CAPACITY = "TEST_CHILD_CAPACITY";
17
+ export const CHILD_PLACEMENT_UNSUPPORTED = "CHILD_PLACEMENT_UNSUPPORTED";
18
+ export const TEST_CHILD_UNAVAILABLE = "TEST_CHILD_UNAVAILABLE";
19
+ /** A full pool with no reported expiry parks at most one default slot TTL. */
20
+ export const FALLBACK_PARK_MS = 180_000;
21
+ export const SAMPLE_INTERVAL_MS = 5_000;
22
+ export const SAMPLE_METHOD = "ps_pgid_sample";
23
+
24
+ /** The three tool calls, over the run's retrying caller. */
25
+ export function testChildApi(rpc) {
26
+ return {
27
+ place: (leaseId) => rpc.call("place_test_child", { lease_id: leaseId }),
28
+ renew: (slotId) => rpc.call("renew_test_child_slot", { slot_id: slotId }),
29
+ release: (slotId, childResources) => rpc.call("release_test_child_slot", { slot_id: slotId, ...(childResources ? { child_resources: childResources } : {}) }),
30
+ };
31
+ }
32
+
33
+ /**
34
+ * Codex #1691 P1: a full pool parks on ONE platform wait that wakes when a slot in its pool is
35
+ * released (the `test_child_slot` spine signal, subject = run host) or when the pool's oldest
36
+ * slot expires (`timer:deadline=`, the only moment an unreleased slot can free) — never a
37
+ * fixed-interval retry.
38
+ */
39
+ export function testChildWaitArgv({ runHost, deadline, since = null }) {
40
+ // `bb wait` always prints one JSON receipt; it has no --json flag (Codex #1691 r2).
41
+ // Codex r3: `--since <signal_cursor>` replays a release that landed between the decision and
42
+ // the wait arming (the server reads the cursor under the pool lock that releases also take).
43
+ const argv = ["wait", `event:type=test_child_slot,subject=${runHost}`, `timer:deadline=${deadline}`];
44
+ if (Number.isSafeInteger(since) && since >= 0) argv.push("--since", String(since));
45
+ return argv;
46
+ }
47
+
48
+ export function defaultTestChildWait(target, { bin = process.execPath, cli = process.argv[1], run = spawn } = {}) {
49
+ return new Promise((resolve) => {
50
+ // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process -- fixed argv, no shell.
51
+ const child = run(bin, [cli, ...testChildWaitArgv(target)], { stdio: ["ignore", "ignore", "inherit"] });
52
+ // Codex #1691 r4: a run that loses its transport or is signalled stops this park at once.
53
+ const onAbort = () => { try { child.kill("SIGTERM"); } catch { /* already gone */ } };
54
+ if (target.signal?.aborted) onAbort();
55
+ else target.signal?.addEventListener?.("abort", onAbort, { once: true });
56
+ child.on("exit", (code) => { target.signal?.removeEventListener?.("abort", onAbort); resolve(code === 0 && !target.signal?.aborted); });
57
+ child.on("error", () => resolve(false));
58
+ });
59
+ }
60
+
61
+ /**
62
+ * Place the child and take its slot, waiting (holding nothing) while the pool is full.
63
+ * Returns `{ ok: true, slotId, ttlSeconds, placement, waits }` or
64
+ * `{ ok: false, code, error, placement?, waits }`. Never throws.
65
+ */
66
+ export async function acquireTestChildSlot({ api, leaseId, wait = defaultTestChildWait, log = () => {}, isStopped = () => false, maxWaits = Infinity, onPark = async () => {}, signal = null }) {
67
+ const waits = [];
68
+ for (;;) {
69
+ let answer;
70
+ try { answer = await api.place(leaseId); } catch (error) { answer = { ok: false, error: String(error?.message ?? error) }; }
71
+ const data = answer?.data;
72
+ if (answer?.ok && data?.success) {
73
+ const placement = data.child_placement ?? null;
74
+ if (placement?.host_kind !== "requester") {
75
+ return { ok: false, code: CHILD_PLACEMENT_UNSUPPORTED, placement, waits, slotId: data.slot_id,
76
+ error: `the control plane placed this child on ${placement?.host ?? "another host"} (${placement?.placement_reason ?? "unknown"}), but this CLI runs children only on the requester; child-on-host is BOT-3030` };
77
+ }
78
+ return { ok: true, slotId: data.slot_id, ttlSeconds: data.ttl_seconds ?? 180, expiresAt: data.expires_at ?? null, placement, waits };
79
+ }
80
+ if (data?.code === TEST_CHILD_CAPACITY) {
81
+ // The pool's next expiry bounds the park; a missing one falls back to one slot TTL from now.
82
+ const expiryMs = Date.parse(data.next_expiry_at ?? "");
83
+ const deadline = Number.isFinite(expiryMs) ? new Date(expiryMs).toISOString() : new Date(Date.now() + FALLBACK_PARK_MS).toISOString();
84
+ if (waits.length === 0) {
85
+ log(`stack: ${TEST_CHILD_CAPACITY}: all ${data.slots} test_child slot(s) on ${data.run_host} are held — waiting (no slot is held while waiting)`);
86
+ }
87
+ waits.push({ at: new Date().toISOString(), held: data.held ?? null, slots: data.slots ?? null, run_host: data.run_host ?? null });
88
+ if (waits.length > maxWaits || isStopped()) {
89
+ return { ok: false, code: TEST_CHILD_CAPACITY, waits, error: `all test_child slots on ${data.run_host} stayed held` };
90
+ }
91
+ // A wait that could not park (refused, unreachable, killed) ends the run: re-placing at
92
+ // once would turn a platform failure into a control-plane poll loop.
93
+ // Codex r3: the already-active lease stays alive while the run waits (its owner touches it).
94
+ try { await onPark(); } catch { /* the lease's own heartbeat decides; a failed touch is not a wait failure */ }
95
+ const since = Number.isSafeInteger(Number(data.signal_cursor)) ? Number(data.signal_cursor) : null;
96
+ let parked = false;
97
+ try { parked = await wait({ runHost: data.run_host, deadline, since, ...(signal ? { signal } : {}) }); } catch { parked = false; }
98
+ if (isStopped() || signal?.aborted) return { ok: false, code: TEST_CHILD_CAPACITY, waits, error: "stopped while waiting for a test_child slot" };
99
+ if (!parked) {
100
+ return { ok: false, code: TEST_CHILD_CAPACITY, waits,
101
+ error: `all test_child slots on ${data.run_host} are held and the wait for a free test_child slot failed; the child was not started` };
102
+ }
103
+ if (isStopped()) return { ok: false, code: TEST_CHILD_CAPACITY, waits, error: "stopped while waiting for a test_child slot" };
104
+ continue;
105
+ }
106
+ const code = data?.code ?? TEST_CHILD_UNAVAILABLE;
107
+ return { ok: false, code, waits, placement: data?.child_placement ?? null,
108
+ error: `the control plane did not place the test child, so it was not started (${data?.message ?? data?.error ?? answer?.error ?? "no answer"})` };
109
+ }
110
+ }
111
+
112
+ /** `ps` CPU time → seconds: Linux `[[dd-]hh:]mm:ss`, macOS `[hh:]mm:ss.ss`. */
113
+ export function parseCpuTime(raw) {
114
+ const s = String(raw ?? "").trim();
115
+ if (!s) return null;
116
+ let days = 0; let rest = s;
117
+ const dash = s.indexOf("-");
118
+ if (dash > 0) { days = Number(s.slice(0, dash)); rest = s.slice(dash + 1); }
119
+ const parts = rest.split(":").map(Number);
120
+ if (!parts.length || parts.some((n) => !Number.isFinite(n)) || !Number.isFinite(days)) return null;
121
+ let secs = 0;
122
+ for (const p of parts) secs = secs * 60 + p;
123
+ return days * 86_400 + secs;
124
+ }
125
+
126
+ /** Rows of `ps -A -o pid=,pgid=,rss=,time=,comm=` (rss in KiB). */
127
+ export function parsePsRows(text) {
128
+ const rows = [];
129
+ for (const line of String(text ?? "").split("\n")) {
130
+ const m = line.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/);
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] });
133
+ }
134
+ return rows;
135
+ }
136
+
137
+ export function readPs({ run = spawnSync } = {}) {
138
+ // 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 });
140
+ if (r.status !== 0 || typeof r.stdout !== "string") return null;
141
+ return parsePsRows(r.stdout);
142
+ }
143
+
144
+ /**
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.
148
+ */
149
+ export function startChildSampler(pgid, { ps = readPs, intervalMs = SAMPLE_INTERVAL_MS, setInterval: si = setInterval, clearInterval: ci = clearInterval, now = Date.now } = {}) {
150
+ const startedAt = now();
151
+ let peakRss = 0; let samples = 0; let failed = 0;
152
+ const cpuByPid = new Map();
153
+ const sample = () => {
154
+ let rows;
155
+ try { rows = ps(); } catch { rows = null; }
156
+ if (!rows) { failed++; return; }
157
+ const group = rows.filter((r) => r.pgid === pgid);
158
+ if (!group.length) return;
159
+ 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));
162
+ };
163
+ sample();
164
+ const timer = si(sample, intervalMs);
165
+ timer?.unref?.();
166
+ return {
167
+ stop() {
168
+ ci(timer);
169
+ const cpu = [...cpuByPid.values()].reduce((a, b) => a + b, 0);
170
+ return {
171
+ peak_rss_bytes: peakRss, cpu_seconds: Math.round(cpu * 100) / 100,
172
+ samples, failed_samples: failed, interval_ms: intervalMs,
173
+ wall_seconds: Math.round((now() - startedAt) / 100) / 10, method: SAMPLE_METHOD,
174
+ };
175
+ },
176
+ };
177
+ }
178
+
179
+ const CLASSES = [
180
+ ["claude_code", /claude/i], ["codex", /codex/i], ["chromium", /chrom|playwright/i],
181
+ ["docker", /docker|com\.docker|vpnkit|qemu|orbstack/i], ["node", /(^|\/)(node|deno|bun|pnpm|npm)$/i],
182
+ ];
183
+ export function classifyComm(comm) {
184
+ for (const [name, re] of CLASSES) if (re.test(comm)) return name;
185
+ return "other";
186
+ }
187
+
188
+ /** The minimal requester sample: load, free memory and resident GB by process class. */
189
+ export function requesterSample({ rows = readPs(), load = loadavg(), ncpu = cpus().length, free = freemem(), total = totalmem() } = {}) {
190
+ const gbByClass = {};
191
+ for (const r of rows ?? []) {
192
+ const c = classifyComm(r.comm);
193
+ gbByClass[c] = (gbByClass[c] ?? 0) + r.rssBytes;
194
+ }
195
+ for (const k of Object.keys(gbByClass)) gbByClass[k] = Math.round(gbByClass[k] / 1024 ** 3 * 10) / 10;
196
+ return {
197
+ load1: Math.round((load?.[0] ?? 0) * 100) / 100, ncpu,
198
+ mem_total_gb: Math.round(total / 1024 ** 3 * 10) / 10, mem_free_gb: Math.round(free / 1024 ** 3 * 10) / 10,
199
+ rss_gb_by_class: rows ? gbByClass : null,
200
+ };
201
+ }
202
+
203
+ /** Receipt fields for the run (snake_case, bounded). */
204
+ export function testChildReceiptFields(tc) {
205
+ if (!tc) return {};
206
+ return {
207
+ test_child: true,
208
+ ...(tc.placement ? { child_placement: tc.placement } : {}),
209
+ ...(tc.resources ? { child_resources: tc.resources } : {}),
210
+ ...(tc.requesterSample ? { requester_sample: tc.requesterSample } : {}),
211
+ ...(tc.waits?.length ? { test_child_waits: tc.waits.length, test_child_first_wait_at: tc.waits[0].at } : {}),
212
+ ...(tc.released != null ? { test_child_slot_released: tc.released } : {}),
213
+ };
214
+ }
package/src/wait-core.mjs CHANGED
@@ -136,6 +136,9 @@ export const SIGNAL_TYPES = Object.freeze([
136
136
  // agent's lower-case UUID), recipient-scoped to that agent. The bb-status
137
137
  // band's waits badge wakes on it; the band's own relay wait never emits it.
138
138
  "agent_wait",
139
+ // BOT-3240: a test_child slot in the caller's tenant was released (subject = the pool's
140
+ // run host). `bb stack run --test-child` parks on it while its pool is full.
141
+ "test_child_slot",
139
142
  ]);
140
143
 
141
144
  const LOCK_SUBTYPES = Object.freeze(["playwright_lane", "vite_port", "backend_port", "supabase_local"]);
@@ -415,6 +418,9 @@ const VALIDATORS = {
415
418
  const hasWorkflowFilter = p.workflow !== undefined;
416
419
  const hasWorkflowIdFilter = p.workflow_id !== undefined;
417
420
  const hasWorkflowPathFilter = p.workflow_path !== undefined;
421
+ if (p.attempt !== undefined && (p.run_id === undefined || !/^[1-9]\d*$/.test(String(p.attempt)) || !Number.isSafeInteger(Number(p.attempt)))) {
422
+ throw new Error("ci attempt= needs a positive integer and run_id=<id>");
423
+ }
418
424
  if (p.scope !== undefined) {
419
425
  if (p.scope === "latest") {
420
426
  if (hasBranchFilter || hasWorkflowFilter || hasWorkflowIdFilter || hasWorkflowPathFilter) {
@@ -457,7 +463,7 @@ const VALIDATORS = {
457
463
  }
458
464
  if (p.run_id !== undefined) {
459
465
  if (!String(p.run_id).trim()) throw new Error("ci run_id must be non-empty");
460
- return { repo, scope: "run_id", runId: String(p.run_id).trim(), pr: p.pr != null ? String(p.pr).trim() : null };
466
+ return { repo, scope: "run_id", runId: String(p.run_id).trim(), pr: p.pr != null ? String(p.pr).trim() : null, ...(p.attempt === undefined ? {} : { attempt: Number(p.attempt) }) };
461
467
  }
462
468
  if (!String(p.sha).trim()) throw new Error("ci sha must be non-empty");
463
469
  const workflow = p.workflow === undefined ? null : String(p.workflow).trim();
@@ -562,6 +568,10 @@ const VALIDATORS = {
562
568
  }
563
569
  return { type: p.type, subject: id };
564
570
  }
571
+ // BOT-3240: a test_child_slot wait names its pool's run host; without one it could never match.
572
+ if (p.type === "test_child_slot" && !subject) {
573
+ throw new Error("event:type=test_child_slot needs subject=<run host>");
574
+ }
565
575
  return { type: p.type, subject };
566
576
  },
567
577
  };
@@ -1547,7 +1557,14 @@ function conditionMatchesSignal(condition, signal, waitSessionId) {
1547
1557
  if (signal.signal_type !== "ci_run") return false;
1548
1558
  // Repo is pinned via the payload (subject may be run:<id> for uncorrelated runs).
1549
1559
  if (String(signal.payload?.repo ?? "").toLowerCase() !== params.repo.toLowerCase()) return false;
1550
- if (params.scope === "run_id") return String(signal.payload?.run_id) === params.runId;
1560
+ if (params.scope === "run_id") {
1561
+ if (String(signal.payload?.run_id) !== params.runId) return false;
1562
+ if (params.attempt == null) return true;
1563
+ const source = signal.payload?.source_kind;
1564
+ return (source === "workflow_run" || source === "webhook_workflow_run" || source === "typed_ci") &&
1565
+ String(signal.payload?.run_attempt ?? "") === String(params.attempt) &&
1566
+ (params.attempt > 1 || signal.payload?.run_attempt_known === true);
1567
+ }
1551
1568
  if (params.scope === "sha") {
1552
1569
  if (signal.payload?.head_sha !== params.sha) return false;
1553
1570
  if (params.workflow != null) {
package/src/wait.mjs CHANGED
@@ -141,7 +141,7 @@ CONDITIONS (TYPE:key=val,key=val — repeat for several; --any wakes on the fir
141
141
  commit_sha; thread comments do not, so they never match sha=);
142
142
  the usage-limit decline always passes sha=. Any other key is
143
143
  refused (exit 4).
144
- ci:repo=<owner/repo>,{scope=latest,pr=<n> | run_id=<id> | sha=<sha>[,workflow=<name>]
144
+ ci:repo=<owner/repo>,{scope=latest,pr=<n> | run_id=<id>[,attempt=<n>] | sha=<sha>[,workflow=<name>]
145
145
  | scope=next[,sha=<sha>][,branch=<name>][,workflow=<name>]
146
146
  [,workflow_id=<id>][,workflow_path=<path>]}
147
147
  a run's terminal conclusion (owner-scoped) — not a
@@ -149,6 +149,8 @@ CONDITIONS (TYPE:key=val,key=val — repeat for several; --any wakes on the fir
149
149
  GitHub Actions or an external check_suite provider.
150
150
  A repo with no CI feed is rejected (no_signal_source).
151
151
  scope=latest,pr=<n> follows the PR's current head.
152
+ run_id=<id>,attempt=<n> waits for that exact GitHub
153
+ Actions attempt, ignoring older or unknown attempts.
152
154
  scope=next is LIVE-ONLY: it wakes on the first terminal
153
155
  run delivered AFTER arm (post-merge / cron / scheduled),
154
156
  never replays a finished run, and needs no run_id/pr.