benignswarm 0.12.164 → 0.12.166

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.
@@ -1,17 +1,21 @@
1
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
+ import { randomBytes } from "node:crypto";
3
+ import { dirname, join } from "node:path";
3
4
  import { agentRef } from "./config.js";
4
5
  import { createGateMarkerScanner } from "./commands/lock-run.js";
5
6
  import { createLockHeartbeatReporter } from "./lock-heartbeat.js";
6
7
  import { CliError } from "./errors.js";
7
8
  import { retryGitFetch } from "./git-fetch.js";
9
+ const MERGE_TRAIN_API_RETRY_MS = 5 * 60_000;
8
10
  export const CLI_VERSION_CONFLICT_FILES = [
9
11
  "package-lock.json",
10
12
  "packages/cli/package.json",
11
13
  "packages/cli/src/version.ts",
12
14
  ];
15
+ export const PG_BASELINE_CONFLICT_FILE = "apps/api/pg-migrations/0001_baseline.sql";
13
16
  export const MECHANICALLY_RESOLVABLE_CONFLICT_FILES = [
14
17
  ...CLI_VERSION_CONFLICT_FILES,
18
+ PG_BASELINE_CONFLICT_FILE,
15
19
  ];
16
20
  const MAX_RE_GATE_ATTEMPTS = 3;
17
21
  const SHA_RE = /^[0-9a-f]{7,64}$/i;
@@ -24,8 +28,12 @@ export function shaMatches(left, right) {
24
28
  return false;
25
29
  return a.startsWith(b) || b.startsWith(a);
26
30
  }
31
+ export const TRAIN_GATE_STAGES = ["typecheck", "api tests", "cli tests", "web tests", "web build", "cli build", "published CLI contract"];
32
+ export function supportedTrainGateStage(stage) {
33
+ return TRAIN_GATE_STAGES.find(name => name === stage);
34
+ }
27
35
  /** Resolve the shell command and complete-suite lock label from merge.gate_command. */
