benignswarm 0.12.166 → 0.12.168

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.
@@ -16,7 +16,7 @@ import { basename, dirname, join } from "node:path";
16
16
  import { bool, str } from "../args.js";
17
17
  import { agentRef, configRoot, loadAgent, resolveAgentName } from "../config.js";
18
18
  import { Client } from "../client.js";
19
- import { heartbeatIfActive, reportWatcherHeartbeat, resolveActivitySource } from "../heartbeat.js";
19
+ import { heartbeatIfActive, reportWakeOutcomeChange, reportWatcherHeartbeat, resolveActivitySource } from "../heartbeat.js";
20
20
  import { cleanupDeferredUnitWorktree, scanProject, unitWorktrees } from "./worktrees.js";
21
21
  import { branchAndHead, formatBytes, freeSpaceProbe, pruneReport, removePrunable } from "../git.js";
22
22
  import { CliError } from "../errors.js";
@@ -25,7 +25,7 @@ import { acquireWatchLock } from "../lock.js";
25
25
  import { formatUpdates, gatherUpdates, reportDelivery } from "./hook.js";
26
26
  import { currentAssignmentEvent, deliveredAssignmentBinding } from "../turn-binding.js";
27
27
  import { writeFileAtomic } from "../shared-file.js";
28
- import { readState, updateState } from "../state.js";
28
+ import { readState, updateState, recordWakeAttempt } from "../state.js";
29
29
  import { probeCapabilities } from "../capabilities.js";
30
30
  import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText, recoveryBriefWasDelivered } from "../brief.js";
31
31
  import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, MAX_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS, markTurnUnverified, unverifiedTurn } from "../turn-guard.js";
