benignswarm 0.12.158 → 0.12.159

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.
@@ -2,7 +2,9 @@ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { agentRef } from "./config.js";
4
4
  import { createGateMarkerScanner } from "./commands/lock-run.js";
5
+ import { createLockHeartbeatReporter } from "./lock-heartbeat.js";
5
6
  import { CliError } from "./errors.js";
7
+ import { retryGitFetch } from "./git-fetch.js";
6
8
  const MAX_RE_GATE_ATTEMPTS = 3;
7
9
  const SHA_RE = /^[0-9a-f]{7,64}$/i;
8
10
  export function shaMatches(left, right) {
@@ -54,10 +56,44 @@ export function parseFailedGateStep(output, stepTimeline) {
54
56
  const failedTimelineStep = [...stepTimeline].reverse().find((s) => s.exit_code !== null && s.exit_code !== 0);
55
57
  return failedTimelineStep?.name ?? "gate";
56
58
  }
59
+ // The failure blocks of a test log: vitest's " FAIL <file> > <test>" sections up to the next separator rule
60
+ // (⎯) or FAIL line, and node:test's "not ok" entries with their indented details. Nothing else.
61
+ export function failingTestText(output) {
62
+ const lines = output.replace(/\x1b\[[0-9;]*m/g, "").split(/\r?\n/);
63
+ const blocks = [];
64
+ let current = null;
65
+ let nodeIndent = -1;
66
+ for (const line of lines) {
67
+ const vitestFail = /^\s*FAIL\s+\S/.test(line);
68
+ const notOk = /^(\s*)not ok \d+/.exec(line);
69
+ if (vitestFail || notOk) {
70
+ if (current)
71
+ blocks.push(current.join("\n"));
72
+ current = [line];
73
+ nodeIndent = notOk ? notOk[1].length : -1;
74
+ continue;
75
+ }
76
+ if (!current)
77
+ continue;
78
+ const endsVitest = nodeIndent < 0 && /⎯{3,}/.test(line);
79
+ const endsNode = nodeIndent >= 0 && line.trim() !== "" && (line.length - line.trimStart().length) <= nodeIndent;
80
+ if (endsVitest || endsNode) {
81
+ blocks.push(current.join("\n"));
82
+ current = null;
83
+ continue;
84
+ }
85
+ current.push(line);
86
+ }
87
+ if (current)
88
+ blocks.push(current.join("\n"));
89
+ return blocks.join("\n");
90
+ }
57
91
  export function detectUnitAttributedFailureFromOutput(output, entries) {
58
92
  const unitSet = new Set(entries.map((e) => e.work_unit_number));
59
93
  const matches = new Set();
60
- for (const m of output.matchAll(/\b(?:WU\s*#?|unit\s*#?)(\d+)\b/gi)) {
94
+ // WU #853: read only the failing tests' own output (title, assertion, stack). Passing test titles, merge
95
+ // commit messages and other log lines name units too, and once sent #802 back for #836's failure.
96
+ for (const m of failingTestText(output).matchAll(/\b(?:WU\s*#?|unit\s*#?)(\d+)\b/gi)) {
61
97
  const n = Number(m[1]);
62
98
  if (unitSet.has(n))
63
99
  matches.add(n);
@@ -93,19 +129,19 @@ async function resolveEntryCommitSha(worktreeDir, entry, runner, env) {
93
129
  };
94
130
  let sha = await resolveLocal();
95
131
  if (!sha) {
96
- await runner("git", ["-C", worktreeDir, "fetch", "--no-tags", "origin", entry.branch], {
132
+ await retryGitFetch(() => runner("git", ["-C", worktreeDir, "fetch", "--no-tags", "origin", `+refs/heads/${entry.branch}:refs/remotes/origin/${entry.branch}`], {
97
133
  cwd: worktreeDir,
98
134
  env,
99
135
  timeoutMs: 120_000,
100
- });
136
+ }), `fetch origin/${entry.branch}`);
101
137
  sha = await resolveLocal();
102
138
  }
103
139
  if (!sha) {
104
- await runner("git", ["-C", worktreeDir, "fetch", "--no-tags", "origin", entry.approved_head], {
140
+ await retryGitFetch(() => runner("git", ["-C", worktreeDir, "fetch", "--no-tags", "origin", entry.approved_head], {
105
141
  cwd: worktreeDir,
106
142
  env,
107
143
  timeoutMs: 120_000,
108
- });
144
+ }), `fetch commit ${entry.approved_head}`);
109
145
  sha = await resolveLocal();
110
146
  }
111
147
  if (!sha) {
@@ -179,11 +215,11 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
179
215
  while (true) {
180
216
  // 1. Fetch origin and check out current remote target.
181
217
  const { baseSha } = await h.runStep("fetch target", async () => {
182
- const fetchRes = await h.runner("git", ["-C", h.worktreeDir, "fetch", "--prune", "--no-tags", "origin"], {
218
+ const fetchRes = await retryGitFetch(() => h.runner("git", ["-C", h.worktreeDir, "fetch", "--no-tags", "origin", `+refs/heads/${trainRun.target_branch}:refs/remotes/origin/${trainRun.target_branch}`], {
183
219
  cwd: h.worktreeDir,
184
220
  env: gitEnv,
185
221
  timeoutMs: 120_000,
186
- });
222
+ }), `fetch origin/${trainRun.target_branch}`);
187
223
  if (fetchRes.status !== 0) {
188
224
  throw new Error(`git fetch origin failed: ${(fetchRes.stderr || fetchRes.stdout).trim().slice(0, 300)}`);
189
225
  }
@@ -287,161 +323,208 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
287
323
  let attributionReason = null;
288
324
  let gateExitCode = 0;
289
325
  if (gateSpec) {
290
- gateExitCode = await h.runWithLock({
291
- lock: "complete-suite",
292
- project: job.project,
293
- identity: agentRef(h.agentCreds),
294
- machine: h.agentCreds.machine,
295
- unit: anchorUnit,
296
- note: `merge-train ${trainRun.id} (${included.map((i) => `#${i.entry.work_unit_number}`).join(",")}) @ ${candidateSha.slice(0, 9)}`,
297
- commandLabel: gateSpec.commandLabel,
298
- ...(h.lockPollMs === undefined ? {} : { pollMs: h.lockPollMs }),
299
- run: async (lockContext) => {
300
- const lockedEnv = { ...gitEnv };
301
- if (lockContext?.jobId)
302
- lockedEnv.B9S_LOCK_JOB_ID = lockContext.jobId;
303
- if (lockContext?.slot !== undefined)
304
- lockedEnv.B9S_LOCK_SLOT = String(lockContext.slot);
305
- else
306
- delete lockedEnv.B9S_LOCK_SLOT;
307
- lockedEnv.BSCHAT_UX_JOB_ARTIFACT_DIR = h.jobArtifactDir;
308
- h.setFingerprint(await h.buildFingerprint(lockedEnv, lockContext));
309
- const heartbeatController = new AbortController();
310
- let heartbeatTimer;
311
- let heartbeatInFlight;
312
- let heartbeatFailure;
313
- if (lockContext?.heartbeat) {
314
- const heartbeatMs = h.lockHeartbeatMs ?? 15_000;
315
- heartbeatTimer = setInterval(() => {
316
- if (heartbeatInFlight)
326
+ try {
327
+ gateExitCode = await h.runWithLock({
328
+ lock: "complete-suite",
329
+ project: job.project,
330
+ identity: agentRef(h.agentCreds),
331
+ machine: h.agentCreds.machine,
332
+ unit: anchorUnit,
333
+ note: `merge-train ${trainRun.id} (${included.map((i) => `#${i.entry.work_unit_number}`).join(",")}) @ ${candidateSha.slice(0, 9)}`,
334
+ commandLabel: gateSpec.commandLabel,
335
+ ...(h.lockPollMs === undefined ? {} : { pollMs: h.lockPollMs }),
336
+ run: async (lockContext) => {
337
+ const lockedEnv = { ...gitEnv };
338
+ if (lockContext?.jobId)
339
+ lockedEnv.B9S_LOCK_JOB_ID = lockContext.jobId;
340
+ if (lockContext?.slot !== undefined)
341
+ lockedEnv.B9S_LOCK_SLOT = String(lockContext.slot);
342
+ else
343
+ delete lockedEnv.B9S_LOCK_SLOT;
344
+ lockedEnv.BSCHAT_UX_JOB_ARTIFACT_DIR = h.jobArtifactDir;
345
+ h.setFingerprint(await h.buildFingerprint(lockedEnv, lockContext));
346
+ const heartbeatController = new AbortController();
347
+ let heartbeatTimer;
348
+ let heartbeatInFlight;
349
+ let heartbeatFailure;
350
+ let gateCommandPid;
351
+ const reportHeartbeat = lockContext?.heartbeat
352
+ ? createLockHeartbeatReporter(lockContext.heartbeat, {
353
+ onRetry: (error, delayMs) => h.onLogLine(`merge-train job ${job.id} (${lockContext.jobId}) lock heartbeat failed transiently; retrying in ${delayMs}ms: ${error instanceof Error ? error.message : String(error)}`),
354
+ })
355
+ : undefined;
356
+ if (lockContext?.heartbeat) {
357
+ const heartbeatMs = h.lockHeartbeatMs ?? 15_000;
358
+ heartbeatTimer = setInterval(() => {
359
+ if (heartbeatInFlight)
360
+ return;
361
+ heartbeatInFlight = reportHeartbeat(gateCommandPid).then(() => undefined, (error) => {
362
+ heartbeatFailure = error;
363
+ if (heartbeatTimer)
364
+ clearInterval(heartbeatTimer);
365
+ h.onLogLine(`merge-train job ${job.id} (${lockContext.jobId}) lost its lock lease; aborting`);
366
+ heartbeatController.abort();
367
+ }).finally(() => { heartbeatInFlight = undefined; });
368
+ }, heartbeatMs);
369
+ heartbeatTimer.unref?.();
370
+ }
371
+ const throwIfHeartbeatFailed = () => {
372
+ if (!heartbeatFailure)
317
373
  return;
318
- heartbeatInFlight = lockContext.heartbeat().then(() => undefined, (error) => {
319
- heartbeatFailure = error;
320
- if (heartbeatTimer)
321
- clearInterval(heartbeatTimer);
322
- h.onLogLine(`merge-train job ${job.id} (${lockContext.jobId}) lock heartbeat failed; aborting`);
323
- heartbeatController.abort();
324
- }).finally(() => { heartbeatInFlight = undefined; });
325
- }, heartbeatMs);
326
- heartbeatTimer.unref?.();
327
- }
328
- const throwIfHeartbeatFailed = () => {
329
- if (!heartbeatFailure)
330
- return;
331
- throw new CliError("lock_heartbeat_failed", `job ${lockContext?.jobId ?? job.id} stopped because its lock heartbeat failed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`);
332
- };
333
- const runGateAtHead = async (stepName, unitForCmd, headSha) => {
334
- throwIfHeartbeatFailed();
335
- const spec = resolveTrainGateCommand(trainRun.gate_command, unitForCmd, headSha, h.worktreeDir);
336
- if (!spec)
337
- return { status: 0, output: "" };
338
- return h.runStep(stepName, async () => {
339
- let output = "";
340
- const res = await h.runner(spec.execCmd, spec.execArgs, {
341
- cwd: h.worktreeDir,
342
- env: lockedEnv,
343
- timeoutMs: 1_800_000,
344
- signal: heartbeatController.signal,
345
- onStdoutChunk: (chunk) => {
346
- output += chunk;
347
- if (stepName === "gate")
348
- scanner.push(chunk);
349
- for (const line of chunk.split(/\r?\n/)) {
350
- if (line.trim())
351
- lockContext?.onOutput?.(line.slice(0, 200));
352
- }
353
- },
354
- onStderrChunk: (chunk) => {
355
- output += chunk;
356
- },
357
- });
358
- if (!res.stdout && !res.stderr && res.error)
359
- output += `${res.error.message}\n`;
374
+ const code = heartbeatFailure instanceof CliError && heartbeatFailure.code === "lock_lease_lost" ? "lock_lease_lost" : "lock_heartbeat_failed";
375
+ throw new CliError(code, `job ${lockContext?.jobId ?? job.id} stopped because its lock lease could not be renewed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`);
376
+ };
377
+ const runGateAtHead = async (stepName, unitForCmd, headSha) => {
360
378
  throwIfHeartbeatFailed();
361
- return { status: res.status ?? 1, output };
362
- }, (r) => r.status);
363
- };
364
- const scanner = createGateMarkerScanner();
365
- try {
366
- const mainRun = await runGateAtHead("gate", anchorUnit, candidateSha);
367
- scanner.push("", true);
368
- const scanResult = scanner.result();
369
- gateOutputText = mainRun.output;
370
- gateVerifiedBaseline = scanResult.verified_baseline_sha ?? null;
371
- gateTestedTree = scanResult.tested_tree_sha ?? candidateTreeSha;
372
- const logDir = join(h.jobArtifactDir, "gate");
373
- mkdirSync(logDir, { recursive: true });
374
- writeFileSync(join(logDir, `gate-train-${candidateSha.slice(0, 9)}.log`), mainRun.output || `exit ${mainRun.status}\n`);
375
- if (mainRun.status !== 0) {
376
- failedStep = parseFailedGateStep(mainRun.output, h.stepTimeline);
377
- if (included.length === 1) {
378
- attributedUnitNumber = included[0].entry.work_unit_number;
379
- attributionMethod = "single_unit";
380
- attributionReason = `only WU #${attributedUnitNumber} was included when ${failedStep} failed`;
381
- }
382
- else {
383
- const outputHint = detectUnitAttributedFailureFromOutput(mainRun.output, included.map((i) => i.entry));
384
- if (outputHint) {
385
- attributedUnitNumber = outputHint.unitNumber;
386
- attributionMethod = "unit_output";
387
- attributionReason = outputHint.reason;
379
+ const spec = resolveTrainGateCommand(trainRun.gate_command, unitForCmd, headSha, h.worktreeDir);
380
+ if (!spec)
381
+ return { status: 0, output: "" };
382
+ return h.runStep(stepName, async () => {
383
+ let output = "";
384
+ const res = await h.runner(spec.execCmd, spec.execArgs, {
385
+ cwd: h.worktreeDir,
386
+ env: lockedEnv,
387
+ timeoutMs: 1_800_000,
388
+ signal: heartbeatController.signal,
389
+ onStdoutChunk: (chunk) => {
390
+ output += chunk;
391
+ if (stepName === "gate")
392
+ scanner.push(chunk);
393
+ for (const line of chunk.split(/\r?\n/)) {
394
+ if (line.trim())
395
+ lockContext?.onOutput?.(line.slice(0, 200));
396
+ }
397
+ },
398
+ onStderrChunk: (chunk) => {
399
+ output += chunk;
400
+ },
401
+ onStart: (pid) => {
402
+ gateCommandPid = pid;
403
+ if (reportHeartbeat) {
404
+ heartbeatInFlight = reportHeartbeat(pid).then(() => undefined, (error) => {
405
+ heartbeatFailure = error;
406
+ if (heartbeatTimer)
407
+ clearInterval(heartbeatTimer);
408
+ h.onLogLine(`merge-train job ${job.id} (${lockContext?.jobId ?? job.id}) lost its lock lease; aborting`);
409
+ heartbeatController.abort();
410
+ }).finally(() => { heartbeatInFlight = undefined; });
411
+ }
412
+ },
413
+ });
414
+ if (!res.stdout && !res.stderr && res.error)
415
+ output += `${res.error.message}\n`;
416
+ throwIfHeartbeatFailed();
417
+ return { status: res.status ?? 1, output };
418
+ }, (r) => r.status);
419
+ };
420
+ const scanner = createGateMarkerScanner();
421
+ try {
422
+ const mainRun = await runGateAtHead("gate", anchorUnit, candidateSha);
423
+ scanner.push("", true);
424
+ const scanResult = scanner.result();
425
+ gateOutputText = mainRun.output;
426
+ gateVerifiedBaseline = scanResult.verified_baseline_sha ?? null;
427
+ gateTestedTree = scanResult.tested_tree_sha ?? candidateTreeSha;
428
+ const logDir = join(h.jobArtifactDir, "gate");
429
+ mkdirSync(logDir, { recursive: true });
430
+ writeFileSync(join(logDir, `gate-train-${candidateSha.slice(0, 9)}.log`), mainRun.output || `exit ${mainRun.status}\n`);
431
+ if (mainRun.status !== 0) {
432
+ failedStep = parseFailedGateStep(mainRun.output, h.stepTimeline);
433
+ if (included.length === 1) {
434
+ attributedUnitNumber = included[0].entry.work_unit_number;
435
+ attributionMethod = "single_unit";
436
+ attributionReason = `only WU #${attributedUnitNumber} was included when ${failedStep} failed`;
388
437
  }
389
438
  else {
390
- // Binary-search prefixes [0..mid] to find the first failing unit.
391
- let lo = 0;
392
- let hi = included.length - 1;
393
- while (lo < hi) {
394
- const mid = Math.floor((lo + hi) / 2);
395
- await resetCleanWorktree(h.worktreeDir, baseSha, h.runner, gitEnv);
396
- for (let i = 0; i <= mid; i++) {
397
- const part = included[i];
398
- await mergeEntryIntoHead(h.worktreeDir, part.entry, part.resolvedSha, trainRun.require_merge_commit, h.runner, gitEnv);
399
- }
400
- const midRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "HEAD"], {
401
- cwd: h.worktreeDir,
402
- env: gitEnv,
403
- timeoutMs: 15_000,
404
- });
405
- const midSha = midRev.stdout.trim().toLowerCase();
406
- const probe = await runGateAtHead(`bisect WU #${included.slice(0, mid + 1).map((x) => x.entry.work_unit_number).join(",#")}`, included[0].entry.work_unit_number, midSha);
407
- if (probe.status === 0)
408
- lo = mid + 1;
409
- else
410
- hi = mid;
439
+ const outputHint = detectUnitAttributedFailureFromOutput(mainRun.output, included.map((i) => i.entry));
440
+ if (outputHint) {
441
+ attributedUnitNumber = outputHint.unitNumber;
442
+ attributionMethod = "unit_output";
443
+ attributionReason = outputHint.reason;
411
444
  }
412
- if (lo === 0) {
413
- // Verify baseline target wasn't already broken before blaming the first unit.
414
- await resetCleanWorktree(h.worktreeDir, baseSha, h.runner, gitEnv);
415
- const baseProbe = await runGateAtHead(`bisect target ${baseSha.slice(0, 9)}`, anchorUnit, baseSha);
416
- if (baseProbe.status !== 0) {
417
- attributedUnitNumber = null;
418
- attributionMethod = "unattributed";
419
- attributionReason = `target branch ${trainRun.target_branch} at ${baseSha.slice(0, 9)} already failed ${failedStep}`;
445
+ else {
446
+ // Binary-search prefixes [0..mid] to find the first failing unit.
447
+ let lo = 0;
448
+ let hi = included.length - 1;
449
+ while (lo < hi) {
450
+ const mid = Math.floor((lo + hi) / 2);
451
+ await resetCleanWorktree(h.worktreeDir, baseSha, h.runner, gitEnv);
452
+ for (let i = 0; i <= mid; i++) {
453
+ const part = included[i];
454
+ await mergeEntryIntoHead(h.worktreeDir, part.entry, part.resolvedSha, trainRun.require_merge_commit, h.runner, gitEnv);
455
+ }
456
+ const midRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "HEAD"], {
457
+ cwd: h.worktreeDir,
458
+ env: gitEnv,
459
+ timeoutMs: 15_000,
460
+ });
461
+ const midSha = midRev.stdout.trim().toLowerCase();
462
+ const probe = await runGateAtHead(`bisect WU #${included.slice(0, mid + 1).map((x) => x.entry.work_unit_number).join(",#")}`, included[0].entry.work_unit_number, midSha);
463
+ if (probe.status === 0)
464
+ lo = mid + 1;
465
+ else
466
+ hi = mid;
467
+ }
468
+ if (lo === 0) {
469
+ // Verify baseline target wasn't already broken before blaming the first unit.
470
+ await resetCleanWorktree(h.worktreeDir, baseSha, h.runner, gitEnv);
471
+ const baseProbe = await runGateAtHead(`bisect target ${baseSha.slice(0, 9)}`, anchorUnit, baseSha);
472
+ if (baseProbe.status !== 0) {
473
+ attributedUnitNumber = null;
474
+ attributionMethod = "unattributed";
475
+ attributionReason = `target branch ${trainRun.target_branch} at ${baseSha.slice(0, 9)} already failed ${failedStep}`;
476
+ }
477
+ else {
478
+ attributedUnitNumber = included[0].entry.work_unit_number;
479
+ attributionMethod = "bisect";
480
+ attributionReason = `bisect confirmed ${trainRun.target_branch} passes and WU #${attributedUnitNumber} fails ${failedStep}`;
481
+ }
420
482
  }
421
483
  else {
422
- attributedUnitNumber = included[0].entry.work_unit_number;
484
+ attributedUnitNumber = included[lo].entry.work_unit_number;
423
485
  attributionMethod = "bisect";
424
- attributionReason = `bisect confirmed ${trainRun.target_branch} passes and WU #${attributedUnitNumber} fails ${failedStep}`;
486
+ attributionReason = `bisect isolated failure at ${failedStep} to WU #${attributedUnitNumber}`;
425
487
  }
426
488
  }
427
- else {
428
- attributedUnitNumber = included[lo].entry.work_unit_number;
429
- attributionMethod = "bisect";
430
- attributionReason = `bisect isolated failure at ${failedStep} to WU #${attributedUnitNumber}`;
431
- }
432
489
  }
433
490
  }
491
+ return { exit_code: mainRun.status, ...scanResult };
434
492
  }
435
- return { exit_code: mainRun.status, ...scanResult };
436
- }
437
- finally {
438
- if (heartbeatTimer)
439
- clearInterval(heartbeatTimer);
440
- await heartbeatInFlight;
441
- throwIfHeartbeatFailed();
442
- }
443
- },
444
- }, h.agentClient, h.onLogLine);
493
+ finally {
494
+ if (heartbeatTimer)
495
+ clearInterval(heartbeatTimer);
496
+ await heartbeatInFlight;
497
+ throwIfHeartbeatFailed();
498
+ }
499
+ },
500
+ }, h.agentClient, h.onLogLine);
501
+ }
502
+ catch (error) {
503
+ if (!(error instanceof CliError) || !["lock_heartbeat_failed", "lock_lease_lost"].includes(error.code))
504
+ throw error;
505
+ const reason = `merge train job lost its complete-suite lock during the gate: ${error.message}`;
506
+ return {
507
+ status: "failed",
508
+ resolvedHead: candidateSha,
509
+ error: reason,
510
+ trainResult: {
511
+ target_branch: trainRun.target_branch,
512
+ base_sha: baseSha,
513
+ merged_sha: candidateSha,
514
+ tested_tree_sha: candidateTreeSha,
515
+ verified_baseline_sha: null,
516
+ push_verified: false,
517
+ included_units: trainRun.entries.map((entry) => entry.work_unit_number),
518
+ landed_units: [],
519
+ skipped_units: [],
520
+ failed_step: "job lost",
521
+ attributed_unit_number: null,
522
+ attribution_method: "unattributed",
523
+ attribution_reason: reason.slice(0, 500),
524
+ retry_count: retryCount,
525
+ },
526
+ };
527
+ }
445
528
  }
446
529
  if (gateExitCode !== 0) {
447
530
  const stepLabel = failedStep ?? parseFailedGateStep(gateOutputText, h.stepTimeline);
@@ -470,11 +553,11 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
470
553
  }
471
554
  // 4. Verify target did NOT move mid-gate before pushing.
472
555
  const targetCheck = await h.runStep("verify target & preflight push", async () => {
473
- const fetchTarget = await h.runner("git", ["-C", h.worktreeDir, "fetch", "--no-tags", "origin", trainRun.target_branch], {
556
+ const fetchTarget = await retryGitFetch(() => h.runner("git", ["-C", h.worktreeDir, "fetch", "--no-tags", "origin", `+refs/heads/${trainRun.target_branch}:refs/remotes/origin/${trainRun.target_branch}`], {
474
557
  cwd: h.worktreeDir,
475
558
  env: gitEnv,
476
559
  timeoutMs: 120_000,
477
- });
560
+ }), `fetch origin/${trainRun.target_branch}`);
478
561
  if (fetchTarget.status !== 0) {
479
562
  throw new Error(`git fetch origin ${trainRun.target_branch} before push failed`);
480
563
  }
@@ -567,11 +650,11 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
567
650
  if (pushRes.status === 0)
568
651
  return { kind: "pushed" };
569
652
  // Push failed or timed out cleanly/ambiguously: verify actual state on origin/<target> before deciding.
570
- const postFetch = await h.runner("git", ["-C", h.worktreeDir, "fetch", "--no-tags", "origin", trainRun.target_branch], {
653
+ const postFetch = await retryGitFetch(() => h.runner("git", ["-C", h.worktreeDir, "fetch", "--no-tags", "origin", `+refs/heads/${trainRun.target_branch}:refs/remotes/origin/${trainRun.target_branch}`], {
571
654
  cwd: h.worktreeDir,
572
655
  env: gitEnv,
573
656
  timeoutMs: 60_000,
574
- });
657
+ }), `fetch origin/${trainRun.target_branch}`);
575
658
  if (postFetch.status !== 0) {
576
659
  return {
577
660
  kind: "inconclusive",
package/dist/ux-jobs.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { evidenceTextHeaders } from "./evidence-text.js";
1
2
  import { createHash, randomBytes } from "node:crypto";
2
3
  import { spawn, spawnSync } from "node:child_process";
3
4
  import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statfsSync, unlinkSync, writeFileSync } from "node:fs";
@@ -7,11 +8,13 @@ import { Client } from "./client.js";
7
8
  import { agentRef, configRoot, loadAgent, listSaved } from "./config.js";
8
9
  import { guessType } from "./commands/evidence.js";
9
10
  import { createGateMarkerScanner, runUnderLock } from "./commands/lock-run.js";
11
+ import { createLockHeartbeatReporter } from "./lock-heartbeat.js";
10
12
  import { CliError } from "./errors.js";
11
13
  import { composeMachinePath, requireInstall } from "./install.js";
12
14
  import { isolatedSubprocessEnv } from "./container.js";
13
15
  import { writeFileAtomic } from "./shared-file.js";
14
16
  import { runMergeTrainWorkflow } from "./merge-train.js";
17
+ import { retryGitFetch } from "./git-fetch.js";
15
18
  const SLUG_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
16
19
  const SHA_RE = /^[0-9a-f]{7,64}$/i;
17
20
  const MAX_UX_JOB_LOG_TAIL = 2000;
@@ -347,6 +350,8 @@ export const spawnAsyncCommand = (cmd, args, opts) => new Promise((resolve) => {
347
350
  shell: false,
348
351
  detached: process.platform !== "win32",
349
352
  });
353
+ if (child.pid !== undefined)
354
+ opts.onStart?.(child.pid);
350
355
  let stdout = "";
351
356
  let stderr = "";
352
357
  const append = (cur, chunk) => {
@@ -535,21 +540,11 @@ export async function prepareUxJobWorktree(baseDir, jobDir, branch, head, runner
535
540
  throw new Error(`invalid recorded commit head: ${JSON.stringify(head)}`);
536
541
  }
537
542
  const requireAncestry = options.requireBranchAncestry !== false;
538
- if (options.fetchOrigin) {
539
- const fetchAll = await runner("git", ["-C", baseDir, "fetch", "--prune", "--no-tags", "origin"], {
540
- cwd: baseDir,
541
- env,
542
- timeoutMs: 120_000,
543
- });
544
- if (fetchAll.status !== 0) {
545
- throw new Error(`git fetch origin failed: ${(fetchAll.stderr || fetchAll.stdout).trim().slice(0, 300)}`);
546
- }
547
- }
548
- const fetchBranch = await runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", branch], {
543
+ const fetchBranch = await retryGitFetch(() => runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", `+refs/heads/${branch}:refs/remotes/origin/${branch}`], {
549
544
  cwd: baseDir,
550
545
  env,
551
546
  timeoutMs: 120_000,
552
- });
547
+ }), `fetch origin/${branch}`);
553
548
  if (fetchBranch.status !== 0 && requireAncestry) {
554
549
  throw new Error(`git fetch origin ${branch} failed: ${(fetchBranch.stderr || fetchBranch.stdout).trim().slice(0, 300)}`);
555
550
  }
@@ -576,7 +571,7 @@ export async function prepareUxJobWorktree(baseDir, jobDir, branch, head, runner
576
571
  timeoutMs: 15_000,
577
572
  });
578
573
  if (hasCommit.status !== 0) {
579
- await runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", head], { cwd: baseDir, env, timeoutMs: 120_000 });
574
+ await retryGitFetch(() => runner("git", ["-C", baseDir, "fetch", "--no-tags", "origin", head], { cwd: baseDir, env, timeoutMs: 120_000 }), `fetch commit ${head}`);
580
575
  hasCommit = await runner("git", ["-C", baseDir, "cat-file", "-e", `${head}^{commit}`], { cwd: baseDir, env, timeoutMs: 15_000 });
581
576
  }
582
577
  if (hasCommit.status !== 0) {
@@ -678,9 +673,8 @@ async function defaultUploadEvidence(agentCreds, project, file) {
678
673
  "content-type": file.contentType,
679
674
  "x-bschat-sha256": sha,
680
675
  "x-bschat-filename": file.filename,
681
- "x-bschat-label": file.label.slice(0, 500),
682
676
  "x-bschat-kind": file.kind,
683
- "x-bschat-claim": file.claim.slice(0, 300),
677
+ ...await evidenceTextHeaders(client, project, { label: file.label.slice(0, 500), claim: file.claim.slice(0, 300) }),
684
678
  };
685
679
  const res = await fetch(`${agentCreds.url}/projects/${encodeURIComponent(project)}/evidence`, {
686
680
  method: "POST",
@@ -720,7 +714,7 @@ function forwardLockedChunks(onOutput, onLine) {
720
714
  }
721
715
  async function defaultRunWithLock(opts, agentClient, log) {
722
716
  const lockDeps = {
723
- call: (method, path, body) => agentClient.call(method, path, body),
717
+ call: (method, path, body) => agentClient.call(method, path, body, path.endsWith("/running") ? { signal: AbortSignal.timeout(10_000) } : {}),
724
718
  run: (_command, context) => opts.run(context),
725
719
  sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
726
720
  interrupted: () => false,
@@ -1134,16 +1128,21 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1134
1128
  let heartbeatTimer;
1135
1129
  let heartbeatInFlight;
1136
1130
  let heartbeatFailure;
1131
+ const reportHeartbeat = lockContext?.heartbeat
1132
+ ? createLockHeartbeatReporter(lockContext.heartbeat, {
1133
+ onRetry: (error, delayMs) => ctx.log(`${jobKind} job ${job.id} (${lockContext.jobId}) lock heartbeat failed transiently; retrying in ${delayMs}ms: ${error instanceof Error ? error.message : String(error)}`),
1134
+ })
1135
+ : undefined;
1137
1136
  if (lockContext?.heartbeat) {
1138
1137
  const heartbeatMs = deps.lockHeartbeatMs ?? 15_000;
1139
1138
  heartbeatTimer = setInterval(() => {
1140
1139
  if (heartbeatInFlight)
1141
1140
  return;
1142
- heartbeatInFlight = lockContext.heartbeat().then(() => undefined, (error) => {
1141
+ heartbeatInFlight = reportHeartbeat().then(() => undefined, (error) => {
1143
1142
  heartbeatFailure = error;
1144
1143
  if (heartbeatTimer)
1145
1144
  clearInterval(heartbeatTimer);
1146
- ctx.log(`${jobKind} job ${job.id} (${lockContext.jobId}) could not refresh its lock heartbeat; stopping the command to avoid running without the lock`);
1145
+ ctx.log(`${jobKind} job ${job.id} (${lockContext.jobId}) lost its lock lease; stopping the command`);
1147
1146
  heartbeatController.abort();
1148
1147
  }).finally(() => {
1149
1148
  heartbeatInFlight = undefined;
@@ -1154,7 +1153,8 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1154
1153
  const throwIfHeartbeatFailed = () => {
1155
1154
  if (!heartbeatFailure)
1156
1155
  return;
1157
- throw new CliError("lock_heartbeat_failed", `job ${lockContext?.jobId ?? job.id} stopped because its lock heartbeat failed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`);
1156
+ const code = heartbeatFailure instanceof CliError && heartbeatFailure.code === "lock_lease_lost" ? "lock_lease_lost" : "lock_heartbeat_failed";
1157
+ throw new CliError(code, `job ${lockContext?.jobId ?? job.id} stopped because its lock lease could not be renewed: ${heartbeatFailure instanceof Error ? heartbeatFailure.message : String(heartbeatFailure)}`);
1158
1158
  };
1159
1159
  const runLockedStep = async (stepName, cmd, args, stepOpts) => {
1160
1160
  throwIfHeartbeatFailed();
@@ -1167,6 +1167,7 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1167
1167
  env: lockedEnv,
1168
1168
  timeoutMs: stepOpts.timeoutMs,
1169
1169
  signal: heartbeatController.signal,
1170
+ onStart: stepOpts.onStart,
1170
1171
  onStdoutChunk: (chunk) => {
1171
1172
  if (stepOpts.captureCombined)
1172
1173
  combined += chunk;
@@ -1201,6 +1202,17 @@ export async function executeUxJob(machineClient, job, ctx, deps = {}) {
1201
1202
  const { res: gateRes, combined: fullOutput } = await runLockedStep("gate", "/bin/sh", ["scripts/gate.sh", resolvedHead], {
1202
1203
  timeoutMs: 1_800_000,
1203
1204
  captureCombined: true,
1205
+ onStart: (pid) => {
1206
+ if (!reportHeartbeat)
1207
+ return;
1208
+ heartbeatInFlight = reportHeartbeat(pid).then(() => undefined, (error) => {
1209
+ heartbeatFailure = error;
1210
+ if (heartbeatTimer)
1211
+ clearInterval(heartbeatTimer);
1212
+ ctx.log(`${jobKind} job ${job.id} (${lockContext?.jobId ?? job.id}) lost its lock lease; stopping the command`);
1213
+ heartbeatController.abort();
1214
+ }).finally(() => { heartbeatInFlight = undefined; });
1215
+ },
1204
1216
  onStdoutLine: (line) => scanner.push(`${line}\n`),
1205
1217
  });
1206
1218
  scanner.push("", true);
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const CLI_VERSION = "0.12.158";
1
+ export const CLI_VERSION = "0.12.159";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "benignswarm",
3
- "version": "0.12.158",
3
+ "version": "0.12.159",
4
4
  "description": "b9s: chat, status board and evidence store for coding agents (benignswarm.org)",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {