@botbuddy/cli 1.121.4 → 1.122.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,9 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.122.0
4
+
5
+ - BOT-3646: every failed `bb status-band read` is recorded. Each failure appends one JSON line to `~/.botbuddy/status-band-failures.jsonl` (0600, in a 0700 folder, capped at 256 KiB by dropping the oldest lines) with `at`, `harness_session_id`, `ticket`, `code`, `source` (`bb`, `linear`, `local` or `bootstrap`), `http_status`, `cli_version` and, for `session_bind_failed`, its snake_case `reason`. It never records a token, a title, a branch, a URL or any text from a server. A symlinked, shared or unwritable log is left alone, and logging never changes the read's output or exit code. `session_starting` and `repo_binding_missing` are states, not failures, and are not recorded. The error envelope now carries `source` and, for an HTTP refusal, `http_status`; every error code is unchanged. Every read (good or failed) carries `recent_failures`, this session's last five entries, newest first. The band (1.12.0) names the failing source ("Linear refused access (HTTP 401)…" instead of "BB or Linear refused access") and lists the recent failures in Details. A band reading an older CLI keeps the old lines.
6
+
3
7
  ## 1.121.3
4
8
 
5
9
  - 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.
@@ -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.11.0"
14
+ "version": "1.12.0"
15
15
  },