28
- export function resolveTrainGateCommand(gateCommand, anchorUnitNumber, candidateSha, worktreeDir) {
36
+ export function resolveTrainGateCommand(gateCommand, anchorUnitNumber, candidateSha, worktreeDir, stage) {
29
37
  let resolved = gateCommand ? gateCommand.trim() : null;
30
38
  if (resolved) {
31
39
  resolved = resolved.replaceAll("{unit}", String(anchorUnitNumber)).replaceAll("{head}", candidateSha);
@@ -40,11 +48,12 @@ export function resolveTrainGateCommand(gateCommand, anchorUnitNumber, candidate
40
48
  }
41
49
  const parts = resolved.split(/\s+/).filter(Boolean);
42
50
  if (parts.length >= 1 && parts[0] === "scripts/gate.sh") {
51
+ const args = stage ? [...parts, "--stage", stage] : parts;
43
52
  return {
44
- commandLine: resolved,
45
- commandLabel: parts,
53
+ commandLine: stage ? `${resolved} --stage ${JSON.stringify(stage)}` : resolved,
54
+ commandLabel: args,
46
55
  execCmd: "/bin/sh",
47
- execArgs: parts,
56
+ execArgs: args,
48
57
  };
49
58
  }
50
59
  return {
@@ -343,6 +352,25 @@ async function tryResolveMechanicalMergeConflicts(worktreeDir, entry, conflictin
343
352
  return false;
344
353
  }
345
354
  }
355
+ if (conflictingFiles.includes(PG_BASELINE_CONFLICT_FILE)) {
356
+ // This file is generated from the complete SQLite migration set. Keep the current
357
+ // accumulated baseline while merging each unit; the post-batch generator below writes
358
+ // the authoritative baseline after every included migration has landed.
359
+ const ours = await runner("git", ["-C", worktreeDir, "checkout", "--ours", "--", PG_BASELINE_CONFLICT_FILE], {
360
+ cwd: worktreeDir,
361
+ env,
362
+ timeoutMs: 30_000,
363
+ });
364
+ if (ours.status !== 0)
365
+ return false;
366
+ const add = await runner("git", ["-C", worktreeDir, "add", "--", PG_BASELINE_CONFLICT_FILE], {
367
+ cwd: worktreeDir,
368
+ env,
369
+ timeoutMs: 30_000,
370
+ });
371
+ if (add.status !== 0)
372
+ return false;
373
+ }
346
374
  const remaining = await runner("git", ["-C", worktreeDir, "diff", "--name-only", "--diff-filter=U"], {
347
375
  cwd: worktreeDir,
348
376
  env,
@@ -397,6 +425,12 @@ async function mergeEntryIntoHead(worktreeDir, entry, resolvedSha, requireMergeC
397
425
  }
398
426
  return { ok: true };
399
427
  }
428
+ export function cliVersionBumpRequired(paths) {
429
+ return paths.some((path) => path.startsWith("packages/cli/") || path.startsWith("packages/skill"));
430
+ }
431
+ export function pgBaselineRefreshRequired(paths) {
432
+ return paths.some((path) => path.startsWith("apps/api/migrations/") && path.endsWith(".sql"));
433
+ }
400
434
  /**
401
435
  * Executes a claimed merge-train gate job: merges queued approved heads onto origin/<target>
402
436
  * in order, leaves conflicting units out, runs the configured gate under complete-suite lock,
@@ -404,10 +438,13 @@ async function mergeEntryIntoHead(worktreeDir, entry, resolvedSha, requireMergeC
404
438
  * pass, and attributes failures by bisection or unit-attributed output.
405
439
  */
406
440
  export async function runMergeTrainWorkflow(job, trainRun, h) {
441
+ if (h.resumePassedGate)
442
+ return resumePassedTrainGate(job, trainRun, h, h.resumePassedGate);
407
443
  const gitEnv = withGitIdentityEnv(h.childEnv);
408
444
  const activeEntries = trainRun.entries.map((entry) => ({ entry }));
409
445
  const skippedUnits = [];
410
446
  let retryCount = 0;
447
+ let passedGatePersisted = false;
411
448
  const retryReasons = [];
412
449
  while (true) {
413
450
  // 1. Fetch origin and check out current remote target.
@@ -492,6 +529,69 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
492
529
  },
493
530
  };
494
531
  }
532
+ // SQLite migrations from every included unit land together. Regenerate the PostgreSQL
533
+ // baseline once from that complete merged tree before running the gate, then commit the
534
+ // generated file into the exact candidate that the gate verifies.
535
+ await h.runStep("refresh merged PostgreSQL baseline", async () => {
536
+ const changed = await h.runner("git", ["-C", h.worktreeDir, "diff", "--name-only", baseSha, "HEAD"], {
537
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
538
+ });
539
+ if (changed.status !== 0)
540
+ throw new Error(`could not inspect merged migration paths: ${(changed.stderr || changed.stdout).trim().slice(0, 300)}`);
541
+ if (!pgBaselineRefreshRequired(changed.stdout.split(/\r?\n/).filter(Boolean)))
542
+ return 0;
543
+ const generate = await h.runner("npm", ["run", "pg:generate-baseline", "-w", "apps/api"], {
544
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 120_000,
545
+ });
546
+ if (generate.status !== 0)
547
+ throw new Error(`PostgreSQL baseline generation failed: ${(generate.stderr || generate.stdout).trim().slice(0, 500)}`);
548
+ h.onLogLine(generate.stdout.trim());
549
+ const pending = await h.runner("git", ["-C", h.worktreeDir, "diff", "--quiet", "--", "apps/api/pg-migrations/0001_baseline.sql"], {
550
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
551
+ });
552
+ if (pending.status === 1) {
553
+ const add = await h.runner("git", ["-C", h.worktreeDir, "add", "--", "apps/api/pg-migrations/0001_baseline.sql"], {
554
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
555
+ });
556
+ if (add.status !== 0)
557
+ throw new Error(`could not stage generated PostgreSQL baseline: ${(add.stderr || add.stdout).trim().slice(0, 300)}`);
558
+ const commit = await h.runner("git", ["-C", h.worktreeDir, "commit", "-m", "chore(api): refresh PostgreSQL baseline after migration batch"], {
559
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 30_000,
560
+ });
561
+ if (commit.status !== 0)
562
+ throw new Error(`could not commit generated PostgreSQL baseline: ${(commit.stderr || commit.stdout).trim().slice(0, 300)}`);
563
+ }
564
+ else if (pending.status !== 0)
565
+ throw new Error(`could not check generated PostgreSQL baseline changes: ${(pending.stderr || pending.stdout).trim().slice(0, 300)}`);
566
+ return 0;
567
+ }, () => 0);
568
+ // The published CLI version identifies an immutable source tree. When this train lands
569
+ // CLI or skill changes, bump the version before calculating the candidate head and gate.
570
+ await h.runStep("bump merged CLI version", async () => {
571
+ const changed = await h.runner("git", ["-C", h.worktreeDir, "diff", "--name-only", baseSha, "HEAD"], {
572
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
573
+ });
574
+ if (changed.status !== 0)
575
+ throw new Error(`could not inspect merged paths for CLI version bump: ${(changed.stderr || changed.stdout).trim().slice(0, 300)}`);
576
+ if (!cliVersionBumpRequired(changed.stdout.split(/\r?\n/).filter(Boolean)))
577
+ return 0;
578
+ const bump = await h.runner("/bin/sh", ["scripts/bump-cli.sh"], { cwd: h.worktreeDir, env: gitEnv, timeoutMs: 60_000 });
579
+ if (bump.status !== 0)
580
+ throw new Error(`scripts/bump-cli.sh failed: ${(bump.stderr || bump.stdout).trim().slice(0, 500)}`);
581
+ h.onLogLine(bump.stdout.trim());
582
+ const pending = await h.runner("git", ["-C", h.worktreeDir, "diff", "--quiet"], { cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000 });
583
+ if (pending.status === 1) {
584
+ const add = await h.runner("git", ["-C", h.worktreeDir, "add", "packages/cli/package.json", "packages/cli/src/version.ts", "package-lock.json"], { cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000 });
585
+ if (add.status !== 0)
586
+ throw new Error(`could not stage CLI version bump: ${(add.stderr || add.stdout).trim().slice(0, 300)}`);
587
+ const commit = await h.runner("git", ["-C", h.worktreeDir, "commit", "-m", "chore(cli): bump version after merge-train CLI changes"], { cwd: h.worktreeDir, env: gitEnv, timeoutMs: 30_000 });
588
+ if (commit.status !== 0)
589
+ throw new Error(`could not commit CLI version bump: ${(commit.stderr || commit.stdout).trim().slice(0, 300)}`);
590
+ }
591
+ else if (pending.status !== 0)
592
+ throw new Error(`could not check CLI version bump changes: ${(pending.stderr || pending.stdout).trim().slice(0, 300)}`);
593
+ return 0;
594
+ });
495
595
  const headRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "HEAD"], {
496
596
  cwd: h.worktreeDir,
497
597
  env: gitEnv,
@@ -542,7 +642,16 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
542
642
  lockedEnv.B9S_LOCK_SLOT = String(lockContext.slot);
543
643
  else
544
644
  delete lockedEnv.B9S_LOCK_SLOT;
545
- lockedEnv.BSCHAT_UX_JOB_ARTIFACT_DIR = h.jobArtifactDir;
645
+ const gateInstanceId = lockContext?.jobId ?? randomBytes(8).toString("hex");
646
+ const gateInstanceDir = join(dirname(h.worktreeDir), `gate-${job.id}-${gateInstanceId}`);
647
+ const gateScratchDir = join(gateInstanceDir, "tmp");
648
+ const gateArtifactDir = join(h.jobArtifactDir, "gates", gateInstanceId);
649
+ mkdirSync(gateScratchDir, { recursive: true, mode: 0o700 });
650
+ mkdirSync(gateArtifactDir, { recursive: true, mode: 0o700 });
651
+ lockedEnv.TMPDIR = gateScratchDir;
652
+ lockedEnv.TMP = gateScratchDir;
653
+ lockedEnv.TEMP = gateScratchDir;
654
+ lockedEnv.BSCHAT_UX_JOB_ARTIFACT_DIR = gateArtifactDir;
546
655
  h.setFingerprint(await h.buildFingerprint(lockedEnv, lockContext));
547
656
  const heartbeatController = new AbortController();
548
657
  const commandSignal = lockContext?.signal ? AbortSignal.any([heartbeatController.signal, lockContext.signal]) : heartbeatController.signal;
@@ -576,25 +685,29 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
576
685
  const code = heartbeatFailure instanceof CliError && heartbeatFailure.code === "lock_lease_lost" ? "lock_lease_lost" : "lock_heartbeat_failed";
577
686
  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)}`);
578
687
  };
579
- const runGateAtHead = async (stepName, unitForCmd, headSha) => {
688
+ const runGateAtHead = async (stepName, unitForCmd, headSha, options = {}) => {
580
689
  throwIfHeartbeatFailed();
581
- const spec = resolveTrainGateCommand(trainRun.gate_command, unitForCmd, headSha, h.worktreeDir);
690
+ const worktreeDir = options.worktreeDir ?? h.worktreeDir;
691
+ const gateEnv = { ...(options.env ?? lockedEnv) };
692
+ delete gateEnv.GATE_STAGE;
693
+ const lockContextForGate = options.lockContext ?? lockContext;
694
+ const spec = resolveTrainGateCommand(trainRun.gate_command, unitForCmd, headSha, worktreeDir, options.stage);
582
695
  if (!spec)
583
696
  return { status: 0, output: "" };
584
697
  return h.runStep(stepName, async () => {
585
698
  let output = "";
586
699
  const res = await h.runner(spec.execCmd, spec.execArgs, {
587
- cwd: h.worktreeDir,
588
- env: lockedEnv,
700
+ cwd: worktreeDir,
701
+ env: gateEnv,
589
702
  timeoutMs: 1_800_000,
590
703
  signal: commandSignal,
591
704
  onStdoutChunk: (chunk) => {
592
705
  output += chunk;
593
- if (stepName === "gate")
706
+ if (options.scanReceipt)
594
707
  scanner.push(chunk);
595
708
  for (const line of chunk.split(/\r?\n/)) {
596
709
  if (line.trim())
597
- lockContext?.onOutput?.(line.slice(0, 200));
710
+ lockContextForGate?.onOutput?.(line.slice(0, 200));
598
711
  }
599
712
  },
600
713
  onStderrChunk: (chunk) => {
@@ -615,13 +728,194 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
615
728
  });
616
729
  if (!res.stdout && !res.stderr && res.error)
617
730
  output += `${res.error.message}\n`;
618
- throwIfHeartbeatFailed();
731
+ if (!options.keepSuccessfulResultOnHeartbeatError || (res.status ?? 1) !== 0)
732
+ throwIfHeartbeatFailed();
619
733
  return { status: res.status ?? 1, output };
620
734
  }, (r) => r.status);
621
735
  };
736
+ let probeStage;
737
+ const runIsolatedProbe = async (stepName, parts) => {
738
+ const probeId = randomBytes(8).toString("hex");
739
+ const probeRoot = join(dirname(h.worktreeDir), `parallel-${job.id}-${probeId}`);
740
+ const probeWorktree = join(probeRoot, "checkout");
741
+ const scratchDir = join(probeRoot, "tmp");
742
+ const artifactDir = join(h.jobArtifactDir, "parallel-gates", probeId);
743
+ mkdirSync(probeRoot, { recursive: true, mode: 0o700 });
744
+ mkdirSync(scratchDir, { recursive: true, mode: 0o700 });
745
+ mkdirSync(artifactDir, { recursive: true, mode: 0o700 });
746
+ let worktreeAdded = false;
747
+ let probeOutput = "";
748
+ try {
749
+ const added = await h.runner("git", ["-C", h.worktreeDir, "worktree", "add", "--detach", probeWorktree, baseSha], {
750
+ cwd: h.worktreeDir,
751
+ env: gitEnv,
752
+ timeoutMs: 60_000,
753
+ });
754
+ if (added.status !== 0)
755
+ return { status: 2, output: `could not create isolated probe checkout: ${(added.stderr || added.stdout).trim()}`, sha: null };
756
+ worktreeAdded = true;
757
+ for (const part of parts) {
758
+ const merged = await mergeEntryIntoHead(probeWorktree, part.entry, part.resolvedSha, trainRun.require_merge_commit, h.runner, gitEnv);
759
+ if (!merged.ok)
760
+ return { status: 2, output: `probe merge failed for WU #${part.entry.work_unit_number}: ${merged.error}`, sha: null };
761
+ }
762
+ const rev = await h.runner("git", ["-C", probeWorktree, "rev-parse", "HEAD"], { cwd: probeWorktree, env: gitEnv, timeoutMs: 15_000 });
763
+ if (rev.status !== 0)
764
+ return { status: 2, output: "could not resolve isolated probe candidate", sha: null };
765
+ const probeSha = rev.stdout.trim().toLowerCase();
766
+ const spec = resolveTrainGateCommand(trainRun.gate_command, anchorUnit, probeSha, probeWorktree, probeStage);
767
+ if (!spec)
768
+ return { status: 0, output: "", sha: probeSha };
769
+ const result = await h.runWithLock({
770
+ lock: "complete-suite",
771
+ project: job.project,
772
+ identity: agentRef(h.agentCreds),
773
+ machine: h.agentCreds.machine,
774
+ unit: anchorUnit,
775
+ note: `merge-train ${trainRun.id} probe ${stepName} (${parts.map((part) => `#${part.entry.work_unit_number}`).join(",")}) @ ${probeSha.slice(0, 9)}`,
776
+ commandLabel: spec.commandLabel,
777
+ ...(h.lockPollMs === undefined ? {} : { pollMs: h.lockPollMs }),
778
+ // Do not reuse remoteJobId across parallel bisect probes: remoteJobId derives a
779
+ // single deterministic job_token, which causes parallel probes to collide on the
780
+ // same complete-suite slot (note receipt mismatch + premature release failure).
781
+ ...(h.signal ? { signal: h.signal } : {}),
782
+ run: async (probeLock) => {
783
+ const probeEnv = {
784
+ ...gitEnv,
785
+ TMPDIR: scratchDir,
786
+ TMP: scratchDir,
787
+ TEMP: scratchDir,
788
+ BSCHAT_UX_JOB_ARTIFACT_DIR: artifactDir,
789
+ };
790
+ delete probeEnv.GATE_STAGE;
791
+ if (probeLock?.jobId)
792
+ probeEnv.B9S_LOCK_JOB_ID = probeLock.jobId;
793
+ if (!Number.isSafeInteger(probeLock?.slot) || probeLock.slot < 1 || probeLock.slot > 3) {
794
+ throw new CliError("lock_protocol_mismatch", "The server did not assign a valid complete-suite slot to an isolated gate; the gate was not started. Inspect the lock state: b9s locks");
795
+ }
796
+ probeEnv.B9S_LOCK_SLOT = String(probeLock.slot);
797
+ const heartbeatMs = h.lockHeartbeatMs ?? 15_000;
798
+ const probeHeartbeat = probeLock?.heartbeat
799
+ ? createLockHeartbeatReporter(probeLock.heartbeat, {
800
+ onRetry: (error, delayMs) => h.onLogLine(`merge-train probe ${probeLock.jobId} heartbeat retry in ${delayMs}ms: ${error instanceof Error ? error.message : String(error)}`),
801
+ })
802
+ : undefined;
803
+ const probeAbort = new AbortController();
804
+ let timer;
805
+ let heartbeat;
806
+ let heartbeatError;
807
+ let pid;
808
+ const abortWithParent = () => probeAbort.abort(heartbeatController.signal.reason);
809
+ heartbeatController.signal.addEventListener("abort", abortWithParent, { once: true });
810
+ const recordHeartbeatFailure = (error) => {
811
+ heartbeatError = error;
812
+ probeAbort.abort(error);
813
+ };
814
+ const sendProbeHeartbeat = (commandPid) => {
815
+ if (!probeHeartbeat)
816
+ return Promise.resolve();
817
+ if (heartbeat)
818
+ return heartbeat;
819
+ heartbeat = probeHeartbeat(commandPid).catch(recordHeartbeatFailure).finally(() => { heartbeat = undefined; });
820
+ return heartbeat;
821
+ };
822
+ if (probeHeartbeat) {
823
+ timer = setInterval(() => { void sendProbeHeartbeat(pid); }, heartbeatMs);
824
+ timer.unref?.();
825
+ }
826
+ const throwIfProbeHeartbeatFailed = () => {
827
+ if (!heartbeatError)
828
+ return;
829
+ const code = heartbeatError instanceof CliError && heartbeatError.code === "lock_lease_lost" ? "lock_lease_lost" : "lock_heartbeat_failed";
830
+ throw new CliError(code, `isolated gate ${probeLock?.jobId ?? stepName} stopped because its complete-suite lease could not be renewed: ${heartbeatError instanceof Error ? heartbeatError.message : String(heartbeatError)}`, undefined, heartbeatError instanceof CliError ? heartbeatError.httpStatus : 503);
831
+ };
832
+ try {
833
+ const probe = await h.runStep(stepName, async () => {
834
+ let output = "";
835
+ const commandResult = await h.runner(spec.execCmd, spec.execArgs, {
836
+ cwd: probeWorktree,
837
+ env: probeEnv,
838
+ timeoutMs: 1_800_000,
839
+ signal: probeAbort.signal,
840
+ onStart: (nextPid) => { pid = nextPid; void sendProbeHeartbeat(pid); },
841
+ onStdoutChunk: (chunk) => { output += chunk; for (const line of chunk.split(/\r?\n/))
842
+ if (line.trim())
843
+ probeLock?.onOutput?.(line.slice(0, 200)); },
844
+ onStderrChunk: (chunk) => { output += chunk; },
845
+ });
846
+ if (!commandResult.stdout && !commandResult.stderr && commandResult.error)
847
+ output += `${commandResult.error.message}\n`;
848
+ if (heartbeat)
849
+ await heartbeat;
850
+ throwIfProbeHeartbeatFailed();
851
+ probeOutput = output;
852
+ return { status: commandResult.status ?? 1, output };
853
+ }, (gate) => gate.status);
854
+ return probe.status;
855
+ }
856
+ finally {
857
+ if (timer)
858
+ clearInterval(timer);
859
+ await heartbeat;
860
+ heartbeatController.signal.removeEventListener("abort", abortWithParent);
861
+ throwIfProbeHeartbeatFailed();
862
+ }
863
+ },
864
+ }, h.agentClient, h.onLogLine);
865
+ return { status: result, output: probeOutput, sha: probeSha };
866
+ }
867
+ finally {
868
+ if (worktreeAdded) {
869
+ const removed = await h.runner("git", ["-C", h.worktreeDir, "worktree", "remove", "--force", probeWorktree], {
870
+ cwd: h.worktreeDir,
871
+ env: gitEnv,
872
+ timeoutMs: 60_000,
873
+ });
874
+ if (removed.status !== 0) {
875
+ throw new Error(`could not remove isolated probe worktree ${probeWorktree}: ${(removed.stderr || removed.stdout).trim()}`);
876
+ }
877
+ }
878
+ rmSync(probeRoot, { recursive: true, force: true });
879
+ }
880
+ };
881
+ const isolateInParallel = async (parts) => {
882
+ if (parts.length < 2)
883
+ return { unit: parts[0]?.entry.work_unit_number ?? null };
884
+ const midpoint = Math.floor((parts.length - 1) / 2);
885
+ const left = parts.slice(0, midpoint + 1);
886
+ const right = parts.slice(midpoint + 1);
887
+ const [leftProbe, rightProbe] = await Promise.all([
888
+ runIsolatedProbe(`bisect left WU #${left.map((part) => part.entry.work_unit_number).join(",#")}`, left),
889
+ runIsolatedProbe(`bisect right WU #${right.map((part) => part.entry.work_unit_number).join(",#")}`, right),
890
+ ]);
891
+ for (const probe of [leftProbe, rightProbe]) {
892
+ if (probe.status !== 0) {
893
+ const retry = classifyRetryableGateFailure(probe.output, probe.status);
894
+ if (retry)
895
+ return { unit: null, retry };
896
+ }
897
+ }
898
+ // A merge conflict or gate setup failure that is not one of the explicit retry
899
+ // signatures cannot safely identify a culprit; let the prefix algorithm below
900
+ // retain its established interaction semantics.
901
+ if (!leftProbe.sha || !rightProbe.sha || leftProbe.status === 2 || rightProbe.status === 2)
902
+ return { unit: null };
903
+ if (leftProbe.status === 0 && rightProbe.status === 0)
904
+ return { unit: null };
905
+ if (leftProbe.status !== 0 && rightProbe.status !== 0)
906
+ return { unit: null };
907
+ const failing = leftProbe.status !== 0 ? left : right;
908
+ const failingOutput = leftProbe.status !== 0 ? leftProbe.output : rightProbe.output;
909
+ const direct = detectUnitAttributedFailureFromOutput(failingOutput, failing.map((part) => part.entry));
910
+ if (direct)
911
+ return { unit: direct.unitNumber, reason: direct.reason };
912
+ if (failing.length === 1)
913
+ return { unit: failing[0].entry.work_unit_number };
914
+ return isolateInParallel(failing);
915
+ };
622
916
  const scanner = createGateMarkerScanner();