@@ -244,7 +244,7 @@ export async function watch(p, out, dependencies = {}) {
244
244
  // The watcher sits in a checkout on the machine, so it keeps the worktree registry current: a
245
245
  // scan on start and then hourly reports worktrees nobody is touching, which agent calls never would.
246
246
  const scanCreds = loadAgent(name);
247
- const watcherClient = once ? null : Client.forAgent(scanCreds, undefined, { presence: false });
247
+ const watcherClient = once ? null : Client.forAgent(scanCreds, undefined, { presence: false, machineIdentity: true });
248
248
  let lastScan = 0;
249
249
  let lastCapabilities = 0;
250
250
  // A watcher holding a pending wake-up makes no server call, so a revoked key (the agent moved to
@@ -258,12 +258,13 @@ export async function watch(p, out, dependencies = {}) {
258
258
  if (watcherClient) {
259
259
  try {
260
260
  const phase = turnMode && probe ? probe.phase() : null;
261
- const saved = turnMode ? readState(name).watch_turn_binding : undefined;
261
+ const reportState = readState(name);
262
+ const saved = turnMode ? reportState.watch_turn_binding : undefined;
262
263
  const observed = phase && !("missing" in phase) && phase.running && phase.startedAt && saved?.started_at === phase.startedAt ? saved : null;
263
264
  const binding = observed?.work_unit_number && observed.assignment_event_id
264
265
  ? { work_unit_number: observed.work_unit_number, assignment_event_id: observed.assignment_event_id }
265
266
  : null;
266
- await (dependencies.reportWatcher ?? reportWatcherHeartbeat)(watcherClient, interval, turnMode ? "turn" : "queue", { startedAt: observed?.started_at ?? null, binding });
267
+ await (dependencies.reportWatcher ?? reportWatcherHeartbeat)(watcherClient, interval, turnMode ? "turn" : "queue", { startedAt: observed?.started_at ?? null, binding }, readState(name).wake_attempt);
267
268
  }
268
269
  catch (e) {
269
270
  log(`watcher heartbeat failed: ${e.message}`);
@@ -386,8 +387,18 @@ export async function watch(p, out, dependencies = {}) {
386
387
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
387
388
  }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness, currentWatcherOomKillCount, turn?.antigravityRuntime?.sandbox);
388
389
  else {
390
+ const previousWakeAttempts = JSON.stringify(readState(name).wake_attempts ?? null);
389
391
  const result = await (dependencies.wakeOnce ?? wakeOnce)(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered, undefined, false, undefined, undefined, undefined, 0, dependencies.wakeOnceDependencies);
390
392
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
393
+ const updatedState = readState(name);
394
+ if (!turnMode && watcherClient && JSON.stringify(updatedState.wake_attempts ?? null) !== previousWakeAttempts) {
395
+ try {
396
+ await reportWakeOutcomeChange(watcherClient, interval, JSON.parse(previousWakeAttempts), updatedState.wake_attempts, dependencies.reportWatcher ?? reportWatcherHeartbeat);
397
+ }
398
+ catch (e) {
399
+ log(`watcher wake outcome report failed: ${e.message}`);
400
+ }
401
+ }
391
402
  }
392
403
  }
393
404
  catch (e) {
@@ -447,7 +458,7 @@ export async function watch(p, out, dependencies = {}) {
447
458
  if (exec) {
448
459
  const cmd = exec.replaceAll("{count}", String(total)).replaceAll("{summary}", shellQuote(summary)).replaceAll("{text}", shellQuote(update.text));
449
460
  log(`new activity (${summary}); running: ${cmd}`);
450
- const code = await run(cmd, update.text, { BSCHAT_TEXT: update.text, BSCHAT_SUMMARY: summary, BSCHAT_COUNT: String(total) });
461
+ const { code } = await runCommand(cmd, update.text, { BSCHAT_TEXT: update.text, BSCHAT_SUMMARY: summary, BSCHAT_COUNT: String(total) });
451
462
  if (code !== 0) {
452
463
  log(`command exited ${code}`);
453
464
  delivered = false;
@@ -1190,15 +1201,28 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
1190
1201
  return { ...onDisk, watch_turn_binding: { ...pending, launched_at: startedAt } };
1191
1202
  });
1192
1203
  turnSink(startedTurn);
1204
+ recordWakeAttempt(name, { success: true });
1193
1205
  }
1194
1206
  else {
1195
1207
  log(`${prefix}[${tier}] queueing wake-up: ${summary}`);
1196
- const code = await run(cmd, wake, env);
1208
+ const { code, error: launchError } = await runCommand(cmd, wake, env);
1209
+ const attemptedAt = new Date().toISOString();
1210
+ updateState(name, (onDisk) => {
1211
+ const previous = onDisk.wake_attempts ?? { consecutive_failures: 0, last_failure_at: null, last_failure_exit_code: null, last_failure_message: null, last_success_at: null };
1212
+ return {
1213
+ ...onDisk,
1214
+ wake_attempts: code === 0
1215
+ ? { ...previous, consecutive_failures: 0, last_success_at: attemptedAt }
1216
+ : { ...previous, consecutive_failures: Math.min(previous.consecutive_failures + 1, Number.MAX_SAFE_INTEGER), last_failure_at: attemptedAt, last_failure_exit_code: code, last_failure_message: (launchError ?? `Wake command exited with code ${code}`).slice(0, 300) },
1217
+ };
1218
+ });
1197
1219
  if (code !== 0) {
1220
+ recordWakeAttempt(name, { success: false, exitCode: code, message: `wake command exited ${code}` });
1198
1221
  // The agent was NOT woken. Leave nothing pending so the next poll tries again.
1199
1222
  log(`wake command exited ${code}; will retry next poll. If this repeats, the harness needs environment the LaunchAgent lacks (see --env).`);
1200
1223
  return false;
1201
1224
  }
1225
+ recordWakeAttempt(name, { success: true });
1202
1226
  }
1203
1227
  // Tell the server a wake-up was queued, so it can tell a busy agent from a broken wake path
1204
1228
  // (no harness activity long after). A failure here is logged; the agent was woken regardless.
@@ -2014,12 +2038,22 @@ async function processLag(name, st, fresh, log) {
2014
2038
  function shellQuote(s) {
2015
2039
  return `'${s.replace(/'/g, `'\\''`)}'`;
2016
2040
  }
2017
- function run(cmd, stdin, env) {
2041
+ export function runCommand(cmd, stdin, env) {
2018
2042
  return new Promise((resolve) => {
2019
2043
  const child = spawn("/bin/sh", ["-c", cmd], { stdio: ["pipe", "inherit", "inherit"], env: { ...process.env, ...env } });
2044
+ let stdinError;
2045
+ let stdinClosedEarly = false;
2046
+ child.stdin.on("error", (error) => {
2047
+ // A short-lived command may close stdin before the wake payload is written. EPIPE means
2048
+ // the child chose not to read the payload; it is not an unhandled watcher failure.
2049
+ if (error.code === "EPIPE")
2050
+ stdinClosedEarly = true;
2051
+ else
2052
+ stdinError = error;
2053
+ });
2020
2054
  child.stdin.end(stdin);
2021
- child.on("close", (code) => resolve(code ?? 1));
2022
- child.on("error", () => resolve(1));
2055
+ child.on("close", (code) => resolve({ code: code ?? 1, ...(stdinError ? { error: stdinError.message } : {}), ...(stdinClosedEarly ? { stdinClosedEarly: true } : {}) }));
2056
+ child.on("error", (error) => resolve({ code: 1, error: error.message }));
2023
2057
  });
2024
2058
  }
2025
2059
  /**
@@ -245,12 +245,18 @@ export async function worktrees(p, out, timeouts = {}) {
245
245
  }
246
246
  /** Scan the repository at cwd and report it. Shared with the watcher, which runs it periodically. */
247
247
  export async function scanProject(creds, project, options = {}) {
248
- const scan = scanWorktrees(options.cwd ?? process.cwd(), options);
248
+ const client = Client.forAgent(creds, undefined, { presence: false });
249
+ const timeoutMs = options.requestTimeoutMs ?? WORKTREE_SCAN_TIMEOUT_MS;
250
+ const targets = await timedClientCall(client, "GET", `/projects/${project}/worktrees/scan-targets`, undefined, timeoutMs, `worktree target for project ${project}`);
251
+ const originTargetsByBranch = new Map();
252
+ for (const row of targets.unit_targets) {
253
+ if (!originTargetsByBranch.has(row.branch))
254
+ originTargetsByBranch.set(row.branch, row.target);
255
+ }
256
+ const scan = scanWorktrees(options.cwd ?? process.cwd(), { ...options, measureDisk: true, originTarget: targets.default_target, originTargetsByBranch });
249
257
  if (!scan)
250
258
  throw new CliError("not_a_repo", "the current directory is not inside a git repository", "Run b9s worktrees scan from a checkout of the project's repository.");
251
259
  const machine = defaultMachine();
252
- const client = Client.forAgent(creds, undefined, { presence: false });
253
- const timeoutMs = options.requestTimeoutMs ?? WORKTREE_SCAN_TIMEOUT_MS;
254
260
  options.onProgress?.(`Reporting worktrees for project ${project} (timeout ${timeoutMs} ms)`);
255
261
  const r = await timedClientCall(client, "POST", `/projects/${project}/worktrees/scan`, { machine, repo: scan.repo, worktrees: scan.worktrees }, timeoutMs, `worktree registry scan for project ${project}`);
256
262
  return { machine, repo: scan.repo, recorded: r.recorded, missing: r.missing };
@@ -11,7 +11,8 @@ import { readState, updateState } from "../state.js";
11
11
  import { codexRollout, sessionsOf } from "../sessions.js";
12
12
  import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
13
13
  import { CliError, WrittenReceiptMismatchError } from "../errors.js";
14
- import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, hasRemote, inspectRemoteBranch, isAncestor, isShaBranchName, pushBranchToOrigin, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, verifyUnitHeadOnOrigin, worktreeForBranch, worktreeState } from "../git.js";
14
+ import { branchAndHead, commitAtTime, defaultMachine, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, hasRemote, inspectRemoteBranch, isAncestor, isShaBranchName, machineIdentityForAgent, pushBranchToOrigin, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, verifyUnitHeadOnOrigin, worktreeForBranch, worktreeState } from "../git.js";
15
+ import { executeScopedGateForSubmit, scopedGatePlan } from "../scoped-gate.js";
15
16
  import { join, resolve } from "node:path";
16
17
  import { formatStepRules, table } from "../output.js";
17
18
  import { restoreRecoveryArchive, sha256 as recoverySha256 } from "../recovery-archive.js";
@@ -644,8 +645,8 @@ function reportSubmitScopeChecklist(scope) {
644
645
  }
645
646
  process.stderr.write(`b9s: pre-submit scope checklist (verify each item and its evidence):\n${numbered.map((line) => ` [ ] ${line}`).join("\n")}\n`);
646
647
  }
647
- export function submitPayload(fields, hasReviewRules, target, cwd = process.cwd()) {
648
- const paths = changedPathsAgainstTarget(target, cwd);
648
+ export function submitPayload(fields, includeChangedPaths, target, cwd = process.cwd(), precomputedPaths) {
649
+ const paths = precomputedPaths ?? changedPathsAgainstTarget(target, cwd);
649
650
  const directories = {}, fileKinds = {};
650
651
  for (const path of paths) {
651
652
  const slash = path.lastIndexOf("/");
@@ -655,7 +656,7 @@ export function submitPayload(fields, hasReviewRules, target, cwd = process.cwd(
655
656
  directories[directory] = (directories[directory] ?? 0) + 1;
656
657
  fileKinds[kind] = (fileKinds[kind] ?? 0) + 1;
657
658
  }
658
- return { ...fields, changed_paths: hasReviewRules ? paths : [], changed_path_summary: { total: paths.length, by_directory: directories, by_file_kind: fileKinds, paths: paths.slice(0, 200), truncated: paths.length > 200 } };
659
+ return { ...fields, changed_paths: includeChangedPaths ? paths : [], changed_path_summary: { total: paths.length, by_directory: directories, by_file_kind: fileKinds, paths: paths.slice(0, 200), truncated: paths.length > 200 } };
659
660
  }
660
661
  export function branchValueIdsAtHead(values, head) {
661
662
  if (!head)
@@ -753,7 +754,7 @@ export async function wu(p, out) {
753
754
  const createdReceiptLine = (u) => `WU #${u.number} created: ${u.title}`;
754
755
  const fmt = (u) => {
755
756
  const waitList = Array.isArray(u.waits_on) ? u.waits_on : u.waiting_on ? [u.waiting_on] : [];
756
- const flags = [u.priority === "urgent" ? "URGENT" : null, u.assigned_by ? `assigned by ${u.assigned_by}` : null, u.preferred_name ? `reserved for ${u.preferred_name}${u.hold ? " until free" : ""}` : null, u.hold && u.status === "assigned" ? "held" : null, waitList.length ? `waits on ${waitList.map((n) => `#${n}`).join(", ")}` : null, u.lands_with ? `lands with WU #${u.lands_with}` : null, u.review_wait ? `waiting on ${u.review_wait.type === "unit" ? `WU #${u.review_wait.target}` : u.review_wait.type === "ask" ? `ask ${u.review_wait.target}` : u.review_wait.type === "machine" ? `machine ${u.review_wait.target}` : u.review_wait.type === "text" ? u.review_wait.target : "evidence"} for ${Math.max(0, Math.round((Date.now() - Date.parse(u.review_wait.started_at)) / 60000))} min` : null, u.milestone ? `milestone ${u.milestone}` : null, u.target ? `lands in ${u.target}` : null, u.replay_of ? "REPLAY" : null, u.trial_tags?.length ? `trial on ${u.trial_tags.map((t) => `#${t}`).join(" ")}` : null].filter(Boolean).join(" · ");
757
+ const flags = [u.held_for_review ? "HELD FOR REVIEW" : null, u.priority === "urgent" ? "URGENT" : null, u.assigned_by ? `assigned by ${u.assigned_by}` : null, u.preferred_name ? `reserved for ${u.preferred_name}${u.hold ? " until free" : ""}` : null, u.hold && u.status === "assigned" ? "held for busy owner" : null, waitList.length ? `waits on ${waitList.map((n) => `#${n}`).join(", ")}` : null, u.lands_with ? `lands with WU #${u.lands_with}` : null, u.review_wait ? `waiting on ${u.review_wait.type === "unit" ? `WU #${u.review_wait.target}` : u.review_wait.type === "ask" ? `ask ${u.review_wait.target}` : u.review_wait.type === "machine" ? `machine ${u.review_wait.target}` : u.review_wait.type === "text" ? u.review_wait.target : "evidence"} for ${Math.max(0, Math.round((Date.now() - Date.parse(u.review_wait.started_at)) / 60000))} min` : null, u.milestone ? `milestone ${u.milestone}` : null, u.target ? `lands in ${u.target}` : null, u.replay_of ? "REPLAY" : null, u.trial_tags?.length ? `trial on ${u.trial_tags.map((t) => `#${t}`).join(" ")}` : null].filter(Boolean).join(" · ");
757
758
  const reviewers = u.reviewers.map((r) => `${r.name}${r.tags.length ? ` for ${r.tags.map((t) => `#${t}`).join(" ")}` : ""}`).join(", ");
758
759
  const approvals = u.approvals.map((a) => a.name).join(", ");
759
760
  return [
@@ -831,7 +832,8 @@ export async function wu(p, out) {
831
832
  const priority = str(p.flags, "priority");
832
833
  if (priority !== undefined && priority !== "normal" && priority !== "urgent")
833
834
  throw new CliError("usage", "--priority must be urgent or normal");
834
- const r = await client.call("POST", base, { client_id: clientId, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...symbolicBranchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, ...startTelemetry(name) }, { retries: 3 });
835
+ const reviewHold = bool(p.flags, "review-hold");
836
+ const r = await client.call("POST", base, { client_id: clientId, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), evidence: list("evidence"), after: afterUnits(), reworks: list("reworks").map(Number), force: bool(p.flags, "force"), held_for_review: reviewHold, ...(priority ? { priority } : {}), ...symbolicBranchAndHead(), worktree: process.cwd(), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, ...startTelemetry(name) }, { retries: 3 });
835
837
  const n = r.unit.number;
836
838
  const created = createdReceipt(r.unit, r);
837
839
  if (r.unit.waiting_on != null) {
@@ -841,6 +843,10 @@ export async function wu(p, out) {
841
843
  // Report the irreversible create before any local worktree or start step can fail. JSON
842
844
  // callers receive this compact, stable receipt instead of the later start envelope.
843
845
  out.print(withRuleText(createdReceiptLine(r.unit), r, "cut"), created);
846
+ if (reviewHold) {
847
+ out.print(`${fmt(r.unit)}\nHeld for review; no worker or automation can take it until an assigner or operator releases it with b9s wu release-for-review ${n}.`, created);
848
+ return;
849
+ }
844
850
  const contextDecision = await contextDecisionForStart(client, base, r.unit, name, p);
845
851
  const { path, branch, mode } = prepareWorktree(n, r.unit, await processDef(), p, await checkoutExclude());
846
852
  const where = symbolicBranchAndHead(path);
@@ -865,6 +871,12 @@ export async function wu(p, out) {
865
871
  }
866
872
  const to = str(p.flags, "to");
867
873
  const reason = str(p.flags, "reason");
874
+ const overrideWakeability = bool(p.flags, "override-unwakeable");
875
+ const overrideReason = str(p.flags, "override-reason");
876
+ if (overrideWakeability && !overrideReason?.trim())
877
+ throw new CliError("usage", '--override-unwakeable requires --override-reason "why this unavailable target must receive work"');
878
+ if (overrideReason !== undefined && !overrideWakeability)
879
+ throw new CliError("usage", "--override-reason requires --override-unwakeable");
868
880
  const priority = str(p.flags, "priority");
869
881
  if (priority !== undefined && priority !== "normal" && priority !== "urgent")
870
882
  throw new CliError("usage", "--priority must be urgent or normal");
@@ -876,7 +888,7 @@ export async function wu(p, out) {
876
888
  throw new CliError("usage", "amend an existing unit session requirement with wu scope before assigning it");
877
889
  if (p.flags.after !== undefined)
878
890
  throw new CliError("usage", "--after applies when creating a unit; use b9s wu wait to change an existing unit's wait");
879
- const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }) });
891
+ const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }), ...(overrideWakeability ? { override_unwakeable: true, override_reason: overrideReason } : {}) });
880
892
  out.print(withRuleText(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}`, r, "cut"), r);
881
893
  return;
882
894
  }
@@ -892,7 +904,7 @@ export async function wu(p, out) {
892
904
  const scope = await scopeText();
893
905
  const replay = str(p.flags, "replay-of");
894
906
  const clientId = randomUUID();
895
- const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, ...(baseFlag !== undefined ? { base: baseFlag } : {}), ...(continueFlag ? { continue: true } : {}), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(priority ? { priority } : {}), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
907
+ const r = await client.call("POST", `${base}/assign`, { client_id: clientId, to, title, scope, ...(str(p.flags, "summary") === undefined ? {} : { plain_summary: str(p.flags, "summary") }), tags: unitTags, requires: list("requires"), ...(sessionRequirement() === undefined ? {} : { session_requirement: sessionRequirement() }), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: explicitBranch, ...(baseFlag !== undefined ? { base: baseFlag } : {}), ...(continueFlag ? { continue: true } : {}), target: str(p.flags, "target") ?? null, lands_with: parseLandsWith(str(p.flags, "lands-with")), milestone: str(p.flags, "milestone") ?? null, hold: !!p.flags.hold, held_for_review: bool(p.flags, "review-hold"), force: bool(p.flags, "force"), ...(overrideWakeability ? { override_unwakeable: true, override_reason: overrideReason } : {}), ...(priority ? { priority } : {}), ...(reason === undefined ? {} : { reason }) }, { retries: 3 });
896
908
  const clientWarnings = [];
897
909
  if (explicitBranch && baseFlag === undefined && repoName() && hasRemote("origin")) {
898
910
  const remoteState = inspectRemoteBranch(explicitBranch);
@@ -908,6 +920,22 @@ export async function wu(p, out) {
908
920
  out.print(withRuleText(`${createdReceiptLine(r.unit)}\n${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${assignmentGuidanceOutput([...(r.warnings ?? []), ...clientWarnings])}`, r, "cut"), createdReceipt(r.unit, r));
909
921
  return;
910
922
  }
923
+ case "release-for-review": {
924
+ const raw = p.positionals.slice(2).join(",");
925
+ const numbers = [...new Set(raw.split(",").map((value) => {
926
+ const trimmed = value.trim().replace(/^#/, "");
927
+ if (!/^\d+$/.test(trimmed) || Number(trimmed) < 1)
928
+ throw new CliError("usage", "wu release-for-review expects one or more comma-separated unit numbers");
929
+ return Number(trimmed);
930
+ }))];
931
+ if (!numbers.length)
932
+ throw new CliError("usage", "wu release-for-review <n>[,<n>...]");
933
+ const released = [];
934
+ for (const number of numbers)
935
+ released.push((await client.call("POST", `${base}/${number}/review-hold/release`, {})).unit);
936
+ out.print(released.map((unit) => `${fmt(unit)}\nReview hold released; normal dispatch resumed.`).join("\n"), { units: released });
937
+ return;
938
+ }
911
939
  case "park": {
912
940
  const note = str(p.flags, "note");
913
941
  if (!note?.trim())
@@ -942,9 +970,15 @@ export async function wu(p, out) {
942
970
  // Pull a queued unit: for yourself (qualified by works or trial), or for someone with --to (assigners).
943
971
  const to = str(p.flags, "to") ?? null;
944
972
  const reason = str(p.flags, "reason");
973
+ const overrideWakeability = bool(p.flags, "override-unwakeable");
974
+ const overrideReason = str(p.flags, "override-reason");
975
+ if (overrideWakeability && (!to || !overrideReason?.trim()))
976
+ throw new CliError("usage", '--override-unwakeable requires --to <agent> and --override-reason "why this unavailable target must receive work"');
977
+ if (overrideReason !== undefined && !overrideWakeability)
978
+ throw new CliError("usage", "--override-reason requires --override-unwakeable");
945
979
  if (reason !== undefined && !to)
946
980
  throw new CliError("usage", 'wu take <n> --to <agent> --reason "why" is only for an assigner handing work to a named agent');
947
- const r = await client.call("POST", `${base}/${num()}/take`, { to, ...(reason === undefined ? {} : { reason }) });
981
+ const r = await client.call("POST", `${base}/${num()}/take`, { to, ...(reason === undefined ? {} : { reason }), ...(overrideWakeability ? { override_unwakeable: true, override_reason: overrideReason } : {}) });
948
982
  out.print(`${fmt(r.unit)}\n${to ? `Handed to ${r.unit.owner_name}.` : `Yours. Start it: b9s wu start ${r.unit.number}`}`, r);
949
983
  return;
950
984
  }
@@ -1079,6 +1113,44 @@ export async function wu(p, out) {
1079
1113
  throw new CliError("rebase_required", `WU #${num()} needs rebase onto ${unitTarget}; run b9s wu submit ${num()} from the unit worktree after rebasing`);
1080
1114
  }
1081
1115
  const pr = str(p.flags, "pr") ?? null;
1116
+ const changedPaths = where.head ? changedPathsAgainstTarget(unitTarget) : [];
1117
+ const fullUnitHead = where.head ? fullSha("HEAD") : null;
1118
+ let scopedReceipt = null;
1119
+ if (fullUnitHead && def.merge?.require_gate_receipt) {
1120
+ const plan = scopedGatePlan(changedPaths, def.merge);
1121
+ if (plan.required && plan.stages.length > 0) {
1122
+ const originTargetSha = fullSha(`refs/remotes/origin/${unitTarget}^{commit}`);
1123
+ const existing = submitRecord.scoped_gate_status?.receipt;
1124
+ const matchesExisting = Boolean(existing
1125
+ && existing.exit_code === 0
1126
+ && existing.unit_head === fullUnitHead
1127
+ && existing.target_branch === unitTarget
1128
+ && originTargetSha
1129
+ && existing.target_sha === originTargetSha
1130
+ && (rebased === true || existing.merged_sha !== fullUnitHead)
1131
+ && Array.isArray(existing.stages)
1132
+ && plan.stages.every((stage) => existing.stages.includes(stage)));
1133
+ if (matchesExisting) {
1134
+ process.stderr.write(`b9s: reusing passing scoped gate receipt for ${fullUnitHead.slice(0, 9)} merged with origin/${unitTarget} (${originTargetSha.slice(0, 9)})\n`);
1135
+ }
1136
+ else {
1137
+ process.stderr.write(`b9s: running local scoped submit gate stages [${plan.stages.join(", ")}] for ${fullUnitHead.slice(0, 9)} merged with current origin/${unitTarget}\n`);
1138
+ scopedReceipt = await executeScopedGateForSubmit({
1139
+ unitNumber: num(),
1140
+ unitHead: fullUnitHead,
1141
+ targetBranch: unitTarget,
1142
+ changedPaths,
1143
+ machine: machineIdentityForAgent(creds.machine),
1144
+ merge: def.merge,
1145
+ });
1146
+ if (scopedReceipt) {
1147
+ rebased = scopedReceipt.rebased ?? rebased;
1148
+ await client.call("POST", `${base}/${num()}/scoped-gate-receipts`, scopedReceipt);
1149
+ process.stderr.write(`b9s: recorded self-attested scoped gate receipt for merged head ${scopedReceipt.merged_sha.slice(0, 9)} (unit ${scopedReceipt.unit_head.slice(0, 9)} + origin/${unitTarget} ${scopedReceipt.target_sha.slice(0, 9)})\n`);
1150
+ }
1151
+ }
1152
+ }
1153
+ }
1082
1154
  const telemetry = await roundTelemetry(client, base, num(), name, project);
1083
1155
  let branchValueIds = [];
1084
1156
  if (where.head) {
@@ -1091,7 +1163,7 @@ export async function wu(p, out) {
1091
1163
  process.stderr.write(`b9s: could not attach branch measure results: ${error.message}\n`);
1092
1164
  }
1093
1165
  }
1094
- 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);
1166
+ 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 }) }, Boolean(def.review_rules?.length || def.merge?.require_gate_receipt), unitTarget, process.cwd(), where.head ? changedPaths : []);
1095
1167
  const r = await client.call("POST", `${base}/${num()}/submit`, payload);
