@botbuddy/cli 1.91.2 → 1.93.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,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.93.0
4
+
5
+ - BOT-3362: `bb push [git push args]` runs the push (pre-push lanes and the push) as a tracked, detached command run and returns at once with its run id. `bb wait 'push:id=<id>'` returns the terminal receipt. Its `push` field lists each lane's result, its compute slot wait and load wait, the totals, the outcome (`pushed`, `hooks_failed`, `push_failed`, `interrupted`, `timed_out`) and the gate (`gated`, `no_hooks`, `ungated` for `LEFTHOOK=0`). `waiting_over=<s>` also wakes once the push has held for host compute that long; this wake is local. The live phase is written to `~/.botbuddy/command-runs/<id>.context.json.push.json`. A second push from the same worktree is refused (exit 4 `push_in_progress`) and names the first push.
6
+
7
+ ## 1.92.0
8
+
9
+ - BOT-3394: the bb-status band's WAITS row shows the session's own push held at the host compute gate, from `get_session_status`'s new `push_wait`: "push waiting for host compute · 17× load · 1h 24m" or "push waiting for a compute slot · 2 of 3 · 12m", linked to /waits. `bb status-band read` carries it as `push_wait` (`reason`, `load_ratio`, `slot_position`, `waiting_count`, `since`), null when none is held or BB did not say. The badge goes once the lane starts or the push ends: while a push is held the band's relay also wakes on a one-minute `timer:duration=60` (now on `bb status-band relay`'s allow-list, which takes up to 20 conditions) and re-reads, because no signal yet says a held lane started. A band whose BB reports `push_wait` also re-reads on each quiet relay timeout (~9.5 min), so a hold that begins after its last read still shows.
10
+
3
11
  ## 1.91.2
4
12
 
5
13
  - BOT-3402: a Go daemon host reports `node`, `pnpm` and `deno` as test-child capabilities only when each prints its version inside a child's own sandbox (a throwaway systemd unit with the child's user, mounts and PATH). A Corepack `pnpm` shim that cannot run there is no longer reported, `deno` is reported for the first time, and the report carries `pnpm_version` and `deno_version` next to `node_version`. The probe runs once per five-minute report, never when a child starts; if the probe itself cannot run, the last verdict stands and the report carries `probe_error`. `bb stack run --child-requires` help names `pnpm` and `deno`.
@@ -296,6 +296,8 @@ const LINKS = {
296
296
  pr: (repo, n) => APP + "/kanban?card=pr:" + repo + "%23" + n,
297
297
  // BOT-3223 AC-1: a wait badge opens that wait on BB's Waits page.
298
298
  wait: (id) => APP + "/waits?wait=" + id,
299
+ // BOT-3394: a push held for compute opens /waits, where every held push is listed.
300
+ pushes: APP + "/waits",
299
301
  // BOT-3152 AC-2: the web top bar's Staging chip link (STAGING_HREF).
300
302
  staging: APP + "/release-readiness/staging/latest",
301
303
  };
