@botbuddy/cli 1.121.2 → 1.121.4

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.121.3
4
+
5
+ - BOT-3644: the bb-status band no longer fails on long titles. `bb status-band read` used to refuse the whole snapshot with `invalid_response` when a ticket title, a blocker title or the branch name was over 240 characters, which is common for user-story titles. It now shortens that text to 240 characters ending in "…"; the branch still matches tickets and PRs by its full name. Every bootstrap failure the band reports now names its own code (`bootstrap_refused` or the server's code, `not_authenticated`, `ticket_exclusivity_unverified`, `ticket_attribution_required`, `cache_cleanup_credential_missing`, `cached_session_close_failed`, `session_persist_failed`, `session_cleanup_unconfirmed`, `cached_session_unretired`) instead of `bootstrap_failed`. The band (1.11.0) never shows the catch-all "Status unavailable": every code `bb status-band read` emits has its own line, and a code it does not know is shown by name. After a transient failure (`source_unreachable`, `source_unavailable`, `invalid_response`, `status_unavailable`) it keeps the last good status on screen, marked STALE with the code, and reads again by itself after 30 s, doubling to at most 5 min. Identity and configuration failures still clear the band and are not retried.
6
+
3
7
  ## 1.121.2
4
8
 
5
9
  - BOT-3524: the fleet host daemon reports each stack's true memory high-water mark as `memory_peak_bytes`. It is the sum of the stack's containers' cgroup marks: cgroup v2 `memory.peak`, read from the cgroup that the container's own `/proc/<pid>/cgroup` names (its leaf must name the container ID), or cgroup v1 `max_usage` from the Engine stats. Summing per-container marks is an upper bound on the peak of the stack's total, which no cgroup records because compose containers share no parent cgroup. The mark counts page cache, like `memory.current`, so it is never below `memory_used_bytes`. Each container's highest mark is kept in the daemon's local state, so a restart, which gives the container a fresh cgroup, does not lower the stack's peak. When any running member's mark can't be read (Docker Desktop, a kernel older than 5.19), `memory_peak_status` is `unavailable` and no value is sent. Before, the peak was the larger of two 30 s polls and missed every spike between them.
@@ -11,7 +11,7 @@
11
11
  "name": "bb-status",
12
12
  "source": "./bb-status",
13
13
  "description": "BB session status above the prompt: tickets, PRs with review counts, epic, staging, context use and active waits, for BotBuddy and Supply Guard sessions",
14
- "version": "1.10.0"
14
+ "version": "1.11.0"
15
15
  },