16
16
  {
17
17
  "name": "bb-session",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bb-status",
3
- "version": "1.11.0",
3
+ "version": "1.12.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"
@@ -166,6 +166,21 @@ Claude turn events and is separate from Linear state.
166
166
  The POC rejects incomplete blocker pages (>100 relations) rather than showing a
167
167
  false unblocked state. Demo dependencies are illustrative, not current Linear facts.
168
168
 
169
+ **Failed reads are recorded** (BOT-3646). Each failed `bb status-band read` appends one
170
+ JSON line to `~/.botbuddy/status-band-failures.jsonl` (0600, capped at 256 KiB, oldest
171
+ lines dropped): `at`, `harness_session_id`, `ticket`, `code`, `source` (`bb`, `linear`,
172
+ `local` or `bootstrap`), `http_status`, `cli_version`, and `reason` for
173
+ `session_bind_failed`. No token, title, branch, URL or server text is ever written.
174
+ `session_starting` and `repo_binding_missing` are not failures and are not recorded.
175
+ To see what has been failing:
176
+
177
+ ```bash
178
+ tail -n 20 ~/.botbuddy/status-band-failures.jsonl
179
+ ```
180
+
181
+ The band names the failing source in its error line, and Details lists this session's
182
+ last five failures (`recent_failures` in the read's output).
183
+
169
184
  ## Verification
170
185
 
171
186
  See [EVIDENCE.md](EVIDENCE.md) for the recorded receipts and limits.
@@ -46,6 +46,14 @@ let sessionStartedAt = null;
46
46
  let retryAfterMs = null;
47
47
  // BOT-3281: the snake_case cause of a failed bootstrap (session_bind_failed).
48
48
  let bindReason = null;
49
+ // BOT-3646: which source failed (bb | linear | local | bootstrap) and its HTTP
50
+ // status, for the error line and the STALE line; and the session's recent
51
+ // failures as `bb status-band read` recorded them, for Details.
52
+ let errorSource = null;
53
+ let errorStatus = null;
54
+ let faultSource = null;
55
+ let faultStatus = null;
56
+ let failures = [];
49
57
  // BOT-3212: the waits badge pulses once, for PULSE_MS, when the count changes.
50
58
  const PULSE_MS = 2000;
51
59
  let pulsing = false;
@@ -93,6 +101,43 @@ const ERRORS = {
93
101
  cli_missing: "Install the bb CLI (npm i -g @botbuddy/cli), then run bb setup.",
94
102
  cli_outdated: "Update the bb CLI (bb update) to use this band.",
95
103
  };
104
+ // BOT-3646 AC-3: a source refusal names its source; null keeps the old line.
105
+ const SOURCE_NAMES = { bb: "BB", linear: "Linear" };
106
+ const FAILURE_SOURCES = { bb: "BB", linear: "Linear", local: "local check", bootstrap: "bootstrap" };
107
+ function httpStatusOf(v) {
108
+ return Number.isSafeInteger(v) && v >= 100 && v <= 599 ? v : null;
109
+ }
110
+ function sourcedText(code, source, status) {
111
+ const who = SOURCE_NAMES[source];
112
+ if (!who) return null;
113
+ const http = status ? " (HTTP " + status + ")" : "";
114
+ if (code === "source_unauthorized")
115
+ return who + " refused access" + http + ". " +
116
+ (source === "linear" ? "Check LINEAR_BB_API_KEY, then Refresh." : "Run `bb doctor --fix` in this worktree, then Refresh.");
117
+ if (code === "source_unreachable") return who + " could not be reached. Refresh to retry.";
118
+ if (code === "source_unavailable") return who + " is unavailable" + http + ". Refresh to retry.";
119
+ if (code === "source_rejected") return who + " rejected the status request. Refresh to retry.";
120
+ return null;
121
+ }
122
+ // BOT-3646 AC-4: only entries whose every field matches its pattern are drawn.
123
+ const FAILURE_AT = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
124
+ function recentList(value) {
125
+ if (!Array.isArray(value)) return [];
126
+ return value
127
+ .filter(
128
+ (f) =>
129
+ f && typeof f === "object" &&
130
+ typeof f.at === "string" && FAILURE_AT.test(f.at) &&
131
+ typeof f.code === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(f.code) &&
132
+ Object.hasOwn(FAILURE_SOURCES, f.source) &&
133
+ (f.http_status === null || httpStatusOf(f.http_status) !== null),
134
+ )
135
+ .slice(0, 5);
136
+ }
137
+ function failureLine(f) {
138
+ return f.at.slice(5, 10) + " " + f.at.slice(11, 16) + "Z · " + f.code + " · " + FAILURE_SOURCES[f.source] +
139
+ (f.http_status ? " · HTTP " + f.http_status : "");
140
+ }
96
141
  function errorText() {
97
142
  // BOT-3213 AC-4: the hint speaks in the tenant's own prefix when it is known.
98
143
  if (errorCode === "ticket_missing" && hintPrefix)
@@ -102,6 +147,8 @@ function errorText() {
102
147
  );
103
148
  if (errorCode === "session_bind_failed")
104
149
  return "BB could not connect this session (" + (bindReason || "bootstrap_failed") + "). Refresh to retry.";
150
+ const sourced = sourcedText(errorCode, errorSource, errorStatus);
151
+ if (sourced) return sourced;
105
152
  // BOT-3644 AC-2: never a catch-all that names no cause.
106
153
  return ERRORS[errorCode] || "BB status failed (" + errorCode + "). Refresh to retry.";
107
154
  }
@@ -417,6 +464,8 @@ async function refresh($, { wake = false, keep = false } = {}) {
417
464
  }
418
465
  }
419
466
  errorCode = null;
467
+ errorSource = null;
468
+ errorStatus = null;
420
469
  loading = true;
421
470
  unbound = false;
422
471
  $.ui.invalidate("ui.render");
@@ -451,6 +500,8 @@ async function refresh($, { wake = false, keep = false } = {}) {
451
500
  // A bb older than `status-band` prints its usage error, not JSON.
452
501
  throw new Error(/Unknown command/.test(String(result.stderr)) ? "cli_outdated" : "invalid_response");
453
502
  }
503
+ // BOT-3646 AC-4: an older CLI sends no list, so none is drawn.
504
+ failures = recentList(data?.recent_failures);
454
505
  if (result.exitCode !== 0 && data?.error === "repo_binding_missing") {
455
506
  unbound = true;
456
507
  snapshot = null;
@@ -459,6 +510,8 @@ async function refresh($, { wake = false, keep = false } = {}) {
459
510
  if (result.exitCode !== 0) {
460
511
  hintPrefix = data?.error === "ticket_missing" && /^[A-Z]{2,10}$/.test(data.prefix ?? "") ? data.prefix : null;
461
512
  bindReason = data?.error === "session_bind_failed" && typeof data.reason === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(data.reason) ? data.reason : null;
513
+ errorSource = Object.hasOwn(FAILURE_SOURCES, data?.source) ? data.source : null;
514
+ errorStatus = httpStatusOf(data?.http_status);
462
515
  retryAfterMs = data?.error === "session_starting" && Number.isFinite(data.retry_after_ms) ? Math.min(Math.max(data.retry_after_ms, 1000), 30000) : null;
463
516
  throw new Error(
464
517
  typeof data.error === "string" ? data.error : "source_unavailable",
@@ -505,7 +558,11 @@ async function refresh($, { wake = false, keep = false } = {}) {
505
558
  : "status_unavailable";
506
559
  // BOT-3644 AC-4: a transient failure keeps the last good status (STALE);
507
560
  // any other failure clears it, so a wrong identity is never left drawn.
508
- if (TRANSIENT.has(errorCode) && snapshot) readFault = errorCode;
561
+ if (TRANSIENT.has(errorCode) && snapshot) {
562
+ readFault = errorCode;
563
+ faultSource = errorSource;
564
+ faultStatus = errorStatus;
565
+ }
509
566
  else {
510
567
  snapshot = null;
511
568
  readFault = null;
@@ -760,7 +817,7 @@ function stale() {
760
817
  }
761
818
  function staleText() {
762
819
  if (readFault) {
763
- const why = ERRORS[readFault] || "BB status failed (" + readFault + "). Refresh to retry.";
820
+ const why = sourcedText(readFault, faultSource, faultStatus) || ERRORS[readFault] || "BB status failed (" + readFault + "). Refresh to retry.";
764
821
  return "STALE · " + (why.includes("(" + readFault + ")") ? why : why.replace(/\.( Refresh|$)/, " (" + readFault + ").$1"));
765
822
  }
766
823
  if (relayFault === "session_expired")
@@ -1639,6 +1696,7 @@ export function register(on) {
1639
1696
  stopRelay();
1640
1697
  generation++;
1641
1698
  snapshot = null;
1699
+ failures = [];
1642
1700
  keptLive = false;
1643
1701
  selectedTicket = undefined;
1644
1702
  mode = "live";
@@ -1765,6 +1823,11 @@ export function register(on) {
1765
1823
  links.push(Link({ label: "Open BB ↗", href: APP }));
1766
1824
  children.push(Box({ flexDirection: "row", columnGap: 2, children: links }));
1767
1825
  }
1826
+ // BOT-3646 AC-4: what `bb status-band read` recorded for this session.
1827
+ if (mode === "live" && failures.length) {
1828
+ children.push(Text({ bold: true, children: ["Recent failures · " + failures.length] }));
1829
+ for (const f of failures) children.push(Text({ key: "failure-" + f.at + f.code, dimColor: true, children: [failureLine(f)] }));
1830
+ }
1768
1831
  children.push(
1769
1832
  Box({
1770
1833
  flexDirection: "row",
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.121.4",
3
- "source_commit": "6a9058be35b650acfa8a120186f6c6be5f1f3648",
4
- "source_sha256": "f29cb4b7bb0e300a0c93e55b935ad5edb65b6669c545afde66483d40c3a883f2",
2
+ "release_version": "1.122.0",
3
+ "source_commit": "acf84d6dcb5b798c12211a7100fd9f0484fa5083",
4
+ "source_sha256": "139c27662b3b06efa85043262cf1b146975b042231c326c0e8e34f4c5cf47bbc",
5
5
  "target": "darwin-arm64",
6
- "sha256": "2c94361ae9fe7d5d4e71aa608ffa55f8ba9b9b5c249e5f8b9896258b25b11e3e"
6
+ "sha256": "2e1ebbe7356b0ea5717ff1a808d4b2120076078067bc70ccd13312c4b8abd451"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.121.4",
3
- "source_commit": "6a9058be35b650acfa8a120186f6c6be5f1f3648",
4
- "source_sha256": "f29cb4b7bb0e300a0c93e55b935ad5edb65b6669c545afde66483d40c3a883f2",
2
+ "release_version": "1.122.0",
3
+ "source_commit": "acf84d6dcb5b798c12211a7100fd9f0484fa5083",
4
+ "source_sha256": "139c27662b3b06efa85043262cf1b146975b042231c326c0e8e34f4c5cf47bbc",
5
5
  "target": "linux-x64",
6
- "sha256": "99005ff0fe3f71396c8a5f1b06f7dc853977af6dd6bcabb19601115320f166af"
6
+ "sha256": "67d42648ddce7000f7382aa85810b529ffca62ca43e77476b2aa8115196ca856"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.121.4",
4
- "source_commit": "6a9058be35b650acfa8a120186f6c6be5f1f3648",
5
- "source_sha256": "f29cb4b7bb0e300a0c93e55b935ad5edb65b6669c545afde66483d40c3a883f2",
3
+ "release_version": "1.122.0",
4
+ "source_commit": "acf84d6dcb5b798c12211a7100fd9f0484fa5083",
5
+ "source_sha256": "139c27662b3b06efa85043262cf1b146975b042231c326c0e8e34f4c5cf47bbc",
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": "2c94361ae9fe7d5d4e71aa608ffa55f8ba9b9b5c249e5f8b9896258b25b11e3e",
11
+ "sha256": "2e1ebbe7356b0ea5717ff1a808d4b2120076078067bc70ccd13312c4b8abd451",
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": "99005ff0fe3f71396c8a5f1b06f7dc853977af6dd6bcabb19601115320f166af",
18
+ "sha256": "67d42648ddce7000f7382aa85810b529ffca62ca43e77476b2aa8115196ca856",
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.4",
3
+ "version": "1.122.0",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,176 @@
1
+ // BOT-3646: every failed `bb status-band read` leaves one line in a private,
2
+ // size-capped, machine-wide JSONL log, so a blank band is diagnosed from data
3
+ // instead of a screenshot. Codes and enums only: never a token, title, branch,
4
+ // URL or any free text from a server. Logging is best-effort and never changes
5
+ // the read's own output or exit code.
6
+ import { constants } from "node:fs";
7
+ import { lstat, mkdir, open, readFile, rename, rm } from "node:fs/promises";
8
+ import { homedir } from "node:os";
9
+ import { dirname, join } from "node:path";
10
+ import { randomBytes } from "node:crypto";
11
+
12
+ export const FAILURE_LOG_CAP = 256 * 1024;
13
+ export const RECENT_LIMIT = 5;
14
+ export const SOURCES = new Set(["bb", "linear", "local", "bootstrap"]);
15
+ const CODE = /^[a-z][a-z0-9_]{0,63}$/;
16
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
17
+ const TICKET = /^[A-Z]{2,10}-[1-9]\d{0,6}$/;
18
+ const SEMVER = /^\d{1,4}\.\d{1,5}\.\d{1,6}(?:-[0-9A-Za-z.-]{1,40})?$/;
19
+ const ISO = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
20
+
21
+ // Resolved at call time, so a test (or a sandbox) that moves HOME moves the log.
22
+ export function failureLogPath(home = homedir()) {
23
+ return join(home, ".botbuddy", "status-band-failures.jsonl");
24
+ }
25
+
26
+ const httpStatus = (v) => (Number.isSafeInteger(v) && v >= 100 && v <= 599 ? v : null);
27
+
28
+ // The one place a line is shaped: every field is checked against its pattern
29
+ // and anything else becomes null, so nothing free-form can reach the file.
30
+ export function failureEntry({ at, harnessSessionId, ticket, code, source, status, cliVersion, reason }) {
31
+ const when = new Date(at);
32
+ const entry = {
33
+ at: Number.isFinite(when.getTime()) ? when.toISOString() : new Date(0).toISOString(),
34
+ harness_session_id: typeof harnessSessionId === "string" && UUID.test(harnessSessionId) ? harnessSessionId.toLowerCase() : null,
35
+ ticket: typeof ticket === "string" && TICKET.test(ticket) ? ticket : null,
36
+ code: typeof code === "string" && CODE.test(code) ? code : "status_unavailable",
37
+ source: SOURCES.has(source) ? source : "local",
38
+ http_status: httpStatus(status),
39
+ cli_version: typeof cliVersion === "string" && SEMVER.test(cliVersion) ? cliVersion : null,
40
+ };
41
+ if (entry.code === "session_bind_failed") entry.reason = typeof reason === "string" && CODE.test(reason) ? reason : "bootstrap_failed";
42
+ return entry;
43
+ }
44
+
45
+ // A log we may touch: a regular file, not a link, owned privately.
46
+ async function privateFile(path) {
47
+ let info;
48
+ try {
49
+ info = await lstat(path);
50
+ } catch (error) {
51
+ return error?.code === "ENOENT" ? "absent" : null;
52
+ }
53
+ if (!info.isFile() || (info.mode & 0o077) !== 0 || info.nlink > 1) return null;
54
+ return info;
55
+ }
56
+
57
+ // Keep the newest whole lines that fit in half the cap, written to a fresh
58
+ // private file and renamed over the old one.
59
+ async function trim(path, cap) {
60
+ const text = await readFile(path, "utf8");
61
+ const lines = text.split("\n").filter(Boolean);
62
+ const kept = [];
63
+ let size = 0;
64
+ for (let i = lines.length - 1; i >= 0; i--) {
65
+ const n = Buffer.byteLength(lines[i]) + 1;
66
+ if (size + n > cap / 2) break;
67
+ kept.unshift(lines[i]);
68
+ size += n;
69
+ }
70
+ const tmp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
71
+ const handle = await open(tmp, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
72
+ try {
73
+ await handle.writeFile(kept.length ? kept.join("\n") + "\n" : "");
74
+ } finally {
75
+ await handle.close();
76
+ }
77
+ await rename(tmp, path).catch(async (error) => {
78
+ await rm(tmp, { force: true });
79
+ throw error;
80
+ });
81
+ }
82
+
83
+ // Codex P2 on #2030: bands in several sessions append to one file, so the size
84
+ // check, trim, rename and append run under one interprocess lock file. A lock
85
+ // older than LOCK_STALE_MS belongs to a writer that died and is broken; a writer
86
+ // that cannot get the lock within LOCK_WAIT_MS gives up rather than delay the read.
87
+ const LOCK_WAIT_MS = 2000;
88
+ const LOCK_STALE_MS = 10000;
89
+ async function withLogLock(path, fn) {
90
+ const lock = path + ".lock";
91
+ const deadline = Date.now() + LOCK_WAIT_MS;
92
+ for (;;) {
93
+ try {
94
+ await (await open(lock, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600)).close();
95
+ break;
96
+ } catch (error) {
97
+ if (error?.code !== "EEXIST") throw error;
98
+ const held = await lstat(lock).catch(() => null);
99
+ if (held && Date.now() - held.mtimeMs > LOCK_STALE_MS) {
100
+ await rm(lock, { force: true });
101
+ continue;
102
+ }
103
+ if (Date.now() > deadline) return false;
104
+ // In-process backoff between lock attempts, bounded by LOCK_WAIT_MS.
105
+ await new Promise((resolve) => setTimeout(resolve, 5 + Math.floor(Math.random() * 20)));
106
+ }
107
+ }
108
+ try {
109
+ return await fn();
110
+ } finally {
111
+ await rm(lock, { force: true });
112
+ }
113
+ }
114
+
115
+ // Appends one entry. Returns true when it was written; never throws.
116
+ export async function appendFailure(entry, { path = failureLogPath(), cap = FAILURE_LOG_CAP } = {}) {
117
+ try {
118
+ const line = JSON.stringify(failureEntry(entry)) + "\n";
119
+ const bytes = Buffer.byteLength(line);
120
+ if (bytes > cap) return false;
121
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
122
+ return await withLogLock(path, () => appendLocked(path, line, bytes, cap));
123
+ } catch {
124
+ return false;
125
+ }
126
+ }
127
+ async function appendLocked(path, line, bytes, cap) {
128
+ const before = await privateFile(path);
129
+ if (!before) return false;
130
+ if (before !== "absent" && before.size + bytes > cap) await trim(path, cap);
131
+ const handle = await open(path, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | constants.O_NOFOLLOW, 0o600);
132
+ try {
133
+ const info = await handle.stat();
134
+ if (!info.isFile() || (info.mode & 0o077) !== 0 || info.nlink > 1) return false;
135
+ await handle.write(line);
136
+ } finally {
137
+ await handle.close();
138
+ }
139
+ return true;
140
+ }
141
+
142
+ // What the band may draw for one entry; null when any field is off-pattern.
143
+ export function recentEntry(e) {
144
+ if (!e || typeof e !== "object") return null;
145
+ if (typeof e.at !== "string" || !ISO.test(e.at)) return null;
146
+ if (typeof e.code !== "string" || !CODE.test(e.code)) return null;
147
+ if (!SOURCES.has(e.source)) return null;
148
+ if (e.http_status !== null && httpStatus(e.http_status) === null) return null;
149
+ return { at: e.at, code: e.code, source: e.source, http_status: e.http_status };
150
+ }
151
+
152
+ // This harness session's newest entries, newest first; [] on any fault.
153
+ export async function recentFailures(harnessSessionId, { path = failureLogPath(), limit = RECENT_LIMIT, cap = FAILURE_LOG_CAP } = {}) {
154
+ try {
155
+ if (typeof harnessSessionId !== "string" || !UUID.test(harnessSessionId)) return [];
156
+ const info = await privateFile(path);
157
+ if (!info || info === "absent" || info.size > cap * 2) return [];
158
+ const harness = harnessSessionId.toLowerCase();
159
+ const lines = (await readFile(path, "utf8")).split("\n");
160
+ const out = [];
161
+ for (let i = lines.length - 1; i >= 0 && out.length < limit; i--) {
162
+ let e;
163
+ try {
164
+ e = JSON.parse(lines[i]);
165
+ } catch {
166
+ continue;
167
+ }
168
+ if (e?.harness_session_id !== harness) continue;
169
+ const safe = recentEntry(e);
170
+ if (safe) out.push(safe);
171
+ }
172
+ return out;
173
+ } catch {
174
+ return [];
175
+ }
176
+ }
@@ -6,6 +6,8 @@ import { promisify } from "node:util";
6
6
  import { join } from "node:path";
7
7
  import { findAgentStateRoot } from "./agent-state.mjs";
8
8
  import { bindable, claudeHolderActive, takeOverGoneHolder } from "./harness-holder.mjs";
9
+ import { appendFailure, failureLogPath, recentFailures, SOURCES } from "./status-band-failures.mjs";
10
+ import { VERSION } from "./version.mjs";
9
11
 
10
12
  export { claudeHolderActive };
11
13
  // BOT-3259: BB's one project figure (v_project_progress): Must + unsure members
@@ -218,7 +220,12 @@ function safeText(value, max = 240) {
218
220
  if (!t || /[\u0000-\u001f\u007f\u202a-\u202e\u2066-\u2069]/u.test(t)) return null;
219
221
  return t.length > max ? t.slice(0, max - 1) + "…" : t;
220
222
  }
223
+ // BOT-3646 AC-3: which source a refusal came from, so the band can name it.
224
+ function sourceOf(url) {
225
+ return new URL(url).hostname === "api.linear.app" ? "linear" : "bb";
226
+ }
221
227
  async function jsonRequest(url, init, fetchImpl, timeoutMs = 8000) {
228
+ const source = sourceOf(url);
222
229
  let response;
223
230
  try {
224
231
  response = await fetchImpl(url, {
@@ -227,21 +234,22 @@ async function jsonRequest(url, init, fetchImpl, timeoutMs = 8000) {
227
234
  signal: AbortSignal.timeout(timeoutMs),
228
235
  });
229
236
  } catch {
230
- refuse("source_unreachable");
237
+ refuse("source_unreachable", { source });
231
238
  }
232
239
  if (!response.ok)
233
240
  refuse(
234
241
  response.status === 401 || response.status === 403
235
242
  ? "source_unauthorized"
236
243
  : "source_unavailable",
244
+ { source, httpStatus: response.status },
237
245
  );
238
246
  let body;
239
247
  try {
240
248
  body = await response.json();
241
249
  } catch {
242
- refuse("invalid_response");
250
+ refuse("invalid_response", { source });
243
251
  }
244
- if (body?.errors || body?.error || body?.isError) refuse("source_rejected");
252
+ if (body?.errors || body?.error || body?.isError) refuse("source_rejected", { source });
245
253
  return body;
246
254
  }
247
255
  async function readSession(cwd) {
@@ -268,6 +276,8 @@ export async function readStatus({
268
276
  linearKey,
269
277
  // BOT-3135: a relay wake skips the slow epic read; the mod keeps the last epic.
270
278
  skipEpic = false,
279
+ // BOT-3646: the ticket the read is for, once known, for the failure log.
280
+ trace = {},
271
281
  now = () => Date.now(),
272
282
  fetchImpl = fetch,
273
283
  branchReader = async (path) =>
@@ -325,6 +335,7 @@ export async function readStatus({
325
335
  const selected = ticketId === undefined ? null : [...new Set(String(ticketId).split(","))];
326
336
  if (selected && (!selected.length || selected.length > 5 || !selected.every((k) => keyPattern.test(k))))
327
337
  refuse("ticket_missing");
338
+ trace.ticket = selected?.[0] ?? branchKeys[0] ?? null;
328
339
  const identity = await jsonRequest(
329
340
  "https://api.bot-buddy.ai/functions/v1/mcp-server/tools/whoami",
330
341
  {
@@ -384,6 +395,7 @@ export async function readStatus({
384
395
  const coordinator = ownOk ? coordinatorOf(own) : null;
385
396
  const bindingKind = selected ? "selected" : sessionKeys.length ? "session" : coordinator ? "project" : "branch";
386
397
  const keys = selected ?? (sessionKeys.length ? sessionKeys : bindingKind === "project" ? [] : branchKeys);
398
+ trace.ticket = keys[0] ?? null;
387
399
  // The hint names this tenant's own key prefix (BOT-3213 AC-4).
388
400
  if (!keys.length && bindingKind !== "project") refuse("ticket_missing", { prefix });
389
401
  const key = keys[0] ?? null;
@@ -760,7 +772,7 @@ async function keepSessionAlive({ cwd, harnessSessionId, now, heartbeat, renew }
760
772
  await renew({ cwd, harnessSessionId });
761
773
  } catch (error) {
762
774
  const code = error?.code ?? error?.message;
763
- refuse(RENEW_CODES.has(code) ? code : "session_renewal_failed");
775
+ refuse(RENEW_CODES.has(code) ? code : "session_renewal_failed", { source: "bb" });
764
776
  }
765
777
  }
766
778
 
@@ -771,9 +783,11 @@ function bindFailed(failure) {
771
783
  const code = failure?.code ?? failure?.message;
772
784
  const error = new Error("session_bind_failed");
773
785
  error.reason = typeof code === "string" && /^[a-z][a-z0-9_]{0,63}$/.test(code) ? code : "bootstrap_failed";
786
+ error.source = "bootstrap";
774
787
  return error;
775
788
  }
776
789
 
790
+ const NOT_FAILURES = new Set(["session_starting", "repo_binding_missing"]);
777
791
  export async function main(args, {
778
792
  out = process.stdout,
779
793
  cwd = process.cwd(),
@@ -785,7 +799,11 @@ export async function main(args, {
785
799
  holderActive = (holder, worktree) => claudeHolderActive(holder, worktree, { env, now }),
786
800
  withLock = lockBandState,
787
801
  now = () => Date.now(),
802
+ // BOT-3646: where failures are recorded, and the version each line names.
803
+ failureLogFile = failureLogPath(),
804
+ version = VERSION,
788
805
  } = {}) {
806
+ const trace = {};
789
807
  try {
790
808
  args = [...args];
791
809
  const skipEpic = args.at(-1) === "--skip-epic";
@@ -808,7 +826,7 @@ export async function main(args, {
808
826
  // worktree (a `cd` in the session moves it); the binding and the session
809
827
  // cache live at the worktree's root, so read from there.
810
828
  cwd = await findAgentStateRoot(await realpath(cwd).catch(() => cwd));
811
- const request = { cwd, harnessSessionId: args[1], ticketId: args[3], linearKey: env.LINEAR_BB_API_KEY, skipEpic };
829
+ const request = { cwd, harnessSessionId: args[1], ticketId: args[3], linearKey: env.LINEAR_BB_API_KEY, skipEpic, trace };
812
830
  if (UUID.test(args[1])) await keepSessionAlive({ cwd, harnessSessionId: args[1], now, heartbeat, renew });
813
831
  let snapshot;
814
832
  try {
@@ -852,14 +870,32 @@ export async function main(args, {
852
870
  }
853
871
  snapshot = await read(request);
854
872
  }
855
- out.write(JSON.stringify(snapshot) + "\n");
873
+ // BOT-3646 AC-4: the session's recent failures ride along on a good read too,
874
+ // so Details still shows what went wrong after the band recovered.
875
+ const recent = await recentFailures(args[1], { path: failureLogFile });
876
+ out.write(JSON.stringify(recent.length ? { ...snapshot, recent_failures: recent } : snapshot) + "\n");
856
877
  return 0;
857
878
  } catch (error) {
858
879
  const known = /^[a-z_]+$/.test(error?.message ?? "") ? error.message : "status_unavailable";
859
880
  const prefix = known === "ticket_missing" && /^[A-Z]{2,10}$/.test(error?.prefix ?? "") ? { prefix: error.prefix } : {};
860
881
  const retry = known === "session_starting" && Number.isFinite(error?.retryAfterMs) ? { retry_after_ms: Math.ceil(error.retryAfterMs) } : {};
861
882
  const reason = known === "session_bind_failed" ? { reason: error.reason } : {};
862
- out.write(JSON.stringify({ error: known, ...prefix, ...retry, ...reason }) + "\n");
883
+ // BOT-3646 AC-3: which source failed; anything not tagged is a local refusal.
884
+ const source = SOURCES.has(error?.source) ? error.source : "local";
885
+ const status = Number.isSafeInteger(error?.httpStatus) && error.httpStatus >= 100 && error.httpStatus <= 599 ? { http_status: error.httpStatus } : {};
886
+ let recent = [];
887
+ // BOT-3646 AC-1: record every failure; a session still starting and a repo
888
+ // with no binding are states, not failures, and are never recorded.
889
+ if (!NOT_FAILURES.has(known)) {
890
+ const harnessSessionId = args?.[1];
891
+ const ticket = typeof args?.[3] === "string" ? args[3].split(",")[0] : trace.ticket;
892
+ await appendFailure(
893
+ { at: now(), harnessSessionId, ticket, code: known, source, status: status.http_status, cliVersion: version, reason: error?.reason },
894
+ { path: failureLogFile },
895
+ );
896
+ recent = await recentFailures(harnessSessionId, { path: failureLogFile });
897
+ }
898
+ out.write(JSON.stringify({ error: known, source, ...status, ...prefix, ...retry, ...reason, ...(recent.length ? { recent_failures: recent } : {}) }) + "\n");
863
899
  return 1;
864
900
  }
865
901
  }