@@ -485,7 +487,7 @@ async function refresh($, { wake = false, keep = false } = {}) {
485
487
  // What the band waits on: each ticket, the agent's own waits (BOT-3212), each PR
486
488
  // still open or draft, and, when BotBuddy blockers are listed, each ticket's
487
489
  // last blocker clearing, and the epic's Linear project (BOT-3136).
488
- const MAX_CONDITIONS = 19;
490
+ const MAX_CONDITIONS = 20;
489
491
  function waitConditions(s) {
490
492
  // BOT-3152 AC-2: unknown staging (null: a failed read) also wakes on it
491
493
  // (review on #1616), so the next incident re-reads; only a tenant known to
@@ -512,10 +514,14 @@ function waitConditions(s) {
512
514
  for (const p of s.prs || [])
513
515
  if (p.state === "open" || p.state === "draft")
514
516
  conds.push("pr-review:repo=" + p.repo + ",pr=" + p.number);
515
- // At most 5 tickets, the agent's waits, 5 PRs (state + review), blockers, epic
516
- // and staging: 19, the relay's limit, so no wake is ever dropped (review on
517
- // #1616, round 4; BOT-3212).
518
- return [...conds, ...staging].slice(0, MAX_CONDITIONS);
517
+ // BOT-3394: no signal says a held pre-push lane started, so while a push is
518
+ // held the relay also wakes on a one-minute timer and the badge drops on the
519
+ // next read. A platform gap (no execution-run signal), not a poll loop.
520
+ const timer = pushWaitText(s.push_wait, currentTime) ? ["timer:duration=60"] : [];
521
+ // At most 5 tickets, the agent's waits, 5 PRs (state + review), blockers, epic,
522
+ // staging and the held-push timer: 20, the relay's limit, so no wake is ever
523
+ // dropped (review on #1616, round 4; BOT-3212; BOT-3394).
524
+ return [...timer, ...conds, ...staging].slice(0, MAX_CONDITIONS);
519
525
  }
520
526
  // Ending the loop's stream kills the child; a module unload does the same.
521
527
  function stopRelay() {
@@ -606,7 +612,9 @@ function startRelay($) {
606
612
  // BOT-3286 (Codex P2 on #1727): no signal carries a coordinator
607
613
  // registering, ending or going idle, so a shown badge re-reads on each
608
614
  // quiet timeout (~9.5 min).
609
- if (snapshot?.epic && snapshot.epic.coordinator !== undefined) await wakeRead();
615
+ // BOT-3394 (Codex P2 on #1814): nor does a push starting to hold for
616
+ // compute (BOT-3410), so a BB that reports push_wait re-reads here too.
617
+ if ((snapshot?.epic && snapshot.epic.coordinator !== undefined) || (snapshot && snapshot.push_wait !== undefined)) await wakeRead();
610
618
  } else if (res.exit === 5) {
611
619
  backoffMs = Math.min(backoffMs ? backoffMs * 2 : 30000, 300000);
612
620
  since = cursor || since;
@@ -1032,6 +1040,50 @@ function waitBadges(el, key, w, now) {
1032
1040
  if (w.count > out.length) out.push(dim(el, "+" + (w.count - out.length) + " more"));
1033
1041
  return out;
1034
1042
  }
1043
+ // BOT-3394 AC-1/AC-2: the session's own push held at the host compute gate —
1044
+ // "⏳ push waiting for host compute · 17× load · 1h 24m" or "⏳ push waiting for
1045
+ // a compute slot · 2 of 3 · 12m" — or null when none is held or BB did not say.
1046
+ function pushAge(fromIso, now) {
1047
+ const mins = Math.max(0, Math.floor((now - Date.parse(fromIso)) / 60000));
1048
+ if (mins < 60) return mins + "m";
1049
+ return Math.floor(mins / 60) + "h" + (mins % 60 ? " " + (mins % 60) + "m" : "");
1050
+ }
1051
+ function loadText(r) {
1052
+ return (r >= 10 ? String(Math.round(r)) : String(Math.round(r * 10) / 10)) + "× load";
1053
+ }
1054
+ function pushWaitText(p, now) {
1055
+ if (!p || typeof p !== "object" || typeof p.since !== "string" || !Number.isFinite(Date.parse(p.since))) return null;
1056
+ const whole = (v) => Number.isSafeInteger(v) && v >= 0;
1057
+ let parts;
1058
+ if (p.reason === "host_load") {
1059
+ parts = ["push waiting for host compute"];
1060
+ if (Number.isFinite(p.load_ratio) && p.load_ratio >= 0) parts.push(loadText(p.load_ratio));
1061
+ } else if (p.reason === "compute_slot") {
1062
+ parts = ["push waiting for a compute slot"];
1063
+ if (whole(p.slot_position) && p.slot_position > 0)
1064
+ parts.push(p.slot_position + (whole(p.waiting_count) && p.waiting_count >= p.slot_position ? " of " + p.waiting_count : ""));
1065
+ } else return null;
1066
+ parts.push(pushAge(p.since, now));
1067
+ return "⏳ " + parts.join(" · ");
1068
+ }
1069
+ function pushWaitBadge(el, key, p, now) {
1070
+ const text = pushWaitText(p, now);
1071
+ if (!text) return [];
1072
+ const { bg, fg } = badgeColors(ICON.violet);
1073
+ const link = el.Link({ href: LINKS.pushes, label: "↗" });
1074
+ if (pills() && typeof el.Svg === "function")
1075
+ return [el.Box({ key: key + "-push", flexDirection: "row", flexShrink: 0, alignItems: "center", columnGap: 1, children: [pillSvg(el, { text, fill: bg }), link] })];
1076
+ return [
1077
+ el.Box({
1078
+ key: key + "-push",
1079
+ flexDirection: "row",
1080
+ flexShrink: 0,
1081
+ backgroundColor: bg,
1082
+ paddingX: 1,
1083
+ children: [el.Text({ color: fg, children: [text + " "] }), link],
1084
+ }),
1085
+ ];
1086
+ }
1035
1087
  // The context alarm's red pill (above 30%), or nothing.
1036
1088
  function contextBadge(el, key) {
1037
1089
  const alarm = contextAlarm(context);
@@ -1337,7 +1389,11 @@ function bandLines(el, $, inPane) {
1337
1389
  ...contextBadge(el, k("line-context")),
1338
1390
  ...uncategorisedBadge(el, k("line-project"), s.epic),
1339
1391
  ];
1340
- const waitsRow = headerRow(el, k("line-waits"), TITLES.waits, widths.ids, waitBadges(el, k("line-context"), s.waits, currentTime));
1392
+ const waitsRow = headerRow(el, k("line-waits"), TITLES.waits, widths.ids, [
1393
+ // BOT-3394: the session's own push held for compute leads its waits.
1394
+ ...pushWaitBadge(el, k("line-waits"), s.push_wait, currentTime),
1395
+ ...waitBadges(el, k("line-context"), s.waits, currentTime),
1396
+ ]);
1341
1397
  const statusRow = headerRow(el, k("line-status"), TITLES.status, widths.ids, statuses);
1342
1398
  if (waitsRow) lines.unshift(waitsRow);
1343
1399
  if (statusRow) lines.unshift(statusRow);
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.91.2",
3
- "source_commit": "04b4a85491485b854987b6d5aa08b22ba8dde6c2",
4
- "source_sha256": "32d16ac6cd57b4879a07f04cb239e20ef33638c100c8703c138c7533438f6d70",
2
+ "release_version": "1.93.0",
3
+ "source_commit": "5f725b542bdc9a9b70237cd6fab5b8fd7afab6ce",
4
+ "source_sha256": "733c52c77401497b156d678fca78ad0075aaba4b768ef615d0e6275c4d0886a3",
5
5
  "target": "darwin-arm64",
6
- "sha256": "50c4455ce224c7816d1747ceaa7d6bd98a87cb52a02a3bb6773d3d028b02ea03"
6
+ "sha256": "a481ec7dde1b215228b000aadf59b6b039f52594cf5fe437c5d0936d7b6a25f8"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.91.2",
3
- "source_commit": "04b4a85491485b854987b6d5aa08b22ba8dde6c2",
4
- "source_sha256": "32d16ac6cd57b4879a07f04cb239e20ef33638c100c8703c138c7533438f6d70",
2
+ "release_version": "1.93.0",
3
+ "source_commit": "5f725b542bdc9a9b70237cd6fab5b8fd7afab6ce",
4
+ "source_sha256": "733c52c77401497b156d678fca78ad0075aaba4b768ef615d0e6275c4d0886a3",
5
5
  "target": "linux-x64",
6
- "sha256": "8f4f4f84c54519542b2ffea144daefe97f0cd1a2adec8c006c89d6534c21cc4d"
6
+ "sha256": "82453b27c5c4d174414b9186f6043a05a798ba63c5dfc3bea080cefec1f02e24"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.91.2",
4
- "source_commit": "04b4a85491485b854987b6d5aa08b22ba8dde6c2",
5
- "source_sha256": "32d16ac6cd57b4879a07f04cb239e20ef33638c100c8703c138c7533438f6d70",
3
+ "release_version": "1.93.0",
4
+ "source_commit": "5f725b542bdc9a9b70237cd6fab5b8fd7afab6ce",
5
+ "source_sha256": "733c52c77401497b156d678fca78ad0075aaba4b768ef615d0e6275c4d0886a3",
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": "50c4455ce224c7816d1747ceaa7d6bd98a87cb52a02a3bb6773d3d028b02ea03",
11
+ "sha256": "a481ec7dde1b215228b000aadf59b6b039f52594cf5fe437c5d0936d7b6a25f8",
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": "8f4f4f84c54519542b2ffea144daefe97f0cd1a2adec8c006c89d6534c21cc4d",
18
+ "sha256": "82453b27c5c4d174414b9186f6043a05a798ba63c5dfc3bea080cefec1f02e24",
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.91.2",
3
+ "version": "1.93.0",
4
4
  "description": "BotBuddy — Swarm coordination CLI for multi-agent workflows",
5
5
  "type": "module",
6
6
  "bin": {
package/src/commands.mjs CHANGED
@@ -16,6 +16,7 @@ import { cmdStack } from "./stack.mjs";
16
16
  import { cmdManagedAllocation } from "./managed-allocation.mjs";
17
17
  import { cmdDocker } from "./docker-hygiene.mjs";
18
18
  import { cmdRun } from "./run.mjs";
19
+ import { cmdPush } from "./push.mjs";
19
20
  import { cmdTest } from "./test-lane.mjs";
20
21
  import { cmdEvidence } from "./evidence.mjs";
21
22
  import { cmdFeedback } from "./feedback.mjs";
@@ -66,7 +67,7 @@ export function shouldCheckForUpdates(argv) {
66
67
  export const LOCAL_HELP_COMMANDS = Object.freeze([
67
68
  "wait", "stack", "pw", "docker", "run", "mcp", "login", "setup", "doctor", "host",
68
69
  "staging-pool", "daemon", "evidence", "feedback", "usage", "telemetry", "allocation",
69
- "release-notes", "status-band",
70
+ "release-notes", "status-band", "push",
70
71
  ]);
71
72
  const HELP_WORDS = new Set(["help", "--help", "-h"]);
72
73
 
@@ -143,6 +144,8 @@ export async function run(argv, {
143
144
  case "docker": return cmdDocker(args);
144
145
  case "daemon": return cmdDaemon(args);
145
146
  case "run": return cmdRun(args);
147
+ // BOT-3362: the push as a tracked, waitable command run.
148
+ case "push": return cmdPush(args);
146
149
  case "telemetry": return cmdTelemetry(args);
147
150
  // BOT-803: local Claude/Codex token usage → usage-ingest (fail-open).
148
151
  case "usage": {
@@ -341,6 +344,7 @@ ${bold("DURABLE WORKLOADS")} (${cyan("bb help run")})
341
344
  Run locally with a durable lifecycle outbox
342
345
  run status <run_id> Read status and exact available log or receipt commands
343
346
  run inspect|cancel <run_id> Read or stop one command run
347
+ push [git push args] Push as a tracked run: lanes, compute hold, receipt
344
348
  telemetry <status|replay|doctor>
345
349
  Inspect, replay, or gate durable lifecycle delivery
346
350
 
@@ -0,0 +1,173 @@
1
+ // BOT-3362 — what a `bb push` run is doing, read from the worktree's own lane records.
2
+ //
3
+ // The pre-push lanes (scripts/log-test-run.mjs) keep one open record per running lane
4
+ // in `.botbuddy/test-runs/.lanes-open/` — with its live phase and, since BOT-3393, the
5
+ // compute gate's wait (`context.compute`) — and the push's per-lane results in
6
+ // `.botbuddy/test-runs/.invocation-state.json`. This module turns those into the push's
7
+ // live phase (for its status file and a waiting_over wake) and its receipt summary.
8
+ // Dependency-free: it reads local files only, never the network.
9
+
10
+ import { readFileSync, readdirSync, watch } from "node:fs";
11
+ import { dirname, basename, join } from "node:path";
12
+
13
+ export const PUSH_LOCK_FILE = "push.lock.json";
14
+ const TEST_RUNS = join(".botbuddy", "test-runs");
15
+ // `canceled_signal`: the lane's child was killed (e.g. OOM SIGKILL) and the hook still refused the push.
16
+ const FAILED_LANE_OUTCOMES = new Set(["failed", "timed_out", "crashed", "abandoned", "canceled_signal"]);
17
+
18
+ function readJson(path) {
19
+ try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
20
+ }
21
+
22
+ function pidAlive(pid) {
23
+ if (!Number.isInteger(pid) || pid <= 0) return false;
24
+ try { process.kill(pid, 0); return true; } catch (err) { return err.code === "EPERM"; }
25
+ }
26
+
27
+ /** The open lane records of live lanes in a worktree (a dead lane's record is ignored). */
28
+ export function readOpenLaneRecords(root, { alive = pidAlive } = {}) {
29
+ const dir = join(root, TEST_RUNS, ".lanes-open");
30
+ let names = [];
31
+ try { names = readdirSync(dir); } catch { return []; }
32
+ return names.filter((n) => n.endsWith(".json")).map((n) => readJson(join(dir, n))).filter((m) => m && alive(m.pid));
33
+ }
34
+
35
+ export function readInvocationState(root) {
36
+ return readJson(join(root, TEST_RUNS, ".invocation-state.json"));
37
+ }
38
+
39
+ /** This push's invocation: one that started after the push was launched. */
40
+ function ownInvocation(invocationState, launchedAt) {
41
+ if (!invocationState || !invocationState.started_at) return null;
42
+ return Date.parse(invocationState.started_at) >= Date.parse(launchedAt) ? invocationState : null;
43
+ }
44
+
45
+ /**
46
+ * The live phase: `waiting` (a lane holds for compute: reason, lane, since, load,
47
+ * position), `hooks` (lanes run), or `pushing` (this push's hooks finished, git pushes).
48
+ */
49
+ export function derivePushPhase({ markers: allMarkers = [], invocationState = null, launchedAt }) {
50
+ // Codex #1815: only this push's own lanes count — another invocation's lane in the
51
+ // same worktree (an older push, an ad-hoc lane) must never read as this push holding.
52
+ const own = ownInvocation(invocationState, launchedAt);
53
+ const prefix = own?.invocation_id ? `lefthook:${own.invocation_id}:` : null;
54
+ const markers = prefix ? allMarkers.filter((m) => String(m?.source_run_id ?? "").startsWith(prefix)) : [];
55
+ const waiting = markers
56
+ .filter((m) => m?.context?.phase === "waiting")
57
+ .sort((a, b) => String(a.phase_since ?? "").localeCompare(String(b.phase_since ?? "")));
58
+ if (waiting.length) {
59
+ const first = waiting[0];
60
+ const compute = first.context.compute ?? {};
61
+ return {
62
+ // A compute hold names its gate reason; any other wait (a stack lease, hermetic
63
+ // capacity) names the lane's own reason, and carries no load or slot position.
64
+ phase: "waiting", reason: compute.reason ?? first.reason ?? null, lane: first.lane ?? null, waiting_since: first.phase_since ?? null,
65
+ load_ratio: compute.reason ? compute.load_ratio ?? null : null, slot_position: compute.reason ? compute.slot_position ?? null : null, waiting_lanes: waiting.length,
66
+ };
67
+ }
68
+ if (markers.length) return { phase: "hooks", lanes_running: markers.length };
69
+ if (own?.finished) return { phase: "pushing" };
70
+ return { phase: "hooks", lanes_running: 0 };
71
+ }
72
+
73
+ /** One line naming the push's phase (the run's meaningful transition, ≤160 chars). */
74
+ export function pushTransitionText(phase) {
75
+ if (phase?.phase === "pushing") return "push: hooks finished, pushing";
76
+ if (phase?.phase !== "waiting") return "push: running pre-push lanes";
77
+ const lane = phase.lane ?? "a lane";
78
+ const text = phase.reason === "host_load" ? `push waiting for host compute · ${phase.load_ratio ?? "?"}× load · ${lane}`
79
+ : phase.reason === "compute_slot" ? `push waiting for a compute slot · position ${phase.slot_position ?? "?"} · ${lane}`
80
+ : `push waiting: ${phase.reason ?? "unknown"} · ${lane}`;
81
+ return text.slice(0, 160);
82
+ }
83
+
84
+ const sumOrNull = (values) => {
85
+ const present = values.filter((v) => Number.isFinite(v));
86
+ return present.length ? present.reduce((a, b) => a + b, 0) : null;
87
+ };
88
+
89
+ /** The receipt's `push` field: each lane's result and compute wait, and the outcome. */
90
+ export function pushSummary({ status, gate, launchedAt, invocationState }) {
91
+ const own = gate === "ungated" ? null : ownInvocation(invocationState, launchedAt);
92
+ const lanes = Object.entries(own?.lanes ?? {}).map(([lane, v]) => ({
93
+ lane, outcome: v?.outcome ?? null, waiting_ms: v?.waiting_ms ?? 0,
94
+ slot_wait_ms: v?.compute?.slot_wait_ms ?? null, load_wait_ms: v?.compute?.load_wait_ms ?? null,
95
+ load_ratio_at_start: v?.compute?.load_ratio_at_start ?? null,
96
+ }));
97
+ const outcome = {
98
+ success: "pushed", cancelled: "interrupted", timed_out: "timed_out", owner_lost: "owner_lost",
99
+ failure: lanes.some((l) => FAILED_LANE_OUTCOMES.has(l.outcome)) ? "hooks_failed" : "push_failed",
100
+ }[status] ?? status;
101
+ return {
102
+ outcome,
103
+ gate: gate === "ungated" ? "ungated" : own ? "gated" : "no_hooks",
104
+ invocation_id: own?.invocation_id ?? null,
105
+ lanes,
106
+ slot_wait_ms: sumOrNull(lanes.map((l) => l.slot_wait_ms)),
107
+ load_wait_ms: sumOrNull(lanes.map((l) => l.load_wait_ms)),
108
+ };
109
+ }
110
+
111
+ /**
112
+ * Wake once the push has held for compute for `thresholdSeconds`. Event-driven: a
113
+ * change to the status file re-evaluates, and a timer fires at the exact moment the
114
+ * threshold passes; `recheckMs` is only a backstop for a missed file event.
115
+ * Resolves to a matched entry; `stop()` releases the watch and timers.
116
+ */
117
+ export function watchPushWaiting({
118
+ runId, thresholdSeconds, readStatus, onChange, conditionId = null,
119
+ now = Date.now, setTimeoutFn = setTimeout, clearTimeoutFn = clearTimeout, recheckMs = 15_000,
120
+ }) {
121
+ let resolveMatch;
122
+ const promise = new Promise((resolve) => { resolveMatch = resolve; });
123
+ let timer = null;
124
+ let done = false;
125
+ let unsubscribe = () => {};
126
+ const stop = () => {
127
+ done = true;
128
+ if (timer) clearTimeoutFn(timer);
129
+ timer = null;
130
+ try { unsubscribe(); } catch { /* already closed */ }
131
+ };
132
+ const evaluate = () => {
133
+ if (done) return;
134
+ if (timer) clearTimeoutFn(timer);
135
+ timer = null;
136
+ const status = readStatus();
137
+ let next = recheckMs;
138
+ const since = Date.parse(status?.waiting_since ?? "");
139
+ if (status?.phase === "waiting" && Number.isFinite(since)) {
140
+ const waitedMs = now() - since;
141
+ if (waitedMs >= thresholdSeconds * 1000) {
142
+ const match = {
143
+ condition_id: conditionId, signal_type: "push_waiting", subject_key: `run:${runId}`,
144
+ payload: {
145
+ run_id: runId, phase: "waiting", reason: status.reason ?? null, lane: status.lane ?? null, waiting_since: status.waiting_since,
146
+ waited_seconds: Math.floor(waitedMs / 1000), load_ratio: status.load_ratio ?? null, slot_position: status.slot_position ?? null,
147
+ threshold_seconds: thresholdSeconds,
148
+ },
149
+ };
150
+ stop();
151
+ resolveMatch(match);
152
+ return;
153
+ }
154
+ next = Math.min(next, thresholdSeconds * 1000 - waitedMs);
155
+ }
156
+ timer = setTimeoutFn(evaluate, next);
157
+ timer?.unref?.();
158
+ };
159
+ unsubscribe = onChange(evaluate) ?? (() => {});
160
+ evaluate();
161
+ return { promise, stop };
162
+ }
163
+
164
+ /** Watch a status file's directory for changes to that file. Returns the unsubscribe. */
165
+ export function watchFile(path, fn) {
166
+ try {
167
+ const watcher = watch(dirname(path), (_event, name) => { if (!name || name === basename(path)) fn(); });
168
+ watcher.unref?.();
169
+ return () => watcher.close();
170
+ } catch {
171
+ return () => {};
172
+ }
173
+ }
package/src/push.mjs ADDED
@@ -0,0 +1,289 @@
1
+ // BOT-3362 — `bb push`: the push as a tracked, waitable command run.
2
+ //
3
+ // `git push` runs the pre-push lanes, and on a loaded host those lanes can hold for
4
+ // compute for hours (BOT-2391) with nothing outside the hook showing why. `bb push`
5
+ // launches `git push …` as a BOT-1350 detached command run (`tool_category git_push`)
6
+ // bound to this worktree's session, ticket, branch and head SHA, and:
7
+ // * keeps one push per worktree (a pid-fenced `.botbuddy/push.lock.json`);
8
+ // * has its worker write the push's live phase (hooks / waiting with reason, lane,
9
+ // load and since / pushing) to `<run context>.push.json`, and name each phase
10
+ // change on the run as a meaningful transition;
11
+ // * adds a `push` summary to the receipt: each lane's result and slot / load wait;
12
+ // * is waited on with `bb wait 'push:id=<id>'` (the command-run terminal), and
13
+ // `waiting_over=<s>` also wakes once the push has held for compute that long.
14
+
15
+ import { linkSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
16
+ import { execFileSync } from "node:child_process";
17
+ import { join } from "node:path";
18
+ import { EXIT, RUN_SCHEMA_VERSION, contextPath, launchRun } from "./run.mjs";
19
+ import { DELIVERY_CALL_TIMEOUT_MS } from "./run-delivery.mjs";
20
+ import {
21
+ PUSH_LOCK_FILE, derivePushPhase, pushSummary, pushTransitionText, readInvocationState, readOpenLaneRecords, watchFile, watchPushWaiting,
22
+ } from "./push-status.mjs";
23
+
24
+ export { PUSH_LOCK_FILE, derivePushPhase, pushSummary, pushTransitionText, watchPushWaiting } from "./push-status.mjs";
25
+
26
+ /** Where a push run's worker writes its live phase (beside the sealed run context). */
27
+ export function pushStatusPath(runId) { return `${contextPath(runId)}.push.json`; }
28
+
29
+ function pidAlive(pid) {
30
+ if (!Number.isInteger(pid) || pid <= 0) return false;
31
+ try { process.kill(pid, 0); return true; } catch (err) { return err.code === "EPERM"; }
32
+ }
33
+
34
+ function readJson(path) {
35
+ try { return JSON.parse(readFileSync(path, "utf8")); } catch { return null; }
36
+ }
37
+
38
+ function writeJsonAtomic(path, value) {
39
+ const tmp = `${path}.${process.pid}.tmp`;
40
+ writeFileSync(tmp, JSON.stringify(value), { mode: 0o600 });
41
+ renameSync(tmp, path);
42
+ }
43
+
44
+ function worktreeRoot(cwd) {
45
+ try { return execFileSync("git", ["rev-parse", "--show-toplevel"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); }
46
+ catch { return cwd; }
47
+ }
48
+
49
+ const pushWait = (runId) => `bb wait 'push:id=${runId}'`;
50
+
51
+ /** A lock record (or reclaim mutex) this old with no readable owner was left by a crash. */
52
+ export const PUSH_LOCK_STALE_MS = 30_000;
53
+
54
+ function ageMs(path) {
55
+ try { return Date.now() - statSync(path).mtimeMs; } catch { return Infinity; }
56
+ }
57
+
58
+ /** Create `path` atomically WITH its content (write a temp file, hard-link it in). */
59
+ function linkCreate(path, content) {
60
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
61
+ writeFileSync(tmp, content, { mode: 0o600 });
62
+ try { linkSync(tmp, path); } finally { rmSync(tmp, { force: true }); }
63
+ }
64
+
65
+ /**
66
+ * Take the worktree's push lock, or report the push that holds it. Codex #1815: the
67
+ * record is created with its content (no half-written window); an unreadable record
68
+ * is held unless it is stale; and a dead holder's lock is removed only under a
69
+ * reclaim mutex, after re-reading that it is still the same dead record.
70
+ */
71
+ /**
72
+ * Codex #1815: whether a push run is still alive, from its sealed context: its worker,
73
+ * or its workload's process group (git and hooks can outlive a crashed worker), or a
74
+ * run whose context was just sealed and whose worker has not recorded itself yet.
75
+ */
76
+ function runAlive(runId, { readRunContext, contextAgeMs, alive }) {
77
+ if (!runId) return false;
78
+ const context = readRunContext(runId);
79
+ if (!context) return false;
80
+ if (alive(context.worker_pid)) return true;
81
+ const group = context.workload_pid;
82
+ if (Number.isInteger(group) && group > 0) {
83
+ try { process.kill(-group, 0); return true; } catch (err) { if (err.code === "EPERM") return true; }
84
+ if (alive(group)) return true;
85
+ }
86
+ return !Number.isInteger(context.worker_pid) && contextAgeMs(runId) < PUSH_LOCK_STALE_MS;
87
+ }
88
+
89
+ function takePushLock(lockPath, { alive, workloadAlive }) {
90
+ const held = (record) => Boolean(record) && (alive(record.pid) || workloadAlive(record.run_id));
91
+ const record = () => JSON.stringify({ run_id: null, pid: process.pid, created_at: new Date().toISOString() });
92
+ const mutexPath = `${lockPath}.reclaim`;
93
+ for (let attempt = 0; attempt < 3; attempt += 1) {
94
+ try {
95
+ linkCreate(lockPath, record());
96
+ return { taken: true };
97
+ } catch (err) {
98
+ if (err.code !== "EEXIST") throw err;
99
+ }
100
+ const holder = readJson(lockPath);
101
+ if (held(holder)) return { taken: false, holder };
102
+ if (!holder && ageMs(lockPath) < PUSH_LOCK_STALE_MS) return { taken: false, holder: null };
103
+ // Reclaim a dead (or long-unreadable) holder's lock under the mutex.
104
+ if (ageMs(mutexPath) >= PUSH_LOCK_STALE_MS) rmSync(mutexPath, { force: true });
105
+ try { linkCreate(mutexPath, String(process.pid)); } catch (err) {
106
+ if (err.code === "EEXIST") return { taken: false, holder };
107
+ throw err;
108
+ }
109
+ try {
110
+ const again = readJson(lockPath);
111
+ const same = JSON.stringify(again) === JSON.stringify(holder);
112
+ if (same && !held(again)) rmSync(lockPath, { force: true });
113
+ else if (held(again)) return { taken: false, holder: again };
114
+ } finally {
115
+ rmSync(mutexPath, { force: true });
116
+ }
117
+ }
118
+ return { taken: false, holder: readJson(lockPath) };
119
+ }
120
+
121
+ /**
122
+ * Launch `git push <argv>` as a tracked push run from `root`.
123
+ * `runFlags` are extra `bb run` flags (for example `--session-id`); the session is
124
+ * otherwise resolved like `bb run`'s.
125
+ */
126
+ export async function launchPush(argv, {
127
+ root = worktreeRoot(process.cwd()), runFlags = [], call = null, spawnImpl, env = process.env, alive = pidAlive, launch = launchRun,
128
+ readRunContext = (runId) => readJson(contextPath(runId)), contextAgeMs = (runId) => ageMs(contextPath(runId)),
129
+ workloadAlive = (runId) => runAlive(runId, { readRunContext, contextAgeMs, alive }),
130
+ } = {}) {
131
+ const dir = join(root, ".botbuddy");
132
+ mkdirSync(dir, { recursive: true });
133
+ const lockPath = join(dir, PUSH_LOCK_FILE);
134
+ const lock = takePushLock(lockPath, { alive, workloadAlive });
135
+ if (!lock.taken) {
136
+ const runId = lock.holder?.run_id ?? null;
137
+ return { exitCode: EXIT.INVALID, receipt: {
138
+ schema_version: RUN_SCHEMA_VERSION, outcome: "refused", error: "push_in_progress", run_id: runId,
139
+ message: runId ? `A push from this worktree is already running (${runId}); wait for it instead of starting another.` : "A push from this worktree is already starting.",
140
+ ...(runId ? { wait_command: pushWait(runId) } : {}), exit_code: EXIT.INVALID,
141
+ } };
142
+ }
143
+ // LEFTHOOK=0 skips every pre-push lane: the push is recorded as ungated, not hidden.
144
+ const gate = env.LEFTHOOK === "0" ? "ungated" : "gated";
145
+ let result;
146
+ try {
147
+ result = await launch([...runFlags, "--environment", "local", "--category", "git_push", "--", "git", "push", ...argv], {
148
+ cwd: root, env, ...(call ? { call } : {}), ...(spawnImpl ? { spawnImpl } : {}), push: { root, gate },
149
+ // Codex #1815: the lock names its run before the worker starts, so a launcher
150
+ // killed at the handoff leaves a lock its live run still holds.
151
+ beforeSpawn: (runId) => writeJsonAtomic(lockPath, { run_id: runId, pid: process.pid, created_at: new Date().toISOString() }),
152
+ });
153
+ } catch (err) {
154
+ rmSync(lockPath, { force: true });
155
+ throw err;
156
+ }
157
+ if (result.exitCode !== EXIT.OK || result.receipt?.outcome !== "launched") {
158
+ rmSync(lockPath, { force: true });
159
+ return result;
160
+ }
161
+ const runId = result.receipt.run_id;
162
+ // The detached worker owns the push from here; its pid fences the lock.
163
+ writeJsonAtomic(lockPath, { run_id: runId, pid: result.workerPid ?? process.pid, created_at: new Date().toISOString() });
164
+ return { exitCode: EXIT.OK, receipt: {
165
+ ...result.receipt, gate, push_lock: lockPath, status_path: pushStatusPath(runId),
166
+ wait_command: pushWait(runId), waiting_wait_command: `bb wait 'push:id=${runId},waiting_over=1800'`,
167
+ } };
168
+ }
169
+
170
+ /**
171
+ * Worker side: track the push's live phase while git runs, and name each change on
172
+ * the run. Returns `stop()`; it never throws into the worker.
173
+ */
174
+ export function startPushMonitor(context, call, {
175
+ intervalMs = 2_000, setIntervalFn = setInterval, statusPath = `${context.context_path}.push.json`, stopBudgetMs = 2_000,
176
+ } = {}) {
177
+ const root = context.push.root;
178
+ const lockPath = join(root, ".botbuddy", PUSH_LOCK_FILE);
179
+ try {
180
+ const lock = readJson(lockPath);
181
+ if (lock?.run_id === context.run_id) writeJsonAtomic(lockPath, { ...lock, pid: process.pid });
182
+ } catch { /* the launcher's record still fences the push */ }
183
+ let last = null;
184
+ let chain = Promise.resolve();
185
+ const tick = () => {
186
+ let phase;
187
+ try {
188
+ phase = context.push.gate === "ungated" ? { phase: "pushing" } : derivePushPhase({ markers: readOpenLaneRecords(root), invocationState: readInvocationState(root), launchedAt: context.launched_at });
189
+ writeJsonAtomic(statusPath, { run_id: context.run_id, ...phase, updated_at: new Date().toISOString() });
190
+ } catch { return; }
191
+ const key = `${phase.phase}:${phase.reason ?? ""}:${phase.lane ?? ""}`;
192
+ if (key === last) return;
193
+ last = key;
194
+ const text = pushTransitionText(phase);
195
+ // Codex #1815: an advisory phase update is bounded, like the worker lease's renewals,
196
+ // so a stalled call can never hold back the push's receipt or its lock release.
197
+ chain = chain.then(() => call("update_command_run", { run_id: context.run_id, run_credential: context.run_credential, status: "running", meaningful_transition: text }, {
198
+ signal: AbortSignal.timeout(DELIVERY_CALL_TIMEOUT_MS),
199
+ ...(typeof context.server_url === "string" && context.server_url ? { serverUrl: context.server_url } : {}),
200
+ })).catch(() => {});
201
+ };
202
+ tick();
203
+ const timer = setIntervalFn(tick, intervalMs);
204
+ timer.unref?.();
205
+ return {
206
+ async stop() {
207
+ clearInterval(timer);
208
+ let bound;
209
+ await Promise.race([chain, new Promise((resolve) => { bound = setTimeout(resolve, stopBudgetMs); bound.unref?.(); })]);
210
+ clearTimeout(bound);
211
+ try { writeJsonAtomic(statusPath, { run_id: context.run_id, phase: "done", updated_at: new Date().toISOString() }); } catch { /* best effort */ }
212
+ },
213
+ };
214
+ }
215
+
216
+ /** The receipt's push summary for a finished run, and release of the worktree lock. */
217
+ export function finishPush(context, status) {
218
+ const summary = pushSummary({ status, gate: context.push.gate, launchedAt: context.launched_at, invocationState: readInvocationState(context.push.root) });
219
+ const lockPath = join(context.push.root, ".botbuddy", PUSH_LOCK_FILE);
220
+ if (readJson(lockPath)?.run_id === context.run_id) rmSync(lockPath, { force: true });
221
+ return summary;
222
+ }
223
+
224
+ function watchCondition(condition) {
225
+ const path = pushStatusPath(condition.params.runId);
226
+ return watchPushWaiting({
227
+ runId: condition.params.runId, thresholdSeconds: condition.params.waitingOver, conditionId: condition.id,
228
+ readStatus: () => readJson(path), onChange: (fn) => watchFile(path, fn),
229
+ });
230
+ }
231
+
232
+ /**
233
+ * `bb wait` side: the local waiting_over trigger for the push conditions, or null.
234
+ * Codex #1815: every threshold-bearing push condition is watched; the first to fire
235
+ * wins, and stop() releases them all.
236
+ */
237
+ export function pushLocalTrigger(conditions, { watch = watchCondition } = {}) {
238
+ const watchers = conditions.filter((c) => c.type === "push" && c.params.waitingOver).map((c) => watch(c));
239
+ if (!watchers.length) return null;
240
+ return {
241
+ promise: Promise.race(watchers.map((w) => w.promise)),
242
+ stop() { for (const w of watchers) { try { w.stop(); } catch { /* already released */ } } },
243
+ };
244
+ }
245
+
246
+ /**
247
+ * `bb push [--rerun-reason <json>] [--] [git push args]`. Only a leading
248
+ * --rerun-reason is ours (a retry of a push at the same commit repeats the run's
249
+ * fingerprint, which the server refuses without a reason); the rest is git push's.
250
+ */
251
+ export function parsePushArgs(argv) {
252
+ const runFlags = [];
253
+ const errors = [];
254
+ let i = 0;
255
+ while (i < argv.length && argv[i] === "--rerun-reason") {
256
+ if (argv[i + 1] == null) { errors.push("--rerun-reason needs a JSON object"); i += 1; break; }
257
+ runFlags.push("--rerun-reason", argv[i + 1]);
258
+ i += 2;
259
+ }
260
+ const rest = argv.slice(i);
261
+ return { runFlags, gitArgs: rest[0] === "--" ? rest.slice(1) : rest, errors };
262
+ }
263
+
264
+ export async function cmdPush(argv, { out = (s) => process.stdout.write(s) } = {}) {
265
+ if (argv[0] === "--help" || argv[0] === "-h") {
266
+ out(`bb push [--rerun-reason <json>] [git push args] — run the push as a tracked, waitable command run (BOT-3362).
267
+
268
+ Launches \`git push <args>\` (its pre-push lanes and the push) as a detached bb run
269
+ bound to this worktree, prints the run id, and returns at once. Wait on it with:
270
+ bb wait 'push:id=<run_id>' the push's terminal receipt
271
+ bb wait 'push:id=<run_id>,waiting_over=1800' also wake if it holds for compute 30 min
272
+ The receipt's \`push\` field lists each lane's result and its compute slot / load wait.
273
+ One push per worktree: a second is refused with the first's id (exit 4).
274
+ LEFTHOOK=0 pushes are recorded as ungated.
275
+ `);
276
+ return EXIT.OK;
277
+ }
278
+ const { runFlags, gitArgs, errors } = parsePushArgs(argv);
279
+ if (errors.length) {
280
+ out(`${JSON.stringify({ schema_version: RUN_SCHEMA_VERSION, outcome: "rejected", errors, exit_code: EXIT.INVALID })}\n`);
281
+ return EXIT.INVALID;
282
+ }
283
+ const { exitCode, receipt } = await launchPush(gitArgs, { runFlags });
284
+ if (receipt?.error === "rerun_reason_required") {
285
+ receipt.hint = "This commit was already pushed with bb push in this session. Retry with: bb push --rerun-reason '{\"code\":\"flaky_suspected\",\"detail\":\"<why>\"}' <git push args>";
286
+ }
287
+ out(`${JSON.stringify(receipt)}\n`);
288
+ return exitCode;
289
+ }
package/src/run.mjs CHANGED
@@ -25,6 +25,7 @@ import { createTelemetryOutbox } from "./telemetry-outbox.mjs";
25
25
  import { deliverExecutionEvent } from "./telemetry-delivery.mjs";
26
26
  import { attestTelemetryCredential, loadTelemetryIdentity } from "./telemetry-config.mjs";
27
27
  import { VERSION } from "./version.mjs";
28
+ import { finishPush, startPushMonitor } from "./push.mjs";
28
29
  import {
29
30
  TERMINAL_RETRY_BUDGET_MS, DELIVERY_CALL_TIMEOUT_MS, callWithContextIdentity, classifyTerminalUpdateFailure, contextServerUrl,
30
31
  ensureRunDelivery, parkedRecord, runDelivery, terminalUpdateAccepted,
@@ -679,7 +680,7 @@ function rejectedSessionReceipt(error, runId) {
679
680
  }
680
681
 
681
682
  export async function launchRun(argv, {
682
- cwd = process.cwd(), spawnImpl = spawn, call = null, childEnv = null, testRun = null,
683
+ cwd = process.cwd(), spawnImpl = spawn, call = null, childEnv = null, testRun = null, push = null, beforeSpawn = null,
683
684
  resolveCredential = null, renewCredential = selfHealAgentSession, env = process.env, getSourceSha = sourceSha,
684
685
  } = {}) {
685
686
  const parsed = parseRunArgs(argv, env);
@@ -747,10 +748,14 @@ export async function launchRun(argv, {
747
748
  // every callback is attributable to the same agent. It deliberately stays
748
749
  // outside child_env, receipts, and the workload's process environment.
749
750
  const knownSession = opts.sessionId ?? managedCredential?.identity?.sessionId ?? managedCredential?.sessionId;
750
- await writeJson(context, { schema_version: RUN_SCHEMA_VERSION, context_path: context, run_id: runId, run_credential: registration.data.run_credential, receipt_upload: registration.data.receipt_upload, command, command_hash: commandFingerprint, source_sha: launchSourceSha, cwd, timeout_seconds: opts.timeout, receipt_path: receipt, launched_at: new Date().toISOString(), server_url: SERVER_URL, worker_heartbeat_ttl_seconds: WORKER_HEARTBEAT_TTL_SECONDS, ...(opts.sessionToken ? { callback_session_token: opts.sessionToken } : {}), ...(knownSession ? { callback_session_id: knownSession } : {}), ...(childEnv && Object.keys(childEnv).length ? { child_env: childEnv } : {}), ...(testRun ? { test_run: testRun } : {}) });
751
+ await writeJson(context, { schema_version: RUN_SCHEMA_VERSION, context_path: context, run_id: runId, run_credential: registration.data.run_credential, receipt_upload: registration.data.receipt_upload, command, command_hash: commandFingerprint, source_sha: launchSourceSha, cwd, timeout_seconds: opts.timeout, receipt_path: receipt, launched_at: new Date().toISOString(), server_url: SERVER_URL, worker_heartbeat_ttl_seconds: WORKER_HEARTBEAT_TTL_SECONDS, ...(opts.sessionToken ? { callback_session_token: opts.sessionToken } : {}), ...(knownSession ? { callback_session_id: knownSession } : {}), ...(childEnv && Object.keys(childEnv).length ? { child_env: childEnv } : {}), ...(testRun ? { test_run: testRun } : {}), ...(push ? { push } : {}) });
752
+ // BOT-3362: a caller may bind its own ownership record to the run before the worker starts.
753
+ if (beforeSpawn) await beforeSpawn(runId);
751
754
  const [file, args] = workerInvocation(context);
755
+ let workerPid = null;
752
756
  try {
753
757
  const worker = spawnImpl(file, args, { detached: true, stdio: "ignore", windowsHide: true });
758
+ workerPid = Number.isInteger(worker.pid) ? worker.pid : null;
754
759
  worker.unref();
755
760
  } catch (error) {
756
761
  // BOT-1572 (Codex P2): use effectiveCall — `call` may be null (the token-pinned
@@ -758,7 +763,7 @@ export async function launchRun(argv, {
758
763
  await effectiveCall("update_command_run", { run_id: runId, run_credential: registration.data.run_credential, status: "owner_lost", invalidated_reason: `launcher_failed:${error instanceof Error ? error.message : String(error)}` });
759
764
  return { exitCode: EXIT.INTERNAL, receipt: { schema_version: RUN_SCHEMA_VERSION, outcome: "owner_lost", run_id: runId, exit_code: EXIT.INTERNAL } };
760
765
  }
761
- return { exitCode: EXIT.OK, receipt: { schema_version: RUN_SCHEMA_VERSION, outcome: "launched", run_id: runId,
766
+ return { exitCode: EXIT.OK, workerPid, receipt: { schema_version: RUN_SCHEMA_VERSION, outcome: "launched", run_id: runId,
762
767
  ...(knownSession ? { session_id: knownSession } : { session_binding: "server_derived" }),
763
768
  durable_owner: "detached_worker", receipt_path: receipt, reentry: "update_command_run publishes the terminal callback for this run_id",
764
769
  // BOT-2318: the exact pending wait for this run. Keep its result pending in
@@ -877,6 +882,8 @@ export async function runWorker(contextFile, {
877
882
  // BOT-1510: for a test lane, tail the reporter's NDJSON and flush per-case
878
883
  // verdicts while the child runs. The test process never touches the network.
879
884
  const lane = context.test_run ? startLaneFlusher(context, callbackCall) : null;
885
+ // BOT-3362: a push run tracks its live phase (hooks / waiting / pushing) while git runs.
886
+ const pushMonitor = context.push ? startPushMonitor(context, callbackCall) : null;
880
887
  let killTimer;
881
888
  const timer = setTimeout(() => {
882
889
  timedOut = true;
@@ -891,6 +898,7 @@ export async function runWorker(contextFile, {
891
898
  await logWrites;
892
899
  await cancellationStateWrite;
893
900
  if (lane) await lane.stop();
901
+ if (pushMonitor) await pushMonitor.stop();
894
902
  const endedAt = new Date().toISOString();
895
903
  if (result.error) {
896
904
  const receipt = await finalize(context, { status: "owner_lost", startedAt, endedAt, exitCode: null, signal: null, reason: `workload_spawn_failed:${result.error.message}`, output: capture.output, outputCharacters: capture.characters }, callbackCall, retry);
@@ -1205,6 +1213,10 @@ async function finalize(context, state, call, retry = {}) {
1205
1213
  const progress = laneProgressFromText(events);
1206
1214
  if (progress) receipt.test_counts = progress;
1207
1215
  }
1216
+ // BOT-3362: each pre-push lane's result and compute wait, and the push's outcome.
1217
+ if (context.push) {
1218
+ try { receipt.push = finishPush(context, state.status); } catch { /* the command receipt stands without it */ }
1219
+ }
1208
1220
  await writeJson(context.receipt_path, receipt);
1209
1221
  const bytes = await stat(context.receipt_path);
1210
1222
  const sha256 = createHash("sha256").update(await readFile(context.receipt_path)).digest("hex");
@@ -124,6 +124,19 @@ function waitsOf(own) {
124
124
  .map((i) => ({ id: i.id.toLowerCase(), label: safeText(i.label).slice(0, 40), created_at: new Date(i.created_at).toISOString() }));
125
125
  return { count: w.active, oldest_at: new Date(w.oldest_at).toISOString(), items };
126
126
  }
127
+ // BOT-3394 AC-1/AC-2: the session's own push held at the compute gate, for the
128
+ // band's WAITS row; null when none, from an older BB, or anything malformed.
129
+ function pushWaitOf(own) {
130
+ const p = own?.push_wait;
131
+ if (!p || typeof p !== "object" || !["host_load", "compute_slot"].includes(p.reason)) return null;
132
+ if (typeof p.waiting_since !== "string" || !Number.isFinite(Date.parse(p.waiting_since))) return null;
133
+ const count = (v) => (v == null ? null : Number.isSafeInteger(v) && v >= 0 && v <= 999 ? v : undefined);
134
+ const ratio = p.load_ratio == null ? null : Number.isFinite(p.load_ratio) && p.load_ratio >= 0 && p.load_ratio < 10000 ? p.load_ratio : undefined;
135
+ const position = count(p.slot_position);
136
+ const waiting = count(p.waiting_count);
137
+ if (ratio === undefined || position === undefined || waiting === undefined) return null;
138
+ return { reason: p.reason, load_ratio: ratio, slot_position: position, waiting_count: waiting, since: new Date(p.waiting_since).toISOString() };
139
+ }
127
140
  function refuse(code, extra = {}) {
128
141
  throw Object.assign(new Error(code), extra);
129
142
  }
@@ -612,6 +625,9 @@ export async function readStatus({
612
625
  epic_unreadable: useSession ? false : !skipEpic && !Array.isArray(epicHealth?.epics),
613
626
  staging: ownOk ? stagingOf(own) : null,
614
627
  waits: ownOk ? waitsOf(own) : null,
628
+ // BOT-3394: absent when BB did not say (an older server), so the band knows
629
+ // whether a quiet timeout should re-read for a hold that began after this read.
630
+ ...(ownOk && "push_wait" in own ? { push_wait: pushWaitOf(own) } : {}),
615
631
  // BOT-3136: where the tickets came from — the registered session, an explicit
616
632
  // pick, or (only when the session registered none) a guess from the branch.
617
633
  binding: bindingKind,
@@ -20,13 +20,16 @@ const PROJECT = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}";
20
20
  const STAGING = "event:type=staging_incident";
21
21
  // BOT-3212 AC-2: the waits badge wakes when one of the agent's own waits starts or ends.
22
22
  const AGENT_WAITS = `event:type=agent_wait,subject=${PROJECT}`;
23
+ // BOT-3394: no signal says a held pre-push lane started, so while the band shows
24
+ // one it re-reads on this one fixed timer (the platform gap is ticketed).
25
+ export const PUSH_WAIT_TIMER = "timer:duration=60";
23
26
  const CONDITION = new RegExp(
24
- `^(?:linear:issue=${KEY}|unblocked:${KEY}|pr-(?:state|review):repo=${REPO},pr=[1-9]\\d{0,6}|event:type=linear_project,subject=${PROJECT}|${STAGING}|${AGENT_WAITS})$`,
27
+ `^(?:linear:issue=${KEY}|unblocked:${KEY}|pr-(?:state|review):repo=${REPO},pr=[1-9]\\d{0,6}|event:type=linear_project,subject=${PROJECT}|${STAGING}|${AGENT_WAITS}|${PUSH_WAIT_TIMER})$`,
25
28
  );
26
29
  const CURSOR = /^\d{1,16}$/;
27
30
  // The band's largest list: 5 tickets, 5 PRs (state + review), blockers, epic,
28
- // staging and the agent's own waits (BOT-3212).
29
- const MAX_CONDITIONS = 19;
31
+ // staging, the agent's own waits (BOT-3212) and the held-push timer (BOT-3394).
32
+ const MAX_CONDITIONS = 20;
30
33
  export const CLI_ENTRY = join(resolve(dirname(fileURLToPath(import.meta.url)), ".."), "bin", "botbuddy.mjs");
31
34
 
32
35
  function invalid() {
package/src/wait-core.mjs CHANGED
@@ -267,6 +267,21 @@ const VALIDATORS = {
267
267
  }
268
268
  return { runId };
269
269
  },
270
+ // BOT-3362: a `bb push` run. The server sees the command-run terminal condition
271
+ // (serverConditions); `waiting_over=<s>` adds a LOCAL trigger that wakes once the
272
+ // push has held for compute that long (the push runs on this machine).
273
+ push: (p) => {
274
+ const unexpected = Object.keys(p).filter((key) => key !== "id" && key !== "waiting_over");
275
+ if (unexpected.length) throw new Error(`push does not accept ${unexpected.join(", ")}`);
276
+ const runId = String(p.id ?? "").trim().toLowerCase();
277
+ if (!COMMAND_RUN_ID.test(runId)) throw new Error("push needs id=<the run id bb push printed>");
278
+ let waitingOver = null;
279
+ if (p.waiting_over !== undefined) {
280
+ waitingOver = Number(p.waiting_over);
281
+ if (!Number.isInteger(waitingOver) || waitingOver <= 0) throw new Error("push waiting_over must be a positive integer number of seconds");
282
+ }
283
+ return { runId, waitingOver };
284
+ },
270
285
  "staging-pool-refill": (p, raw) => {
271
286
  const pair = /^\s*id\s*=\s*([0-9A-Fa-f-]+)\s*$/.exec(raw ?? "");
272
287
  if (!pair || Object.keys(p).length !== 1 || p.id !== pair[1]) {
@@ -786,6 +801,14 @@ function prReviewFiltersMatch(signal, params, guard) {
786
801
  * @param {string[]} specs
787
802
  * @returns {{conditions: object[], errors: {spec: string, message: string}[]}}
788
803
  */
804
+ /**
805
+ * BOT-3362: the conditions as the relay sees them. A `push` condition is the
806
+ * server's command-run terminal condition for its run; its `waiting_over` stays local.
807
+ */
808
+ export function serverConditions(conditions) {
809
+ return conditions.map((c) => (c.type === "push" ? { id: c.id, type: "command-run", params: { runId: c.params.runId } } : c));
810
+ }
811
+
789
812
  export function parseConditions(specs) {
790
813
  const errors = [];
791
814
  const conditions = [];
@@ -812,6 +835,13 @@ export function parseConditions(specs) {
812
835
  }
813
836
  });
814
837
 
838
+ // BOT-3362 (Codex #1815): a push condition is the relay's command-run condition,
839
+ // which must be the only condition of its wait (BOT-2318). Refuse the composition
840
+ // here, with the reason, instead of letting registration refuse it later.
841
+ if (errors.length === 0 && conditions.some((c) => c.type === "push") && conditions.length > 1) {
842
+ errors.push({ spec: "push", message: "push must be the only condition of its wait (it is a command-run wait); wait on each push separately" });
843
+ }
844
+
815
845
  // A claim=true lock must be the SOLE condition. Server-side, a grant atomically
816
846
  // hands over the lock and marks the wait matched; but the client independently
817
847
  // wakes on whichever frame arrives first, so an --any wait mixing a claim with a
@@ -1443,6 +1473,7 @@ function conditionMatchesSignal(condition, signal, waitSessionId) {
1443
1473
  case "test-run":
1444
1474
  return signal.signal_type === "test_run" && signal.subject_key === `run:${params.runId}`;
1445
1475
  case "command-run":
1476
+ case "push":
1446
1477
  return signal.signal_type === "command_run" &&
1447
1478
  signal.subject_key === `run:${params.runId}` &&
1448
1479
  signal.payload?.run_id === params.runId &&
@@ -1830,6 +1861,10 @@ export async function runWaitLoop({
1830
1861
  waitSessionId,
1831
1862
  conditions,
1832
1863
  deadlineMs = null,
1864
+ // BOT-3362: an optional local wake ({promise, stop}) — e.g. a push's waiting_over.
1865
+ // Its promise resolves to a matched entry; it races every frame and alarm, and
1866
+ // stop() releases it whichever way the wait ends.
1867
+ localTrigger = null,
1833
1868
  timers = null,
1834
1869
  since = null,
1835
1870
  connect,
@@ -1930,6 +1965,7 @@ export async function runWaitLoop({
1930
1965
  };
1931
1966
 
1932
1967
  const finalize = async (outcome, extra = {}) => {
1968
+ try { localTrigger?.stop?.(); } catch { /* releasing a watcher never changes the receipt */ }
1933
1969
  // A terminal receipt supersedes any pending alarm — cancel their timers so none outlives
1934
1970
  // the wait and holds the event loop open (Codex round-40 P2).
1935
1971
  clearPendingAlarmTimers();
@@ -2085,6 +2121,12 @@ export async function runWaitLoop({
2085
2121
  });
2086
2122
  };
2087
2123
 
2124
+ // BOT-3362: a local trigger (a push held for compute past waiting_over) is a MATCH.
2125
+ const fireLocal = (match) => finalize("matched", {
2126
+ exitCode: EXIT.MATCHED,
2127
+ matched: [{ seq: null, ...match, provenance: "local" }],
2128
+ });
2129
+
2088
2130
  // The recovery grace bounds one invocation's transport work; it must never
2089
2131
  // decide the original logical wait. The caller leaves this typed result out
2090
2132
  // of the durable terminal checkpoint so `bb wait resume` can try the same
@@ -2094,9 +2136,13 @@ export async function runWaitLoop({
2094
2136
  : fireAlarm();
2095
2137
 
2096
2138
  // A single promise that resolves when the earliest alarm passes.
2097
- const deadlinePromise = replayGraceAlarm == null
2139
+ const alarmPromise = replayGraceAlarm == null
2098
2140
  ? new Promise(() => {}) // no alarm: only a pushed signal can wake us
2099
2141
  : sleepFn(Math.max(0, replayGraceAlarm.atMs - now())).then(() => ({ __deadline: true }));
2142
+ // BOT-3362: a local trigger joins the alarm race; it is never part of a durable replay.
2143
+ const deadlinePromise = localTrigger?.promise && replayOnlyThroughMs == null
2144
+ ? Promise.race([alarmPromise, localTrigger.promise.then((match) => (match ? { __local: match } : new Promise(() => {})))])
2145
+ : alarmPromise;
2100
2146
 
2101
2147
  // BOT-1147 AC-3: only probe when a linear condition is armed and a probe is
2102
2148
  // wired — every other wait type is unaffected.
@@ -2240,6 +2286,7 @@ export async function runWaitLoop({
2240
2286
  deadlinePromise,
2241
2287
  sleepFn(waitMs).then(() => ({ __retry: true })),
2242
2288
  ]);
2289
+ if (raced && raced.__local) return fireLocal(raced.__local);
2243
2290
  if (raced && raced.__deadline) return fireReplayGraceExpired();
2244
2291
  continue;
2245
2292
  }
@@ -2267,6 +2314,7 @@ export async function runWaitLoop({
2267
2314
  if (preDeadlineProbePromise && !preDeadlineProbeDone) racers.push(preDeadlineProbePromise);
2268
2315
  const raced = await Promise.race(racers);
2269
2316
 
2317
+ if (raced && raced.__local) return fireLocal(raced.__local);
2270
2318
  if (raced && raced.__deadline) return fireReplayGraceExpired();
2271
2319
  if (raced && raced.__streamDropped) {
2272
2320
  pendingNext = null;
@@ -2562,6 +2610,7 @@ export async function runWaitLoop({
2562
2610
  }
2563
2611
  const waitMs = backoff(Math.max(1, failures));
2564
2612
  const raced = await Promise.race([deadlinePromise, sleepFn(waitMs).then(() => ({ __retry: true }))]);
2565
- if (raced && raced.__deadline) return fireReplayGraceExpired();
2613
+ if (raced && raced.__local) return fireLocal(raced.__local);
2614
+ if (raced && raced.__deadline) return fireReplayGraceExpired();
2566
2615
  }
2567
2616
  }
package/src/wait.mjs CHANGED
@@ -13,7 +13,8 @@
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, parseSseFrames, runWaitLoop, normalizeSince, truncateReceipt, formatPrReviewSnapshotWarnings, prStateArmMatches, formatCiLatestRunNotice, formatUnknownWorkflowGuidance, reviewTimeoutNotice } from "./wait-core.mjs";
16
+ import { EXIT, describeConditionErrors, parseConditions, serverConditions, parseSseFrames, runWaitLoop, normalizeSince, truncateReceipt, formatPrReviewSnapshotWarnings, prStateArmMatches, formatCiLatestRunNotice, formatUnknownWorkflowGuidance, reviewTimeoutNotice } from "./wait-core.mjs";
17
+ import { pushLocalTrigger } from "./push.mjs";
17
18
  import { readAgentBinding, withPrincipalReceipt } from "./wait-profile.mjs";
18
19
  import { VERSION } from "./version.mjs";
19
20
  import { fileURLToPath } from "node:url";
@@ -165,6 +166,9 @@ CONDITIONS (TYPE:key=val,key=val — repeat for several; --any wakes on the fir
165
166
  valid workflow=/workflow_id=/workflow_path= lines.
166
167
  test-run:id=<run_id> a test run reaching a terminal status (owner-scoped);
167
168
  bb test <lane> prints the exact line to arm.
169
+ push:id=<run_id>[,waiting_over=<s>] BOT-3362: the bb push run's terminal receipt; with
170
+ waiting_over, also wake once the push has held for
171
+ host compute that many seconds (local, this machine)
168
172
  command-run:id=<run_id> BOT-2318: the bb run you registered reaching a terminal
169
173
  outcome (succeeded, failed, cancelled, timed_out,
170
174
  owner_lost, invalidated). Exit 0 on any terminal outcome;
@@ -2291,7 +2295,8 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2291
2295
  let reg;
2292
2296
  for (;;) {
2293
2297
  try {
2294
- reg = await registerWait(opts, conditions, new Date(deadlineMs).toISOString());
2298
+ // BOT-3362: a push condition reaches the relay as its command-run terminal condition.
2299
+ reg = await registerWait(opts, serverConditions(conditions), new Date(deadlineMs).toISOString());
2295
2300
  break;
2296
2301
  } catch (error) {
2297
2302
  if (!shouldRenewCachedSession(error, opts.credentialSource, attempts)) throw error;
@@ -2675,6 +2680,8 @@ export async function runWait(argv, { recoveryLocalWaitId = null } = {}) {
2675
2680
  const { receipt, exitCode } = await runWaitLoop({
2676
2681
  waitSessionId,
2677
2682
  conditions,
2683
+ // BOT-3362: a push's waiting_over is watched locally (the push runs on this machine).
2684
+ localTrigger: pushLocalTrigger(conditions),
2678
2685
  deadlineMs: loopDeadlineMs,
2679
2686
  replayOnlyThroughMs: replayExpiredRecovery ? deadlineMs : null,
2680
2687
  since: effectiveSince,