@botbuddy/cli 1.78.3 → 1.79.1

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.79.0
4
+
5
+ - The bb-status band's STATUS line warns while the session's project has tickets with none of the Must, Unsure or Could labels (BOT-3263): an amber `⚠ 26 project tickets not categorised` with a ↗ to the project drawer filtered to them (`&progress=uncategorised`). The count is BB's `progress_uncategorised`; against an older MCP that does not send it there is no warning. The project row's badge is unchanged. bb-status plugin 1.6.0.
6
+
3
7
  ## 1.78.0
4
8
 
5
9
  - `bb release-notes tags` lists the tenant's release-note tag groups: each group's rules, values, retired values and what the internal and external views show; `--json` prints the server's answer (BOT-3164). `tags group <key> [--label …] [--min n] [--max n] [--position n] [--internal-only] [--carries-version]`, `tags add|retire <group> <value>` and `tags view <group> --audience internal|external --show|--tag-only|--hide [--label …]` change them with your own sign-in (the manage scope). A refusal prints its code and changes nothing.
@@ -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.5.0"
14
+ "version": "1.6.0"
15
15
  },
16
16
  {
17
17
  "name": "bb-session",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bb-status",
3
- "version": "1.5.0",
3
+ "version": "1.6.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"
@@ -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."
@@ -141,7 +146,9 @@ function validProgress(p) {
141
146
  return (
142
147
  !!p &&
143
148
  PROGRESS_KINDS.every(([k]) => Number.isSafeInteger(p[k]) && p[k] >= 0 && p[k] <= 100000) &&
144
- p.unsure <= p.remaining
149
+ p.unsure <= p.remaining &&
150
+ // BOT-3263: optional (an older MCP does not send it).
151
+ (p.uncategorised === undefined || (Number.isSafeInteger(p.uncategorised) && p.uncategorised >= 0 && p.uncategorised <= 100000))
145
152
  );
146
153
  }
147
154
  function countsText(c) {
@@ -390,6 +397,7 @@ async function refresh($, { wake = false, keep = false } = {}) {
390
397
  }
391
398
  if (result.exitCode !== 0) {
392
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;
393
401
  retryAfterMs = data?.error === "session_starting" && Number.isFinite(data.retry_after_ms) ? Math.min(Math.max(data.retry_after_ms, 1000), 30000) : null;
394
402
  throw new Error(
395
403
  typeof data.error === "string" ? data.error : "source_unavailable",
@@ -1012,6 +1020,28 @@ function contextBadge(el, key) {
1012
1020
  : el.Box({ key: key + "-ctx", flexDirection: "row", flexShrink: 0, backgroundColor: "error", paddingX: 1, children: [el.Text({ color: "#ffffff", bold: true, children: [alarm] })] }),
1013
1021
  ];
1014
1022
  }
1023
+ // BOT-3263: an amber STATUS pill while live project tickets carry no Must /
1024
+ // Unsure / Could label (Linear "Commitment" tags), with a ↗ to the drawer
1025
+ // filtered to them. Nothing without the count (an older MCP) or at zero.
1026
+ const AMBER = "#b45309";
1027
+ function uncategorisedBadge(el, key, epic) {
1028
+ const n = epic?.progress?.uncategorised;
1029
+ if (!Number.isSafeInteger(n) || n < 1) return [];
1030
+ const text = "⚠ " + n + " project " + (n === 1 ? "ticket" : "tickets") + " not categorised";
1031
+ const link = el.Link({ href: LINKS.projectProgress(epic.id, "uncategorised"), label: "↗" });
1032
+ if (pills() && typeof el.Svg === "function")
1033
+ return [el.Box({ key: key + "-uncategorised", flexDirection: "row", flexShrink: 0, alignItems: "center", columnGap: 1, children: [pillSvg(el, { text, fill: AMBER, bold: true }), link] })];
1034
+ return [
1035
+ el.Box({
1036
+ key: key + "-uncategorised",
1037
+ flexDirection: "row",
1038
+ flexShrink: 0,
1039
+ backgroundColor: AMBER,
1040
+ paddingX: 1,
1041
+ children: [el.Text({ color: "#ffffff", bold: true, children: [text + " "] }), link],
1042
+ }),
1043
+ ];
1044
+ }
1015
1045
  // BOT-3245: statuses and waits are separate, titled rows on the tree's grid
1016
1046
  // (Jono, 2026-11-15: "Staging green is a wait. Staging red is a status."). The
1017
1047
  // title fills the id column; the badges start in the status-badge column and
@@ -1254,6 +1284,7 @@ function bandLines(el, $, inPane) {
1254
1284
  const statuses = [
1255
1285
  ...(s.staging?.red ? [stagingBanner(el, $, k("line-staging"), s.staging.since, s.staging.release_manager)] : []),
1256
1286
  ...contextBadge(el, k("line-context")),
1287
+ ...uncategorisedBadge(el, k("line-project"), s.epic),
1257
1288
  ];
1258
1289
  const waitsRow = headerRow(el, k("line-waits"), TITLES.waits, widths.ids, waitBadges(el, k("line-context"), s.waits, currentTime));
1259
1290
  const statusRow = headerRow(el, k("line-status"), TITLES.status, widths.ids, statuses);
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.78.3",
3
- "source_commit": "016217f2bb60798780bd8de86bd2e0a20585a31a",
4
- "source_sha256": "a47b7b82b6f2b3b5e2cd7ba4e6a06f4749c9f02b3f83917496a7f875e147927d",
2
+ "release_version": "1.79.1",
3
+ "source_commit": "5ba649dea08020282a31646a7e9fffb64a28ccce",
4
+ "source_sha256": "d158a1c8e6e2469aef1004b6d9f5caf1a91b4f3bf133ecbdfa0bb445924fb674",
5
5
  "target": "darwin-arm64",
6
- "sha256": "7cc6f65cb8fadc76b5e7a890a94b8dd7ba4249223d13d6b6bde80af5598d908d"
6
+ "sha256": "5ccb904a8628df3bfaa457e648e9be1467eefd6de54e5791193ff98b8cac6a40"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.78.3",
3
- "source_commit": "016217f2bb60798780bd8de86bd2e0a20585a31a",
4
- "source_sha256": "a47b7b82b6f2b3b5e2cd7ba4e6a06f4749c9f02b3f83917496a7f875e147927d",
2
+ "release_version": "1.79.1",
3
+ "source_commit": "5ba649dea08020282a31646a7e9fffb64a28ccce",
4
+ "source_sha256": "d158a1c8e6e2469aef1004b6d9f5caf1a91b4f3bf133ecbdfa0bb445924fb674",
5
5
  "target": "linux-x64",
6
- "sha256": "4561b9a97f8c3271ad73c1254bc374e75cad40419be82a05ef2d25d29253a8bc"
6
+ "sha256": "c5a9e9cbfd4dd73c914f2aefe1e91afdeb98166b4d8694e39d689f38a734efe1"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.78.3",
4
- "source_commit": "016217f2bb60798780bd8de86bd2e0a20585a31a",
5
- "source_sha256": "a47b7b82b6f2b3b5e2cd7ba4e6a06f4749c9f02b3f83917496a7f875e147927d",
3
+ "release_version": "1.79.1",
4
+ "source_commit": "5ba649dea08020282a31646a7e9fffb64a28ccce",
5
+ "source_sha256": "d158a1c8e6e2469aef1004b6d9f5caf1a91b4f3bf133ecbdfa0bb445924fb674",
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": "7cc6f65cb8fadc76b5e7a890a94b8dd7ba4249223d13d6b6bde80af5598d908d",
11
+ "sha256": "5ccb904a8628df3bfaa457e648e9be1467eefd6de54e5791193ff98b8cac6a40",
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": "4561b9a97f8c3271ad73c1254bc374e75cad40419be82a05ef2d25d29253a8bc",
18
+ "sha256": "c5a9e9cbfd4dd73c914f2aefe1e91afdeb98166b4d8694e39d689f38a734efe1",
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.3",
3
+ "version": "1.79.1",
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
+ }
@@ -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.
@@ -16,7 +18,10 @@ function mustUnsureProgress(src) {
16
18
  const u = n(src?.progress_unsure);
17
19
  const p = n(src?.progress_percent);
18
20
  if (c === null || r === null || u === null || p === null || p > 100 || u > r) return null;
19
- return { progress: { complete: c, remaining: r, unsure: u }, done: c, total: c + r, percent: p };
21
+ // BOT-3263: live tickets with no Must / Unsure / Could label (absent from an older MCP).
22
+ const x = n(src?.progress_uncategorised);
23
+ const progress = x === null ? { complete: c, remaining: r, unsure: u } : { complete: c, remaining: r, unsure: u, uncategorised: x };
24
+ return { progress, done: c, total: c + r, percent: p };
20
25
  }
21
26
 
22
27
  const execFileAsync = promisify(execFile);
@@ -602,110 +607,13 @@ export async function readStatus({
602
607
  // `bb bootstrap` runs. A cache another harness session holds is never
603
608
  // bootstrapped over: that session owns the worktree's identity.
604
609
  //
605
- // A holder is judged by its Claude session, not by the BB session's expiry: any
606
- // `bb` command in the worktree (another session's `bb wait`, a hook) restores
607
- // and renews the cached BB session, so a holder that ended long ago can stay
608
- // "live" in BB indefinitely and lock every later session out (SG worktree
609
- // amazing-euclid, 2026-11-14). A holder whose Claude transcript has been silent
610
- // for HOLDER_IDLE_MS is gone; one with no transcript on this host keeps the
611
- // 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).
612
612
  const BINDABLE = new Set(["session_missing", "session_mismatch", "session_expired"]);
613
613
  // BOT-3222: the bb-session hook's bootstrap is bounded at 20 s (hooks.json
614
614
  // timeout 30 s); the band waits this long after its session starts before it
615
615
  // bootstraps a session itself.
616
616
  export const START_GRACE_MS = 30_000;
617
- const HOLDER_IDLE_MS = 30 * 60 * 1000;
618
- const UUID_ONLY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
619
- // true: the holder's transcript was written within HOLDER_IDLE_MS; false: it
620
- // exists and has been silent longer; null: no transcript found (unknown).
621
- export async function claudeHolderActive(holder, worktree, { env = process.env, now = () => Date.now() } = {}) {
622
- const id = String(holder || "").toLowerCase();
623
- if (!UUID_ONLY.test(id)) return null;
624
- const projects = join(env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude"), "projects");
625
- const mtime = async (dir) => {
626
- try {
627
- return (await stat(join(projects, dir, `${id}.jsonl`))).mtimeMs;
628
- } catch {
629
- return null;
630
- }
631
- };
632
- // Claude Code names a project's directory after its path, every
633
- // non-alphanumeric character replaced by "-".
634
- let at = await mtime(String(worktree).replace(/[^a-zA-Z0-9]/g, "-"));
635
- if (at == null) {
636
- let dirs = [];
637
- try {
638
- dirs = await readdir(projects);
639
- } catch {
640
- return null;
641
- }
642
- for (const dir of dirs) {
643
- const found = await mtime(dir);
644
- if (found != null && (at == null || found > at)) at = found;
645
- }
646
- }
647
- if (at == null) return null;
648
- return now() - at < HOLDER_IDLE_MS;
649
- }
650
- // Returns false (never bind), true (bootstrap as is), or { aside } — another
651
- // holder's cache to move out of the way first. The bootstrap would otherwise
652
- // try to retire that BB session and discard the new one when it cannot: the
653
- // server refuses the retirement for a live session (which would end the waits
654
- // other sessions still run on its token), and refuses it for an EXPIRED one too
655
- // whenever the durable credential is an owner bearer, since close_session needs
656
- // an agent identity (BOT-3252: the band then stayed on "belongs to another
657
- // session" forever in a reused worktree). Set aside, a live session expires on
658
- // its own once nothing renews it; the file is kept for recovery.
659
- async function bindable(cwd, harnessSessionId, now, holderActive) {
660
- let state;
661
- let root;
662
- try {
663
- root = await realpath(cwd);
664
- state = JSON.parse(await readFile(join(root, ".botbuddy/agent-state.json"), "utf8"));
665
- } catch (error) {
666
- return error?.code === "ENOENT";
667
- }
668
- const holder = typeof state?.harness_session_id === "string" ? state.harness_session_id.toLowerCase() : "";
669
- if (!holder || holder === harnessSessionId.toLowerCase()) return true;
670
- const expired = !(Date.parse(state.expires_at) > now());
671
- const active = await holderActive(holder, root).catch(() => null);
672
- if (active === true) return false;
673
- if ((active === false || expired) && UUID_ONLY.test(holder)) {
674
- return {
675
- cache: join(root, ".botbuddy/agent-state.json"),
676
- aside: join(root, `.botbuddy/agent-state.superseded-${holder.slice(0, 8)}.json`),
677
- root,
678
- holder,
679
- sessionId: state.session_id ?? null,
680
- };
681
- }
682
- return expired;
683
- }
684
- // Codex P2 on #1646: the takeover runs under the same state lock the bootstrap
685
- // and self-heal take, so a cache published while the holder was being checked
686
- // is never the one moved aside. Inside the lock the cache must still be the
687
- // holder and session that were checked; the bootstrap then runs without
688
- // re-taking the (non-reentrant) lock, and a failure restores the holder's cache.
689
- async function takeOverGoneHolder({ cwd, bind, withLock, run }) {
690
- return withLock(cwd, async () => {
691
- let now;
692
- try {
693
- now = JSON.parse(await readFile(bind.cache, "utf8"));
694
- } catch {
695
- return false;
696
- }
697
- if (String(now?.harness_session_id ?? "").toLowerCase() !== bind.holder || (now?.session_id ?? null) !== bind.sessionId) return false;
698
- await rename(bind.cache, bind.aside);
699
- try {
700
- await run();
701
- } catch (error) {
702
- const written = await stat(bind.cache).then(() => true, () => false);
703
- if (!written) await rename(bind.aside, bind.cache).catch(() => {});
704
- throw error;
705
- }
706
- return true;
707
- });
708
- }
709
617
  async function lockBandState(cwd, fn) {
710
618
  const { withHarnessBootstrapLock } = await import("./session-bootstrap.mjs");
711
619
  return withHarnessBootstrapLock({ cwd }, fn);
@@ -776,6 +684,16 @@ async function keepSessionAlive({ cwd, harnessSessionId, now, heartbeat, renew }
776
684
  }
777
685
  }
778
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
+
779
697
  export async function main(args, {
780
698
  out = process.stdout,
781
699
  cwd = process.cwd(),
@@ -845,8 +763,12 @@ export async function main(args, {
845
763
  } else {
846
764
  await bootstrap({ cwd, harnessSessionId: harness, branch });
847
765
  }
848
- } catch {
849
- 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);
850
772
  }
851
773
  snapshot = await read(request);
852
774
  }
@@ -856,7 +778,8 @@ export async function main(args, {
856
778
  const known = /^[a-z_]+$/.test(error?.message ?? "") ? error.message : "status_unavailable";
857
779
  const prefix = known === "ticket_missing" && /^[A-Z]{2,10}$/.test(error?.prefix ?? "") ? { prefix: error.prefix } : {};
858
780
  const retry = known === "session_starting" && Number.isFinite(error?.retryAfterMs) ? { retry_after_ms: Math.ceil(error.retryAfterMs) } : {};
859
- 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");
860
783
  return 1;
861
784
  }
862
785
  }