1096
1168
  const u = r.unit;
1097
1169
  const submitLine = u.status === "classifying"
@@ -1253,11 +1325,17 @@ export async function wu(p, out) {
1253
1325
  const replace = str(p.flags, "replace");
1254
1326
  const withName = str(p.flags, "with");
1255
1327
  const note = str(p.flags, "note");
1328
+ const overrideWakeability = bool(p.flags, "override-unwakeable");
1329
+ const overrideReason = str(p.flags, "override-reason");
1330
+ if (overrideWakeability && (!withName || !overrideReason?.trim()))
1331
+ throw new CliError("usage", '--override-unwakeable requires --with <agent> and --override-reason "why this unavailable reviewer must review"');
1332
+ if (overrideReason !== undefined && !overrideWakeability)
1333
+ throw new CliError("usage", "--override-reason requires --override-unwakeable");
1256
1334
  if (!replace?.trim() || !note?.trim()) {
1257
1335
  throw new CliError("usage", 'wu reviewer <n> --replace <agent> [--with <agent>] --note "why this reviewer is being replaced"');
1258
1336
  }
1259
1337
  const r = await client.call("POST", `${base}/${num()}/reviewer`, {
1260
- replace: replace.trim(), ...(withName?.trim() ? { with: withName.trim() } : {}), note: note.trim(),
1338
+ replace: replace.trim(), ...(withName?.trim() ? { with: withName.trim() } : {}), note: note.trim(), ...(overrideWakeability ? { override_unwakeable: true, override_reason: overrideReason } : {}),
1261
1339
  });
1262
1340
  out.print(withRuleText(fmt(r.unit), r, "submit"), r);
1263
1341
  return;
@@ -2602,19 +2680,26 @@ async function reviewUsage(client, project, name) {
2602
2680
  const until = new Date().toISOString();
2603
2681
  const session = measurableSession(name);
2604
2682
  let since;
2683
+ let cursor;
2605
2684
  try {
2606
2685
  const result = await client.call("GET", `/projects/${project}/agents/me/usage-cursor`);
2607
- if (result.since === null)
2686
+ cursor = result.since;
2687
+ }
2688
+ catch (error) {
2689
+ return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: `could not read session usage cursor: ${error.message}` };
2690
+ }
2691
+ try {
2692
+ if (cursor === null)
2608
2693
  since = sessionStart(session);
2609
2694
  else {
2610
- const cursor = typeof result.since === "string" ? Date.parse(result.since) : NaN;
2611
- if (!Number.isFinite(cursor))
2695
+ const cursorAt = typeof cursor === "string" ? Date.parse(cursor) : NaN;
2696
+ if (!Number.isFinite(cursorAt))
2612
2697
  throw new Error("invalid session usage cursor");
2613
- since = new Date(cursor + 1).toISOString();
2698
+ since = new Date(cursorAt + 1).toISOString();
2614
2699
  }
2615
2700
  }
2616
2701
  catch (error) {
2617
- return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: `could not read session usage cursor: ${error.message}` };
2702
+ return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: `could not read session timestamp: ${error.message}` };
2618
2703
  }
