@botbuddy/cli 1.121.3 → 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 +4 -0
- package/claude-plugin/.claude-plugin/marketplace.json +1 -1
- package/claude-plugin/bb-status/.claude-plugin/plugin.json +1 -1
- package/claude-plugin/bb-status/README.md +15 -0
- package/claude-plugin/bb-status/hooks/register.js +65 -2
- package/daemon/bin/darwin-arm64/botbuddy-daemon +0 -0
- package/daemon/bin/linux-x64/botbuddy-daemon +0 -0
- package/daemon-release/darwin-arm64.json +4 -4
- package/daemon-release/linux-x64.json +4 -4
- package/daemon-release/manifest.json +5 -5
- package/package.json +1 -1
- package/src/host-child.mjs +14 -3
- package/src/stack.mjs +32 -0
- package/src/status-band-failures.mjs +176 -0
- package/src/status-band-read.mjs +43 -7
- package/src/wait-core.mjs +29 -3
- package/src/wait.mjs +47 -1
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.
|
|
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.
|
|
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)
|
|
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",
|
|
Binary file
|
|
Binary file
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
|
-
"release_version": "1.
|
|
3
|
-
"source_commit": "
|
|
4
|
-
"source_sha256": "
|
|
2
|
+
"release_version": "1.122.0",
|
|
3
|
+
"source_commit": "acf84d6dcb5b798c12211a7100fd9f0484fa5083",
|
|
4
|
+
"source_sha256": "139c27662b3b06efa85043262cf1b146975b042231c326c0e8e34f4c5cf47bbc",
|
|
5
5
|
"target": "darwin-arm64",
|
|
6
|
-
"sha256": "
|
|
6
|
+
"sha256": "2e1ebbe7356b0ea5717ff1a808d4b2120076078067bc70ccd13312c4b8abd451"
|
|
7
7
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
|
-
"release_version": "1.
|
|
3
|
-
"source_commit": "
|
|
4
|
-
"source_sha256": "
|
|
2
|
+
"release_version": "1.122.0",
|
|
3
|
+
"source_commit": "acf84d6dcb5b798c12211a7100fd9f0484fa5083",
|
|
4
|
+
"source_sha256": "139c27662b3b06efa85043262cf1b146975b042231c326c0e8e34f4c5cf47bbc",
|
|
5
5
|
"target": "linux-x64",
|
|
6
|
-
"sha256": "
|
|
6
|
+
"sha256": "67d42648ddce7000f7382aa85810b529ffca62ca43e77476b2aa8115196ca856"
|
|
7
7
|
}
|
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schema_version": 1,
|
|
3
|
-
"release_version": "1.
|
|
4
|
-
"source_commit": "
|
|
5
|
-
"source_sha256": "
|
|
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": "
|
|
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": "
|
|
18
|
+
"sha256": "67d42648ddce7000f7382aa85810b529ffca62ca43e77476b2aa8115196ca856",
|
|
19
19
|
"mode": "0755"
|
|
20
20
|
}
|
|
21
21
|
}
|
package/package.json
CHANGED
package/src/host-child.mjs
CHANGED
|
@@ -26,6 +26,11 @@ export const HOST_CHILD_DEFAULT_MAX_RUNTIME_S = 3600;
|
|
|
26
26
|
* dependency layer keeps a claim alive with "preparing" reports up to here).
|
|
27
27
|
*/
|
|
28
28
|
export const HOST_CHILD_PREPARE_CAP_MS = 45 * 60_000;
|
|
29
|
+
/**
|
|
30
|
+
* BOT-3568: a detached host child's wait outlasts an outage of this machine (asleep, roaming)
|
|
31
|
+
* inside the platform wait (`bb wait --outage-budget`), up to the run's own give-up time.
|
|
32
|
+
*/
|
|
33
|
+
export const HOST_CHILD_WAIT_OUTAGE_MAX_S = 86_400;
|
|
29
34
|
const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
30
35
|
|
|
31
36
|
/** The four requester tool calls, over the run's retrying caller. */
|
|
@@ -79,9 +84,12 @@ export function childEnvFrom(names, env = process.env) {
|
|
|
79
84
|
/** How long a stop that the control plane has not yet accepted waits before asking again. */
|
|
80
85
|
export const HOST_CHILD_CANCEL_RETRY_MS = 30_000;
|
|
81
86
|
|
|
82
|
-
export function hostChildWaitArgv({ runId, deadline, since = null }) {
|
|
87
|
+
export function hostChildWaitArgv({ runId, deadline, since = null, outageBudgetSeconds = null }) {
|
|
83
88
|
const argv = ["wait", `event:type=test_child_run,subject=${runId}`, `timer:deadline=${deadline}`];
|
|
84
89
|
if (Number.isSafeInteger(since) && since >= 0) argv.push("--since", String(since));
|
|
90
|
+
if (Number.isSafeInteger(outageBudgetSeconds) && outageBudgetSeconds >= 1) {
|
|
91
|
+
argv.push("--outage-budget", String(Math.min(outageBudgetSeconds, HOST_CHILD_WAIT_OUTAGE_MAX_S)));
|
|
92
|
+
}
|
|
85
93
|
return argv;
|
|
86
94
|
}
|
|
87
95
|
|
|
@@ -111,7 +119,7 @@ export function hostRunExitCode(run) {
|
|
|
111
119
|
export async function startHostChild({
|
|
112
120
|
api, upload, slotId, argv, env = {}, worktreeRoot, maxRuntimeSeconds = HOST_CHILD_DEFAULT_MAX_RUNTIME_S,
|
|
113
121
|
bundle: prebuilt = null, wait = defaultHostChildWait, log = () => {}, writeOutput = (s) => process.stdout.write(s), now = Date.now,
|
|
114
|
-
signal = undefined, artifactGlobs = [], fetchArtifacts = fetch, testRunId = null, callbackPort = null,
|
|
122
|
+
signal = undefined, artifactGlobs = [], fetchArtifacts = fetch, testRunId = null, callbackPort = null, outlastOutages = false,
|
|
115
123
|
}) {
|
|
116
124
|
const bundle = prebuilt ?? buildHeadBundle(worktreeRoot);
|
|
117
125
|
if (!bundle.ok) return { ok: false, code: "HOST_CHILD_BUNDLE_FAILED", error: bundle.error };
|
|
@@ -228,7 +236,10 @@ export async function startHostChild({
|
|
|
228
236
|
waitAbort = new AbortController();
|
|
229
237
|
const onAbort = () => waitAbort.abort("done");
|
|
230
238
|
abort.signal.addEventListener("abort", onAbort, { once: true });
|
|
231
|
-
|
|
239
|
+
// BOT-3568: a detached host child's wait rides out this machine's outage itself, for as long
|
|
240
|
+
// as the run may still end; when even that wait gives up, the run is given up as before.
|
|
241
|
+
const outage = outlastOutages ? { outageBudgetSeconds: Math.max(1, Math.ceil((giveUpAt - now()) / 1000)) } : {};
|
|
242
|
+
const parked = await wait({ runId, deadline, since, signal: waitAbort.signal, ...outage }).catch(() => false);
|
|
232
243
|
abort.signal.removeEventListener("abort", onAbort);
|
|
233
244
|
const retry = waitAbort.signal.reason === "cancel_retry";
|
|
234
245
|
waitAbort = null;
|
package/src/stack.mjs
CHANGED
|
@@ -4647,6 +4647,12 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
4647
4647
|
let callbackCleanupError = null;
|
|
4648
4648
|
let forwardAttestation = null;
|
|
4649
4649
|
let tunnelLost = null;
|
|
4650
|
+
// BOT-3568: set as a host child starts; until then every run is treated as needing this machine.
|
|
4651
|
+
let requesterRouteNeeded = true;
|
|
4652
|
+
// BOT-3568: a loss on this machine's side that a detached host child rode out (for the receipt).
|
|
4653
|
+
let requesterLinkLost = null;
|
|
4654
|
+
// BOT-3568: a host run is being created or waited on before its handle is assigned here.
|
|
4655
|
+
let hostChildStarting = false;
|
|
4650
4656
|
// BOT-2780: the requester origin closed under a live run (SSH loss or forward failure).
|
|
4651
4657
|
let originLost = null;
|
|
4652
4658
|
const placement = { mode: null, hostKey: null, requesterHost: null, transport: "none", forwards: null, bundle: null, placementReason: null, considered: null, admission: null,
|
|
@@ -4832,6 +4838,11 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
4832
4838
|
return cleanupPromise;
|
|
4833
4839
|
};
|
|
4834
4840
|
|
|
4841
|
+
// BOT-3568: a host child whose every route is on its host (no native callback to this machine,
|
|
4842
|
+
// no requester origin) does not need this machine while it runs: losing the forward, the
|
|
4843
|
+
// heartbeat or a slot renewal here never stops it. Its host keeps its slot and lease alive.
|
|
4844
|
+
const hostChildDetachable = () => !requesterRouteNeeded;
|
|
4845
|
+
const hostChildDetached = () => Boolean((child?.hostRun || hostChildStarting) && !childResult && hostChildDetachable());
|
|
4835
4846
|
// Test seam: a fake child's pid is never a real process group.
|
|
4836
4847
|
const signalGroup = adapters.signalChildGroup ?? childGroupSignal;
|
|
4837
4848
|
const stopChild = (signal = "SIGTERM", forcedCode = null) => {
|
|
@@ -5799,6 +5810,12 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
5799
5810
|
const forwardTarget = sshTarget;
|
|
5800
5811
|
tunnel.onExit((exit) => {
|
|
5801
5812
|
if (childResult) return;
|
|
5813
|
+
if (hostChildDetached()) {
|
|
5814
|
+
// BOT-3568: a host child reaches its stack on its host; the forwards were never its route.
|
|
5815
|
+
requesterLinkLost ??= { kind: "forward", ...exit, target: forwardTarget };
|
|
5816
|
+
stderrLine(`stack: the SSH forward to ${forwardTarget ?? "the serving host"} ended (${exit.signal ? `signal ${exit.signal}` : `exit ${exit.code ?? "?"}`}); the host child keeps running on its host and this run waits for its result`);
|
|
5817
|
+
return;
|
|
5818
|
+
}
|
|
5802
5819
|
// BOT-3109: when the loss was seen, even before a child exists (stopChild stamps only a running one).
|
|
5803
5820
|
incidentBox.lossAtMs ??= Date.now();
|
|
5804
5821
|
tunnelLost = { ...exit, target: forwardTarget };
|
|
@@ -5975,6 +5992,8 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
5975
5992
|
}, Math.max(1_000, Math.floor((current.data.idle_ttl_secs ?? opts.idleTtl ?? 1800) * 1000 / 3)));
|
|
5976
5993
|
prepTouch?.unref?.();
|
|
5977
5994
|
let started;
|
|
5995
|
+
requesterRouteNeeded = Boolean(useNativeCallback || execution.requesterOrigin);
|
|
5996
|
+
hostChildStarting = !hostEnv.error;
|
|
5978
5997
|
activeWaitAbort = new AbortController();
|
|
5979
5998
|
try {
|
|
5980
5999
|
started = hostEnv.error ? { ok: false, code: "TEST_CHILD_ENV_REFUSED", error: hostEnv.error } : await startHostChild({
|
|
@@ -5983,6 +6002,9 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
5983
6002
|
maxRuntimeSeconds: opts.childMaxRuntime ?? HOST_CHILD_DEFAULT_MAX_RUNTIME_S,
|
|
5984
6003
|
...(adapters.hostChildBundle ? { bundle: adapters.hostChildBundle } : {}),
|
|
5985
6004
|
...(adapters.hostChildWait ? { wait: adapters.hostChildWait } : {}),
|
|
6005
|
+
// BOT-3568: a detached host child's wait outlasts this machine's outage in the platform
|
|
6006
|
+
// wait itself, instead of stopping a run that does not need this machine.
|
|
6007
|
+
...(hostChildDetachable() ? { outlastOutages: true } : {}),
|
|
5986
6008
|
log: stderrLine, ...(adapters.hostChildOutput ? { writeOutput: adapters.hostChildOutput } : {}),
|
|
5987
6009
|
signal: activeWaitAbort.signal, artifactGlobs: opts.childArtifacts ?? [],
|
|
5988
6010
|
testRunId: adapters.hostChildTestRunId !== undefined ? adapters.hostChildTestRunId : testRunIdFrom(),
|
|
@@ -5994,6 +6016,7 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
5994
6016
|
if (prepRenew) clock.clearInterval(prepRenew);
|
|
5995
6017
|
if (prepTouch) clock.clearInterval(prepTouch);
|
|
5996
6018
|
}
|
|
6019
|
+
hostChildStarting = false;
|
|
5997
6020
|
if (started.ok && prepLost) {
|
|
5998
6021
|
started.child.stop();
|
|
5999
6022
|
started.child.detach();
|
|
@@ -6041,6 +6064,8 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
6041
6064
|
} else if (r?.ok && r.data?.success === false) {
|
|
6042
6065
|
fenceSlotLost(r.data.code ?? "TEST_CHILD_SLOT_LOST");
|
|
6043
6066
|
} else if (testChild.confirmedUntilMs != null && renewNow() >= testChild.confirmedUntilMs) {
|
|
6067
|
+
// BOT-3568: a detached host child's host keeps its slot alive; only a definite answer ends it.
|
|
6068
|
+
if (hostChildDetached()) return;
|
|
6044
6069
|
fenceSlotLost("TEST_CHILD_SLOT_LOST");
|
|
6045
6070
|
}
|
|
6046
6071
|
}, renewMs);
|
|
@@ -6112,6 +6137,13 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
|
|
|
6112
6137
|
heartbeatRetry?.unref?.();
|
|
6113
6138
|
return;
|
|
6114
6139
|
}
|
|
6140
|
+
if (hostChildDetached()) {
|
|
6141
|
+
// BOT-3568: the host keeps a detached host child's lease alive while it runs; an
|
|
6142
|
+
// unanswered requester is not a reason to stop it. Keep touching on the cadence.
|
|
6143
|
+
if (!requesterLinkLost) stderrLine("stack: the control plane is not answering this machine; the host child keeps running on its host");
|
|
6144
|
+
requesterLinkLost ??= { kind: "heartbeat" };
|
|
6145
|
+
return;
|
|
6146
|
+
}
|
|
6115
6147
|
heartbeatUnanswered = true;
|
|
6116
6148
|
}
|
|
6117
6149
|
fencing = true;
|
|
@@ -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
|
+
}
|
package/src/status-band-read.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
}
|
package/src/wait-core.mjs
CHANGED
|
@@ -925,6 +925,8 @@ export const CONDITION_PARSE_ERRORS = Object.freeze([
|
|
|
925
925
|
"condition_conflict", "empty", "syntax",
|
|
926
926
|
]);
|
|
927
927
|
const MAX_DESCRIBED_CONDITION_ERRORS = 16;
|
|
928
|
+
// BOT-3568: how many times one wait revives its reaper-abandoned registration.
|
|
929
|
+
const MAX_WAIT_REVIVALS = 20;
|
|
928
930
|
const TYPE_TOKEN_RE = /^[a-z0-9_-]{1,32}$/;
|
|
929
931
|
|
|
930
932
|
function editDistanceAtMost(a, b, limit) {
|
|
@@ -1934,6 +1936,13 @@ export async function runWaitLoop({
|
|
|
1934
1936
|
// BB_WAIT_DEBUG; tests inject a collector to assert the line.
|
|
1935
1937
|
debug = null,
|
|
1936
1938
|
maxReconnects = 50,
|
|
1939
|
+
// BOT-3568: with a budget, consecutive failed connects end the wait once the outage has lasted
|
|
1940
|
+
// this long, whatever their count (a requester offline for minutes keeps its wait). Null: count only.
|
|
1941
|
+
outageBudgetMs = null,
|
|
1942
|
+
// BOT-3568 (Codex #2021): with an outage budget, an outage longer than the wait reaper's grace
|
|
1943
|
+
// abandons the registration. This re-registers the same logical wait (the server revives the
|
|
1944
|
+
// same session); true lets the loop reconnect from where it was.
|
|
1945
|
+
reviveAbandoned = null,
|
|
1937
1946
|
receiptMaxBytes = 10240,
|
|
1938
1947
|
now = Date.now,
|
|
1939
1948
|
// BOT-1147 AC-3: a `linear` wait truthfully degrades when the Linear webhook
|
|
@@ -1993,6 +2002,14 @@ export async function runWaitLoop({
|
|
|
1993
2002
|
// relay recycles its stream every few minutes is ended only by its match or its deadline.
|
|
1994
2003
|
let reconnects = 0;
|
|
1995
2004
|
let failures = 0;
|
|
2005
|
+
// BOT-3568: revivals of a reaper-abandoned registration (bounded; see reviveAbandoned).
|
|
2006
|
+
let revivals = 0;
|
|
2007
|
+
// BOT-3568: when the current run of consecutive failures began (null while connected).
|
|
2008
|
+
let outageStartedAt = null;
|
|
2009
|
+
// With a budget, the outage's elapsed time alone decides (Codex #2021); without one, the count.
|
|
2010
|
+
const outageExhausted = () => (outageBudgetMs == null
|
|
2011
|
+
? failures > maxReconnects
|
|
2012
|
+
: now() - (outageStartedAt ?? now()) >= outageBudgetMs);
|
|
1996
2013
|
const noteBackendUnreachable = () => { if (!degraded.includes("backend_unreachable")) degraded.push("backend_unreachable"); };
|
|
1997
2014
|
const noteDegraded = (marker) => { if (!degraded.includes(marker)) degraded.push(marker); };
|
|
1998
2015
|
|
|
@@ -2338,8 +2355,9 @@ export async function runWaitLoop({
|
|
|
2338
2355
|
stream = await connect(connectCursor);
|
|
2339
2356
|
} catch (err) {
|
|
2340
2357
|
failures += 1;
|
|
2358
|
+
outageStartedAt ??= now();
|
|
2341
2359
|
noteBackendUnreachable();
|
|
2342
|
-
if (
|
|
2360
|
+
if (outageExhausted()) {
|
|
2343
2361
|
return finalize("error", { exitCode: EXIT.BACKEND, error: `reconnect budget exhausted: ${String(err && err.message || err)}` });
|
|
2344
2362
|
}
|
|
2345
2363
|
const waitMs = backoff(failures);
|
|
@@ -2406,7 +2424,7 @@ export async function runWaitLoop({
|
|
|
2406
2424
|
if (!frame) continue;
|
|
2407
2425
|
// BOT-2351: the relay answered on this connection, so the backend is reachable —
|
|
2408
2426
|
// the consecutive-failure budget starts over.
|
|
2409
|
-
if (!deliveredFrame) { deliveredFrame = true; failures = 0; }
|
|
2427
|
+
if (!deliveredFrame) { deliveredFrame = true; failures = 0; outageStartedAt = null; }
|
|
2410
2428
|
|
|
2411
2429
|
if (frame.event === "connected") {
|
|
2412
2430
|
let connected = {};
|
|
@@ -2463,6 +2481,13 @@ export async function runWaitLoop({
|
|
|
2463
2481
|
(parsed.wait_session_id == null || parsed.wait_session_id === waitSessionId)) {
|
|
2464
2482
|
continue;
|
|
2465
2483
|
}
|
|
2484
|
+
if (parsed.error === "wait_abandoned" && parsed.reason === "ended_by_server" && outageBudgetMs != null &&
|
|
2485
|
+
reviveAbandoned && revivals < MAX_WAIT_REVIVALS && await reviveAbandoned()) {
|
|
2486
|
+
revivals += 1;
|
|
2487
|
+
noteDegraded("wait_revived");
|
|
2488
|
+
streamEnded = true;
|
|
2489
|
+
break;
|
|
2490
|
+
}
|
|
2466
2491
|
if (parsed.error === "wait_abandoned") {
|
|
2467
2492
|
return finalize("abandoned", {
|
|
2468
2493
|
exitCode: EXIT.ABANDONED,
|
|
@@ -2661,7 +2686,8 @@ export async function runWaitLoop({
|
|
|
2661
2686
|
reconnects += 1;
|
|
2662
2687
|
if (!deliveredFrame) {
|
|
2663
2688
|
failures += 1;
|
|
2664
|
-
|
|
2689
|
+
outageStartedAt ??= now();
|
|
2690
|
+
if (outageExhausted()) {
|
|
2665
2691
|
// BOT-2407 AC-4: only consecutive failures spend the budget, so a give-up is always
|
|
2666
2692
|
// an outage — name it. A connection that ended before any frame is
|
|
2667
2693
|
// `stream_ended_empty`; `backend_unreachable` / `stream_dropped` are already noted.
|
package/src/wait.mjs
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
// Usage: botbuddy wait [--any] <condition>... [options]
|
|
14
14
|
// Run botbuddy wait --help for the condition grammar.
|
|
15
15
|
|
|
16
|
-
import { EXIT, describeConditionErrors, parseConditions, serverConditions, parseSseFrames, runWaitLoop, normalizeSince, truncateReceipt, formatPrReviewSnapshotWarnings, prStateArmMatches, formatCiLatestRunNotice, formatUnknownWorkflowGuidance, reviewTimeoutNotice } from "./wait-core.mjs";
|
|
16
|
+
import { EXIT, describeConditionErrors, nextBackoff, parseConditions, serverConditions, parseSseFrames, runWaitLoop, normalizeSince, truncateReceipt, formatPrReviewSnapshotWarnings, prStateArmMatches, formatCiLatestRunNotice, formatUnknownWorkflowGuidance, reviewTimeoutNotice } from "./wait-core.mjs";
|
|
17
17
|
import { pushLocalTrigger } from "./push.mjs";
|
|
18
18
|
import { readAgentBinding, withPrincipalReceipt } from "./wait-profile.mjs";
|
|
19
19
|
import { VERSION } from "./version.mjs";
|
|
@@ -291,6 +291,9 @@ OPTIONS
|
|
|
291
291
|
--allow-short-timeout <reason>
|
|
292
292
|
accept a cap under 7200 s (a CI job budget, a probe); the reason is recorded
|
|
293
293
|
on the wait. Automation may set $BOTBUDDY_WAIT_SHORT_TIMEOUT_REASON instead.
|
|
294
|
+
--outage-budget <s> keep reconnecting through an outage of up to <s> seconds (1..86400) before
|
|
295
|
+
giving up (exit 5): registration and the stream both retry with backoff.
|
|
296
|
+
For a wait whose machine may sleep or roam (a host child's requester).
|
|
294
297
|
--since <seq> resume from a prior receipt's next_cursor (0..9007199254740991; replay what you missed)
|
|
295
298
|
--receipt-max-bytes <n> cap the receipt (512..65536; default 10240; payloads truncate to pointers)
|
|
296
299
|
--heartbeat keep this agent session alive while waiting (so it is not reaped)
|
|
@@ -496,6 +499,7 @@ function parseArgv(argv) {
|
|
|
496
499
|
else if (a === "--deadline-at") opts.deadlineAt = optionValue(); // internal recovery argv; never shown as public API
|
|
497
500
|
else if (a === "--since") { opts.sinceProvided = true; opts.since = optionValue(); }
|
|
498
501
|
else if (a === "--receipt-max-bytes") opts.receiptMaxBytes = Number(optionValue());
|
|
502
|
+
else if (a === "--outage-budget") opts.outageBudget = Number(optionValue());
|
|
499
503
|
else if (a === "--url") opts.url = optionValue();
|
|
500
504
|
// BOT-1574: --token and --profile are RETIRED. A wait authenticates from
|
|
501
505
|
// $BOTBUDDY_SESSION_TOKEN (minted by register_agent) alone; the per-machine
|
|
@@ -562,6 +566,16 @@ export function registerRefusalRecovery(errorCode, conditions) {
|
|
|
562
566
|
return null;
|
|
563
567
|
}
|
|
564
568
|
|
|
569
|
+
/**
|
|
570
|
+
* BOT-3568: a registration that never reached the relay (no HTTP answer: DNS, connection refused
|
|
571
|
+
* or reset, a dropped socket). Any HTTP answer, typed or not, is the relay speaking and is not one.
|
|
572
|
+
*/
|
|
573
|
+
export function isRegisterTransportFailure(error) {
|
|
574
|
+
if (!error || error.status != null || error.contended || error.code === "wait_registration_contended") return false;
|
|
575
|
+
const cause = error.cause ?? {};
|
|
576
|
+
return error instanceof TypeError || /^(ECONN|ENOTFOUND|EAI_AGAIN|ETIMEDOUT|EPIPE|UND_ERR)/.test(String(cause.code ?? error.code ?? ""));
|
|
577
|
+
}
|
|
578
|
+
|
|
565
579
|
async function registerWait(opts, conditions, deadlineIso) {
|
|
566
580
|
// BOT-1649: a relay wait authenticates from the per-session `bb_sess_` token
|
|
567
581
|
// ($BOTBUDDY_AGENT_SESSION_TOKEN) — the relay derives agent, tenant, and session from it.
|
|
@@ -2121,6 +2135,12 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
|
|
|
2121
2135
|
await emitReceipt({ schema_version: 1, outcome: "error", error: "invalid_timeout" });
|
|
2122
2136
|
process.exit(EXIT.INVALID);
|
|
2123
2137
|
}
|
|
2138
|
+
if (opts.outageBudget !== undefined && (!Number.isSafeInteger(opts.outageBudget) || opts.outageBudget < 1 || opts.outageBudget > 86400)) {
|
|
2139
|
+
process.stderr.write("bb-wait: --outage-budget must be an integer from 1 through 86400 seconds\n");
|
|
2140
|
+
await emitReceipt({ schema_version: 1, outcome: "error", error: "invalid_outage_budget", minimum: 1, maximum: 86400 });
|
|
2141
|
+
process.exit(EXIT.INVALID);
|
|
2142
|
+
}
|
|
2143
|
+
opts.outageBudgetMs = opts.outageBudget === undefined ? null : opts.outageBudget * 1000;
|
|
2124
2144
|
if (!Number.isSafeInteger(opts.receiptMaxBytes) || opts.receiptMaxBytes < MIN_RECEIPT_MAX_BYTES ||
|
|
2125
2145
|
opts.receiptMaxBytes > MAX_RECEIPT_MAX_BYTES) {
|
|
2126
2146
|
process.stderr.write(`bb-wait: --receipt-max-bytes must be an integer from ${MIN_RECEIPT_MAX_BYTES} through ${MAX_RECEIPT_MAX_BYTES}\n`);
|
|
@@ -2341,6 +2361,10 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
|
|
|
2341
2361
|
// BOT-3483: retries of a contended registration (same opts.localWaitId each time).
|
|
2342
2362
|
const contentionBackoff = waitRegisterContentionBackoffMs();
|
|
2343
2363
|
let contentionRetries = 0;
|
|
2364
|
+
// BOT-3568: with --outage-budget, a registration that cannot reach the relay is retried
|
|
2365
|
+
// with backoff on the same logical wait until the budget (or the wait's deadline) runs out.
|
|
2366
|
+
let outageStartedAt = null;
|
|
2367
|
+
let outageRetries = 0;
|
|
2344
2368
|
let reg;
|
|
2345
2369
|
for (;;) {
|
|
2346
2370
|
try {
|
|
@@ -2359,6 +2383,16 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
|
|
|
2359
2383
|
error.attempts = contentionRetries + 1;
|
|
2360
2384
|
throw error;
|
|
2361
2385
|
}
|
|
2386
|
+
if (opts.outageBudgetMs != null && isRegisterTransportFailure(error)) {
|
|
2387
|
+
outageStartedAt ??= Date.now();
|
|
2388
|
+
outageRetries += 1;
|
|
2389
|
+
const delay = nextBackoff(outageRetries);
|
|
2390
|
+
if (Date.now() - outageStartedAt + delay < opts.outageBudgetMs && Date.now() + delay < deadlineMs) {
|
|
2391
|
+
if (outageRetries === 1) process.stderr.write(`bb-wait: the relay is unreachable (${String(error?.message ?? error)}); retrying for up to ${opts.outageBudgetMs / 1000} s\n`);
|
|
2392
|
+
await new Promise((resolve) => setTimeout(resolve, delay));
|
|
2393
|
+
continue;
|
|
2394
|
+
}
|
|
2395
|
+
}
|
|
2362
2396
|
if (!shouldRenewCachedSession(error, opts.credentialSource, attempts)) throw error;
|
|
2363
2397
|
attempts += 1;
|
|
2364
2398
|
await clearAgentState(process.cwd());
|
|
@@ -2768,6 +2802,18 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
|
|
|
2768
2802
|
connect,
|
|
2769
2803
|
feedLagProbe,
|
|
2770
2804
|
receiptMaxBytes: opts.receiptMaxBytes,
|
|
2805
|
+
outageBudgetMs: opts.outageBudgetMs,
|
|
2806
|
+
// BOT-3568 (Codex #2021): the reaper abandoned this registration while the machine was away.
|
|
2807
|
+
// Re-register the same logical wait; the server revives the same session, and the loop
|
|
2808
|
+
// reconnects from where it was. Anything but that exact revival keeps today's exit 11.
|
|
2809
|
+
reviveAbandoned: async () => {
|
|
2810
|
+
try {
|
|
2811
|
+
const revived = await registerWait(opts, serverConditions(conditions), new Date(deadlineMs).toISOString());
|
|
2812
|
+
return revived?.status === "active" && revived.waitSessionId === waitSessionId;
|
|
2813
|
+
} catch {
|
|
2814
|
+
return false;
|
|
2815
|
+
}
|
|
2816
|
+
},
|
|
2771
2817
|
startedAt: checkpoint.created_at,
|
|
2772
2818
|
// BOT-1837: a timeout receipt carries the arm-time CI notice, so a caller
|
|
2773
2819
|
// reading only the receipt learns the run it meant had already finished.
|