@botbuddy/cli 1.79.0 → 1.80.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.
@@ -37,6 +37,8 @@ let hintPrefix = null;
37
37
  // session's bootstrap to the bb-session hook in its first 30 s.
38
38
  let sessionStartedAt = null;
39
39
  let retryAfterMs = null;
40
+ // BOT-3281: the snake_case cause of a failed bootstrap (session_bind_failed).
41
+ let bindReason = null;
40
42
  // BOT-3212: the waits badge pulses once, for PULSE_MS, when the count changes.
41
43
  const PULSE_MS = 2000;
42
44
  let pulsing = false;
@@ -50,6 +52,7 @@ const ERRORS = {
50
52
  "This Claude session has no supported session identifier.",
51
53
  session_mismatch:
52
54
  "BB identity belongs to another session. Connect BB for this Claude session.",
55
+ session_bind_failed: "BB could not connect this session. Refresh to retry.",
53
56
  session_changed: "BB session changed during refresh. Refresh again.",
54
57
  session_invalid: "BB session is invalid. Reconnect BB in this worktree.",
55
58
  // BOT-3206: the band renews its own session; these name the exact command
@@ -83,6 +86,8 @@ function errorText() {
83
86
  "Use a ticket branch (" + hintPrefix.toLowerCase() + "-…) or /bb-status live " + hintPrefix +
84
87
  "-123, or register as coordinator: bb bootstrap --project-id P-" + hintPrefix + "-…."
85
88
  );
89
+ if (errorCode === "session_bind_failed")
90
+ return "BB could not connect this session (" + (bindReason || "bootstrap_failed") + "). Refresh to retry.";
86
91
  return (
87
92
  ERRORS[errorCode] ||
88
93
  "Status unavailable. Check BB and Linear connections, then refresh."
@@ -392,6 +397,7 @@ async function refresh($, { wake = false, keep = false } = {}) {
392
397
  }
393
398
  if (result.exitCode !== 0) {
394
399
  hintPrefix = data?.error === "ticket_missing" && /^[A-Z]{2,10}$/.test(data.prefix ?? "") ? data.prefix : null;
400
+ bindReason = data?.error === "session_bind_failed" && typeof data.reason === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(data.reason) ? data.reason : null;
395
401
  retryAfterMs = data?.error === "session_starting" && Number.isFinite(data.retry_after_ms) ? Math.min(Math.max(data.retry_after_ms, 1000), 30000) : null;
396
402
  throw new Error(
397
403
  typeof data.error === "string" ? data.error : "source_unavailable",
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.79.0",
3
- "source_commit": "926b867cc8a12c5cc7deca234e5b090757fab556",
4
- "source_sha256": "05a2c737d49e584ec7edaa3568d94e40c49408c94e2fa8631186b97839f4693e",
2
+ "release_version": "1.80.0",
3
+ "source_commit": "40ae6662590d709ca177465336070212099da96e",
4
+ "source_sha256": "fa319e00266beb29eacade57591904178ab264252d42f8204002d453a77040b1",
5
5
  "target": "darwin-arm64",
6
- "sha256": "9713ffc2cf3f7e281ebdef89a9b3e3297aac8c8276b00a27d9b802af3b05fbfb"
6
+ "sha256": "71f9fad2e1a3d47199bf30499fa44468eda18503d5d35cca4b5fc636490b481f"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.79.0",
3
- "source_commit": "926b867cc8a12c5cc7deca234e5b090757fab556",
4
- "source_sha256": "05a2c737d49e584ec7edaa3568d94e40c49408c94e2fa8631186b97839f4693e",
2
+ "release_version": "1.80.0",
3
+ "source_commit": "40ae6662590d709ca177465336070212099da96e",
4
+ "source_sha256": "fa319e00266beb29eacade57591904178ab264252d42f8204002d453a77040b1",
5
5
  "target": "linux-x64",
6
- "sha256": "51a3a649fd7f713592d020ceeb77155fd73ac83423fed5820d053d7d49902838"
6
+ "sha256": "9a6eae8b85b2dae57ae7b77143cb78cc642d32fa43b91322ac7401d7afadf39b"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.79.0",
4
- "source_commit": "926b867cc8a12c5cc7deca234e5b090757fab556",
5
- "source_sha256": "05a2c737d49e584ec7edaa3568d94e40c49408c94e2fa8631186b97839f4693e",
3
+ "release_version": "1.80.0",
4
+ "source_commit": "40ae6662590d709ca177465336070212099da96e",
5
+ "source_sha256": "fa319e00266beb29eacade57591904178ab264252d42f8204002d453a77040b1",
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": "9713ffc2cf3f7e281ebdef89a9b3e3297aac8c8276b00a27d9b802af3b05fbfb",
11
+ "sha256": "71f9fad2e1a3d47199bf30499fa44468eda18503d5d35cca4b5fc636490b481f",
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": "51a3a649fd7f713592d020ceeb77155fd73ac83423fed5820d053d7d49902838",
18
+ "sha256": "9a6eae8b85b2dae57ae7b77143cb78cc642d32fa43b91322ac7401d7afadf39b",
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.79.0",
3
+ "version": "1.80.0",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
package/src/commands.mjs CHANGED
@@ -38,7 +38,8 @@ import { GIT_TRANSPORT_PASSING, checkGitTransport, formatGitTransportLine } from
38
38
  import { formatPublishIp, isLoopbackIp, probeEnginePublishIp, publishIpFix } from "./docker-publish-ip.mjs";
39
39
  import { cmdHost, fixHelperWorkers, formatHelperWorkersLines, inspectHelperWorkers } from "./helper-host.mjs";
40
40
  import { clearAgentState, resolveAgentSessionCredential, selfHealAgentSession } from "./agent-session.mjs";
41
- import { readAgentState } from "./agent-state.mjs";
41
+ import { readAgentState, worktreeRoot } from "./agent-state.mjs";
42
+ import { bindable, claudeHolderActive, takeOverGoneHolder } from "./harness-holder.mjs";
42
43
  import { runUsage, usageStatus } from "./usage/sync.mjs";
43
44
  import { cmdTestIngest, doctorTestIngest, formatTestIngestLine } from "./test-ingest.mjs";
44
45
  import { installUsageAgent, usageAgentStatus } from "./usage/launchd.mjs";
@@ -1199,6 +1200,10 @@ export async function cmdBootstrap(args, {
1199
1200
  bootstrapHarnessSession: bootstrapSession = bootstrapHarnessSession,
1200
1201
  getConfig: getCfg = getConfig,
1201
1202
  env = process.env,
1203
+ cwd = process.cwd(),
1204
+ // BOT-3281: a Claude bootstrap takes over a gone holder's cache by the band's rule.
1205
+ holderActive = (holder, worktree) => claudeHolderActive(holder, worktree, { env }),
1206
+ now = () => Date.now(),
1202
1207
  log = (line) => console.log(line),
1203
1208
  die: fail = die,
1204
1209
  } = {}) {
@@ -1277,7 +1282,8 @@ export async function cmdBootstrap(args, {
1277
1282
  const nativeIdentityError = validateBootstrapNativeIdentity({ type, ticketId, codexThreadId, claudeDesktopSessionId });
1278
1283
  if (nativeIdentityError) fail(nativeIdentityError);
1279
1284
  if (!nameExplicit) name = `${name}-${harnessSessionId.slice(0, 8)}`;
1280
- const state = await bootstrapSession({
1285
+ const bootstrapInput = {
1286
+ cwd,
1281
1287
  name,
1282
1288
  type,
1283
1289
  harnessSessionId,
@@ -1294,7 +1300,8 @@ export async function cmdBootstrap(args, {
1294
1300
  model,
1295
1301
  effort,
1296
1302
  harness: `botbuddy-${type}-launcher`,
1297
- });
1303
+ };
1304
+ const state = await bootstrapClaimingGoneHolder({ type, harnessSessionId, cwd, bootstrapInput, bootstrapSession, withLock, holderActive, now });
1298
1305
  if (state.linkage?.status === "gap") fail(state.linkage.warning || "bb bootstrap requires ticket attribution or --no-ticket-reason.");
1299
1306
  // BOT-1945: name (never the bearer of) an unowned cached session this bootstrap
1300
1307
  // replaced, so a leftover live holder is visible instead of silent.
@@ -1304,6 +1311,34 @@ export async function cmdBootstrap(args, {
1304
1311
  log(JSON.stringify({ agent_id: state.agent_id, display_name: state.display_name, session_id: state.session_id, expires_at: state.expires_at, ...(projectId ? { project_id: projectId, role: "coordinator" } : {}), ...(state.ticket_signals?.concurrency ? { ticket_session_warning: state.ticket_signals.concurrency } : {}), ...(state.replaced_cached_session ? { replaced_cached_session: state.replaced_cached_session } : {}) }));
1305
1312
  }
1306
1313
 
1314
+ // BOT-3281: the bb-session start-up hook runs `bb bootstrap --type claude` in
1315
+ // worktrees later Claude sessions reuse. With an earlier session's cache in
1316
+ // place the bootstrap retires that BB session with close_session on the owner
1317
+ // bearer, which the server refuses (agent_identity_required), so a reused
1318
+ // worktree's new session was never bound. A holder the band would take over
1319
+ // (its Claude session gone, or expired with no transcript here) is set aside
1320
+ // first, under the same state lock the bootstrap then runs in; a failure puts
1321
+ // the holder's cache back. A live holder, or a non-Claude bootstrap, is left
1322
+ // to the bootstrap's own rules.
1323
+ const HARNESS_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1324
+ async function bootstrapClaimingGoneHolder({ type, harnessSessionId, cwd, bootstrapInput, bootstrapSession, withLock, holderActive, now }) {
1325
+ if (type !== "claude" || !HARNESS_UUID.test(harnessSessionId)) return bootstrapSession(bootstrapInput);
1326
+ const root = await worktreeRoot(cwd);
1327
+ const bind = await bindable(root, harnessSessionId, now, holderActive);
1328
+ if (!bind || typeof bind !== "object") return bootstrapSession(bootstrapInput);
1329
+ let state;
1330
+ const done = await takeOverGoneHolder({
1331
+ cwd: root,
1332
+ bind,
1333
+ withLock: (lockCwd, fn) => withLock({ cwd: lockCwd }, fn),
1334
+ run: async () => {
1335
+ state = await bootstrapSession({ ...bootstrapInput, transaction: (_options, operation) => operation(root) });
1336
+ },
1337
+ });
1338
+ // The cache changed while the holder was checked: bootstrap by the usual rules.
1339
+ return done ? state : bootstrapSession(bootstrapInput);
1340
+ }
1341
+
1307
1342
  /** BOT-2457: local preflight mirrors the server's ticket-link identity gate. */
1308
1343
  export function validateBootstrapNativeIdentity({ type, ticketId, codexThreadId, claudeDesktopSessionId }) {
1309
1344
  if (!ticketId) return null;
@@ -0,0 +1,108 @@
1
+ // BOT-3281: who holds a worktree's BB session cache, and when a new Claude
2
+ // session may take it over. Shared by the bb-status band (BOT-3152 AC-5,
3
+ // BOT-3252) and `bb bootstrap --type claude`, the bb-session start-up hook
4
+ // (BOT-3222), so both bind a reused worktree by the same rule.
5
+ //
6
+ // A holder is judged by its Claude session, not by the BB session's expiry: any
7
+ // `bb` command in the worktree (another session's `bb wait`, a hook) restores
8
+ // and renews the cached BB session, so a holder that ended long ago can stay
9
+ // "live" in BB indefinitely and lock every later session out (SG worktree
10
+ // amazing-euclid, 2026-11-14). A holder whose Claude transcript has been silent
11
+ // for HOLDER_IDLE_MS is gone; one with no transcript on this host keeps the
12
+ // BB-expiry rule.
13
+ import { readFile, readdir, realpath, rename, stat } from "node:fs/promises";
14
+ import { join } from "node:path";
15
+ import { homedir } from "node:os";
16
+
17
+ export const HOLDER_IDLE_MS = 30 * 60 * 1000;
18
+ const UUID_ONLY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
19
+ // true: the holder's transcript was written within HOLDER_IDLE_MS; false: it
20
+ // exists and has been silent longer; null: no transcript found (unknown).
21
+ export async function claudeHolderActive(holder, worktree, { env = process.env, now = () => Date.now() } = {}) {
22
+ const id = String(holder || "").toLowerCase();
23
+ if (!UUID_ONLY.test(id)) return null;
24
+ const projects = join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "projects");
25
+ const mtime = async (dir) => {
26
+ try {
27
+ return (await stat(join(projects, dir, `${id}.jsonl`))).mtimeMs;
28
+ } catch {
29
+ return null;
30
+ }
31
+ };
32
+ // Claude Code names a project's directory after its path, every
33
+ // non-alphanumeric character replaced by "-".
34
+ let at = await mtime(String(worktree).replace(/[^a-zA-Z0-9]/g, "-"));
35
+ if (at == null) {
36
+ let dirs = [];
37
+ try {
38
+ dirs = await readdir(projects);
39
+ } catch {
40
+ return null;
41
+ }
42
+ for (const dir of dirs) {
43
+ const found = await mtime(dir);
44
+ if (found != null && (at == null || found > at)) at = found;
45
+ }
46
+ }
47
+ if (at == null) return null;
48
+ return now() - at < HOLDER_IDLE_MS;
49
+ }
50
+ // Returns false (never bind), true (bootstrap as is), or { aside } — another
51
+ // holder's cache to move out of the way first. The bootstrap would otherwise
52
+ // try to retire that BB session and discard the new one when it cannot: the
53
+ // server refuses the retirement for a live session (which would end the waits
54
+ // other sessions still run on its token), and refuses it for an EXPIRED one too
55
+ // whenever the durable credential is an owner bearer, since close_session needs
56
+ // an agent identity (BOT-3252: the band then stayed on "belongs to another
57
+ // session" forever in a reused worktree). Set aside, a live session expires on
58
+ // its own once nothing renews it; the file is kept for recovery.
59
+ export async function bindable(cwd, harnessSessionId, now, holderActive) {
60
+ let state;
61
+ let root;
62
+ try {
63
+ root = await realpath(cwd);
64
+ state = JSON.parse(await readFile(join(root, ".botbuddy/agent-state.json"), "utf8"));
65
+ } catch (error) {
66
+ return error?.code === "ENOENT";
67
+ }
68
+ const holder = typeof state?.harness_session_id === "string" ? state.harness_session_id.toLowerCase() : "";
69
+ if (!holder || holder === harnessSessionId.toLowerCase()) return true;
70
+ const expired = !(Date.parse(state.expires_at) > now());
71
+ const active = await holderActive(holder, root).catch(() => null);
72
+ if (active === true) return false;
73
+ if ((active === false || expired) && UUID_ONLY.test(holder)) {
74
+ return {
75
+ cache: join(root, ".botbuddy/agent-state.json"),
76
+ aside: join(root, `.botbuddy/agent-state.superseded-${holder.slice(0, 8)}.json`),
77
+ root,
78
+ holder,
79
+ sessionId: state.session_id ?? null,
80
+ };
81
+ }
82
+ return expired;
83
+ }
84
+ // Codex P2 on #1646: the takeover runs under the same state lock the bootstrap
85
+ // and self-heal take, so a cache published while the holder was being checked
86
+ // is never the one moved aside. Inside the lock the cache must still be the
87
+ // holder and session that were checked; the bootstrap then runs without
88
+ // re-taking the (non-reentrant) lock, and a failure restores the holder's cache.
89
+ export async function takeOverGoneHolder({ cwd, bind, withLock, run }) {
90
+ return withLock(cwd, async () => {
91
+ let now;
92
+ try {
93
+ now = JSON.parse(await readFile(bind.cache, "utf8"));
94
+ } catch {
95
+ return false;
96
+ }
97
+ if (String(now?.harness_session_id ?? "").toLowerCase() !== bind.holder || (now?.session_id ?? null) !== bind.sessionId) return false;
98
+ await rename(bind.cache, bind.aside);
99
+ try {
100
+ await run();
101
+ } catch (error) {
102
+ const written = await stat(bind.cache).then(() => true, () => false);
103
+ if (!written) await rename(bind.aside, bind.cache).catch(() => {});
104
+ throw error;
105
+ }
106
+ return true;
107
+ });
108
+ }
@@ -8,6 +8,8 @@ import { CALL_EXIT, callToolJson, resolveCallAuth } from "./api.mjs";
8
8
  import { cmdReleaseNotesKeys, cmdReleaseNotesOrigins, RELEASE_NOTES_KEYS_USAGE } from "./release-notes-keys.mjs";
9
9
 
10
10
  export const RELEASE_NOTES_USAGE = `Usage: bb release-notes submit <note.json> [--json]
11
+ bb release-notes list [--tag <group>=<value>]... [--type <type>] [--state <state>] [--cursor <cursor>] [--json]
12
+ bb release-notes get <source_key> [--json]
11
13
  bb release-notes grants list [--tenant <slug>] [--json]
12
14
  bb release-notes grants add <email> <submit|manage> [--tenant <slug>] [--json]
13
15
  bb release-notes grants remove <email> <submit|manage> [--tenant <slug>] [--json]
@@ -39,6 +41,15 @@ An unchanged resubmit (a retry) adds none. A refusal names its code
39
41
  (schema_invalid, type_unknown, markup_refused, link_refused,
40
42
  entitlement_missing) and stores nothing.
41
43
 
44
+ Reading. list shows your tenant's notes, newest change first, 50 a page:
45
+ source key, type, state, revision count, internal title and tags. Filters
46
+ combine with AND; repeating --tag for one group matches any of its values;
47
+ --state withdrawn is the only way to list withdrawn notes. When there is more,
48
+ list prints the --cursor for the next page. get prints one note by its exact
49
+ source key: both voices, links and tags; read it before you resubmit, because
50
+ submit replaces the text. --json returns each body as { format, source, ast }.
51
+ Refusals: not_found, tag_group_unknown, tag_value_unknown, type_unknown.
52
+
42
53
  Scopes. Every member and agent key of the tenant reads. Agent keys submit
43
54
  unless their scope list is read-only. Tenant owners manage (and submit)
44
55
  implicitly; a member submits or manages only when an owner grants it:
@@ -59,7 +70,7 @@ own sign-in. A value is retired, never deleted: notes that carry it keep it.
59
70
  --internal-only marks a group that is never shown externally (one-way).
60
71
  view --show shows the tag and its filter, --tag-only the tag, --hide neither.
61
72
 
62
- Exit codes: 0 stored · 1 refused · 2 usage · 3 authentication · 5 BotBuddy unreachable.
73
+ Exit codes: 0 stored or read · 1 refused or not found · 2 usage · 3 authentication · 5 BotBuddy unreachable.
63
74
 
64
75
  Viewer keys and origins (tenant owners, BOT-3158):
65
76
  ${RELEASE_NOTES_KEYS_USAGE.split("\n").slice(1, 5).join("\n")}`;
@@ -79,6 +90,9 @@ export async function cmdReleaseNotes(args, {
79
90
  }
80
91
  if (args[0] === "grants") return cmdGrants(args.slice(1), { resolveAuth, call, log, errorLog });
81
92
  if (args[0] === "tags") return cmdTags(args.slice(1), { resolveAuth, call, log, errorLog });
93
+ // BOT-3166: list and read the tenant's notes.
94
+ if (args[0] === "list") return cmdList(args.slice(1), { resolveAuth, call, log, errorLog });
95
+ if (args[0] === "get") return cmdGet(args.slice(1), { resolveAuth, call, log, errorLog });
82
96
  // BOT-3158: viewer keys and allowed origins.
83
97
  if (args[0] === "keys") return await cmdReleaseNotesKeys(args.slice(1), { resolveAuth, call, log, errorLog });
84
98
  if (args[0] === "origins") return await cmdReleaseNotesOrigins(args.slice(1), { resolveAuth, call, log, errorLog });
@@ -147,7 +161,7 @@ function printRefusalOrFailure(result, json, log, errorLog, nothing) {
147
161
  if (result?.ok && data?.ok === false && typeof data.error === "string") {
148
162
  const refusal = { ok: false, error: data.error, ...(data.field ? { field: data.field } : {}), message: data.message ?? null };
149
163
  if (json) log(JSON.stringify(refusal));
150
- errorLog(`✗ ${refusal.error}${refusal.field ? ` (${refusal.field})` : ""}: ${refusal.message ?? nothing}`);
164
+ errorLog(termClean(`✗ ${refusal.error}${refusal.field ? ` (${refusal.field})` : ""}: ${refusal.message ?? nothing}`));
151
165
  return CALL_EXIT.ERROR;
152
166
  }
153
167
  if (result?.auth) {
@@ -358,3 +372,123 @@ async function cmdTags(argv, { resolveAuth, call, log, errorLog }) {
358
372
  }
359
373
  return CALL_EXIT.OK;
360
374
  }
375
+
376
+ // ── BOT-3166: bb release-notes list | get ──────────────────────────────
377
+
378
+ function readUsage(errorLog) {
379
+ errorLog(RELEASE_NOTES_USAGE);
380
+ return 2;
381
+ }
382
+
383
+ /** list arguments → tool arguments, or null for a usage error. */
384
+ export function parseListArgs(argv) {
385
+ const out = {};
386
+ let json = false;
387
+ for (let i = 0; i < argv.length; i += 1) {
388
+ const a = argv[i];
389
+ if (a === "--json") { json = true; continue; }
390
+ if (!["--tag", "--type", "--state", "--cursor"].includes(a)) return null;
391
+ const v = argv[i + 1];
392
+ if (v === undefined || v === "" || v.startsWith("--")) return null;
393
+ i += 1;
394
+ if (a === "--tag") {
395
+ const at = v.indexOf("=");
396
+ const group = at > 0 ? v.slice(0, at).trim() : "";
397
+ const value = at > 0 ? v.slice(at + 1).trim() : "";
398
+ if (!group || !value) return null;
399
+ out.tags ??= {};
400
+ // Own properties only: a group named constructor is an ordinary key.
401
+ if (!Object.prototype.hasOwnProperty.call(out.tags, group)) out.tags[group] = [];
402
+ out.tags[group].push(value);
403
+ } else {
404
+ const key = a.slice(2);
405
+ if (out[key] !== undefined) return null;
406
+ out[key] = v;
407
+ }
408
+ }
409
+ return { args: out, json };
410
+ }
411
+
412
+ async function callRead(tool, args, { resolveAuth, call }) {
413
+ try {
414
+ const resolved = await resolveAuth({ toolName: tool, preferSession: true });
415
+ return resolved?.error || !resolved?.auth
416
+ ? { ok: false, auth: true }
417
+ : await call(tool, args, { auth: resolved.auth, signal: AbortSignal.timeout(30_000) });
418
+ } catch {
419
+ return { ok: false, status: null };
420
+ }
421
+ }
422
+
423
+ const tagLine = (tags) => (Array.isArray(tags) && tags.length ? tags.map((t) => `${t.label}: ${t.value}`).join(" · ") : "");
424
+ const revisionsWord = (n) => `${n} revision${n === 1 ? "" : "s"}`;
425
+
426
+ // Codex P1 on #1724: note text, titles, keys, tags and links come from other
427
+ // agents. Text output prints control characters (C0 except newline, DEL, C1)
428
+ // and bidi overrides as visible escapes, so a note cannot clear or rewrite the
429
+ // reader's terminal; --json prints the stored values unchanged.
430
+ const CONTROL = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u200e\u200f\u202a-\u202e\u2066-\u2069]/g;
431
+ export function termClean(value) {
432
+ return String(value).replace(CONTROL, (c) => {
433
+ const n = c.charCodeAt(0);
434
+ return n <= 0xff ? `\\x${n.toString(16).padStart(2, "0")}` : `\\u${n.toString(16).padStart(4, "0")}`;
435
+ });
436
+ }
437
+
438
+ async function cmdList(argv, deps) {
439
+ const { errorLog } = deps;
440
+ const log = (line) => deps.log(termClean(line));
441
+ const parsed = parseListArgs(argv);
442
+ if (!parsed) return readUsage(errorLog);
443
+ const result = await callRead("list_release_notes", parsed.args, deps);
444
+ const data = result?.data;
445
+ if (!(result?.ok && data?.ok === true && Array.isArray(data.items))) return printRefusalOrFailure(result, parsed.json, deps.log, errorLog, "");
446
+ if (parsed.json) {
447
+ deps.log(JSON.stringify(data));
448
+ return CALL_EXIT.OK;
449
+ }
450
+ if (data.items.length === 0) {
451
+ log(parsed.args.cursor || Object.keys(parsed.args).length === 0 ? "No release notes yet." : "No release notes match these filters.");
452
+ return CALL_EXIT.OK;
453
+ }
454
+ for (const n of data.items) {
455
+ log(`${n.source_key} · ${n.type} · ${n.state} · ${revisionsWord(n.revisions)} · ${n.title}`);
456
+ const tags = tagLine(n.tags);
457
+ if (tags) log(` ${tags}`);
458
+ }
459
+ if (data.next_cursor) log(`More: bb release-notes list --cursor ${data.next_cursor}${argv.length ? " (repeat your filters)" : ""}`);
460
+ return CALL_EXIT.OK;
461
+ }
462
+
463
+ async function cmdGet(argv, deps) {
464
+ const { log, errorLog } = deps;
465
+ const json = argv.includes("--json");
466
+ const rest = argv.filter((a) => a !== "--json");
467
+ if (rest.length !== 1 || rest[0] === "") return readUsage(errorLog);
468
+ const args = { source_key: rest[0], ...(json ? {} : { render: "text" }) };
469
+ const result = await callRead("get_release_note", args, deps);
470
+ const data = result?.data;
471
+ const n = data?.note;
472
+ if (!(result?.ok && data?.ok === true && n && typeof n === "object")) return printRefusalOrFailure(result, json, log, errorLog, "");
473
+ if (json) {
474
+ const { text: _text, ...rest2 } = data;
475
+ log(JSON.stringify(rest2));
476
+ return CALL_EXIT.OK;
477
+ }
478
+ const text = data.text ?? {};
479
+ const links = (list) => (Array.isArray(list) ? list.map((l) => ` - ${l.name} · ${l.url}`) : []);
480
+ const lines = [`${n.source_key} · ${n.type} · ${n.state} · ${revisionsWord(n.revisions)}`];
481
+ const tags = tagLine(n.tags);
482
+ if (tags) lines.push(`Tags: ${tags}`);
483
+ lines.push("", `Internal: ${n.internal?.title ?? ""}`, text.internal ?? "");
484
+ if (Array.isArray(n.internal_links) && n.internal_links.length) lines.push("", "Internal links:", ...links(n.internal_links));
485
+ lines.push("");
486
+ if (n.external) {
487
+ lines.push(`External: ${n.external.title}`, text.external ?? "");
488
+ if (Array.isArray(n.external_links) && n.external_links.length) lines.push("", "External links:", ...links(n.external_links));
489
+ } else {
490
+ lines.push("External: none");
491
+ }
492
+ log(termClean(lines.join("\n")));
493
+ return CALL_EXIT.OK;
494
+ }
@@ -1,11 +1,13 @@
1
1
  // BOT-2644 / BOT-3152. Read-only host adapter (`bb status-band read`), run from the
2
2
  // installed CLI. Credentials stay in this process, never in the mod.
3
- import { open, readFile, readdir, realpath, rename, stat } from "node:fs/promises";
3
+ import { open, readFile, realpath, stat } from "node:fs/promises";
4
4
  import { execFile } from "node:child_process";
5
5
  import { promisify } from "node:util";
6
6
  import { join } from "node:path";
7
- import { homedir } from "node:os";
8
7
  import { findAgentStateRoot } from "./agent-state.mjs";
8
+ import { bindable, claudeHolderActive, takeOverGoneHolder } from "./harness-holder.mjs";
9
+
10
+ export { claudeHolderActive };
9
11
  // BOT-3259: BB's one project figure (v_project_progress): Must + unsure members
10
12
  // only, complete / remaining / unsure, with BB's percent. Null unless all four
11
13
  // are sane, so an older MCP keeps the legacy done/total.
@@ -605,110 +607,13 @@ export async function readStatus({
605
607
  // `bb bootstrap` runs. A cache another harness session holds is never
606
608
  // bootstrapped over: that session owns the worktree's identity.
607
609
  //
608
- // A holder is judged by its Claude session, not by the BB session's expiry: any
609
- // `bb` command in the worktree (another session's `bb wait`, a hook) restores
610
- // and renews the cached BB session, so a holder that ended long ago can stay
611
- // "live" in BB indefinitely and lock every later session out (SG worktree
612
- // amazing-euclid, 2026-11-14). A holder whose Claude transcript has been silent
613
- // for HOLDER_IDLE_MS is gone; one with no transcript on this host keeps the
614
- // BB-expiry rule.
610
+ // Who holds the cache, and when it may be taken over, is harness-holder.mjs
611
+ // (shared with `bb bootstrap --type claude`, BOT-3281).
615
612
  const BINDABLE = new Set(["session_missing", "session_mismatch", "session_expired"]);
616
613
  // BOT-3222: the bb-session hook's bootstrap is bounded at 20 s (hooks.json
617
614
  // timeout 30 s); the band waits this long after its session starts before it
618
615
  // bootstraps a session itself.
619
616
  export const START_GRACE_MS = 30_000;
620
- const HOLDER_IDLE_MS = 30 * 60 * 1000;
621
- const UUID_ONLY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
622
- // true: the holder's transcript was written within HOLDER_IDLE_MS; false: it
623
- // exists and has been silent longer; null: no transcript found (unknown).
624
- export async function claudeHolderActive(holder, worktree, { env = process.env, now = () => Date.now() } = {}) {
625
- const id = String(holder || "").toLowerCase();
626
- if (!UUID_ONLY.test(id)) return null;
627
- const projects = join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "projects");
628
- const mtime = async (dir) => {
629
- try {
630
- return (await stat(join(projects, dir, `${id}.jsonl`))).mtimeMs;
631
- } catch {
632
- return null;
633
- }
634
- };
635
- // Claude Code names a project's directory after its path, every
636
- // non-alphanumeric character replaced by "-".
637
- let at = await mtime(String(worktree).replace(/[^a-zA-Z0-9]/g, "-"));
638
- if (at == null) {
639
- let dirs = [];
640
- try {
641
- dirs = await readdir(projects);
642
- } catch {
643
- return null;
644
- }
645
- for (const dir of dirs) {
646
- const found = await mtime(dir);
647
- if (found != null && (at == null || found > at)) at = found;
648
- }
649
- }
650
- if (at == null) return null;
651
- return now() - at < HOLDER_IDLE_MS;
652
- }
653
- // Returns false (never bind), true (bootstrap as is), or { aside } — another
654
- // holder's cache to move out of the way first. The bootstrap would otherwise
655
- // try to retire that BB session and discard the new one when it cannot: the
656
- // server refuses the retirement for a live session (which would end the waits
657
- // other sessions still run on its token), and refuses it for an EXPIRED one too
658
- // whenever the durable credential is an owner bearer, since close_session needs
659
- // an agent identity (BOT-3252: the band then stayed on "belongs to another
660
- // session" forever in a reused worktree). Set aside, a live session expires on
661
- // its own once nothing renews it; the file is kept for recovery.
662
- async function bindable(cwd, harnessSessionId, now, holderActive) {
663
- let state;
664
- let root;
665
- try {
666
- root = await realpath(cwd);
667
- state = JSON.parse(await readFile(join(root, ".botbuddy/agent-state.json"), "utf8"));
668
- } catch (error) {
669
- return error?.code === "ENOENT";
670
- }
671
- const holder = typeof state?.harness_session_id === "string" ? state.harness_session_id.toLowerCase() : "";
672
- if (!holder || holder === harnessSessionId.toLowerCase()) return true;
673
- const expired = !(Date.parse(state.expires_at) > now());
674
- const active = await holderActive(holder, root).catch(() => null);
675
- if (active === true) return false;
676
- if ((active === false || expired) && UUID_ONLY.test(holder)) {
677
- return {
678
- cache: join(root, ".botbuddy/agent-state.json"),
679
- aside: join(root, `.botbuddy/agent-state.superseded-${holder.slice(0, 8)}.json`),
680
- root,
681
- holder,
682
- sessionId: state.session_id ?? null,
683
- };
684
- }
685
- return expired;
686
- }
687
- // Codex P2 on #1646: the takeover runs under the same state lock the bootstrap
688
- // and self-heal take, so a cache published while the holder was being checked
689
- // is never the one moved aside. Inside the lock the cache must still be the
690
- // holder and session that were checked; the bootstrap then runs without
691
- // re-taking the (non-reentrant) lock, and a failure restores the holder's cache.
692
- async function takeOverGoneHolder({ cwd, bind, withLock, run }) {
693
- return withLock(cwd, async () => {
694
- let now;
695
- try {
696
- now = JSON.parse(await readFile(bind.cache, "utf8"));
697
- } catch {
698
- return false;
699
- }
700
- if (String(now?.harness_session_id ?? "").toLowerCase() !== bind.holder || (now?.session_id ?? null) !== bind.sessionId) return false;
701
- await rename(bind.cache, bind.aside);
702
- try {
703
- await run();
704
- } catch (error) {
705
- const written = await stat(bind.cache).then(() => true, () => false);
706
- if (!written) await rename(bind.aside, bind.cache).catch(() => {});
707
- throw error;
708
- }
709
- return true;
710
- });
711
- }
712
617
  async function lockBandState(cwd, fn) {
713
618
  const { withHarnessBootstrapLock } = await import("./session-bootstrap.mjs");
714
619
  return withHarnessBootstrapLock({ cwd }, fn);
@@ -779,6 +684,16 @@ async function keepSessionAlive({ cwd, harnessSessionId, now, heartbeat, renew }
779
684
  }
780
685
  }
781
686
 
687
+ // BOT-3281: the band's bootstrap failed. `reason` is the failure's own
688
+ // snake_case code (agent_identity_required, not_authenticated, …) or
689
+ // bootstrap_failed; free text from the bootstrap never reaches the band.
690
+ function bindFailed(failure) {
691
+ const code = failure?.code ?? failure?.message;
692
+ const error = new Error("session_bind_failed");
693
+ error.reason = typeof code === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(code) ? code : "bootstrap_failed";
694
+ return error;
695
+ }
696
+
782
697
  export async function main(args, {
783
698
  out = process.stdout,
784
699
  cwd = process.cwd(),
@@ -848,8 +763,12 @@ export async function main(args, {
848
763
  } else {
849
764
  await bootstrap({ cwd, harnessSessionId: harness, branch });
850
765
  }
851
- } catch {
852
- throw error;
766
+ } catch (failure) {
767
+ // A takeover that found the cache changed under it bootstraps nothing:
768
+ // the read's own refusal stands. Any bootstrap failure names its cause
769
+ // (BOT-3281), never the read's session_mismatch.
770
+ if (failure === error) throw error;
771
+ throw bindFailed(failure);
853
772
  }
854
773
  snapshot = await read(request);
855
774
  }
@@ -859,7 +778,8 @@ export async function main(args, {
859
778
  const known = /^[a-z_]+$/.test(error?.message ?? "") ? error.message : "status_unavailable";
860
779
  const prefix = known === "ticket_missing" && /^[A-Z]{2,10}$/.test(error?.prefix ?? "") ? { prefix: error.prefix } : {};
861
780
  const retry = known === "session_starting" && Number.isFinite(error?.retryAfterMs) ? { retry_after_ms: Math.ceil(error.retryAfterMs) } : {};
862
- out.write(JSON.stringify({ error: known, ...prefix, ...retry }) + "\n");
781
+ const reason = known === "session_bind_failed" ? { reason: error.reason } : {};
782
+ out.write(JSON.stringify({ error: known, ...prefix, ...retry, ...reason }) + "\n");
863
783
  return 1;
864
784
  }
865
785
  }