2619
2704
  if (!since)
2620
2705
  return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: "no earlier usage boundary or timestamped session is available" };
@@ -0,0 +1,76 @@
1
+ import { arch, platform } from 'node:os';
2
+ const TARGETS = {
3
+ 'merge-train-gate-api-tests-pg': { stage: 'api tests', engine: 'pg', workspace: 'apps/api' },
4
+ 'merge-train-gate-api-tests-miniflare': { stage: 'api tests', engine: 'miniflare', workspace: 'apps/api' },
5
+ 'merge-train-gate-cli-tests-node': { stage: 'cli tests', engine: 'node', workspace: 'packages/cli' },
6
+ 'merge-train-gate-web-tests-node': { stage: 'web tests', engine: 'node', workspace: 'apps/web' },
7
+ };
8
+ /** Fetch every page; never turn an unavailable or malformed snapshot into an empty one. */
9
+ export async function loadGateQuarantines(client, project, branch) {
10
+ const expectations = [];
11
+ const seenCursors = new Set();
12
+ let cursor;
13
+ do {
14
+ const query = cursor ? `?limit=100&cursor=${encodeURIComponent(cursor)}` : '?limit=100';
15
+ const page = await client.call('GET', `/projects/${encodeURIComponent(project)}/test-expectations${query}`);
16
+ if (!Array.isArray(page?.expectations))
17
+ throw new Error('test-expectations response omitted its expectations array');
18
+ expectations.push(...page.expectations);
19
+ if (page.next_cursor !== undefined && (typeof page.next_cursor !== 'string' || !page.next_cursor || seenCursors.has(page.next_cursor)))
20
+ throw new Error('test-expectations returned an invalid or repeated cursor');
21
+ cursor = page.next_cursor;
22
+ if (cursor)
23
+ seenCursors.add(cursor);
24
+ } while (cursor);
25
+ const runCache = new Map();
26
+ const result = [];
27
+ for (const expectation of expectations) {
28
+ if (expectation?.status !== 'quarantined')
29
+ continue;
30
+ if (typeof expectation.target_key !== 'string' || typeof expectation.expires_at !== 'string' || !Number.isFinite(Date.parse(expectation.expires_at)))
31
+ throw new Error('quarantined expectation has invalid target or expiry');
32
+ if (Date.parse(expectation.expires_at) <= Date.now())
33
+ continue;
34
+ let target;
35
+ try {
36
+ target = JSON.parse(expectation.target_key);
37
+ }
38
+ catch {
39
+ throw new Error('quarantined expectation has an invalid target key');
40
+ }
41
+ if (!target || typeof target !== 'object' || Array.isArray(target))
42
+ throw new Error('quarantined expectation has an invalid target key');
43
+ const spec = TARGETS[target.target_config];
44
+ if (!spec || target.branch !== branch || target.package !== spec.workspace || target.workspace != null)
45
+ continue;
46
+ const os = platform() === 'darwin' ? 'macos' : platform() === 'win32' ? 'windows' : platform();
47
+ if (target.runner?.os !== os || target.runner?.arch !== arch() || target.runner?.runtime !== `node-${process.versions.node}` || target.runner?.sandbox !== 'unknown' || target.runner?.toolchain != null || target.runner?.container != null || target.runner?.test_configuration != null)
48
+ continue;
49
+ if (typeof expectation.opened_from_run_id !== 'string' || typeof expectation.test_id !== 'string')
50
+ throw new Error('gate quarantine is missing its report or test identity');
51
+ let run = runCache.get(expectation.opened_from_run_id);
52
+ if (!run) {
53
+ const response = await client.call('GET', `/projects/${encodeURIComponent(project)}/test-runs/${encodeURIComponent(expectation.opened_from_run_id)}`);
54
+ run = response?.run;
55
+ if (!run || !Array.isArray(run.tests))
56
+ throw new Error('gate quarantine source report is unavailable');
57
+ runCache.set(expectation.opened_from_run_id, run);
58
+ }
59
+ if (run.source?.package !== spec.workspace || run.source?.target_config !== target.target_config || run.source?.target_branch !== branch || !run.artifact?.evidence_id)
60
+ throw new Error('gate quarantine source report does not match its target');
61
+ const matches = run.tests.filter((test) => test?.id === expectation.test_id && test.identity_comparable !== false);
62
+ if (matches.length !== 1 || typeof matches[0].suite !== 'string')
63
+ throw new Error('gate quarantine does not identify exactly one comparable reported test');
64
+ const suite = matches[0].suite;
65
+ if (!/^(test|src)\/[A-Za-z0-9_.\-/]+$/.test(suite) || suite.split('/').some((part) => !part || part === '.' || part === '..'))
66
+ throw new Error('gate quarantine source report has an unsafe test path');
67
+ const prefix = `${suite}/${suite} :: `;
68
+ if (!expectation.test_id.startsWith(prefix))
69
+ throw new Error('gate quarantine source report has an ambiguous test identity');
70
+ const test = expectation.test_id.slice(prefix.length);
71
+ if (!test || test === '(suite failure)' || /[\x00-\x1f\x7f]/.test(test))
72
+ throw new Error('gate quarantine source report has an invalid test name');
73
+ result.push({ stage: spec.stage, engine: spec.engine, file: `${spec.workspace}/${suite}`, test, expires_at: new Date(expectation.expires_at).toISOString() });
74
+ }
75
+ return result;
76
+ }
@@ -0,0 +1,50 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { existsSync, readFileSync } from 'node:fs';
3
+ import { platform, arch } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { parseTestRunReport } from './test-results.js';
6
+ const STAGES = [
7
+ { stage: 'api tests', engine: 'pg', workspace: 'apps/api', filename: 'api-pg.xml' },
8
+ { stage: 'api tests', engine: 'miniflare', workspace: 'apps/api', filename: 'api-miniflare.xml' },
9
+ { stage: 'cli tests', engine: 'node', workspace: 'packages/cli', filename: 'cli.xml' },
10
+ { stage: 'web tests', engine: 'node', workspace: 'apps/web', filename: 'web.xml' },
11
+ ];
12
+ function machineAlias(machine) {
13
+ const segment = machine.split(/[\\/]/).at(-1) ?? "";
14
+ const alias = segment.toLowerCase().replace(/[^a-z0-9_-]/g, "-").replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, "").slice(0, 64).replace(/^[^a-z0-9]+|[^a-z0-9]+$/g, "");
15
+ return alias || "unknown-runner";
16
+ }
17
+ /** Import real failing Vitest reports as canonical test runs for later quarantine decisions. */
18
+ export async function importFailingGateReports(options) {
19
+ if (!/^[A-Za-z0-9-]{1,100}$/.test(options.trainRunId))
20
+ throw new Error('invalid merge train run ID');
21
+ const imported = [];
22
+ for (const item of STAGES) {
23
+ const path = join(options.dir, item.filename);
24
+ if (!existsSync(path))
25
+ continue; // A pre-test or suite startup error has no importable report.
26
+ const bytes = readFileSync(path);
27
+ const metadata = {
28
+ schema_version: 1,
29
+ source: { commit: options.candidate, target_commit: options.base, target_branch: options.branch, package: item.workspace, target_config: `merge-train-gate-${item.stage.replaceAll(" ", "-")}-${item.engine}` },
30
+ invocation: { argv: ['scripts/gate.sh', item.stage], cwd: '.' },
31
+ runner: { machine: machineAlias(options.creds.machine), os: platform() === 'darwin' ? 'macos' : platform() === 'win32' ? 'windows' : platform(), arch: arch(), runtime: `node-${process.versions.node}`, sandbox: 'unknown' },
32
+ run: { started_at: options.startedAt, ended_at: options.endedAt, exit_status: 1, state: 'completed' },
33
+ };
34
+ const draft = parseTestRunReport(item.filename, bytes, Buffer.from(JSON.stringify(metadata)));
35
+ if (!draft.tests.some(test => test.outcome === 'failed'))
36
+ continue;
37
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
38
+ const response = await fetch(`${options.creds.url.replace(/\/$/, '')}/projects/${encodeURIComponent(options.project)}/evidence`, {
39
+ method: 'POST', headers: { ...options.client.headers(), 'content-type': 'application/xml', 'x-bschat-sha256': sha256, 'x-bschat-filename': `train-${options.trainRunId}-${item.filename}`, 'x-bschat-kind': 'test' }, body: new Uint8Array(bytes), signal: AbortSignal.timeout(30_000),
40
+ });
41
+ const result = await response.json();
42
+ if (!response.ok || typeof result?.evidence?.id !== 'string' || result.evidence.sha256 !== sha256)
43
+ throw new Error(`failed to upload ${item.stage} report (HTTP ${response.status})`);
44
+ const created = await options.client.call('POST', `/projects/${encodeURIComponent(options.project)}/test-runs`, { ...draft, artifact: { evidence_id: result.evidence.id, sha256 } });
45
+ if (typeof created?.run?.run_id !== 'string')
46
+ throw new Error(`${item.stage} report import did not return a run ID`);
47
+ imported.push({ stage: item.stage, runId: created.run.run_id });
48
+ }
49
+ return imported;
50
+ }
package/dist/git.js CHANGED
@@ -169,6 +169,29 @@ export function mergeFacts(cwd, worktree, observedHead) {
169
169
  const count = (range) => { const value = git(["rev-list", "--count", range], cwd); return value !== null && /^\d+$/.test(value) ? Number(value) : null; };
170
170
  return { repo, base, merged, ahead: count(`${base_sha}..${head}`), behind: count(`${head}..${base_sha}`), base_sha };
171
171
  }