623
917
  try {
624
- const mainRun = await runGateAtHead("gate", anchorUnit, candidateSha);
918
+ const mainRun = await runGateAtHead("gate", anchorUnit, candidateSha, { scanReceipt: true, keepSuccessfulResultOnHeartbeatError: true });
625
919
  scanner.push("", true);
626
920
  const scanResult = scanner.result();
627
921
  gateOutputText = mainRun.output;
@@ -630,6 +924,25 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
630
924
  const logDir = join(h.jobArtifactDir, "gate");
631
925
  mkdirSync(logDir, { recursive: true });
632
926
  writeFileSync(join(logDir, `gate-train-${candidateSha.slice(0, 9)}.log`), mainRun.output || `exit ${mainRun.status}\n`);
927
+ if (mainRun.status === 0) {
928
+ // This must be durable before runWithLock attempts its remote release. A passed
929
+ // gate is expensive local work and survives a lock/report outage unchanged.
930
+ await h.persistPassedGate?.({
931
+ version: 1,
932
+ train_run_id: trainRun.id,
933
+ target_branch: trainRun.target_branch,
934
+ base_sha: baseSha,
935
+ candidate_sha: candidateSha,
936
+ candidate_tree_sha: candidateTreeSha,
937
+ tested_tree_sha: gateTestedTree,
938
+ verified_baseline_sha: gateVerifiedBaseline,
939
+ included,
940
+ skipped_units: skippedUnits,
941
+ retry_count: retryCount,
942
+ });
943
+ passedGatePersisted = true;
944
+ throwIfHeartbeatFailed();
945
+ }
633
946
  if (mainRun.status !== 0) {
634
947
  failedStep = parseFailedGateStep(mainRun.output, h.stepTimeline);
635
948
  retryGateReason = classifyRetryableGateFailure(mainRun.output, mainRun.status);
@@ -637,48 +950,64 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
637
950
  h.onLogLine(`merge-train ${trainRun.id}: gate failed with retryable ${retryGateReason} signature`);
638
951
  if (!retryGateReason) {
639
952
  const initialFailedStep = failedStep;
953
+ probeStage = supportedTrainGateStage(initialFailedStep);
640
954
  const outputHint = detectUnitAttributedFailureFromOutput(mainRun.output, included.map((i) => i.entry));
641
955
  let candidateIndex = outputHint
642
956
  ? included.findIndex((item) => item.entry.work_unit_number === outputHint.unitNumber)
643
957
  : included.length === 1 ? 0 : -1;
644
958
  let candidateMethod = outputHint ? "unit_output" : included.length === 1 ? "single_unit" : "bisect";
959
+ let parallelOutputReason;
645
960
  if (candidateIndex < 0 && included.length > 1) {
646
- // Binary-search prefixes [0..mid] to find the first failing unit.
647
- let lo = 0;
648
- let hi = included.length - 1;
649
- while (lo < hi) {
650
- const mid = Math.floor((lo + hi) / 2);
651
- await resetCleanWorktree(h.worktreeDir, baseSha, h.runner, gitEnv);
652
- for (let i = 0; i <= mid; i++) {
653
- const part = included[i];
654
- await mergeEntryIntoHead(h.worktreeDir, part.entry, part.resolvedSha, trainRun.require_merge_commit, h.runner, gitEnv);
961
+ const isolated = await isolateInParallel(included);
962
+ if (isolated.retry) {
963
+ retryGateReason = isolated.retry;
964
+ }
965
+ else if (isolated.unit !== null) {
966
+ candidateIndex = included.findIndex((item) => item.entry.work_unit_number === isolated.unit);
967
+ if (candidateIndex >= 0) {
968
+ candidateMethod = isolated.reason ? "unit_output" : "bisect";
969
+ parallelOutputReason = isolated.reason;
655
970
  }
656
- const midRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "HEAD"], {
657
- cwd: h.worktreeDir,
658
- env: gitEnv,
659
- timeoutMs: 15_000,
660
- });
661
- if (midRev.status !== 0)
662
- throw new Error("could not resolve bisection prefix HEAD");
663
- const midSha = midRev.stdout.trim().toLowerCase();
664
- 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);
665
- if (probe.status !== 0)
666
- retryGateReason = classifyRetryableGateFailure(probe.output, probe.status);
667
- if (retryGateReason)
668
- break;
669
- if (probe.status === 0)
670
- lo = mid + 1;
671
- else
672
- hi = mid;
673
971
  }
674
- candidateIndex = lo;
972
+ else {
973
+ // Parallel probes are ambiguous (both halves pass/fail or a setup/merge issue).
974
+ // Keep the established prefix bisection for that case.
975
+ let lo = 0;
976
+ let hi = included.length - 1;
977
+ while (lo < hi) {
978
+ const mid = Math.floor((lo + hi) / 2);
979
+ await resetCleanWorktree(h.worktreeDir, baseSha, h.runner, gitEnv);
980
+ for (let i = 0; i <= mid; i++) {
981
+ const part = included[i];
982
+ await mergeEntryIntoHead(h.worktreeDir, part.entry, part.resolvedSha, trainRun.require_merge_commit, h.runner, gitEnv);
983
+ }
984
+ const midRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "HEAD"], {
985
+ cwd: h.worktreeDir,
986
+ env: gitEnv,
987
+ timeoutMs: 15_000,
988
+ });
989
+ if (midRev.status !== 0)
990
+ throw new Error("could not resolve bisection prefix HEAD");
991
+ const midSha = midRev.stdout.trim().toLowerCase();
992
+ 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, { stage: probeStage });
993
+ if (probe.status !== 0)
994
+ retryGateReason = classifyRetryableGateFailure(probe.output, probe.status);
995
+ if (retryGateReason)
996
+ break;
997
+ if (probe.status === 0)
998
+ lo = mid + 1;
999
+ else
1000
+ hi = mid;
1001
+ }
1002
+ candidateIndex = lo;
1003
+ }
675
1004
  }