16
16
  {
17
17
  "name": "bb-session",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bb-status",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
4
4
  "description": "BB session status above the prompt: tickets, PRs with review counts, epic, staging, context use and active waits, live only while the session is on screen.",
5
5
  "author": {
6
6
  "name": "BotBuddy"
@@ -19,6 +19,13 @@ let relayStream = null;
19
19
  let relayArmed = false;
20
20
  let keptLive = false;
21
21
  let relayFault = null;
22
+ // BOT-3644 AC-4/5: a transient read failure keeps the last good snapshot on
23
+ // screen (marked STALE with its code) and retries by itself with backoff.
24
+ const TRANSIENT = new Set(["source_unreachable", "source_unavailable", "invalid_response", "status_unavailable"]);
25
+ const READ_RETRY_FIRST_MS = 30000;
26
+ const READ_RETRY_MAX_MS = 300000;
27
+ let readFault = null;
28
+ let readBackoffMs = 0;
22
29
  let backoffMs = 0;
23
30
  const WAKE_READ_GAP_MS = 15000;
24
31
  // BOT-3152 AC-4: while no surface draws this session the relay is parked (no
@@ -76,6 +83,13 @@ const ERRORS = {
76
83
  "BB or Linear refused access. Check the existing connection.",
77
84
  source_unreachable: "BB or Linear could not be reached. Refresh to retry.",
78
85
  source_unavailable: "A status source is unavailable. Refresh to retry.",
86
+ // BOT-3644 AC-2: every code `bb status-band read` emits has its own line
87
+ // (cli/src/status-band-contract.test.mjs keeps the two in step).
88
+ source_rejected: "BB or Linear rejected the status request. Refresh to retry.",
89
+ invalid_response: "BB returned a status the band could not read (invalid_response). Refresh to retry.",
90
+ status_unavailable: "The bb CLI failed without naming a cause (status_unavailable). Refresh to retry.",
91
+ unsafe_link: "BB returned a link the band will not open (unsafe_link). Refresh to retry.",
92
+ invalid_arguments: "The band and the bb CLI disagree on arguments. Run `bb update`, then Refresh.",
79
93
  cli_missing: "Install the bb CLI (npm i -g @botbuddy/cli), then run bb setup.",
80
94
  cli_outdated: "Update the bb CLI (bb update) to use this band.",
81
95
  };
@@ -88,10 +102,8 @@ function errorText() {
88
102
  );
89
103
  if (errorCode === "session_bind_failed")
90
104
  return "BB could not connect this session (" + (bindReason || "bootstrap_failed") + "). Refresh to retry.";
91
- return (
92
- ERRORS[errorCode] ||
93
- "Status unavailable. Check BB and Linear connections, then refresh."
94
- );
105
+ // BOT-3644 AC-2: never a catch-all that names no cause.
106
+ return ERRORS[errorCode] || "BB status failed (" + errorCode + "). Refresh to retry.";
95
107
  }
96
108
  function safeLabel(value, max = 240) {
97
109
  return (
@@ -399,7 +411,10 @@ async function refresh($, { wake = false, keep = false } = {}) {
399
411
  // A Refresh of a live band stays "Live" until its read lands (review on #1598).
400
412
  keptLive = keep && relayArmed && !relayFault && !!snapshot;
401
413
  stopRelay();
402
- if (!keep) snapshot = null;
414
+ if (!keep) {
415
+ snapshot = null;
416
+ readFault = null;
417
+ }
403
418
  }
404
419
  errorCode = null;
405
420
  loading = true;
@@ -475,15 +490,28 @@ async function refresh($, { wake = false, keep = false } = {}) {
475
490
  snapshot = data;
476
491
  hintPrefix = TENANT_PREFIX[data.tenant] || null;
477
492
  relayFault = null;
493
+ readFault = null;
494
+ readBackoffMs = 0;
478
495
  if (!wake) startRelay($);
479
496
  }
480
497
  } catch (error) {
481
498
  if (request === generation) {
482
499
  if (wake) stopRelay();
483
- snapshot = null;
484
- errorCode = Object.hasOwn(ERRORS, error.message)
485
- ? error.message
500
+ // BOT-3644 AC-2: a snake_case code is kept even when the band has no line
501
+ // for it, so errorText() names it.
502
+ const message = String(error?.message ?? "");
503
+ errorCode = Object.hasOwn(ERRORS, message) || /^[a-z][a-z0-9_]{0,63}$/.test(message)
504
+ ? message
486
505
  : "status_unavailable";
506
+ // BOT-3644 AC-4: a transient failure keeps the last good status (STALE);
507
+ // any other failure clears it, so a wrong identity is never left drawn.
508
+ if (TRANSIENT.has(errorCode) && snapshot) readFault = errorCode;
509
+ else {
510
+ snapshot = null;
511
+ readFault = null;
512
+ }
513
+ if (TRANSIENT.has(errorCode)) retryRead($, request);
514
+ else readBackoffMs = 0;
487
515
  // BOT-3222: the hook is still registering this session; read once more
488
516
  // when the adapter says, unless another read has started since.
489
517
  if (errorCode === "session_starting") {
@@ -509,6 +537,22 @@ async function refresh($, { wake = false, keep = false } = {}) {
509
537
  }
510
538
  }
511
539
  }
540
+ // BOT-3644 AC-5: read again after a transient failure: 30 s, doubling, capped
541
+ // at 5 min. Any later read (a Refresh, a wake) bumps `generation` and cancels
542
+ // this one; a hidden session stays parked until a surface draws it again.
543
+ function retryRead($, request) {
544
+ readBackoffMs = Math.min(readBackoffMs ? readBackoffMs * 2 : READ_RETRY_FIRST_MS, READ_RETRY_MAX_MS);
545
+ const after = readBackoffMs;
546
+ void (async () => {
547
+ await delay($, after + 500);
548
+ if (request !== generation || mode !== "live" || !TRANSIENT.has(errorCode)) return;
549
+ if (parked || !(await onScreen($))) {
550
+ parked = true;
551
+ return;
552
+ }
553
+ await refresh($, { keep: true });
554
+ })();
555
+ }
512
556
  // ── BOT-3135 relay ─────────────────────────────────────────────────────
513
557
  // What the band waits on: each ticket, the agent's own waits (BOT-3212), each PR
514
558
  // still open or draft, and, when BotBuddy blockers are listed, each ticket's
@@ -711,10 +755,14 @@ async function followVisibility($) {
711
755
  }
712
756
  function stale() {
713
757
  if (mode !== "live" || !snapshot || parked) return false;
714
- if (relayFault) return true;
758
+ if (relayFault || readFault) return true;
715
759
  return !relayArmed && !keptLive && currentTime - Date.parse(snapshot.observed_at) > 60000;
716
760
  }
717
761
  function staleText() {
762
+ if (readFault) {
763
+ const why = ERRORS[readFault] || "BB status failed (" + readFault + "). Refresh to retry.";
764
+ return "STALE · " + (why.includes("(" + readFault + ")") ? why : why.replace(/\.( Refresh|$)/, " (" + readFault + ").$1"));
765
+ }
718
766
  if (relayFault === "session_expired")
719
767
  return "STALE · BB session expired. Run `bb doctor --fix` in this worktree, then Refresh.";
720
768
  if (relayFault) return "STALE · Live updates stopped. Refresh to check current status.";
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.121.2",
3
- "source_commit": "03f9850b12bb39e9329d674269475b709da44ea1",
4
- "source_sha256": "ef452cc3323570e0e88c2b0c3742a91c597339088447fb15beb0dd79d8eff50d",
2
+ "release_version": "1.121.4",
3
+ "source_commit": "6a9058be35b650acfa8a120186f6c6be5f1f3648",
4
+ "source_sha256": "f29cb4b7bb0e300a0c93e55b935ad5edb65b6669c545afde66483d40c3a883f2",
5
5
  "target": "darwin-arm64",
6
- "sha256": "f86932d45dcaf4414d78835a54f674a34b847820f8c38cf929efae7301a66ff3"
6
+ "sha256": "2c94361ae9fe7d5d4e71aa608ffa55f8ba9b9b5c249e5f8b9896258b25b11e3e"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.121.2",
3
- "source_commit": "03f9850b12bb39e9329d674269475b709da44ea1",
4
- "source_sha256": "ef452cc3323570e0e88c2b0c3742a91c597339088447fb15beb0dd79d8eff50d",
2
+ "release_version": "1.121.4",
3
+ "source_commit": "6a9058be35b650acfa8a120186f6c6be5f1f3648",
4
+ "source_sha256": "f29cb4b7bb0e300a0c93e55b935ad5edb65b6669c545afde66483d40c3a883f2",
5
5
  "target": "linux-x64",
6
- "sha256": "8cb8bea4342bd5508f1ab4d212df92bdb9f611a8cae56c56b67f709e55323ee4"
6
+ "sha256": "99005ff0fe3f71396c8a5f1b06f7dc853977af6dd6bcabb19601115320f166af"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.121.2",
4
- "source_commit": "03f9850b12bb39e9329d674269475b709da44ea1",
5
- "source_sha256": "ef452cc3323570e0e88c2b0c3742a91c597339088447fb15beb0dd79d8eff50d",
3
+ "release_version": "1.121.4",
4
+ "source_commit": "6a9058be35b650acfa8a120186f6c6be5f1f3648",
5
+ "source_sha256": "f29cb4b7bb0e300a0c93e55b935ad5edb65b6669c545afde66483d40c3a883f2",
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": "f86932d45dcaf4414d78835a54f674a34b847820f8c38cf929efae7301a66ff3",
11
+ "sha256": "2c94361ae9fe7d5d4e71aa608ffa55f8ba9b9b5c249e5f8b9896258b25b11e3e",
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": "8cb8bea4342bd5508f1ab4d212df92bdb9f611a8cae56c56b67f709e55323ee4",
18
+ "sha256": "99005ff0fe3f71396c8a5f1b06f7dc853977af6dd6bcabb19601115320f166af",
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.121.2",
3
+ "version": "1.121.4",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
@@ -26,6 +26,11 @@ export const HOST_CHILD_DEFAULT_MAX_RUNTIME_S = 3600;
26
26
  * dependency layer keeps a claim alive with "preparing" reports up to here).
27
27
  */
28
28
  export const HOST_CHILD_PREPARE_CAP_MS = 45 * 60_000;
29
+ /**
30
+ * BOT-3568: a detached host child's wait outlasts an outage of this machine (asleep, roaming)
31
+ * inside the platform wait (`bb wait --outage-budget`), up to the run's own give-up time.
32
+ */
33
+ export const HOST_CHILD_WAIT_OUTAGE_MAX_S = 86_400;
29
34
  const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
30
35
 
31
36
  /** The four requester tool calls, over the run's retrying caller. */
@@ -79,9 +84,12 @@ export function childEnvFrom(names, env = process.env) {
79
84
  /** How long a stop that the control plane has not yet accepted waits before asking again. */
80
85
  export const HOST_CHILD_CANCEL_RETRY_MS = 30_000;
81
86
 
82
- export function hostChildWaitArgv({ runId, deadline, since = null }) {
87
+ export function hostChildWaitArgv({ runId, deadline, since = null, outageBudgetSeconds = null }) {
83
88
  const argv = ["wait", `event:type=test_child_run,subject=${runId}`, `timer:deadline=${deadline}`];
84
89
  if (Number.isSafeInteger(since) && since >= 0) argv.push("--since", String(since));
90
+ if (Number.isSafeInteger(outageBudgetSeconds) && outageBudgetSeconds >= 1) {
91
+ argv.push("--outage-budget", String(Math.min(outageBudgetSeconds, HOST_CHILD_WAIT_OUTAGE_MAX_S)));
92
+ }
85
93
  return argv;
86
94
  }
87
95
 
@@ -111,7 +119,7 @@ export function hostRunExitCode(run) {
111
119
  export async function startHostChild({
112
120
  api, upload, slotId, argv, env = {}, worktreeRoot, maxRuntimeSeconds = HOST_CHILD_DEFAULT_MAX_RUNTIME_S,
113
121
  bundle: prebuilt = null, wait = defaultHostChildWait, log = () => {}, writeOutput = (s) => process.stdout.write(s), now = Date.now,
114
- signal = undefined, artifactGlobs = [], fetchArtifacts = fetch, testRunId = null, callbackPort = null,
122
+ signal = undefined, artifactGlobs = [], fetchArtifacts = fetch, testRunId = null, callbackPort = null, outlastOutages = false,
115
123
  }) {
116
124
  const bundle = prebuilt ?? buildHeadBundle(worktreeRoot);
117
125
  if (!bundle.ok) return { ok: false, code: "HOST_CHILD_BUNDLE_FAILED", error: bundle.error };
@@ -228,7 +236,10 @@ export async function startHostChild({
228
236
  waitAbort = new AbortController();
229
237
  const onAbort = () => waitAbort.abort("done");
230
238
  abort.signal.addEventListener("abort", onAbort, { once: true });
231
- const parked = await wait({ runId, deadline, since, signal: waitAbort.signal }).catch(() => false);
239
+ // BOT-3568: a detached host child's wait rides out this machine's outage itself, for as long
240
+ // as the run may still end; when even that wait gives up, the run is given up as before.
241
+ const outage = outlastOutages ? { outageBudgetSeconds: Math.max(1, Math.ceil((giveUpAt - now()) / 1000)) } : {};
242
+ const parked = await wait({ runId, deadline, since, signal: waitAbort.signal, ...outage }).catch(() => false);
232
243
  abort.signal.removeEventListener("abort", onAbort);
233
244
  const retry = waitAbort.signal.reason === "cancel_retry";
234
245
  waitAbort = null;
@@ -100,6 +100,26 @@ async function closeWithDurableCredential(call, args, options) {
100
100
  }
101
101
  }
102
102
 
103
+ // BOT-3644 AC-3: every bootstrap failure carries a snake_case `code`, so the
104
+ // bb-status band names its cause instead of the catch-all bootstrap_failed.
105
+ // The message stays free text for the CLI; only the code reaches the band.
106
+ const CODE = /^[a-z][a-z0-9_]{0,63}$/;
107
+ function coded(code, message) {
108
+ return Object.assign(new Error(message), { code });
109
+ }
110
+ // A rethrown error keeps its own snake_case code; any other gets `fallback`.
111
+ function tagCode(error, fallback) {
112
+ if (error && typeof error === "object" && !CODE.test(error.code ?? "")) {
113
+ try { error.code = fallback; } catch { /* frozen: bindFailed falls back */ }
114
+ }
115
+ }
116
+ function refusalCode(response) {
117
+ if (response?.auth) return "not_authenticated";
118
+ for (const c of [response?.code, response?.data?.code, response?.data?.error, response?.error])
119
+ if (typeof c === "string" && CODE.test(c)) return c;
120
+ return "bootstrap_refused";
121
+ }
122
+
103
123
  // BOT-1650 (Codex round-24/25): a session was admitted but could not be retired.
104
124
  // Persist a cleanup marker so a later bootstrap retires it, then ALWAYS throw a
105
125
  // failure that preserves the primary cause, the retirement failure, AND any
@@ -119,7 +139,10 @@ async function recordOrphanAndFail({ session, cwd, retirementError, primaryError
119
139
  if (primaryError) parts.push(primaryError.message);
120
140
  parts.push(`the admitted session could not be retired: ${retirementError.message}`);
121
141
  if (persistError) parts.push(`and its cleanup marker could not be persisted: ${persistError.message}`);
122
- const err = new Error(parts.join("; "));
142
+ const err = coded(
143
+ CODE.test(primaryError?.code ?? "") ? primaryError.code : "session_cleanup_unconfirmed",
144
+ parts.join("; "),
145
+ );
123
146
  err.cause = primaryError ?? retirementError;
124
147
  throw err;
125
148
  }
@@ -328,7 +351,7 @@ export async function bootstrapHarnessSession({
328
351
  store = saveHarnessSession,
329
352
  transaction = withHarnessBootstrapLock,
330
353
  } = {}) {
331
- if (!name || !harnessSessionId) throw new Error("bootstrap requires name and harnessSessionId");
354
+ if (!name || !harnessSessionId) throw coded("bootstrap_invalid_arguments", "bootstrap requires name and harnessSessionId");
332
355
  const worktree = await worktreeRoot(cwd);
333
356
  return transaction({ cwd: worktree }, async () => {
334
357
  // BOT-1650 (Codex round-24): before admitting a new session, retry retiring
@@ -377,7 +400,7 @@ export async function bootstrapHarnessSession({
377
400
  harness,
378
401
  }, callOptions);
379
402
  if (!response?.ok || response.isError) {
380
- throw new Error(response?.data?.message || response?.error || "bootstrap_agent_session failed");
403
+ throw coded(refusalCode(response), response?.data?.message || response?.error || "bootstrap_agent_session failed");
381
404
  }
382
405
  // Persist only the four session-secret fields. Ticket signals are intentionally
383
406
  // returned to the launcher, never copied into the runtime credential file.
@@ -386,8 +409,8 @@ export async function bootstrapHarnessSession({
386
409
  // new harness session after a previous session's shutdown was not observed.
387
410
  // The signal remains on the returned result so callers can show the holder;
388
411
  // resource locks, not ticket presence, continue to arbitrate shared state.
389
- if (ticketSignals?.policy) throw new Error(ticketSignals.concurrency?.warning || "Ticket-session exclusivity could not be verified.");
390
- if (linkage?.status === "gap") throw new Error(linkage.warning || "Session bootstrap requires ticket attribution.");
412
+ if (ticketSignals?.policy) throw coded("ticket_exclusivity_unverified", ticketSignals.concurrency?.warning || "Ticket-session exclusivity could not be verified.");
413
+ if (linkage?.status === "gap") throw coded("ticket_attribution_required", linkage.warning || "Session bootstrap requires ticket attribution.");
391
414
  // A new harness may be admitted only after an abandoned cache aged out of
392
415
  // the server's liveness window. Before replacing that file, ask the server
393
416
  // to retire the cached session *only if its authoritative holder-liveness
@@ -405,7 +428,7 @@ export async function bootstrapHarnessSession({
405
428
  // it with its own scoped token first, and if that cannot be confirmed record
406
429
  // an orphan marker for a later bootstrap to drain — then fail closed. Matches
407
430
  // the store()-failure path's no-durable-credential handling.
408
- const primaryError = new Error("a replacement harness cache requires a durable credential to confirm remote session cleanup");
431
+ const primaryError = coded("cache_cleanup_credential_missing", "a replacement harness cache requires a durable credential to confirm remote session cleanup");
409
432
  const direct = await closeWithDurableCredential(call, {
410
433
  session_id: session.session_id,
411
434
  ...(session.session_token_generation ? { session_token_generation: session.session_token_generation } : {}),
@@ -435,7 +458,7 @@ export async function bootstrapHarnessSession({
435
458
  if (direct.closed) return;
436
459
  const confirmed = await closeWithDurableCredential(call, closeArgs, cleanupOptions);
437
460
  if (confirmed.closed) return;
438
- throw new Error(cleanupError(confirmed.response) || direct.error?.message || "new harness session cleanup could not be confirmed");
461
+ throw coded("session_cleanup_unconfirmed", cleanupError(confirmed.response) || direct.error?.message || "new harness session cleanup could not be confirmed");
439
462
  };
440
463
  const cachedCloseArgs = {
441
464
  session_id: cached.session_id,
@@ -446,6 +469,8 @@ export async function bootstrapHarnessSession({
446
469
  try {
447
470
  retired = await call("close_session", cachedCloseArgs, cleanupOptions);
448
471
  } catch (error) {
472
+ // BOT-3644 AC-3: the band names this cause (it is rethrown below).
473
+ tagCode(error, "cached_session_close_failed");
449
474
  // BOT-1650 (Codex round-22): a THROWN cached-close (e.g. its idempotent
450
475
  // close committed but the response was lost) must not bypass cleanup and
451
476
  // strand the newly-admitted session — whose bearer is neither returned nor
@@ -501,7 +526,7 @@ export async function bootstrapHarnessSession({
501
526
  `session_still_active: BB session ${cached.session_id} is still live and holds this worktree's session cache, so it was left running. Use another worktree, or retry once that session has ended.`,
502
527
  ), { code: refusal });
503
528
  }
504
- throw new Error(refusal || "cached harness session is still live or could not be retired");
529
+ throw coded(CODE.test(refusal ?? "") ? refusal : "cached_session_unretired", refusal || "cached harness session is still live or could not be retired");
505
530
  }
506
531
  replacedCachedSession = { session_id: cached.session_id, retired: !leftToExpire };
507
532
  await clearHarnessSession(cached.session_id, {
@@ -514,6 +539,8 @@ export async function bootstrapHarnessSession({
514
539
  try {
515
540
  state = await store(session, { cwd: worktree, harnessSessionId });
516
541
  } catch (error) {
542
+ // BOT-3644 AC-3: the band names this cause (it is rethrown below).
543
+ tagCode(error, "session_persist_failed");
517
544
  // The server session is unusable if this harness cannot persist its only
518
545
  // credential. The freshly issued session bearer is scoped to this exact
519
546
  // session and can self-close, so try it first — the durable OAuth/MCP
package/src/stack.mjs CHANGED
@@ -4647,6 +4647,12 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
4647
4647
  let callbackCleanupError = null;
4648
4648
  let forwardAttestation = null;
4649
4649
  let tunnelLost = null;
4650
+ // BOT-3568: set as a host child starts; until then every run is treated as needing this machine.
4651
+ let requesterRouteNeeded = true;
4652
+ // BOT-3568: a loss on this machine's side that a detached host child rode out (for the receipt).
4653
+ let requesterLinkLost = null;
4654
+ // BOT-3568: a host run is being created or waited on before its handle is assigned here.
4655
+ let hostChildStarting = false;
4650
4656
  // BOT-2780: the requester origin closed under a live run (SSH loss or forward failure).
4651
4657
  let originLost = null;
4652
4658
  const placement = { mode: null, hostKey: null, requesterHost: null, transport: "none", forwards: null, bundle: null, placementReason: null, considered: null, admission: null,
@@ -4832,6 +4838,11 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
4832
4838
  return cleanupPromise;
4833
4839
  };
4834
4840
 
4841
+ // BOT-3568: a host child whose every route is on its host (no native callback to this machine,
4842
+ // no requester origin) does not need this machine while it runs: losing the forward, the
4843
+ // heartbeat or a slot renewal here never stops it. Its host keeps its slot and lease alive.
4844
+ const hostChildDetachable = () => !requesterRouteNeeded;
4845
+ const hostChildDetached = () => Boolean((child?.hostRun || hostChildStarting) && !childResult && hostChildDetachable());
4835
4846
  // Test seam: a fake child's pid is never a real process group.
4836
4847
  const signalGroup = adapters.signalChildGroup ?? childGroupSignal;
4837
4848
  const stopChild = (signal = "SIGTERM", forcedCode = null) => {
@@ -5799,6 +5810,12 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5799
5810
  const forwardTarget = sshTarget;
5800
5811
  tunnel.onExit((exit) => {
5801
5812
  if (childResult) return;
5813
+ if (hostChildDetached()) {
5814
+ // BOT-3568: a host child reaches its stack on its host; the forwards were never its route.
5815
+ requesterLinkLost ??= { kind: "forward", ...exit, target: forwardTarget };
5816
+ stderrLine(`stack: the SSH forward to ${forwardTarget ?? "the serving host"} ended (${exit.signal ? `signal ${exit.signal}` : `exit ${exit.code ?? "?"}`}); the host child keeps running on its host and this run waits for its result`);
5817
+ return;
5818
+ }
5802
5819
  // BOT-3109: when the loss was seen, even before a child exists (stopChild stamps only a running one).
5803
5820
  incidentBox.lossAtMs ??= Date.now();
5804
5821
  tunnelLost = { ...exit, target: forwardTarget };
@@ -5975,6 +5992,8 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5975
5992
  }, Math.max(1_000, Math.floor((current.data.idle_ttl_secs ?? opts.idleTtl ?? 1800) * 1000 / 3)));
5976
5993
  prepTouch?.unref?.();
5977
5994
  let started;
5995
+ requesterRouteNeeded = Boolean(useNativeCallback || execution.requesterOrigin);
5996
+ hostChildStarting = !hostEnv.error;
5978
5997
  activeWaitAbort = new AbortController();
5979
5998
  try {
5980
5999
  started = hostEnv.error ? { ok: false, code: "TEST_CHILD_ENV_REFUSED", error: hostEnv.error } : await startHostChild({
@@ -5983,6 +6002,9 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5983
6002
  maxRuntimeSeconds: opts.childMaxRuntime ?? HOST_CHILD_DEFAULT_MAX_RUNTIME_S,
5984
6003
  ...(adapters.hostChildBundle ? { bundle: adapters.hostChildBundle } : {}),
5985
6004
  ...(adapters.hostChildWait ? { wait: adapters.hostChildWait } : {}),
6005
+ // BOT-3568: a detached host child's wait outlasts this machine's outage in the platform
6006
+ // wait itself, instead of stopping a run that does not need this machine.
6007
+ ...(hostChildDetachable() ? { outlastOutages: true } : {}),
5986
6008
  log: stderrLine, ...(adapters.hostChildOutput ? { writeOutput: adapters.hostChildOutput } : {}),
5987
6009
  signal: activeWaitAbort.signal, artifactGlobs: opts.childArtifacts ?? [],
5988
6010
  testRunId: adapters.hostChildTestRunId !== undefined ? adapters.hostChildTestRunId : testRunIdFrom(),
@@ -5994,6 +6016,7 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5994
6016
  if (prepRenew) clock.clearInterval(prepRenew);
5995
6017
  if (prepTouch) clock.clearInterval(prepTouch);
5996
6018
  }
6019
+ hostChildStarting = false;
5997
6020
  if (started.ok && prepLost) {
5998
6021
  started.child.stop();
5999
6022
  started.child.detach();
@@ -6041,6 +6064,8 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
6041
6064
  } else if (r?.ok && r.data?.success === false) {
6042
6065
  fenceSlotLost(r.data.code ?? "TEST_CHILD_SLOT_LOST");
6043
6066
  } else if (testChild.confirmedUntilMs != null && renewNow() >= testChild.confirmedUntilMs) {
6067
+ // BOT-3568: a detached host child's host keeps its slot alive; only a definite answer ends it.
6068
+ if (hostChildDetached()) return;
6044
6069
  fenceSlotLost("TEST_CHILD_SLOT_LOST");
6045
6070
  }
6046
6071
  }, renewMs);
@@ -6112,6 +6137,13 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
6112
6137
  heartbeatRetry?.unref?.();
6113
6138
  return;
6114
6139
  }
6140
+ if (hostChildDetached()) {
6141
+ // BOT-3568: the host keeps a detached host child's lease alive while it runs; an
6142
+ // unanswered requester is not a reason to stop it. Keep touching on the cadence.
6143
+ if (!requesterLinkLost) stderrLine("stack: the control plane is not answering this machine; the host child keeps running on its host");
6144
+ requesterLinkLost ??= { kind: "heartbeat" };
6145
+ return;
6146
+ }
6115
6147
  heartbeatUnanswered = true;
6116
6148
  }
6117
6149
  fencing = true;
@@ -313,7 +313,9 @@ export async function readStatus({
313
313
  !/^bb_(?:agent|sess)_[0-9a-f]{64}$/.test(state.agent_session_token)
314
314
  )
315
315
  refuse("session_invalid");
316
- const branch = label(await branchReader(root));
316
+ // BOT-3644 AC-1: the branch drives matching whole (git allows long names);
317
+ // only the displayed copy is shortened, so a long name never fails the read.
318
+ const branch = label(await branchReader(root), 4096);
317
319
  const keyPattern = new RegExp(`^${prefix}-[1-9]\\d*$`);
318
320
  const branchTicket = branch.match(
319
321
  new RegExp(`(?:^|/)${prefix.toLowerCase()}-([1-9]\\d*)(?:-|$)`, "i"),
@@ -444,7 +446,7 @@ export async function readStatus({
444
446
  const agent = ownOk ? blockerAgentOf(own, blocker.identifier) : undefined;
445
447
  blockers.push({
446
448
  key: blocker.identifier,
447
- title: label(blocker.title),
449
+ title: safeText(blocker.title) || "Untitled",
448
450
  status: label(blocker.state.name),
449
451
  url: issueLink(blocker.url, blocker.identifier),
450
452
  ...(agent === undefined ? {} : { agent }),
@@ -452,7 +454,7 @@ export async function readStatus({
452
454
  }
453
455
  linearTicket = {
454
456
  key,
455
- title: label(issue.title),
457
+ title: safeText(issue.title) || "Untitled",
456
458
  status: label(issue.state?.name),
457
459
  url: issueLink(issue.url, key),
458
460
  };
@@ -649,7 +651,7 @@ export async function readStatus({
649
651
  harness_session_id: harnessSessionId.toLowerCase(),
650
652
  session_id: state.session_id,
651
653
  observed_at: new Date(now()).toISOString(),
652
- branch,
654
+ branch: safeText(branch),
653
655
  agent: {
654
656
  id: state.agent_id,
655
657
  name: label(identity.agent.display_name, 100),
package/src/wait-core.mjs CHANGED
@@ -925,6 +925,8 @@ export const CONDITION_PARSE_ERRORS = Object.freeze([
925
925
  "condition_conflict", "empty", "syntax",
926
926
  ]);
927
927
  const MAX_DESCRIBED_CONDITION_ERRORS = 16;
928
+ // BOT-3568: how many times one wait revives its reaper-abandoned registration.
929
+ const MAX_WAIT_REVIVALS = 20;
928
930
  const TYPE_TOKEN_RE = /^[a-z0-9_-]{1,32}$/;
929
931
 
930
932
  function editDistanceAtMost(a, b, limit) {
@@ -1934,6 +1936,13 @@ export async function runWaitLoop({
1934
1936
  // BB_WAIT_DEBUG; tests inject a collector to assert the line.
1935
1937
  debug = null,
1936
1938
  maxReconnects = 50,
1939
+ // BOT-3568: with a budget, consecutive failed connects end the wait once the outage has lasted
1940
+ // this long, whatever their count (a requester offline for minutes keeps its wait). Null: count only.
1941
+ outageBudgetMs = null,
1942
+ // BOT-3568 (Codex #2021): with an outage budget, an outage longer than the wait reaper's grace
1943
+ // abandons the registration. This re-registers the same logical wait (the server revives the
1944
+ // same session); true lets the loop reconnect from where it was.
1945
+ reviveAbandoned = null,
1937
1946
  receiptMaxBytes = 10240,
1938
1947
  now = Date.now,
1939
1948
  // BOT-1147 AC-3: a `linear` wait truthfully degrades when the Linear webhook
@@ -1993,6 +2002,14 @@ export async function runWaitLoop({
1993
2002
  // relay recycles its stream every few minutes is ended only by its match or its deadline.
1994
2003
  let reconnects = 0;
1995
2004
  let failures = 0;
2005
+ // BOT-3568: revivals of a reaper-abandoned registration (bounded; see reviveAbandoned).
2006
+ let revivals = 0;
2007
+ // BOT-3568: when the current run of consecutive failures began (null while connected).
2008
+ let outageStartedAt = null;
2009
+ // With a budget, the outage's elapsed time alone decides (Codex #2021); without one, the count.
2010
+ const outageExhausted = () => (outageBudgetMs == null
2011
+ ? failures > maxReconnects
2012
+ : now() - (outageStartedAt ?? now()) >= outageBudgetMs);
1996
2013
  const noteBackendUnreachable = () => { if (!degraded.includes("backend_unreachable")) degraded.push("backend_unreachable"); };
1997
2014
  const noteDegraded = (marker) => { if (!degraded.includes(marker)) degraded.push(marker); };
1998
2015
 
@@ -2338,8 +2355,9 @@ export async function runWaitLoop({
2338
2355
  stream = await connect(connectCursor);
2339
2356
  } catch (err) {
2340
2357
  failures += 1;
2358
+ outageStartedAt ??= now();
2341
2359
  noteBackendUnreachable();
2342
- if (failures > maxReconnects) {
2360
+ if (outageExhausted()) {
2343
2361
  return finalize("error", { exitCode: EXIT.BACKEND, error: `reconnect budget exhausted: ${String(err && err.message || err)}` });
2344
2362
  }
2345
2363
  const waitMs = backoff(failures);
@@ -2406,7 +2424,7 @@ export async function runWaitLoop({
2406
2424
  if (!frame) continue;
2407
2425
  // BOT-2351: the relay answered on this connection, so the backend is reachable —
2408
2426
  // the consecutive-failure budget starts over.
2409
- if (!deliveredFrame) { deliveredFrame = true; failures = 0; }
2427
+ if (!deliveredFrame) { deliveredFrame = true; failures = 0; outageStartedAt = null; }
2410
2428
 
2411
2429
  if (frame.event === "connected") {
2412
2430
  let connected = {};
@@ -2463,6 +2481,13 @@ export async function runWaitLoop({
2463
2481
  (parsed.wait_session_id == null || parsed.wait_session_id === waitSessionId)) {
2464
2482
  continue;
2465
2483
  }
2484
+ if (parsed.error === "wait_abandoned" && parsed.reason === "ended_by_server" && outageBudgetMs != null &&
2485
+ reviveAbandoned && revivals < MAX_WAIT_REVIVALS && await reviveAbandoned()) {
2486
+ revivals += 1;
2487
+ noteDegraded("wait_revived");
2488
+ streamEnded = true;
2489
+ break;
2490
+ }
2466
2491
  if (parsed.error === "wait_abandoned") {
2467
2492
  return finalize("abandoned", {
2468
2493
  exitCode: EXIT.ABANDONED,
@@ -2661,7 +2686,8 @@ export async function runWaitLoop({
2661
2686
  reconnects += 1;
2662
2687
  if (!deliveredFrame) {
2663
2688
  failures += 1;
2664
- if (failures > maxReconnects) {
2689
+ outageStartedAt ??= now();
2690
+ if (outageExhausted()) {
2665
2691
  // BOT-2407 AC-4: only consecutive failures spend the budget, so a give-up is always
2666
2692
  // an outage — name it. A connection that ended before any frame is
2667
2693
  // `stream_ended_empty`; `backend_unreachable` / `stream_dropped` are already noted.
package/src/wait.mjs CHANGED
@@ -13,7 +13,7 @@
13
13
  // Usage: botbuddy wait [--any] <condition>... [options]
14
14
  // Run botbuddy wait --help for the condition grammar.
15
15
 
16
- import { EXIT, describeConditionErrors, parseConditions, serverConditions, parseSseFrames, runWaitLoop, normalizeSince, truncateReceipt, formatPrReviewSnapshotWarnings, prStateArmMatches, formatCiLatestRunNotice, formatUnknownWorkflowGuidance, reviewTimeoutNotice } from "./wait-core.mjs";
16
+ import { EXIT, describeConditionErrors, nextBackoff, parseConditions, serverConditions, parseSseFrames, runWaitLoop, normalizeSince, truncateReceipt, formatPrReviewSnapshotWarnings, prStateArmMatches, formatCiLatestRunNotice, formatUnknownWorkflowGuidance, reviewTimeoutNotice } from "./wait-core.mjs";
17
17
  import { pushLocalTrigger } from "./push.mjs";
18
18
  import { readAgentBinding, withPrincipalReceipt } from "./wait-profile.mjs";
19
19
  import { VERSION } from "./version.mjs";
@@ -291,6 +291,9 @@ OPTIONS
291
291
  --allow-short-timeout <reason>
292
292
  accept a cap under 7200 s (a CI job budget, a probe); the reason is recorded
293
293
  on the wait. Automation may set $BOTBUDDY_WAIT_SHORT_TIMEOUT_REASON instead.
294
+ --outage-budget <s> keep reconnecting through an outage of up to <s> seconds (1..86400) before
295
+ giving up (exit 5): registration and the stream both retry with backoff.
296
+ For a wait whose machine may sleep or roam (a host child's requester).
294
297
  --since <seq> resume from a prior receipt's next_cursor (0..9007199254740991; replay what you missed)
295
298
  --receipt-max-bytes <n> cap the receipt (512..65536; default 10240; payloads truncate to pointers)
296
299
  --heartbeat keep this agent session alive while waiting (so it is not reaped)
@@ -496,6 +499,7 @@ function parseArgv(argv) {
496
499
  else if (a === "--deadline-at") opts.deadlineAt = optionValue(); // internal recovery argv; never shown as public API
497
500
  else if (a === "--since") { opts.sinceProvided = true; opts.since = optionValue(); }
498
501
  else if (a === "--receipt-max-bytes") opts.receiptMaxBytes = Number(optionValue());
502
+ else if (a === "--outage-budget") opts.outageBudget = Number(optionValue());
499
503
  else if (a === "--url") opts.url = optionValue();
500
504
  // BOT-1574: --token and --profile are RETIRED. A wait authenticates from
501
505
  // $BOTBUDDY_SESSION_TOKEN (minted by register_agent) alone; the per-machine
@@ -562,6 +566,16 @@ export function registerRefusalRecovery(errorCode, conditions) {
562
566
  return null;
563
567
  }
564
568
 
569
+ /**
570
+ * BOT-3568: a registration that never reached the relay (no HTTP answer: DNS, connection refused
571
+ * or reset, a dropped socket). Any HTTP answer, typed or not, is the relay speaking and is not one.
572
+ */
573
+ export function isRegisterTransportFailure(error) {
574
+ if (!error || error.status != null || error.contended || error.code === "wait_registration_contended") return false;
575
+ const cause = error.cause ?? {};
576
+ return error instanceof TypeError || /^(ECONN|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|EPIPE|UND_ERR)/.test(String(cause.code ?? error.code ?? ""));
577
+ }
578
+
565
579
  async function registerWait(opts, conditions, deadlineIso) {
566
580
  // BOT-1649: a relay wait authenticates from the per-session `bb_sess_` token
567
581
  // ($BOTBUDDY_AGENT_SESSION_TOKEN) — the relay derives agent, tenant, and session from it.
@@ -2121,6 +2135,12 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2121
2135
  await emitReceipt({ schema_version: 1, outcome: "error", error: "invalid_timeout" });
2122
2136
  process.exit(EXIT.INVALID);
2123
2137
  }
2138
+ if (opts.outageBudget !== undefined && (!Number.isSafeInteger(opts.outageBudget) || opts.outageBudget < 1 || opts.outageBudget > 86400)) {
2139
+ process.stderr.write("bb-wait: --outage-budget must be an integer from 1 through 86400 seconds\n");
2140
+ await emitReceipt({ schema_version: 1, outcome: "error", error: "invalid_outage_budget", minimum: 1, maximum: 86400 });
2141
+ process.exit(EXIT.INVALID);
2142
+ }
2143
+ opts.outageBudgetMs = opts.outageBudget === undefined ? null : opts.outageBudget * 1000;
2124
2144
  if (!Number.isSafeInteger(opts.receiptMaxBytes) || opts.receiptMaxBytes < MIN_RECEIPT_MAX_BYTES ||
2125
2145
  opts.receiptMaxBytes > MAX_RECEIPT_MAX_BYTES) {
2126
2146
  process.stderr.write(`bb-wait: --receipt-max-bytes must be an integer from ${MIN_RECEIPT_MAX_BYTES} through ${MAX_RECEIPT_MAX_BYTES}\n`);
@@ -2341,6 +2361,10 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2341
2361
  // BOT-3483: retries of a contended registration (same opts.localWaitId each time).
2342
2362
  const contentionBackoff = waitRegisterContentionBackoffMs();
2343
2363
  let contentionRetries = 0;
2364
+ // BOT-3568: with --outage-budget, a registration that cannot reach the relay is retried
2365
+ // with backoff on the same logical wait until the budget (or the wait's deadline) runs out.
2366
+ let outageStartedAt = null;
2367
+ let outageRetries = 0;
2344
2368
  let reg;
2345
2369
  for (;;) {
2346
2370
  try {
@@ -2359,6 +2383,16 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2359
2383
  error.attempts = contentionRetries + 1;
2360
2384
  throw error;
2361
2385
  }
2386
+ if (opts.outageBudgetMs != null && isRegisterTransportFailure(error)) {
2387
+ outageStartedAt ??= Date.now();
2388
+ outageRetries += 1;
2389
+ const delay = nextBackoff(outageRetries);
2390
+ if (Date.now() - outageStartedAt + delay < opts.outageBudgetMs && Date.now() + delay < deadlineMs) {
2391
+ if (outageRetries === 1) process.stderr.write(`bb-wait: the relay is unreachable (${String(error?.message ?? error)}); retrying for up to ${opts.outageBudgetMs / 1000} s\n`);
2392
+ await new Promise((resolve) => setTimeout(resolve, delay));
2393
+ continue;
2394
+ }
2395
+ }
2362
2396
  if (!shouldRenewCachedSession(error, opts.credentialSource, attempts)) throw error;
2363
2397
  attempts += 1;
2364
2398
  await clearAgentState(process.cwd());
@@ -2768,6 +2802,18 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2768
2802
  connect,
2769
2803
  feedLagProbe,
2770
2804
  receiptMaxBytes: opts.receiptMaxBytes,
2805
+ outageBudgetMs: opts.outageBudgetMs,
2806
+ // BOT-3568 (Codex #2021): the reaper abandoned this registration while the machine was away.
2807
+ // Re-register the same logical wait; the server revives the same session, and the loop
2808
+ // reconnects from where it was. Anything but that exact revival keeps today's exit 11.
2809
+ reviveAbandoned: async () => {
2810
+ try {
2811
+ const revived = await registerWait(opts, serverConditions(conditions), new Date(deadlineMs).toISOString());
2812
+ return revived?.status === "active" && revived.waitSessionId === waitSessionId;
2813
+ } catch {
2814
+ return false;
2815
+ }
2816
+ },
2771
2817
  startedAt: checkpoint.created_at,
2772
2818
  // BOT-1837: a timeout receipt carries the arm-time CI notice, so a caller
2773
2819
  // reading only the receipt learns the run it meant had already finished.