172
+ /** Resolve the advertised target without updating the checkout's tracking refs. */
173
+ function scanOriginTip(cwd, target, deadline) {
174
+ const timeout = deadline - Date.now();
175
+ if (timeout <= 0)
176
+ return null;
177
+ const ref = `refs/heads/${target}`;
178
+ const env = { ...gitTransportEnv(), GIT_TERMINAL_PROMPT: "0" };
179
+ const listed = spawnSync("git", ["ls-remote", "--exit-code", "--heads", "origin", ref], { cwd, env, timeout, encoding: "utf8" });
180
+ if (listed.status !== 0)
181
+ return null;
182
+ const [sha, advertisedRef] = listed.stdout.trim().split("\t");
183
+ if (advertisedRef !== ref || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(sha))
184
+ return null;
185
+ if (fullSha(`${sha}^{commit}`, cwd) === sha)
186
+ return sha;
187
+ const remaining = deadline - Date.now();
188
+ if (remaining <= 0)
189
+ return null;
190
+ const fetched = spawnSync("git", ["fetch", "--no-tags", "--no-write-fetch-head", "origin", sha], {
191
+ cwd, env, timeout: remaining, encoding: "utf8",
192
+ });
193
+ return fetched.status === 0 && fullSha(`${sha}^{commit}`, cwd) === sha ? sha : null;
194
+ }
172
195
  /** Every linked worktree of the repository at cwd, with the same facts an agent call reports. */
