@botbuddy/cli 1.92.0 → 1.93.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,13 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.93.1
4
+
5
+ - BOT-3362: the `bb push` receipt's `push` field gains `failed_hooks`, which names each lefthook job that refused the push, read from lefthook's summary. A push refused by a job that runs outside lane telemetry (for example `pr-docs`) is now `hooks_failed`, not `push_failed`. A remote rejection, with every hook passed, stays `push_failed`.
6
+
7
+ ## 1.93.0
8
+
9
+ - 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.
10
+
3
11
  ## 1.92.0
4
12
 
5
13
  - 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.
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.92.0",
3
- "source_commit": "eb12c35b7497d8f09df520952472c18e6408aa3b",
4
- "source_sha256": "9a3dd94b97bd47f7933f5b1976304af3bc46ac253a6b767f82aba0dd32f5f485",
2
+ "release_version": "1.93.1",
3
+ "source_commit": "555e8917df316b940fdd1c9ec5ddd862f7e80f3e",
4
+ "source_sha256": "e3a8ddf0f88acf8969071e48b62b5b3f4c4ddb4ca73467b3d5a3edb9a1721500",
5
5
  "target": "darwin-arm64",
6
- "sha256": "2326c4e2c0e067851d488c64f54e25defa389ba3b2acf68b4c969cbd4bd1e0a1"
6
+ "sha256": "1639c59335acd37f14183ecc6e8a6d27682a7d84663bbd67b6dc5f9dd92b47fd"
7
7
  }
@@ -1,7 +1,7 @@
1
1
  {
2
- "release_version": "1.92.0",
3
- "source_commit": "eb12c35b7497d8f09df520952472c18e6408aa3b",
4
- "source_sha256": "9a3dd94b97bd47f7933f5b1976304af3bc46ac253a6b767f82aba0dd32f5f485",
2
+ "release_version": "1.93.1",
3
+ "source_commit": "555e8917df316b940fdd1c9ec5ddd862f7e80f3e",
4
+ "source_sha256": "e3a8ddf0f88acf8969071e48b62b5b3f4c4ddb4ca73467b3d5a3edb9a1721500",
5
5
  "target": "linux-x64",
6
- "sha256": "84c3868a88eefcdbbe22f59fe3f0b1c912aecbbb9d6cd6ec4518cf90244e52a8"
6
+ "sha256": "cb9679de790021710f9c09405d74cf1984c981e0588cdb6427006c9fa72ba0e7"
7
7
  }
