benignswarm 0.12.163 → 0.12.164

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/dist/client.js CHANGED
@@ -373,11 +373,14 @@ export class Client {
373
373
  static raw(url, key, requestOptions = {}) {
374
374
  return new Client(url, key, null, undefined, null, requestOptions);
375
375
  }
376
- requestSignal(external) {
376
+ callerSignal(external) {
377
377
  const signals = [this.requestOptions.signal, external].filter((signal) => Boolean(signal));
378
+ return signals.length > 1 ? AbortSignal.any(signals) : signals[0];
379
+ }
380
+ requestSignal(external) {
381
+ const callerSignal = this.callerSignal(external);
378
382
  const timeout = this.requestOptions.requestTimeoutMs ? AbortSignal.timeout(this.requestOptions.requestTimeoutMs) : undefined;
379
- if (timeout)
380
- signals.push(timeout);
383
+ const signals = [callerSignal, timeout].filter((signal) => Boolean(signal));
381
384
  return { signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0], timeout };
382
385
  }
383
386
  timeoutError(method, path) {
@@ -414,14 +417,22 @@ export class Client {
414
417
  return response;
415
418
  }
416
419
  /**
417
- * opts.retries: how many times to retry on a network failure or a 5xx. Only safe for calls
418
- * that are idempotent on the server (posts carry a client_id for exactly this reason).
420
+ * opts.retries: how many times to retry on a network failure or a 5xx for callers that opt in
421
+ * (safe for idempotent calls such as client_id or lock job_token). Without opts.retries,
422
+ * GET/HEAD retry plain 5xx and rejected fetches up to DEFAULT_OVERLOAD_RETRIES (5) times,
423
+ * transient overload/gateway responses (503/502/504/service_overloaded) retry up to 5 times,
424
+ * and non-idempotent POST 500 stays fail-fast even when marked retryable.
419
425
  */
420
426
  async call(method, path, body, opts = {}) {
421
427
  const headers = this.headers(opts.auto);
422
428
  if (body !== undefined)
423
429
  headers["content-type"] = "application/json";
424
- const retries = opts.retries ?? 0;
430
+ const upperMethod = method.toUpperCase();
431
+ const isRead = upperMethod === "GET" || upperMethod === "HEAD";
432
+ const explicitRetries = opts.retries ?? 0;
433
+ const overloadRetries = Math.max(explicitRetries, DEFAULT_OVERLOAD_RETRIES);
434
+ const sleep = opts.sleepFn ?? sleepWithAbort;
435
+ const retrySignal = this.callerSignal(opts.signal);
425
436
  for (let attempt = 0;; attempt++) {
426
437
  let res;
427
438
  let text;
@@ -438,8 +449,9 @@ export class Client {
438
449
  throw this.timeoutError(method, path);
439
450
  if (this.requestOptions.signal?.aborted || opts.signal?.aborted)
440
451
  throw new CliError("request_aborted", `${method} ${path} aborted before completion`);
441
- if (attempt < retries) {
442
- await backoff(attempt);
452
+ const networkRetries = isRead ? overloadRetries : explicitRetries;
453
+ if (attempt < networkRetries) {
454
+ await sleep(computeBackoffMs(attempt), retrySignal);
443
455
  continue;
444
456
  }
445
457
  throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
@@ -451,12 +463,27 @@ export class Client {
451
463
  json = JSON.parse(text);
452
464
  }
453
465
  catch {
466
+ const transient = isTransientOverloadResponse(res.status, undefined, text, isRead, res.headers);
467
+ const maxAttempts = transient ? overloadRetries : explicitRetries;
468
+ if (res.status >= 500 && attempt < maxAttempts) {
469
+ const delayMs = computeBackoffMs(attempt, parseRetryAfterSeconds(res.headers.get("retry-after")));
470
+ process.stderr.write(`b9s: ${method} ${path} failed (${res.status}); retrying in ${Math.round(delayMs / 1000)}s\n`);
471
+ await sleep(delayMs, retrySignal);
472
+ continue;
473
+ }
454
474
  throw new CliError("bad_response", `${method} ${path} returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
455
475
  }
456
476
  if (!res.ok) {
457
- if (res.status >= 500 && attempt < retries) {
458
- process.stderr.write(`b9s: ${method} ${path} failed (${res.status}${json?.reference ? `, reference ${json.reference}` : ""}); retrying\n`);
459
- await backoff(attempt);
477
+ // Explicit opts.retries marks idempotent POST callers (e.g. client_id / lock job_token);
478
+ // default POST calls without opts.retries stay fail-fast on 500 even if marked retryable.
479
+ const nonIdempotentPost500 = upperMethod === "POST" && res.status === 500 && explicitRetries === 0;
480
+ const transient = isTransientOverloadResponse(res.status, json, text, isRead, res.headers);
481
+ const maxAttempts = transient ? overloadRetries : explicitRetries;
482
+ if (res.status >= 500 && !nonIdempotentPost500 && attempt < maxAttempts) {
483
+ const retryAfter = parseRetryAfterSeconds(res.headers.get("retry-after")) ?? (typeof json?.retry_after === "number" ? json.retry_after : undefined);
484
+ const delayMs = computeBackoffMs(attempt, retryAfter);
485
+ process.stderr.write(`b9s: ${method} ${path} failed (${res.status}${json?.reference ? `, reference ${json.reference}` : ""}); retrying in ${Math.round(delayMs / 1000)}s (${attempt + 1}/${maxAttempts})\n`);
486
+ await sleep(delayMs, retrySignal);
460
487
  continue;
461
488
  }
462
489
  const err = json;
@@ -465,12 +492,12 @@ export class Client {
465
492
  : undefined;
466
493
  throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, hint, res.status);
467
494
  }
468
- const allowsRedactedExcerpt = method.toUpperCase() === "POST" && /^\/agents\/me\/sessions\/[^/]+\/turns\/[^/]+\/complete(?:\?|$)/.test(path);
495
+ const allowsRedactedExcerpt = upperMethod === "POST" && /^\/agents\/me\/sessions\/[^/]+\/turns\/[^/]+\/complete(?:\?|$)/.test(path);
469
496
  try {
470
497
  verifyTextReceipts(json, body, expectedTextReceiptFields(method, path, body, json), allowsRedactedExcerpt ? ["excerpt"] : [], allowsRedactedExcerpt ? ["excerpt"] : [], expectedStoredText(method, path, body, json));
471
498
  }
472
499
  catch (error) {
473
- if (res.status >= 200 && res.status < 300 && error instanceof CliError && !["GET", "HEAD"].includes(method.toUpperCase())) {
500
+ if (res.status >= 200 && res.status < 300 && error instanceof CliError && !isRead) {
474
501
  throw new WrittenReceiptMismatchError(json, error);
475
502
  }
476
503
  throw error;
@@ -479,31 +506,57 @@ export class Client {
479
506
  }
480
507
  }
481
508
  /** Like call(), but returns HTTP status and parsed JSON even for 4xx responses (such as preflight or drain conflicts). */
482
- async callWithStatus(method, path, body) {
509
+ async callWithStatus(method, path, body, opts = {}) {
483
510
  const headers = this.headers();
484
511
  if (body !== undefined)
485
512
  headers["content-type"] = "application/json";
486
- let res;
487
- try {
488
- res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
489
- }
490
- catch (e) {
491
- throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
492
- }
493
- noteServerVersions(res.headers, this.agentName);
494
- const text = await res.text();
495
- let json;
496
- try {
497
- json = JSON.parse(text);
498
- }
499
- catch {
500
- throw new CliError("bad_response", `${method} ${path} returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
501
- }
502
- if (res.status >= 500) {
503
- const err = json;
504
- throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, undefined, res.status);
513
+ const upperMethod = method.toUpperCase();
514
+ const isRead = upperMethod === "GET" || upperMethod === "HEAD";
515
+ const sleep = opts.sleepFn ?? sleepWithAbort;
516
+ const retrySignal = this.callerSignal(opts.signal);
517
+ for (let attempt = 0;; attempt++) {
518
+ let res;
519
+ let text;
520
+ const { signal, timeout } = this.requestSignal(opts.signal);
521
+ try {
522
+ res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal });
523
+ text = await res.text();
524
+ }
525
+ catch (e) {
526
+ if (timeout?.aborted)
527
+ throw this.timeoutError(method, path);
528
+ if (retrySignal?.aborted)
529
+ throw new CliError("request_aborted", `${method} ${path} aborted before completion`);
530
+ if (isRead && attempt < DEFAULT_OVERLOAD_RETRIES) {
531
+ await sleep(computeBackoffMs(attempt), retrySignal);
532
+ continue;
533
+ }
534
+ throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
535
+ }
536
+ noteServerVersions(res.headers, this.agentName);
537
+ let json;
538
+ try {
539
+ json = JSON.parse(text);
540
+ }
541
+ catch {
542
+ if (isTransientOverloadResponse(res.status, undefined, text, isRead, res.headers) && attempt < DEFAULT_OVERLOAD_RETRIES) {
543
+ await sleep(computeBackoffMs(attempt, parseRetryAfterSeconds(res.headers.get("retry-after"))), retrySignal);
544
+ continue;
545
+ }
546
+ throw new CliError("bad_response", `${method} ${path} returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
547
+ }
548
+ if (res.status >= 500) {
549
+ const nonIdempotentPost500 = upperMethod === "POST" && res.status === 500;
550
+ if (!nonIdempotentPost500 && isTransientOverloadResponse(res.status, json, text, isRead, res.headers) && attempt < DEFAULT_OVERLOAD_RETRIES) {
551
+ const retryAfter = parseRetryAfterSeconds(res.headers.get("retry-after")) ?? (typeof json?.retry_after === "number" ? json.retry_after : undefined);
552
+ await sleep(computeBackoffMs(attempt, retryAfter), retrySignal);
553
+ continue;
554
+ }
555
+ const err = json;
556
+ throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, undefined, res.status);
557
+ }
558
+ return { status: res.status, ok: res.ok, json: json };
505
559
  }
506
- return { status: res.status, ok: res.ok, json: json };
507
560
  }
508
561
  wsUrl(path) {
509
562
  return this.url.replace(/^http/, "ws") + path;
@@ -514,6 +567,54 @@ export class Client {
514
567
  return ws;
515
568
  }
516
569
  }
517
- function backoff(attempt) {
518
- return new Promise((r) => setTimeout(r, Math.min(8000, 500 * 2 ** attempt)));
570
+ export const DEFAULT_OVERLOAD_RETRIES = 5;
571
+ export function isTransientOverloadResponse(status, json, _text, isRead, headers) {
572
+ if (isRead && status >= 500)
573
+ return true;
574
+ if (status === 502 || status === 504)
575
+ return true;
576
+ if (json?.error === "service_overloaded")
577
+ return true;
578
+ if (status === 503 && (json?.retryable === true || Boolean(headers?.get("retry-after"))))
579
+ return true;
580
+ return false;
581
+ }
582
+ export function parseRetryAfterSeconds(header) {
583
+ if (!header)
584
+ return undefined;
585
+ const trimmed = header.trim();
586
+ if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
587
+ const n = Number(trimmed);
588
+ return Number.isFinite(n) && n >= 0 ? n : undefined;
589
+ }
590
+ const dateMs = Date.parse(trimmed);
591
+ if (Number.isFinite(dateMs)) {
592
+ return Math.max(0, (dateMs - Date.now()) / 1000);
593
+ }
594
+ return undefined;
595
+ }
596
+ export function computeBackoffMs(attempt, retryAfterSeconds, random = Math.random) {
597
+ const expBase = Math.min(15_000, 1000 * 2 ** attempt);
598
+ const floorMs = retryAfterSeconds !== undefined && Number.isFinite(retryAfterSeconds)
599
+ ? Math.max(expBase, Math.min(30_000, Math.round(retryAfterSeconds * 1000)))
600
+ : expBase;
601
+ const jitter = Math.round(floorMs * 0.3 * Math.max(0, Math.min(1, random())));
602
+ return Math.min(30_000, floorMs + jitter);
603
+ }
604
+ function sleepWithAbort(ms, signal) {
605
+ if (signal?.aborted)
606
+ return Promise.reject(new CliError("request_aborted", "request aborted during retry backoff"));
607
+ const testCap = Number(process.env.B9S_TEST_RETRY_SLEEP_MS);
608
+ const actualMs = Number.isFinite(testCap) && testCap > 0 ? Math.min(ms, testCap) : ms;
609
+ return new Promise((resolve, reject) => {
610
+ const onAbort = () => {
611
+ clearTimeout(timer);
612
+ reject(new CliError("request_aborted", "request aborted during retry backoff"));
613
+ };
614
+ const timer = setTimeout(() => {
615
+ signal?.removeEventListener("abort", onAbort);
616
+ resolve();
617
+ }, actualMs);
618
+ signal?.addEventListener("abort", onAbort, { once: true });
619
+ });
519
620
  }
@@ -168,7 +168,7 @@ export async function status(p, out) {
168
168
  const { client, creds } = agentClient(p);
169
169
  if (sub === "set") {
170
170
  const body = {};
171
- for (const k of ["goal", "task", "state", "blocked-on"]) {
171
+ for (const k of ["goal", "task", "state", "blocked-on", "blocked-kind", "blocked-ref"]) {
172
172
  const v = str(p.flags, k);
173
173
  if (v !== undefined)
174
174
  body[k.replace("-", "_")] = v === "" ? null : v;
@@ -195,7 +195,7 @@ export async function status(p, out) {
195
195
  throw new CliError("usage", "--checks-every takes whole minutes (1 to 1440), or none to clear it");
196
196
  }
197
197
  if (!Object.keys(body).length)
198
- throw new CliError("usage", "status set needs at least one of --state --goal --task --blocked-on --tags --custom --checks-every");
198
+ throw new CliError("usage", "status set needs at least one of --state --goal --task --blocked-on --blocked-kind --blocked-ref --tags --custom --checks-every");
199
199
  const r = await client.call("PUT", creds.project ? `/projects/${creds.project}/agents/me/status` : "/agents/me/status", body);
200
200
  out.print(fmtStatus(r.status), r);
201
201
  return;
@@ -95,13 +95,15 @@ function unlockCommand(o) {
95
95
  return `b9s --as ${shellQuote(o.identity)} unlock ${shellQuote(o.lock)} --job ${shellQuote(o.jobId)}${scope}${project}`;
96
96
  }
97
97
  export async function runUnderLock(o, deps) {
98
+ if (o.signal?.aborted)
99
+ return 130;
98
100
  const now = deps.now ?? Date.now;
99
101
  const seconds = Number(process.env.B9S_LOCK_SILENCE_SECONDS ?? '300');
100
102
  if (!Number.isInteger(seconds) || seconds < 1 || seconds > 86400)
101
103
  throw new CliError('usage', 'B9S_LOCK_SILENCE_SECONDS must be an integer from 1 to 86400');
102
104
  const label = commandLabel(o.command);
103
105
  const base = `/projects/${o.project}/locks/${o.lock}`;
104
- const acquireBody = { unit: o.unit, note: o.note ?? label, shared: o.shared, machine: o.machine, job_token: o.token, lock_run: true, process_pid: process.pid };
106
+ const acquireBody = { unit: o.unit, note: o.note ?? label, shared: o.shared, machine: o.machine, job_token: o.token, lock_run: true, process_pid: process.pid, ...(o.remoteJobId ? { remote_job_id: o.remoteJobId } : {}) };
105
107
  const release = async (completion) => {
106
108
  try {
107
109
  const result = await deps.call("POST", `${base}/release`, { shared: o.shared, machine: o.shared ? undefined : o.machine, job_token: o.token, ...completion });
@@ -141,6 +143,11 @@ export async function runUnderLock(o, deps) {
141
143
  }
142
144
  r = await deps.call("POST", `${base}/acquire`, { ...acquireBody });
143
145
  }
146
+ if (o.signal?.aborted) {
147
+ await release();
148
+ deps.log(`${o.lock}: cancellation arrived before command start; released the lock without running it.`);
149
+ return 130;
150
+ }
144
151
  const startedMs = now();
145
152
  const slot = Number.isInteger(r.slot) ? Number(r.slot) : undefined;
146
153
  if (o.lock === "ux-browser" && (slot === undefined || slot < 1 || slot > 3)) {
@@ -163,7 +170,7 @@ export async function runUnderLock(o, deps) {
163
170
  const timer = setInterval(flush, Math.min(30000, Math.max(250, seconds * 1000 / 4)));
164
171
  let result;
165
172
  try {
166
- result = await deps.run(o.command, { lock: o.lock, jobId: o.jobId, ...(slot === undefined ? {} : { slot }), heartbeat: (commandPid) => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, ...(commandPid === undefined ? {} : { command_pid: commandPid }), silence_seconds: seconds }), reportFault: (fault) => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, silence_seconds: seconds, fault }), onOutput: line => { latest = redactProcessCommand(line).replace(/\bb9sjob_[A-Za-z0-9]{32,80}\b/g, '[redacted]').replace(/\b(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi, '$1[redacted]').replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 200); } });
173
+ result = await deps.run(o.command, { lock: o.lock, jobId: o.jobId, ...(slot === undefined ? {} : { slot }), ...(o.signal ? { signal: o.signal } : {}), heartbeat: (commandPid) => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, ...(commandPid === undefined ? {} : { command_pid: commandPid }), silence_seconds: seconds }), reportFault: (fault) => deps.call("POST", `${base}/running`, { shared: o.shared, machine: o.machine, job_token: o.token, command: label, process_pid: process.pid, silence_seconds: seconds, fault }), onOutput: line => { latest = redactProcessCommand(line).replace(/\bb9sjob_[A-Za-z0-9]{32,80}\b/g, '[redacted]').replace(/\b(Bearer\s+)[A-Za-z0-9._~+\/-]+=*/gi, '$1[redacted]').replace(/[\x00-\x1f\x7f]/g, ' ').slice(0, 200); } });
167
174
  }
168
175
  finally {
169
176
  clearInterval(timer);
@@ -171,7 +178,9 @@ export async function runUnderLock(o, deps) {
171
178
  await pending;
172
179
  }
173
180
  code = typeof result === "number" ? result : result.exit_code;
174
- const released = await release(typeof result === "number" ? { exit_code: code } : { exit_code: code, ...(result.gate_output ? { gate_output: true } : {}), ...(result.verified_baseline_sha ? { verified_baseline_sha: result.verified_baseline_sha } : {}), ...(result.tested_tree_sha ? { tested_tree_sha: result.tested_tree_sha } : {}), ...(result.timeout_reason && code !== 0 ? { timeout_reason: result.timeout_reason } : {}) });
181
+ const released = o.signal?.aborted
182
+ ? await release()
183
+ : await release(typeof result === "number" ? { exit_code: code } : { exit_code: code, ...(result.gate_output ? { gate_output: true } : {}), ...(result.verified_baseline_sha ? { verified_baseline_sha: result.verified_baseline_sha } : {}), ...(result.tested_tree_sha ? { tested_tree_sha: result.tested_tree_sha } : {}), ...(result.timeout_reason && code !== 0 ? { timeout_reason: result.timeout_reason } : {}) });
175
184
  if (released.gate_receipt?.recorded === false) {
176
185
  const configured = released.gate_receipt.configured_command;
177
186
  deps.log(`Gate receipt not recorded: ${released.gate_receipt.reason ?? "the reported gate result was refused"}.${configured ? ` Use the configured command: ${configured}` : " No complete gate command is configured."}`);
@@ -277,6 +286,11 @@ export function processDeps(call, log, heartbeatIntervalMs = 15_000) {
277
286
  child.once("exit", () => { supervisorControl?.end(); });
278
287
  child.once("error", () => { supervisorControl?.end(); });
279
288
  const onOutput = context?.onOutput;
289
+ const abortCommand = () => { if (!childClosed)
290
+ child.kill("SIGTERM"); };
291
+ context?.signal?.addEventListener("abort", abortCommand, { once: true });
292
+ if (context?.signal?.aborted)
293
+ abortCommand();
280
294
  let tail = "";
281
295
  let gateOutput = false;
282
296
  let baseline;
@@ -391,11 +405,12 @@ export function processDeps(call, log, heartbeatIntervalMs = 15_000) {
391
405
  child.stdio[4]?.on("data", (chunk) => statusReader.push(chunk.toString("utf8")));
392
406
  child.stdio[4]?.on("end", () => statusReader.end());
393
407
  forward = (signal) => { child.kill(signal); };
394
- child.once("error", (error) => { childClosed = true; stopHeartbeat(); forward = undefined; reject(new CliError("command_not_started", `could not start ${command[0]}: ${error.message}`)); });
408
+ child.once("error", (error) => { childClosed = true; stopHeartbeat(); forward = undefined; context?.signal?.removeEventListener("abort", abortCommand); reject(new CliError("command_not_started", `could not start ${command[0]}: ${error.message}`)); });
395
409
  // `close` follows stdout's `end`, so the final marker lines have been
396
410
  // consumed before we construct the receipt sent with the lock release.
397
411
  child.once("close", async (code, signal) => {
398
412
  childClosed = true;
413
+ context?.signal?.removeEventListener("abort", abortCommand);
399
414
  stopHeartbeat();
400
415
  await heartbeatInFlight;
401
416
  forward = undefined;
@@ -2410,7 +2410,10 @@ function turnFacts(agent, harness, thread, turnCap = DEFAULT_TURNS_PER_HOUR) {
2410
2410
  const accountFingerprint = harness === "codex" ? codexAccountFingerprint() : null;
2411
2411
  if (!thread || !ph || "missing" in ph)
2412
2412
  return { turn: { running: "missing" in (ph ?? {}) && ph.unknown ? null : false, since: null, work_unit_number: null, assignment_event_id: null }, process: null, paused_until: null, pause_started_at: null, turn_guard: null, ...(harness === "codex" ? { usage_account_fingerprint: accountFingerprint } : {}) };
2413
- const until = !ph.running ? probeFor(harness, thread, agent).limitUntil(ph.lastError) : null;
2413
+ const lastErrorAtMs = Date.parse(ph.lastErrorAt ?? "");
2414
+ const until = !ph.running
2415
+ ? probeFor(harness, thread, agent).limitUntil(ph.lastError, Number.isFinite(lastErrorAtMs) ? lastErrorAtMs : undefined)
2416
+ : null;
2414
2417
  const unpausedAt = readState(agent).turn_unpaused_at ?? 0;
2415
2418
  const paused = until && until > Date.now() && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? new Date(until).toISOString() : null;
2416
2419
  const binding = observedTurnBindingFields(ph.startedAt, savedBinding);
@@ -118,6 +118,14 @@ export async function ux(p, out) {
118
118
  return;
119
119
  }
120
120
  if (sub === "job") {
121
+ if (p.positionals[2] === "cancel") {
122
+ const id = p.positionals[3]?.trim();
123
+ if (!id)
124
+ throw new CliError("usage", "b9s ux job cancel <id>");
125
+ const res = await client.call("POST", `/projects/${project}/ux-jobs/${encodeURIComponent(id)}/cancel`, {});
126
+ out.print(`Remote job ${id}: ${res.cancellation === "requested" ? "cancellation requested; waiting for its command group to stop and release the lock" : "cancelled"}`, res);
127
+ return;
128
+ }
121
129
  const id = p.positionals[2]?.trim();
122
130
  if (!id)
123
131
  throw new CliError("usage", "b9s ux job <id> [--log]");
@@ -777,7 +777,7 @@ export function followCurrentCodexProbe(name, initialThread) {
777
777
  turnError: () => active().turnError(),
778
778
  turnOutput: () => active().turnOutput?.() ?? "",
779
779
  turnTokens: () => active().turnTokens?.() ?? null,
780
- limitUntil: (error) => active().limitUntil(error),
780
+ limitUntil: (error, observedAt) => active().limitUntil(error, observedAt),
781
781
  isLimit: (error) => active().isLimit(error),
782
782
  beginTurn: () => active().beginTurn?.(),
783
783
  };
@@ -1536,8 +1536,12 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
1536
1536
  }
1537
1537
  }
1538
1538
  }
1539
- // A watcher that restarted after a usage-limit failure reads the pause from the session itself.
1540
- const until = !ph.running && Date.parse(ph.lastErrorAt ?? "") > unpausedAt ? probe.limitUntil(ph.lastError) : null;
1539
+ // A watcher that restarted after a usage-limit failure reads the pause from the session itself,
1540
+ // anchored to when the error was recorded so time-of-day resets ("resets 8am") expire once passed.
1541
+ const lastErrorAtMs = Date.parse(ph.lastErrorAt ?? "");
1542
+ const until = !ph.running && lastErrorAtMs > unpausedAt
1543
+ ? probe.limitUntil(ph.lastError, Number.isFinite(lastErrorAtMs) ? lastErrorAtMs : undefined)
1544
+ : null;
1541
1545
  if (until && until > Date.now()) {
1542
1546
  ctl.pausedUntil = until;
1543
1547
  ctl.pausedAt = Date.now();
@@ -24,6 +24,7 @@ import { consoleLink } from "../console-links.js";
24
24
  import { isAntigravityWorkspaceWrite } from "../antigravity.js";
25
25
  import { retryGitFetchSync } from "../git-fetch.js";
26
26
  import { detectVendor } from "../vendor.js";
27
+ import { compareRebasedPatchAgainstApproved } from "../rebase-compare.js";
27
28
  /** WU #858: an Antigravity turn's sandbox is fixed when the turn starts. The watcher grants a unit's prepared
28
29
  * worktree to every later turn (watch.ts), but a worktree created mid-turn by `wu start` is not writable until
29
30
  * then, so the agent is told to end the turn instead of failing to commit or submit there. */
@@ -680,8 +681,10 @@ export async function wu(p, out) {
680
681
  return ` ${branchText}${u.worktree ? ` in ${u.worktree.replace(/^\/(Users|home)\/[^/]+\//, "~/")}` : ""}${u.pr_url ? ` · ${u.pr_url}` : ""}${u.merged_sha ? ` · merged ${u.merged_sha}` : ""}${u.evidence.length ? ` · evidence ${u.evidence.map((e) => `evidence:${e}`).join(" ")}` : ""}`;
681
682
  })(),
682
683
  u.worktree_fault ? ` WORKTREE FAULT (${u.worktree_fault.code}): ${u.worktree_fault.message}` : null,
684
+ u.rebase_needed ? ` REBASE NEEDED (${u.rebase_needed.cause}): rebase onto ${u.rebase_needed.target_branch} and resubmit${u.rebase_needed.train_run_id ? ` · train run ${u.rebase_needed.train_run_id}` : ""}${u.rebase_needed.conflicting_files?.length ? ` · conflicts: ${u.rebase_needed.conflicting_files.join(", ")}` : ""}` : null,
683
685
  (u.base_scope ?? u.scope) ? ` scope: ${u.base_scope ?? u.scope}` : null,
684
686
  u.scope_amendments?.length ? ` scope amendments:\n${u.scope_amendments.map((amendment) => ` ${amendment.at} ${amendment.author}: ${amendment.text}`).join("\n")}` : null,
687
+ u.scope_rulings?.length ? ` binding question rulings:\n${u.scope_rulings.map((ruling) => ` ${ruling.at} ${ruling.level} ruling by ${ruling.actor} (asked by ${ruling.asked_by}): ${ruling.text}\n Question: ${ruling.question}`).join("\n")}` : null,
685
688
  ].filter(Boolean).join("\n");
686
689
  };
687
690
  const processDef = async () => (await client.call("GET", `/projects/${project}/process`)).process.definition;
@@ -932,8 +935,18 @@ export async function wu(p, out) {
932
935
  // when it refuses. Check locally whenever we are in a repo so the claim is always a finding.
933
936
  let pushed = null;
934
937
  let remoteCommitBranch = null;
938
+ let rebaseComparison = null;
935
939
  if (where.head) {
936
- rebased = isAncestor(unitTarget, "HEAD");
940
+ if (submitUnit.rebase_needed && hasRemote("origin")) {
941
+ retryGitFetchSync(["fetch", "--quiet", "origin", `+refs/heads/${unitTarget}:refs/remotes/origin/${unitTarget}`], process.cwd());
942
+ }
943
+ rebased = isAncestor(`refs/remotes/origin/${unitTarget}`, "HEAD") ?? isAncestor(unitTarget, "HEAD");
944
+ if (submitUnit.rebase_needed) {
945
+ if (rebased !== true) {
946
+ throw new CliError("rebase_required", `WU #${num()} needs rebase onto ${unitTarget} before resubmit; rebase onto ${unitTarget}, resolve conflicts, and submit again`, `git fetch origin && git rebase origin/${unitTarget} && b9s wu submit ${num()}`);
947
+ }
948
+ rebaseComparison = compareRebasedPatchAgainstApproved(unitTarget, submitUnit.rebase_needed.prior_approved_head);
949
+ }
937
950
  if (where.branch) {
938
951
  const localBranch = where.branch;
939
952
  const check = findRemoteCommitBranch(where.head, localBranch);
@@ -964,6 +977,9 @@ export async function wu(p, out) {
964
977
  throw new CliError("remote_unavailable", formatRemoteCommitFailure("(detached HEAD)", "origin/<branch>", "the current checkout has no local branch name"), "Check out the unit branch and rerun b9s wu submit");
965
978
  }
966
979
  }
980
+ else if (submitUnit.rebase_needed) {
981
+ throw new CliError("rebase_required", `WU #${num()} needs rebase onto ${unitTarget}; run b9s wu submit ${num()} from the unit worktree after rebasing`);
982
+ }
967
983
  const pr = str(p.flags, "pr") ?? null;
968
984
  const telemetry = await roundTelemetry(client, base, num(), name, project);
969
985
  let branchValueIds = [];
@@ -977,10 +993,15 @@ export async function wu(p, out) {
977
993
  process.stderr.write(`b9s: could not attach branch measure results: ${error.message}\n`);
978
994
  }
979
995
  }
980
- const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, usage: telemetry.usage, context: telemetry.context, compactions_since_last: telemetry.compactions.count, compactions_reason: telemetry.compactions.reason, expect: str(p.flags, "expect"), ...(lesson === undefined ? {} : { lesson }), ...(disputes === undefined ? {} : { disputes }) }, !!def.review_rules?.length, unitTarget);
996
+ const payload = submitPayload({ evidence: evidenceIds, ...where, branch_values: branchValueIds, pr_url: pr, rebased, pushed, ...(rebaseComparison ? { rebase_comparison: rebaseComparison } : {}), usage: telemetry.usage, context: telemetry.context, compactions_since_last: telemetry.compactions.count, compactions_reason: telemetry.compactions.reason, expect: str(p.flags, "expect"), ...(lesson === undefined ? {} : { lesson }), ...(disputes === undefined ? {} : { disputes }) }, !!def.review_rules?.length, unitTarget);
981
997
  const r = await client.call("POST", `${base}/${num()}/submit`, payload);
982
998
  const u = r.unit;
983
- out.print(withRuleText(`${fmt(u)}\n${u.status === "classifying" ? `Waiting for ${u.reviewers[0]?.name} to classify it.` : `Routed to ${u.reviewers.map((x) => `@${x.name}`).join(", ")}; you will be told in chat when it is reviewed.`}${remoteCommitBranch ? `\n${formatRemoteCommitSuccess(remoteCommitBranch)}` : ""}`, r, "submit"), r);
999
+ const submitLine = u.status === "classifying"
1000
+ ? `Waiting for ${u.reviewers[0]?.name} to classify it.`
1001
+ : u.status === "approved" && submitUnit.rebase_needed
1002
+ ? `Approval carried over (${rebaseComparison?.summary ?? "reviewed hunks unchanged"}); re-entered approved state at ${u.head ?? "HEAD"}.`
1003
+ : `Routed to ${u.reviewers.map((x) => `@${x.name}`).join(", ")}; you will be told in chat when it is reviewed.${submitUnit.rebase_needed && rebaseComparison?.changed_hunks?.length ? `\nChanged hunks (${rebaseComparison.changed_hunks.length}): ${rebaseComparison.changed_hunks.slice(0, 5).map((h) => `${h.file}${h.after_header ? ` ${h.after_header}` : ""}`).join("; ")}` : ""}`;
1004
+ out.print(withRuleText(`${fmt(u)}\n${submitLine}${remoteCommitBranch ? `\n${formatRemoteCommitSuccess(remoteCommitBranch)}` : ""}`, r, "submit"), r);
984
1005
  return;
985
1006
  }
986
1007
  case "reopen": {
package/dist/harnesses.js CHANGED
@@ -500,9 +500,10 @@ export function claudeLimitUntil(error, now = Date.now()) {
500
500
  let h = Number(m[1]) % 12;
501
501
  if (m[3].toLowerCase() === "pm")
502
502
  h += 12;
503
- const d = new Date(now);
503
+ const anchor = Number.isFinite(now) ? now : Date.now();
504
+ const d = new Date(anchor);
504
505
  d.setHours(h, Number(m[2] ?? 0), 0, 0);
505
- if (d.getTime() <= now)
506
+ if (d.getTime() <= anchor)
506
507
  d.setDate(d.getDate() + 1);
507
508
  return d.getTime();
508
509
  }
@@ -576,7 +577,7 @@ function claudeProbe(session, ref) {
576
577
  return null;
577
578
  }
578
579
  },
579
- limitUntil: (e) => claudeLimitUntil(e),
580
+ limitUntil: (e, observedAt) => claudeLimitUntil(e, observedAt),
580
581
  isLimit: claudeIsLimit,
581
582
  };
582
583
  }