676
1005
  if (!retryGateReason && candidateIndex >= 0) {
677
1006
  const candidate = included[candidateIndex];
678
1007
  // A first-unit failure may already exist on target/main; never blame its only addition without checking.
679
1008
  if (candidateIndex === 0) {
680
1009
  await resetCleanWorktree(h.worktreeDir, baseSha, h.runner, gitEnv);
681
- const baseProbe = await runGateAtHead(`bisect target ${baseSha.slice(0, 9)}`, anchorUnit, baseSha);
1010
+ const baseProbe = await runGateAtHead(`bisect target ${baseSha.slice(0, 9)}`, anchorUnit, baseSha, { stage: probeStage });
682
1011
  if (baseProbe.status !== 0) {
683
1012
  retryGateReason = classifyRetryableGateFailure(baseProbe.output, baseProbe.status);
684
1013
  if (retryGateReason) {
@@ -719,7 +1048,7 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
719
1048
  });
720
1049
  if (confirmRev.status !== 0)
721
1050
  throw new Error("could not resolve confirmation prefix HEAD");
722
- const confirmation = await runGateAtHead(`confirm failing half through WU #${candidate.entry.work_unit_number}`, included[0].entry.work_unit_number, confirmRev.stdout.trim().toLowerCase());
1051
+ const confirmation = await runGateAtHead(`confirm failing half through WU #${candidate.entry.work_unit_number}`, included[0].entry.work_unit_number, confirmRev.stdout.trim().toLowerCase(), { stage: probeStage });
723
1052
  if (confirmation.status !== 0)
724
1053
  retryGateReason = classifyRetryableGateFailure(confirmation.output, confirmation.status);
725
1054
  if (retryGateReason)
@@ -733,7 +1062,7 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
733
1062
  attributionMethod = candidateMethod;
734
1063
  attributionReason = outputHint?.unitNumber === attributedUnitNumber
735
1064
  ? outputHint.reason
736
- : `${candidateMethod === "single_unit" ? "single unit" : "bisect"} reproduced ${initialFailedStep} after confirmation for WU #${attributedUnitNumber}`;
1065
+ : parallelOutputReason ?? `${candidateMethod === "single_unit" ? "single unit" : "bisect"} reproduced ${initialFailedStep} after confirmation for WU #${attributedUnitNumber}`;
737
1066
  }
738
1067
  }