173
196
  export function scanWorktrees(cwd = process.cwd(), options = {}) {
174
197
  const list = git(["worktree", "list", "--porcelain"], cwd);
@@ -186,6 +209,11 @@ export function scanWorktrees(cwd = process.cwd(), options = {}) {
186
209
  return null;
187
210
  const repo = entries[0].path;
188
211
  options.onProgress?.(`Scanning repository ${repo}`);
212
+ // Apply one wall-clock budget across the repository. A timed-out observation is unknown.
213
+ const diskDeadline = Date.now() + 10_000;
214
+ const completeGraph = options.measureDisk && git(["rev-parse", "--is-shallow-repository"], cwd) === "false";
215
+ const originDeadline = Date.now() + 10_000;
216
+ const targetRevisions = new Map();
189
217
  const worktrees = entries.map(({ path: p, locked }) => {
190
218
  options.onProgress?.(`Scanning worktree ${p}`);
191
219
  const branch = git(["symbolic-ref", "--short", "-q", "HEAD"], p) ?? git(["rev-parse", "--short", "HEAD"], p);
@@ -193,7 +221,25 @@ export function scanWorktrees(cwd = process.cwd(), options = {}) {
193
221
  const worktreeStatus = status(p, options.statusTimeoutMs);
194
222
  const f = head ? mergeFacts(p, p, head) : { base: null, merged: null, ahead: null, behind: null, base_sha: null };
195
223
  const empty = existsSync(p) && readdirSync(p).every((e) => e === ".git");
196
- return { path: p, branch, head, dirty: worktreeStatus === null ? null : worktreeStatus.length > 0, base: f.base, merged: f.merged, ahead: f.ahead, behind: f.behind, base_sha: f.base_sha, empty, locked };
224
+ let disk_bytes = null;
225
+ const remaining = diskDeadline - Date.now();
226
+ if (options.measureDisk && remaining > 0 && isAbsolute(p)) {
227
+ // -x stays on this volume, and excludes Git's shared object store from checkout usage.
228
+ const measurement = spawnSync("du", process.platform === "darwin" ? ["-skx", "-I", ".git", p] : ["-skx", "--exclude=.git", p], { timeout: remaining, encoding: "utf8" });
229
+ const line = measurement.status === 0 ? /^(\d+)\s/.exec(measurement.stdout ?? "") : null;
230
+ const bytes = line ? Number(line[1]) * 1024 : NaN;
231
+ if (Number.isSafeInteger(bytes))
232
+ disk_bytes = bytes;
233
+ }
234
+ const target = (branch ? options.originTargetsByBranch?.get(branch) : undefined) ?? options.originTarget;
235
+ const ref = completeGraph && target && /^[\w./-]{1,100}$/.test(target) ? `origin/${target}` : null;
236
+ if (ref && target && !targetRevisions.has(ref))
237
+ targetRevisions.set(ref, scanOriginTip(cwd, target, originDeadline));
238
+ const origin = ref ? targetRevisions.get(ref) : null;
239
+ const measuredHead = origin && head ? fullSha(head, p) : null;
240
+ const distance = measuredHead ? git(["rev-list", "--left-right", "--count", `${origin}...${measuredHead}`], p)?.match(/^(\d+)\s+(\d+)$/) : null;
241
+ const origin_distance = distance && ref && origin && head ? { ref, sha: origin, head, behind: Number(distance[1]), ahead: Number(distance[2]) } : null;
242
+ return { ...(options.measureDisk ? { disk_bytes, origin_distance } : {}), path: p, branch, head, dirty: worktreeStatus === null ? null : worktreeStatus.length > 0, base: f.base, merged: f.merged, ahead: f.ahead, behind: f.behind, base_sha: f.base_sha, empty, locked };
197
243
  });
198
244
  return { repo, worktrees };
199
245
  }