@@ -1,21 +1,21 @@
1
1
  {
2
2
  "schema_version": 1,
3
- "release_version": "1.92.0",
4
- "source_commit": "eb12c35b7497d8f09df520952472c18e6408aa3b",
5
- "source_sha256": "9a3dd94b97bd47f7933f5b1976304af3bc46ac253a6b767f82aba0dd32f5f485",
3
+ "release_version": "1.93.1",
4
+ "source_commit": "555e8917df316b940fdd1c9ec5ddd862f7e80f3e",
5
+ "source_sha256": "e3a8ddf0f88acf8969071e48b62b5b3f4c4ddb4ca73467b3d5a3edb9a1721500",
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": "2326c4e2c0e067851d488c64f54e25defa389ba3b2acf68b4c969cbd4bd1e0a1",
11
+ "sha256": "1639c59335acd37f14183ecc6e8a6d27682a7d84663bbd67b6dc5f9dd92b47fd",
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": "84c3868a88eefcdbbe22f59fe3f0b1c912aecbbb9d6cd6ec4518cf90244e52a8",
18
+ "sha256": "cb9679de790021710f9c09405d74cf1984c981e0588cdb6427006c9fa72ba0e7",
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.92.0",
3
+ "version": "1.93.1",
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,191 @@
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
+ const ANSI = /\u001b\[[0-9;]*m/g;
90
+
91
+ /**
92
+ * The lefthook jobs that failed, from lefthook's own summary in the push's output
93
+ * (`✗ <job> (<n> seconds)`). It names every refusing job, including the ones that
94
+ * run outside lane telemetry (BOT-3362 acceptance, run aa131db8: `pr-docs`).
95
+ */
96
+ export function failedHooksFromOutput(output) {
97
+ const failed = [];
98
+ for (const line of String(output ?? "").replace(ANSI, "").split("\n")) {
99
+ const match = /^\s*✗\s+([A-Za-z0-9_.:@/-]+)\s+\(/.exec(line);
100
+ if (match && !failed.includes(match[1])) failed.push(match[1]);
101
+ }
102
+ return failed;
103
+ }
104
+
105
+ /** The receipt's `push` field: each lane's result and compute wait, and the outcome. */
106
+ export function pushSummary({ status, gate, launchedAt, invocationState, hookOutput = "" }) {
107
+ const own = gate === "ungated" ? null : ownInvocation(invocationState, launchedAt);
108
+ const lanes = Object.entries(own?.lanes ?? {}).map(([lane, v]) => ({
109
+ lane, outcome: v?.outcome ?? null, waiting_ms: v?.waiting_ms ?? 0,
110
+ slot_wait_ms: v?.compute?.slot_wait_ms ?? null, load_wait_ms: v?.compute?.load_wait_ms ?? null,
111
+ load_ratio_at_start: v?.compute?.load_ratio_at_start ?? null,
112
+ }));
113
+ const failedHooks = status === "success" ? [] : failedHooksFromOutput(hookOutput);
114
+ const outcome = {
115
+ success: "pushed", cancelled: "interrupted", timed_out: "timed_out", owner_lost: "owner_lost",
116
+ failure: lanes.some((l) => FAILED_LANE_OUTCOMES.has(l.outcome)) || failedHooks.length ? "hooks_failed" : "push_failed",
117
+ }[status] ?? status;
118
+ return {
119
+ outcome,
120
+ gate: gate === "ungated" ? "ungated" : own ? "gated" : "no_hooks",
121
+ failed_hooks: failedHooks,
122
+ invocation_id: own?.invocation_id ?? null,
123
+ lanes,
124
+ slot_wait_ms: sumOrNull(lanes.map((l) => l.slot_wait_ms)),
125
+ load_wait_ms: sumOrNull(lanes.map((l) => l.load_wait_ms)),
126
+ };
127
+ }
128
+
129
+ /**
130
+ * Wake once the push has held for compute for `thresholdSeconds`. Event-driven: a
131
+ * change to the status file re-evaluates, and a timer fires at the exact moment the
132
+ * threshold passes; `recheckMs` is only a backstop for a missed file event.
133
+ * Resolves to a matched entry; `stop()` releases the watch and timers.
134
+ */
135
+ export function watchPushWaiting({
136
+ runId, thresholdSeconds, readStatus, onChange, conditionId = null,
137
+ now = Date.now, setTimeoutFn = setTimeout, clearTimeoutFn = clearTimeout, recheckMs = 15_000,
138
+ }) {
139
+ let resolveMatch;
140
+ const promise = new Promise((resolve) => { resolveMatch = resolve; });
141
+ let timer = null;
142
+ let done = false;
143
+ let unsubscribe = () => {};
144
+ const stop = () => {
145
+ done = true;
146
+ if (timer) clearTimeoutFn(timer);
147
+ timer = null;
148
+ try { unsubscribe(); } catch { /* already closed */ }
149
+ };
150
+ const evaluate = () => {
151
+ if (done) return;
152
+ if (timer) clearTimeoutFn(timer);
153
+ timer = null;
154
+ const status = readStatus();
155
+ let next = recheckMs;
156
+ const since = Date.parse(status?.waiting_since ?? "");
157
+ if (status?.phase === "waiting" && Number.isFinite(since)) {
158
+ const waitedMs = now() - since;
159
+ if (waitedMs >= thresholdSeconds * 1000) {
160
+ const match = {
161
+ condition_id: conditionId, signal_type: "push_waiting", subject_key: `run:${runId}`,
162
+ payload: {
163
+ run_id: runId, phase: "waiting", reason: status.reason ?? null, lane: status.lane ?? null, waiting_since: status.waiting_since,
164
+ waited_seconds: Math.floor(waitedMs / 1000), load_ratio: status.load_ratio ?? null, slot_position: status.slot_position ?? null,
165
+ threshold_seconds: thresholdSeconds,
166
+ },
167
+ };
168
+ stop();
169
+ resolveMatch(match);
170
+ return;
171
+ }
172
+ next = Math.min(next, thresholdSeconds * 1000 - waitedMs);
173
+ }
174
+ timer = setTimeoutFn(evaluate, next);
175
+ timer?.unref?.();
176
+ };
177
+ unsubscribe = onChange(evaluate) ?? (() => {});
178
+ evaluate();
179
+ return { promise, stop };
180
+ }
181
+
182
+ /** Watch a status file's directory for changes to that file. Returns the unsubscribe. */
183
+ export function watchFile(path, fn) {
184
+ try {
185
+ const watcher = watch(dirname(path), (_event, name) => { if (!name || name === basename(path)) fn(); });
186
+ watcher.unref?.();
187
+ return () => watcher.close();
188
+ } catch {
189
+ return () => {};
190
+ }
191
+ }
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, hookOutput = "") {
218
+ const summary = pushSummary({ status, gate: context.push.gate, launchedAt: context.launched_at, invocationState: readInvocationState(context.push.root), hookOutput });
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, boundedLog); } 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");
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,