739
1068
  }
@@ -745,12 +1074,15 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
745
1074
  if (heartbeatTimer)
746
1075
  clearInterval(heartbeatTimer);
747
1076
  await heartbeatInFlight;
1077
+ rmSync(gateInstanceDir, { recursive: true, force: true });
748
1078
  throwIfHeartbeatFailed();
749
1079
  }
750
1080
  },
751
1081
  }, h.agentClient, h.onLogLine);
752
1082
  }
753
1083
  catch (error) {
1084
+ if (passedGatePersisted)
1085
+ throw error;
754
1086
  if (!(error instanceof CliError) || !["lock_heartbeat_failed", "lock_lease_lost"].includes(error.code))
755
1087
  throw error;
756
1088
  const reason = `merge train job lost its complete-suite lock during the gate: ${error.message}`;
@@ -860,7 +1192,7 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
860
1192
  included_units: included.map((i) => i.entry.work_unit_number),
861
1193
  merged_sha: candidateSha,
862
1194
  base_sha: baseSha,
863
- });
1195
+ }, { retryForMs: h.apiRetryForMs ?? MERGE_TRAIN_API_RETRY_MS });
864
1196
  if (preflight?.ok !== true) {
865
1197
  if (Array.isArray(preflight?.stale_units) && preflight.stale_units.length > 0) {
866
1198
  return { action: "re_gate_stale", staleUnits: preflight.stale_units };
@@ -907,7 +1239,7 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
907
1239
  continue;
908
1240
  }
909
1241
  const releasePushLease = async () => {
910
- await h.machineClient.call("POST", `/machines/me/merge-train/runs/${encodeURIComponent(trainRun.id)}/release-push`, { push_lease_token: targetCheck.pushLeaseToken }).catch(() => { });
1242
+ await h.machineClient.call("POST", `/machines/me/merge-train/runs/${encodeURIComponent(trainRun.id)}/release-push`, { push_lease_token: targetCheck.pushLeaseToken }, { retryForMs: h.apiRetryForMs ?? MERGE_TRAIN_API_RETRY_MS }).catch(() => { });
911
1243
  };
912
1244
  // 5. Fast-forward push candidateSha to origin/<target_branch> (never force-push).
913
1245
  // Renew advisory lease deadline while git push is active, and ONLY release the server push claim
@@ -921,7 +1253,7 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
921
1253
  const renewTimer = setInterval(() => {
922
1254
  if (renewInFlight)
923
1255
  return;
924
- renewInFlight = Promise.resolve(h.machineClient.call("POST", `/machines/me/merge-train/runs/${encodeURIComponent(trainRun.id)}/renew-push`, { push_lease_token: targetCheck.pushLeaseToken })).then(() => undefined, () => undefined).finally(() => { renewInFlight = undefined; });
1256
+ renewInFlight = Promise.resolve(h.machineClient.call("POST", `/machines/me/merge-train/runs/${encodeURIComponent(trainRun.id)}/renew-push`, { push_lease_token: targetCheck.pushLeaseToken }, { retryForMs: h.apiRetryForMs ?? MERGE_TRAIN_API_RETRY_MS })).then(() => undefined, () => undefined).finally(() => { renewInFlight = undefined; });
925
1257
  }, renewIntervalMs);
926
1258
  renewTimer.unref?.();
927
1259
  const includedNumbers = included.map((i) => i.entry.work_unit_number);
@@ -1107,3 +1439,101 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
1107
1439
  };