package/dist/help.js CHANGED
@@ -53,8 +53,9 @@ Agent commands
53
53
  b9s who [--account] agent status (--account: all projects); shows pressure and your obligations
54
54
  b9s status is this machine ready: install, network interfaces, internet reach, daemon, and what the service last heard from it
55
55
  b9s next [--project p] your obligations in due order; unknown deadlines include their reason
56
- b9s status set [--state s] [--goal g] [--task t] [--blocked-on b] [--tags a,b] [--custom '{json}']
56
+ b9s status set [--state s] [--goal g] [--task t] [--blocked-on b] [--blocked-kind k] [--blocked-ref r] [--tags a,b] [--custom '{json}']
57
57
  [--checks-every <min>|none] not always on but checking on a schedule: say how often
58
+ blocked-kind: waiting_for_answer|waiting_for_unit|waiting_for_operator|waiting_for_review|environment_error|other
58
59
  b9s status history <agent> [--limit n]
59
60
  b9s away (--for <minutes|hours> | --until <ISO timestamp>) --reason "why" mark yourself away for at most 24 h; the steward stops assigning
60
61
  you work and reassigns reviews; use back when you return
@@ -328,6 +329,7 @@ Machine placement enforces configured session slots and reports machine pressure
328
329
  b9s ux run [<task>] [--compare <screen>] --unit <n> [--on <machine>] [--head <sha>]
329
330
  queue a remote seeded browser task or ux:compare on an account machine labeled ux-host or browser
330
331
  b9s ux job <id> [--log] inspect remote browser job diagnostics; --log prints its full log
332
+ b9s ux job cancel <id> cancel a queued or running remote job; refused after a merge-train push claim
331
333
  b9s ux jobs [--unit <n>] [--limit n] list remote browser jobs in this project
332
334
  b9s gate run <n> [--merge-candidate <sha>] [--on <machine>]
333
335
  b9s gate run --train [--target <branch>] [--on <machine>]