@botbuddy/cli 1.115.2 → 1.117.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/src/run.mjs CHANGED
@@ -6,6 +6,8 @@
6
6
  // allowed to call update_command_run. A bb-wait is therefore a notification
7
7
  // mechanism, never the owner of a child process.
8
8
 
9
+ import { adoptRunOwnership, claimRunOwnership } from "./run-ownership.mjs";
10
+ import { withoutRunMarkers } from "./run-markers.mjs";
9
11
  import { createHash, randomUUID } from "node:crypto";
10
12
  import { stackLeaseIdFromEnv, withStackLeaseCorrelation } from "./stack-lease-correlation.mjs";
11
13
  import { mkdir, readFile, writeFile, chmod, unlink, stat, rename } from "node:fs/promises";
@@ -125,6 +127,7 @@ function signalExitCode(signal) {
125
127
  // event), then returns the child verdict even when terminal delivery degrades.
126
128
  export async function launchForegroundRun(argv, {
127
129
  cwd = process.cwd(), spawnImpl = spawn, identity = null, outbox = null, signalEmitter = process, env = process.env,
130
+ claimOwnership = spawnImpl === spawn ? claimRunOwnership : null,
128
131
  } = {}) {
129
132
  const { opts, command, errors } = parseRunArgs(argv);
130
133
  if (errors.length) return { exitCode: EXIT.INVALID, receipt: { schema_version: RUN_SCHEMA_VERSION, outcome: "rejected", errors, exit_code: EXIT.INVALID } };
@@ -179,12 +182,18 @@ export async function launchForegroundRun(argv, {
179
182
  return { exitCode: EXIT.INTERNAL, receipt: { schema_version: RUN_SCHEMA_VERSION, outcome: "rejected", error: error?.code ?? "telemetry_start_not_durable", exit_code: EXIT.INTERNAL } };
180
183
  }
181
184
  let child;
185
+ // BOT-3463: this run owns every process its command launches, setsid or not.
186
+ const ownership = await claimOwnershipQuietly(claimOwnership, { runId, kind: `foreground_${opts.kind}`, cwd, env });
182
187
  try {
183
188
  // A foreground command still needs its own process group: hooks commonly
184
189
  // launch package managers or test runners, whose descendants otherwise
185
190
  // survive a timeout after their immediate parent exits.
186
- child = spawnImpl(command[0], command.slice(1), { cwd, detached: process.platform !== "win32", stdio: "inherit", windowsHide: true });
191
+ child = spawnImpl(command[0], command.slice(1), { cwd, detached: process.platform !== "win32", stdio: "inherit", windowsHide: true,
192
+ ...(ownership ? { env: { ...process.env, ...ownership.env } } : {}) });
193
+ // Not awaited: no tick between spawn and the exit listeners, so a fast exit is never missed.
194
+ void ownership?.recordGroup(child.pid);
187
195
  } catch (error) {
196
+ await ownership?.release();
188
197
  await telemetry.append({ ...base, action: "terminal", producer_event_id: `${runId}:terminal`, producer_sequence: 1, outcome: "crashed", diagnostic: { code: "spawn_failed", category: "spawn" } }).catch(() => {});
189
198
  return { exitCode: EXIT.INTERNAL, receipt: { schema_version: RUN_SCHEMA_VERSION, outcome: "crashed", run_id: runId, telemetry: "degraded", exit_code: EXIT.INTERNAL, ...FOREGROUND_INSPECTION } };
190
199
  }
@@ -197,9 +206,13 @@ export async function launchForegroundRun(argv, {
197
206
  }, opts.timeout * 1000);
198
207
  const forwarded = forwardTerminationSignals(child, signalEmitter);
199
208
  const result = await waitForChild(child);
200
- forwarded.cleanup();
209
+ // The command has ended: its timeout no longer applies, even while cleanup below takes time
210
+ // (Codex #1925 r2 P2).
201
211
  clearTimeout(timeout);
202
212
  clearTimeout(killTimer);
213
+ // BOT-3463: whatever the command left running (a backgrounded dev server) stops with the run.
214
+ if (ownership) await ownership.release();
215
+ forwarded.cleanup();
203
216
  const terminalSignal = forwarded.signal ?? result.signal;
204
217
  const outcome = result.error ? "crashed" : foregroundOutcome({ ...result, signal: terminalSignal, timedOut });
205
218
  let telemetryState = "durable";
@@ -635,6 +648,19 @@ function workerInvocation(context) {
635
648
  return [process.execPath, [bin, "run", "--worker", context]];
636
649
  }
637
650
 
651
+ // BOT-3463: how long a workload's output may keep flowing after its command exited.
652
+ const WORKLOAD_EXIT_DRAIN_MS = 2_000;
653
+
654
+ // BOT-3463: ownership is the cleanup guarantee, not a precondition — a record that cannot be
655
+ // written (an unwritable HOME) is said once and the run goes ahead unowned.
656
+ async function claimOwnershipQuietly(claim, args) {
657
+ if (!claim) return null;
658
+ try { return await claim(args); } catch (error) {
659
+ process.stderr.write(`bb: run ${args.runId} is not tracked for cleanup (${error?.code ?? error?.message ?? error}); processes it leaves behind are not stopped\n`);
660
+ return null;
661
+ }
662
+ }
663
+
638
664
  function sessionFailure(code) { return Object.assign(new Error(code), { code }); }
639
665
 
640
666
  // A selected ID is metadata, not a credential. Require positive private-cache
@@ -682,6 +708,7 @@ function rejectedSessionReceipt(error, runId) {
682
708
  export async function launchRun(argv, {
683
709
  cwd = process.cwd(), spawnImpl = spawn, call = null, childEnv = null, testRun = null, push = null, beforeSpawn = null,
684
710
  resolveCredential = null, renewCredential = selfHealAgentSession, env = process.env, getSourceSha = sourceSha,
711
+ claimOwnership = spawnImpl === spawn ? claimRunOwnership : null,
685
712
  } = {}) {
686
713
  const parsed = parseRunArgs(argv, env);
687
714
  let managedCredential = null;
@@ -753,11 +780,20 @@ export async function launchRun(argv, {
753
780
  if (beforeSpawn) await beforeSpawn(runId);
754
781
  const [file, args] = workerInvocation(context);
755
782
  let workerPid = null;
783
+ // BOT-3463: the run owns its workload's process tree. The launcher claims it; the detached
784
+ // worker it starts becomes the owner, and stops what the workload left when the run ends.
785
+ const ownership = await claimOwnershipQuietly(claimOwnership, { runId, kind: opts.kind ? `detached_${opts.kind}` : "detached", cwd, env });
756
786
  try {
757
- const worker = spawnImpl(file, args, { detached: true, stdio: "ignore", windowsHide: true });
787
+ // The worker owns the run and is never one of its processes (Codex #1925 r3 P1): it carries no
788
+ // run marker, so a sweep after it releases cannot take it while it finalizes. It marks the
789
+ // workload it spawns instead.
790
+ const worker = spawnImpl(file, args, { detached: true, stdio: "ignore", windowsHide: true,
791
+ ...(ownership ? { env: withoutRunMarkers(process.env) } : {}) });
758
792
  workerPid = Number.isInteger(worker.pid) ? worker.pid : null;
793
+ if (ownership && workerPid) await ownership.adoptOwner(workerPid);
759
794
  worker.unref();
760
795
  } catch (error) {
796
+ await ownership?.release();
761
797
  // BOT-1572 (Codex P2): use effectiveCall — `call` may be null (the token-pinned
762
798
  // default path), so calling it here would throw and strand the registered run.
763
799
  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)}` });
@@ -781,9 +817,13 @@ export async function runWorker(contextFile, {
781
817
  // BOT-2530: worker liveness lease renewal cadence (tests inject a fake timer).
782
818
  workerHeartbeatIntervalMs = WORKER_HEARTBEAT_INTERVAL_MS, setIntervalFn = setInterval,
783
819
  liveLogIntervalMs = 1_000,
820
+ adoptOwnership = spawnImpl === spawn ? adoptRunOwnership : null,
784
821
  } = {}) {
785
822
  const retry = { sleep, now, budgetMs: terminalBudgetMs, startDelivery };
786
823
  const context = JSON.parse(await readFile(contextFile, "utf8"));
824
+ // BOT-3463: this worker now owns the run its launcher claimed (null for a pre-fix launcher).
825
+ let ownership = null;
826
+ try { ownership = adoptOwnership ? await adoptOwnership({ runId: context.run_id }) : null; } catch { ownership = null; }
787
827
  const callbackCall = callWithContextIdentity(context, call);
788
828
  const ownerHeartbeat = startOwnerHeartbeat(context, callbackCall);
789
829
  const workerLease = startWorkerLease(context, callbackCall, { intervalMs: workerHeartbeatIntervalMs, setIntervalFn });
@@ -847,7 +887,7 @@ export async function runWorker(contextFile, {
847
887
  return await preWorkloadCancellationReceipt(context);
848
888
  }
849
889
  try {
850
- child = spawnImpl(context.command[0], context.command.slice(1), { cwd: context.cwd, detached: true, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, ...(context.child_env ? { env: { ...process.env, ...context.child_env } } : {}) });
890
+ child = spawnImpl(context.command[0], context.command.slice(1), { cwd: context.cwd, detached: true, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, ...(context.child_env || ownership ? { env: { ...process.env, ...context.child_env, ...ownership?.env } } : {}) });
851
891
  } catch (error) {
852
892
  const endedAt = new Date().toISOString();
853
893
  const receipt = await finalize(context, { status: "owner_lost", startedAt, endedAt, exitCode: null, signal: null, reason: `workload_spawn_failed:${error instanceof Error ? error.message : String(error)}` }, callbackCall, retry);
@@ -857,6 +897,20 @@ export async function runWorker(contextFile, {
857
897
  // Subscribe before any filesystem I/O so a busy parallel test run (or a real
858
898
  // fast failure) cannot lose the sole terminal event.
859
899
  const completion = waitForChild(child);
900
+ // The command's own exit decides whether it beat its deadline, not the later closing of
901
+ // pipes a process it left behind still holds (Codex #1925 r6 P2).
902
+ let workloadExited = false;
903
+ child.once?.("exit", () => { workloadExited = true; });
904
+ // BOT-3463: the run ends when its command exits. A process it backgrounded (a dev server)
905
+ // still holds the output pipes, which would keep the run open until its timeout: after a
906
+ // short drain, stop it, so the pipes close and the run completes. Attached before any await
907
+ // (Codex #1925 P1), like the completion listener, so an immediate exit is never missed.
908
+ if (ownership) {
909
+ child.once?.("exit", () => {
910
+ const drain = setTimeout(() => { void ownership.release(); }, WORKLOAD_EXIT_DRAIN_MS);
911
+ drain.unref?.();
912
+ });
913
+ }
860
914
  // Capture pipes before the first await too. A short-lived command can emit
861
915
  // all of its output while context persistence yields to the filesystem; if
862
916
  // these listeners are attached afterwards, its terminal receipt silently
@@ -879,6 +933,7 @@ export async function runWorker(contextFile, {
879
933
  liveLogTimer = setInterval(flushLiveLog, liveLogIntervalMs);
880
934
  liveLogTimer.unref?.();
881
935
  await persistWorkerContext({ workload_pid: child.pid, worker_state: "running" });
936
+ void ownership?.recordGroup(child.pid);
882
937
  // BOT-1510: for a test lane, tail the reporter's NDJSON and flush per-case
883
938
  // verdicts while the child runs. The test process never touches the network.
884
939
  const lane = context.test_run ? startLaneFlusher(context, callbackCall) : null;
@@ -886,13 +941,18 @@ export async function runWorker(contextFile, {
886
941
  const pushMonitor = context.push ? startPushMonitor(context, callbackCall) : null;
887
942
  let killTimer;
888
943
  const timer = setTimeout(() => {
889
- timedOut = true;
944
+ // Past the deadline the group is still stopped, so held pipes close; a command that had
945
+ // already exited is not reported timed out for it.
946
+ if (!workloadExited) timedOut = true;
890
947
  terminate(child, "SIGTERM");
891
948
  killTimer = setTimeout(() => terminate(child, "SIGKILL"), context.timeout_grace_ms ?? TIMEOUT_GRACE_MS);
892
949
  }, context.timeout_seconds * 1000);
893
950
  const result = await completion;
951
+ // The workload has ended: its timeout no longer applies while cleanup runs (Codex #1925 r2 P2).
894
952
  clearTimeout(timer);
895
953
  clearTimeout(killTimer);
954
+ // BOT-3463: the run ends here; nothing the workload started outlives it.
955
+ if (ownership) await ownership.release();
896
956
  clearInterval(liveLogTimer);
897
957
  flushLiveLog();
898
958
  await logWrites;
@@ -909,6 +969,7 @@ export async function runWorker(contextFile, {
909
969
  return receipt;
910
970
  } finally {
911
971
  clearInterval(liveLogTimer);
972
+ if (ownership) await ownership.release();
912
973
  if (workerLease) await workerLease.stop();
913
974
  if (ownerHeartbeat) await ownerHeartbeat.stop();
914
975
  signalEmitter.removeListener("SIGTERM", cancellationHandler);
@@ -206,6 +206,10 @@ export function buildStackRunOutcomePayload({ fields = {}, exitCode, runId = ran
206
206
  ? fields.failure_mechanism : null;
207
207
  // BOT-2977: sent only on a stale-context refusal, so every other payload keeps its shape.
208
208
  const fenceScope = code === "STALE_AGENT_CONTEXT" && ["session", "agent"].includes(fields.fence_scope) ? fields.fence_scope : null;
209
+ // BOT-3536: the ticket the refusing fence compared with, judged at refusal time rather than
210
+ // from the later `sessions` snapshot; and whether this run rebound its session (any code).
211
+ const registeredTicketId = code === "STALE_AGENT_CONTEXT" ? pick(fields.registered_ticket_id, TICKET_RE)?.toUpperCase() ?? null : null;
212
+ const contextRebound = Boolean(fields.context_rebound && typeof fields.context_rebound === "object");
209
213
  // BOT-3109: the code a requester network loss replaced; sent only on such a run.
210
214
  const underlyingCode = category === "requester" && REQUESTER_UNDERLYING_CODES.has(fields.underlying_code) ? fields.underlying_code : null;
211
215
  return {
@@ -233,10 +237,15 @@ export function buildStackRunOutcomePayload({ fields = {}, exitCode, runId = ran
233
237
  ...(callbackAuthorizationReason ? { callback_authorization_reason: callbackAuthorizationReason } : {}),
234
238
  ...(failureMechanism ? { failure_mechanism: failureMechanism } : {}),
235
239
  ...(fenceScope ? { fence_scope: fenceScope } : {}),
240
+ ...(registeredTicketId ? { registered_ticket_id: registeredTicketId } : {}),
241
+ ...(contextRebound ? { context_rebound: true } : {}),
236
242
  ...(underlyingCode ? { underlying_code: underlyingCode } : {}),
237
243
  };
238
244
  }
239
245
 
246
+ /** Optional keys an older server may refuse as unknown; the send drops each in turn. */
247
+ const LEGACY_OPTIONAL_KEYS = ["failure_mechanism", "fence_scope", "registered_ticket_id", "context_rebound"];
248
+
240
249
  /**
241
250
  * Best-effort record. `channel` is `{ auth, callTool }` from the lifecycle (the
242
251
  * credential the lease calls used); without one there is nothing to authenticate
@@ -263,23 +272,33 @@ export async function reportStackRunOutcome({ fields, exitCode, runId, opts, env
263
272
  });
264
273
  try {
265
274
  const call = Promise.resolve().then(async () => {
266
- const first = await channel.callTool(STACK_RUN_OUTCOME_TOOL, payload, { auth: channel.auth, signal: ac.signal });
275
+ const refused = (res) => !ac.signal.aborted && res?.ok && res?.isError && res?.data?.code === "INVALID_STACK_RUN_OUTCOME" && typeof res?.data?.message === "string";
267
276
  // Older servers reject unknown keys before writing. Retry only that exact,
268
277
  // explicit rejection with the same run id; never retry an uncertain send.
269
- const refusedKey = ["failure_mechanism", "fence_scope"].find((key) => payload[key] &&
270
- typeof first?.data?.message === "string" && first.data.message.startsWith(`unknown key '${key}'`));
271
- if (!ac.signal.aborted && refusedKey && first?.ok && first?.isError &&
272
- first?.data?.code === "INVALID_STACK_RUN_OUTCOME") {
273
- const { [refusedKey]: _omitted, ...legacyPayload } = payload;
274
- return await channel.callTool(STACK_RUN_OUTCOME_TOOL, legacyPayload, { auth: channel.auth, signal: ac.signal });
275
- }
278
+ // BOT-3536: a row can carry more than one newer key, so each refused one is
279
+ // dropped in turn (at most once each), exactly as an older CLI would send it.
280
+ const sendDroppingLegacyKeys = async (body) => {
281
+ let sent = body;
282
+ let res = await channel.callTool(STACK_RUN_OUTCOME_TOOL, sent, { auth: channel.auth, signal: ac.signal });
283
+ for (let dropped = 0; dropped < LEGACY_OPTIONAL_KEYS.length && refused(res); dropped++) {
284
+ const refusedKey = LEGACY_OPTIONAL_KEYS.find((key) => sent[key] !== undefined && res.data.message.startsWith(`unknown key '${key}'`));
285
+ if (!refusedKey) break;
286
+ const { [refusedKey]: _omitted, ...legacyPayload } = sent;
287
+ sent = legacyPayload;
288
+ res = await channel.callTool(STACK_RUN_OUTCOME_TOOL, sent, { auth: channel.auth, signal: ac.signal });
289
+ }
290
+ return { res, sent };
291
+ };
292
+ const { res: first, sent } = await sendDroppingLegacyKeys(payload);
276
293
  // BOT-3109: a server from before the requester category refuses it (or its underlying_code).
277
294
  // Record exactly what that server would have got from an older CLI: the platform code.
278
- const refusedRequester = payload.category === "requester" && payload.underlying_code && typeof first?.data?.message === "string" &&
295
+ // Built from the reduced `sent`, and itself dropping any newer key the server then
296
+ // refuses, so the fallback survives whichever key the server names first (review #1929).
297
+ const refusedRequester = sent.category === "requester" && sent.underlying_code && refused(first) &&
279
298
  (first.data.message.startsWith("unknown key 'underlying_code'") || first.data.message.startsWith("category must be"));
280
- if (!ac.signal.aborted && refusedRequester && first?.ok && first?.isError && first?.data?.code === "INVALID_STACK_RUN_OUTCOME") {
281
- const { underlying_code: underlying, ...rest } = payload;
282
- return await channel.callTool(STACK_RUN_OUTCOME_TOOL, { ...rest, category: "platform", code: underlying }, { auth: channel.auth, signal: ac.signal });
299
+ if (refusedRequester) {
300
+ const { underlying_code: underlying, ...rest } = sent;
301
+ return (await sendDroppingLegacyKeys({ ...rest, category: "platform", code: underlying })).res;
283
302
  }
284
303
  return first;
285
304
  });
package/src/stack.mjs CHANGED
@@ -27,6 +27,7 @@
27
27
  // labelled fallback for when no Helper is available: it runs `supabase start`/
28
28
  // `stop` itself and self-activates/finalizes via the fallback MCP tools.
29
29
 
30
+ import { claimRunOwnership } from "./run-ownership.mjs";
30
31
  import { writeLaneStatus } from "./lane-status.mjs";
31
32
  import { markFeedbackGuidanceShown } from "./feedback-reminder.mjs";
32
33
  import { spawn, spawnSync } from "child_process";
@@ -1769,9 +1770,11 @@ const STALE_CONTEXT_TICKET_RE = /^[A-Z][A-Z0-9]{1,15}-[0-9]{1,12}$/;
1769
1770
  function staleContextRecovery(requested, branchTicket) {
1770
1771
  if (branchTicket === undefined || requested === "unknown") return "";
1771
1772
  const branch = typeof branchTicket === "string" && STALE_CONTEXT_TICKET_RE.test(branchTicket) ? branchTicket : null;
1772
- if (branch === requested) return `Run \`bb doctor --fix\` in this worktree to re-register it for ${requested}, then retry. `;
1773
- return `${branch ? `This worktree's branch is for ${branch}` : "This worktree's branch names no ticket"}, so \`bb doctor --fix\` here would not register ${requested}: `
1774
- + `run \`bb doctor --fix\` in ${requested}'s worktree, or call register_agent with ticket_id ${requested} in this session, then retry. `;
1773
+ // BOT-3536: `bb doctor --fix` renews the session in place (BOT-3219) and keeps its
1774
+ // registered ticket, so it is never offered as the rebind. A ticket-moving heartbeat is.
1775
+ if (branch === requested) return `Rebind this worktree's session with \`bb call heartbeat --json '{"ticket_id":"${requested}"}'\`, then retry. `;
1776
+ return `${branch ? `This worktree's branch is for ${branch}` : "This worktree's branch names no ticket"}, so this run was not rebound to ${requested}: `
1777
+ + `run it from ${requested}'s worktree, or call register_agent with ticket_id ${requested} in this session, then retry. `;
1775
1778
  }
1776
1779
 
1777
1780
  /** BOT-2977: the fence the server applied (`session` for a tier-3 session, else `agent`). */
@@ -1792,21 +1795,65 @@ export function staleContextRefusalFields(data) {
1792
1795
  };
1793
1796
  }
1794
1797
 
1795
- /** BOT-2977: the ticket this checkout's branch names (null when none), read only for a stale-context refusal. */
1796
- export async function currentBranchTicket(cwd = process.cwd()) {
1798
+ /** BOT-3536: this checkout's branch name; undefined when unknown (not a checkout, detached HEAD). */
1799
+ export async function currentBranchName(cwd = process.cwd()) {
1797
1800
  try {
1798
1801
  const git = spawnSync("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000 });
1799
1802
  if (git.status !== 0 || typeof git.stdout !== "string") return undefined;
1800
1803
  const branch = git.stdout.trim();
1801
1804
  // A detached HEAD names no branch, so the branch's ticket is unknown, not absent.
1802
- if (!branch || branch === "HEAD") return undefined;
1803
- const match = branch.match(/(?:^|\/)\s*(bot|ent)-(\d+)(?:-|$)/i);
1804
- return match ? `${match[1].toUpperCase()}-${match[2]}` : null;
1805
+ return !branch || branch === "HEAD" ? undefined : branch;
1805
1806
  } catch {
1806
1807
  return undefined;
1807
1808
  }
1808
1809
  }
1809
1810
 
1811
+ /** The ticket a branch name carries (`<author>/bot-<n>-<slug>`), null when none. */
1812
+ export function branchNameTicket(branch) {
1813
+ const match = typeof branch === "string" ? branch.match(/(?:^|\/)\s*(bot|ent)-(\d+)(?:-|$)/i) : null;
1814
+ return match ? `${match[1].toUpperCase()}-${match[2]}` : null;
1815
+ }
1816
+
1817
+ /** BOT-2977: the ticket this checkout's branch names (null when none), read only for a stale-context refusal. */
1818
+ export async function currentBranchTicket(cwd = process.cwd()) {
1819
+ const branch = await currentBranchName(cwd);
1820
+ return branch === undefined ? undefined : branchNameTicket(branch);
1821
+ }
1822
+
1823
+ /** BOT-3536: credentials that are this worktree's own cached session (never an env/flag token or an operator key). */
1824
+ const REBINDABLE_CREDENTIAL_SOURCES = new Set(["cache", "renewed", "minted"]);
1825
+
1826
+ /**
1827
+ * BOT-3536: the one rebind a stale-context refusal may trigger. An agent that moved
1828
+ * to its next ticket in the same worktree keeps a session registered for the old
1829
+ * one, so the session-scoped fence refuses `--ticket <new>`. When — and only when —
1830
+ * the server refused on the SESSION fence, this checkout's branch names exactly the
1831
+ * requested ticket, the server's registered ticket differs, and the credential is
1832
+ * the worktree's own cached session, send one ticket-moving `heartbeat` on that
1833
+ * session (it writes `sessions.registered_ticket_key`, BOT-2977). The caller then
1834
+ * sends one fresh admission, which the unchanged fence judges again.
1835
+ *
1836
+ * Unlike the CLI auto-renew rejected on 2026-11-08, this never binds the session to
1837
+ * the ticket a run merely ASKS for: the branch must name it, so a run for a ticket
1838
+ * the worktree is not on stays refused. Returns null when no rebind applies, else
1839
+ * `{ rebound, from, to }`.
1840
+ */
1841
+ export async function rebindStaleSession(data, { auth, call, branch = currentBranchName } = {}) {
1842
+ if (data?.code !== "STALE_AGENT_CONTEXT" || staleContextFenceScope(data) !== "session") return null;
1843
+ const { registered_ticket_id: from, requested_ticket_id: to } = staleContextRefusalFields(data);
1844
+ if (!from || !to || from === to) return null;
1845
+ if (!REBINDABLE_CREDENTIAL_SOURCES.has(auth?.__source) || typeof call !== "function") return null;
1846
+ const name = await branch();
1847
+ if (branchNameTicket(name) !== to) return null;
1848
+ let res = null;
1849
+ try { res = await call("heartbeat", { ticket_id: to, branch: name }); } catch { res = null; }
1850
+ // The production answer has no `success` key: a session id, and an `error` on refusal.
1851
+ const sessionId = auth.__identity?.sessionId ?? null;
1852
+ const rebound = Boolean(res?.ok && !res.isError && !res.data?.error && typeof res.data?.session_id === "string"
1853
+ && (!sessionId || res.data.session_id === sessionId));
1854
+ return { rebound, from, to };
1855
+ }
1856
+
1810
1857
  /** The refusal text for a receipt: the server's message, else the CLI's guidance, else the code. */
1811
1858
  export function leaseRefusalError(data, { branchTicket } = {}) {
1812
1859
  if (data?.code === "STALE_AGENT_CONTEXT") {
@@ -4330,8 +4377,8 @@ async function runStackLifecycleWatched(opts, childArgv, adapters, firstBox, fre
4330
4377
  result.cleanup?.ok !== false && !incidentBox.stopSignal) {
4331
4378
  requeuedFrom = { lease_id: result.leaseId, reap_reason: result.reapReason };
4332
4379
  process.stderr.write(`${sessionRequeueNotice(requeuedFrom)}\n`);
4333
- const { incident } = incidentBox;
4334
- incidentBox = { ...freshBox(), incident };
4380
+ const { incident, contextRebound } = incidentBox;
4381
+ incidentBox = { ...freshBox(), incident, ...(contextRebound ? { contextRebound } : {}) };
4335
4382
  // One park budget (--timeout) across both attempts.
4336
4383
  const remaining = remainingParkSecs(opts.timeout, startedAtMs, (adapters.now ?? Date.now)());
4337
4384
  result = await once({ ...opts, queueParkTimeout: remaining });
@@ -4349,7 +4396,9 @@ async function runStackLifecycleWatched(opts, childArgv, adapters, firstBox, fre
4349
4396
  const withOutage = incidentBox.callbackOutage && withStopSignal ? { ...withStopSignal, callbackOutage: incidentBox.callbackOutage } : withStopSignal;
4350
4397
  // BOT-3369: not a receipt field; it sizes the requester-network lookback to this run's grace.
4351
4398
  const withGrace = incidentBox.degradedGraceMs && withOutage && typeof withOutage === "object" ? { ...withOutage, degradedGraceMs: incidentBox.degradedGraceMs } : withOutage;
4352
- const final = await applyRequesterNetworkLoss(withGrace, networkWatch, { failedAtMs: incidentBox.lossAtMs });
4399
+ // BOT-3536: a run that rebound its session says so on every result shape.
4400
+ const withRebound = incidentBox.contextRebound && withGrace && typeof withGrace === "object" ? { ...withGrace, contextRebound: incidentBox.contextRebound } : withGrace;
4401
+ const final = await applyRequesterNetworkLoss(withRebound, networkWatch, { failedAtMs: incidentBox.lossAtMs });
4353
4402
  // BOT-2467: non-enumerable, so the receipt fields and result comparisons never see it.
4354
4403
  if (final && typeof final === "object" && incidentBox.outcomeChannel) {
4355
4404
  Object.defineProperty(final, OUTCOME_CHANNEL, { value: incidentBox.outcomeChannel, enumerable: false });
@@ -4507,6 +4556,9 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
4507
4556
  let leaseId = null;
4508
4557
  let child = null;
4509
4558
  let childResult = null;
4559
+ // BOT-3463: the run owns every process its child launches (a test double owns its own child).
4560
+ const claimOwnership = adapters.claimOwnership ?? (adapters.startChild ? null : claimRunOwnership);
4561
+ let runOwnership = null;
4510
4562
  let connectionFile = null;
4511
4563
  let heartbeat = null;
4512
4564
  let heartbeatRetry = null;
@@ -5060,11 +5112,29 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5060
5112
  // stack digest changed) or that lost a race to a preemption answers with the OLD lease
5061
5113
  // id: wait for it to reach `reaped`, then send the SAME request once more (it then
5062
5114
  // provisions a fresh lease for the slot).
5115
+ // BOT-3536: a session-fence refusal for the ticket this branch names rebinds the
5116
+ // worktree's session once (rebindStaleSession) and sends one FRESH admission; the
5117
+ // unchanged fence judges it again. At most one rebind per run, never a second retry.
5118
+ const admitOnce = () => requestIdentified ? requestIdentified() : api.request(leaseArgs);
5119
+ let rebindTried = false;
5120
+ const admit = async () => {
5121
+ const res = await admitOnce();
5122
+ if (rebindTried || identifiedVerdict || res?.data?.code !== "STALE_AGENT_CONTEXT") return res;
5123
+ rebindTried = true;
5124
+ const rebind = await rebindStaleSession(res.data, {
5125
+ auth: rpc.auth, call: (name, args) => rpc.call(name, args), branch: adapters.branchName ?? (() => currentBranchName()),
5126
+ });
5127
+ if (!rebind?.rebound) return res;
5128
+ incidentBox.contextRebound = { from: rebind.from, to: rebind.to };
5129
+ stderrLine(`stack: this worktree's session was registered for ${rebind.from} and its branch names ${rebind.to}; rebound the session to ${rebind.to} and requesting once more`);
5130
+ renewIdentifiedRequest?.();
5131
+ return admitOnce();
5132
+ };
5063
5133
  let request;
5064
5134
  let idleRetried = false;
5065
5135
  for (let attempt = 0; ; attempt++) {
5066
5136
  activeWaitAbort = new AbortController();
5067
- const admission = await requestWithCapacityWait(() => requestIdentified ? requestIdentified() : api.request(leaseArgs), opts, {
5137
+ const admission = await requestWithCapacityWait(admit, opts, {
5068
5138
  waitCapacity: adapters.waitCapacity ?? defaultWaitCapacity, log: stderrLine, signal: activeWaitAbort.signal,
5069
5139
  });
5070
5140
  activeWaitAbort = null;
@@ -5260,9 +5330,12 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5260
5330
  // BOT-2977: name the re-registration command; the refusal itself is never retried here.
5261
5331
  const fenceScope = staleContextFenceScope(request.data);
5262
5332
  const branchTicket = request.data?.code === "STALE_AGENT_CONTEXT" ? await (adapters.branchTicket ?? currentBranchTicket)() : undefined;
5333
+ // BOT-3536: the ticket the server compared with, recorded at refusal time.
5334
+ const registeredTicketId = request.data?.code === "STALE_AGENT_CONTEXT" ? staleContextRefusalFields(request.data).registered_ticket_id : undefined;
5263
5335
  return {
5264
5336
  exitCode: leaseRefusalExit(request.data?.code), outcome: "error", code: request.data?.code,
5265
5337
  ...(fenceScope ? { fenceScope } : {}),
5338
+ ...(registeredTicketId ? { registeredTicketId } : {}),
5266
5339
  ...capacityStaleReceiptFields(request.data), error: leaseRefusalError(request.data, { branchTicket }),
5267
5340
  ...(request.data?.sqlstate ? { sqlstate: request.data.sqlstate } : {}),
5268
5341
  ...(request.data.lease_id ? { leaseId: request.data.lease_id, state: request.data.state ?? null } : {}),
@@ -5882,7 +5955,13 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
5882
5955
  child = started.child;
5883
5956
  if (hostLocalCallbackRun(opts)) placement.callbackTransport = HOST_LOCAL_CALLBACK_TRANSPORT;
5884
5957
  } else {
5885
- child = startChild(childArgv, childEnv, childCwd);
5958
+ try { runOwnership = claimOwnership ? await claimOwnership({ kind: "stack_run", cwd: childCwd ?? process.cwd() }) : null; } catch (error) {
5959
+ stderrLine(`stack: this run is not tracked for cleanup (${error?.code ?? error?.message ?? error}); processes its child leaves behind are not stopped`);
5960
+ }
5961
+ child = startChild(childArgv, runOwnership ? { ...childEnv, ...runOwnership.env } : childEnv, childCwd);
5962
+ // Not awaited: waitForChild attaches its exit listener below with no tick in between, so a
5963
+ // child that exits at once is never missed. The group is recorded in memory synchronously.
5964
+ void runOwnership?.recordGroup(child.pid);
5886
5965
  }
5887
5966
  if (testChild) {
5888
5967
  // A host child is measured by its own cgroup on the host, not sampled here.
@@ -6002,6 +6081,8 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
6002
6081
  if (opts.hardTtl) hardTimer = clock.setTimeout(() => stopChild("SIGTERM", EXIT.TIMEOUT), opts.hardTtl * 1000);
6003
6082
  hardTimer?.unref?.();
6004
6083
  childResult = await waitForChild(child);
6084
+ // BOT-3463: a dev server the child started stops with the run, before the stack is torn down.
6085
+ if (runOwnership) await runOwnership.release();
6005
6086
  if (testChildRenew) { clock.clearInterval(testChildRenew); testChildRenew = null; }
6006
6087
  if (testChild && child.hostRun) {
6007
6088
  // The host already recorded the cgroup cost on the lease; release without overwriting it.
@@ -6091,6 +6172,8 @@ async function runStackLifecycleOnce(opts, childArgv, adapters, incidentBox) {
6091
6172
  const exitCode = cleanup?.ok === false ? EXIT.CLEANUP_FAILED : classifyStackAuthError(error);
6092
6173
  return { exitCode, outcome: "error", leaseId, error: String(error?.message ?? error), cleanup };
6093
6174
  } finally {
6175
+ // BOT-3463: whichever path ended the run, its processes end with it (idempotent).
6176
+ if (runOwnership) await runOwnership.release();
6094
6177
  // BOT-3240: a run that threw still frees its slot now rather than at TTL.
6095
6178
  if (testChildRenew) clock.clearInterval(testChildRenew);
6096
6179
  if (testChild?.sampler) { try { testChild.resources = testChild.sampler.stop(); } catch { /* best effort */ } testChild.sampler = null; }
@@ -6218,6 +6301,10 @@ export function runReceiptFields(result) {
6218
6301
  // BOT-2977: which fence refused a STALE_AGENT_CONTEXT run (session | agent).
6219
6302
  ...(result.code === "STALE_AGENT_CONTEXT" && (result.fenceScope === "session" || result.fenceScope === "agent")
6220
6303
  ? { fence_scope: result.fenceScope } : {}),
6304
+ // BOT-3536: the ticket the refusing fence compared with, and a session rebind this run made.
6305
+ ...(result.code === "STALE_AGENT_CONTEXT" && typeof result.registeredTicketId === "string" && STALE_CONTEXT_TICKET_RE.test(result.registeredTicketId)
6306
+ ? { registered_ticket_id: result.registeredTicketId } : {}),
6307
+ ...(result.contextRebound ? { context_rebound: { from: result.contextRebound.from, to: result.contextRebound.to } } : {}),
6221
6308
  // BOT-2957: the control-plane gaps this run's callback route rode through (never on a run that had none).
6222
6309
  ...(result.callbackOutage ? { callback_outage: result.callbackOutage } : {}),
6223
6310
  // BOT-2780: the reserved requester origin generated auth links name (never a credential).