1108
1440
  }
1109
1441
  }
1442
+ async function resumePassedTrainGate(job, trainRun, h, checkpoint) {
1443
+ const gitEnv = withGitIdentityEnv(h.childEnv);
1444
+ const candidateSha = checkpoint.candidate_sha;
1445
+ const includedNumbers = checkpoint.included.map(({ entry }) => entry.work_unit_number);
1446
+ const skippedUnits = checkpoint.skipped_units;
1447
+ const makeResult = (pushVerified, outcome, error) => ({
1448
+ status: pushVerified ? "succeeded" : "failed",
1449
+ resolvedHead: candidateSha,
1450
+ ...(error ? { error } : {}),
1451
+ trainResult: {
1452
+ target_branch: checkpoint.target_branch,
1453
+ base_sha: checkpoint.base_sha,
1454
+ merged_sha: candidateSha,
1455
+ tested_tree_sha: checkpoint.tested_tree_sha,
1456
+ verified_baseline_sha: checkpoint.verified_baseline_sha,
1457
+ push_verified: pushVerified,
1458
+ push_outcome: outcome,
1459
+ included_units: includedNumbers,
1460
+ landed_units: pushVerified ? includedNumbers : [],
1461
+ skipped_units: skippedUnits,
1462
+ failed_step: pushVerified ? null : "resume passed gate",
1463
+ attributed_unit_number: null,
1464
+ attribution_method: pushVerified ? null : "unattributed",
1465
+ attribution_reason: error?.slice(0, 500) ?? null,
1466
+ retry_count: checkpoint.retry_count,
1467
+ },
1468
+ });
1469
+ h.setResolvedHead(candidateSha);
1470
+ await resetCleanWorktree(h.worktreeDir, candidateSha, h.runner, gitEnv);
1471
+ const candidateTree = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "HEAD^{tree}"], {
1472
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
1473
+ });
1474
+ const expectedTree = checkpoint.tested_tree_sha ?? checkpoint.candidate_tree_sha;
1475
+ if (candidateTree.status !== 0 || !expectedTree || candidateTree.stdout.trim().toLowerCase() !== expectedTree.toLowerCase()) {
1476
+ throw new Error(`passed gate checkpoint tree does not match candidate ${candidateSha}`);
1477
+ }
1478
+ const targetCheck = await h.runStep("resume passed gate: verify target", async () => {
1479
+ const fetched = await retryGitFetch(() => h.runner("git", ["-C", h.worktreeDir, "fetch", "--no-tags", "origin", `+refs/heads/${checkpoint.target_branch}:refs/remotes/origin/${checkpoint.target_branch}`], {
1480
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 120_000,
1481
+ }), `fetch origin/${checkpoint.target_branch}`);
1482
+ if (fetched.status !== 0)
1483
+ throw new Error(`git fetch origin ${checkpoint.target_branch} before resuming passed gate failed`);
1484
+ const current = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "--verify", `origin/${checkpoint.target_branch}^{commit}`], {
1485
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
1486
+ });
1487
+ if (current.status !== 0)
1488
+ throw new Error(`target branch origin/${checkpoint.target_branch} could not be resolved while resuming passed gate`);
1489
+ return current.stdout.trim().toLowerCase();
1490
+ }, () => 0);
1491
+ // A lost push response may have happened before the daemon restarted. Confirm that case before
1492
+ // acquiring a new lease; the candidate tree remains the exact tree that already passed.
1493
+ const ancestry = await h.runner("git", ["-C", h.worktreeDir, "merge-base", "--is-ancestor", candidateSha, `origin/${checkpoint.target_branch}`], {
1494
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
1495
+ });
1496
+ if (ancestry.status === 0)
1497
+ return makeResult(true, "pushed");
1498
+ if (targetCheck !== checkpoint.base_sha) {
1499
+ return makeResult(false, "not_pushed", `target branch ${checkpoint.target_branch} moved from ${checkpoint.base_sha.slice(0, 9)} to ${targetCheck.slice(0, 9)} after the gate passed; a new gate is required`);
1500
+ }
1501
+ const preflight = await h.machineClient.call("POST", `/machines/me/merge-train/runs/${encodeURIComponent(trainRun.id)}/preflight-push`, { included_units: includedNumbers, merged_sha: candidateSha, base_sha: checkpoint.base_sha }, { retryForMs: h.apiRetryForMs ?? MERGE_TRAIN_API_RETRY_MS });
1502
+ if (preflight.ok !== true || !preflight.push_lease_token) {
1503
+ const reason = preflight.reason ?? (preflight.stale_units?.length
1504
+ ? `approved unit state changed after the gate passed: ${preflight.stale_units.map((item) => `#${item.unit_number} ${item.reason}`).join(", ")}`
1505
+ : "merge train push preflight refused the passed candidate");
1506
+ return makeResult(false, "not_pushed", reason);
1507
+ }
1508
+ let renewInFlight;
1509
+ const renewTimer = setInterval(() => {
1510
+ if (!renewInFlight)
1511
+ renewInFlight = h.machineClient.call("POST", `/machines/me/merge-train/runs/${encodeURIComponent(trainRun.id)}/renew-push`, { push_lease_token: preflight.push_lease_token }, { retryForMs: h.apiRetryForMs ?? MERGE_TRAIN_API_RETRY_MS }).catch((error) => { h.onLogLine(`merge-train ${trainRun.id}: passed-gate push lease renew remains pending: ${error.message}`); })
1512
+ .finally(() => { renewInFlight = undefined; });
1513
+ }, 15_000);
1514
+ renewTimer.unref?.();
1515
+ let pushed;
1516
+ try {
1517
+ pushed = await h.runner("git", ["-C", h.worktreeDir, "push", "origin", `${candidateSha}:refs/heads/${checkpoint.target_branch}`], {
1518
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 120_000,
1519
+ });
1520
+ }
1521
+ finally {
1522
+ clearInterval(renewTimer);
1523
+ await renewInFlight;
1524
+ }
1525
+ const fetched = await retryGitFetch(() => h.runner("git", ["-C", h.worktreeDir, "fetch", "--no-tags", "origin", `+refs/heads/${checkpoint.target_branch}:refs/remotes/origin/${checkpoint.target_branch}`], {
1526
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 120_000,
1527
+ }), `verify origin/${checkpoint.target_branch} after resumed push`);
1528
+ if (fetched.status !== 0)
1529
+ throw new Error(`could not verify origin/${checkpoint.target_branch} after resuming passed gate`);
1530
+ const verified = await h.runner("git", ["-C", h.worktreeDir, "merge-base", "--is-ancestor", candidateSha, `origin/${checkpoint.target_branch}`], {
1531
+ cwd: h.worktreeDir, env: gitEnv, timeoutMs: 15_000,
1532
+ });
1533
+ if (verified.status === 0)
1534
+ return makeResult(true, "pushed");
1535
+ if (pushed.status !== 0) {
1536
+ return makeResult(false, "not_pushed", `resumed git push failed: ${(pushed.stderr || pushed.stdout || pushed.error?.message || "unknown error").trim().slice(0, 300)}`);
1537
+ }
1538
+ throw new Error(`resumed git push returned success but ${candidateSha.slice(0, 9)} is not on origin/${checkpoint.target_branch}`);
1539
+ }