benignswarm 0.12.157 → 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.
@@ -0,0 +1,819 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { agentRef } from "./config.js";
4
+ import { createGateMarkerScanner } from "./commands/lock-run.js";
5
+ import { createLockHeartbeatReporter } from "./lock-heartbeat.js";
6
+ import { CliError } from "./errors.js";
7
+ import { retryGitFetch } from "./git-fetch.js";
8
+ const MAX_RE_GATE_ATTEMPTS = 3;
9
+ const SHA_RE = /^[0-9a-f]{7,64}$/i;
10
+ export function shaMatches(left, right) {
11
+ if (!left || !right)
12
+ return false;
13
+ const a = left.trim().toLowerCase();
14
+ const b = right.trim().toLowerCase();
15
+ if (!SHA_RE.test(a) || !SHA_RE.test(b))
16
+ return false;
17
+ return a.startsWith(b) || b.startsWith(a);
18
+ }
19
+ /** Resolve the shell command and complete-suite lock label from merge.gate_command. */
20
+ export function resolveTrainGateCommand(gateCommand, anchorUnitNumber, candidateSha, worktreeDir) {
21
+ let resolved = gateCommand ? gateCommand.trim() : null;
22
+ if (resolved) {
23
+ resolved = resolved.replaceAll("{unit}", String(anchorUnitNumber)).replaceAll("{head}", candidateSha);
24
+ const stripped = resolved.replace(/^b9s\s+lock\s+run\s+complete-suite\b(?:\s+--\S+(?:\s+(?!--)\S+)?)*\s+--\s+/, "");
25
+ resolved = stripped.trim();
26
+ }
27
+ else if (existsSync(join(worktreeDir, "scripts", "gate.sh"))) {
28
+ resolved = `scripts/gate.sh ${candidateSha}`;
29
+ }
30
+ else {
31
+ return null;
32
+ }
33
+ const parts = resolved.split(/\s+/).filter(Boolean);
34
+ if (parts.length >= 1 && parts[0] === "scripts/gate.sh") {
35
+ return {
36
+ commandLine: resolved,
37
+ commandLabel: parts,
38
+ execCmd: "/bin/sh",
39
+ execArgs: parts,
40
+ };
41
+ }
42
+ return {
43
+ commandLine: resolved,
44
+ commandLabel: parts,
45
+ execCmd: "/bin/sh",
46
+ execArgs: ["-c", resolved],
47
+ };
48
+ }
49
+ export function parseFailedGateStep(output, stepTimeline) {
50
+ const failedAt = [...output.matchAll(/^gate:\s+FAILED at\s+(.+?)\s+\([0-9a-f]{7,40}\)\s*$/gmi)].at(-1);
51
+ if (failedAt?.[1]?.trim())
52
+ return failedAt[1].trim();
53
+ const stageExit = [...output.matchAll(/^gate:\s+(.+?)\s+exit\s+[1-9]\d*(?:\s+in\s+\d+\s+s)?\s*$/gmi)].at(-1);
54
+ if (stageExit?.[1]?.trim())
55
+ return stageExit[1].trim();
56
+ const failedTimelineStep = [...stepTimeline].reverse().find((s) => s.exit_code !== null && s.exit_code !== 0);
57
+ return failedTimelineStep?.name ?? "gate";
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
+ }
91
+ export function detectUnitAttributedFailureFromOutput(output, entries) {
92
+ const unitSet = new Set(entries.map((e) => e.work_unit_number));
93
+ const matches = new Set();
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)) {
97
+ const n = Number(m[1]);
98
+ if (unitSet.has(n))
99
+ matches.add(n);
100
+ }
101
+ if (matches.size === 1) {
102
+ const unitNumber = [...matches][0];
103
+ return { unitNumber, reason: `gate output directly attributed failure to WU #${unitNumber}` };
104
+ }
105
+ return null;
106
+ }
107
+ function withGitIdentityEnv(env) {
108
+ return {
109
+ ...env,
110
+ GIT_AUTHOR_NAME: env.GIT_AUTHOR_NAME ?? "BenignSwarm Merge Train",
111
+ GIT_AUTHOR_EMAIL: env.GIT_AUTHOR_EMAIL ?? "merge-train@benignswarm.org",
112
+ GIT_COMMITTER_NAME: env.GIT_COMMITTER_NAME ?? "BenignSwarm Merge Train",
113
+ GIT_COMMITTER_EMAIL: env.GIT_COMMITTER_EMAIL ?? "merge-train@benignswarm.org",
114
+ };
115
+ }
116
+ async function resolveEntryCommitSha(worktreeDir, entry, runner, env) {
117
+ const resolveLocal = async () => {
118
+ const rev = await runner("git", ["-C", worktreeDir, "rev-parse", "--verify", `${entry.approved_head}^{commit}`], {
119
+ cwd: worktreeDir,
120
+ env,
121
+ timeoutMs: 15_000,
122
+ });
123
+ if (rev.status === 0) {
124
+ const sha = rev.stdout.trim().toLowerCase();
125
+ if (shaMatches(sha, entry.approved_head))
126
+ return sha;
127
+ }
128
+ return null;
129
+ };
130
+ let sha = await resolveLocal();
131
+ if (!sha) {
132
+ await retryGitFetch(() => runner("git", ["-C", worktreeDir, "fetch", "--no-tags", "origin", `+refs/heads/${entry.branch}:refs/remotes/origin/${entry.branch}`], {
133
+ cwd: worktreeDir,
134
+ env,
135
+ timeoutMs: 120_000,
136
+ }), `fetch origin/${entry.branch}`);
137
+ sha = await resolveLocal();
138
+ }
139
+ if (!sha) {
140
+ await retryGitFetch(() => runner("git", ["-C", worktreeDir, "fetch", "--no-tags", "origin", entry.approved_head], {
141
+ cwd: worktreeDir,
142
+ env,
143
+ timeoutMs: 120_000,
144
+ }), `fetch commit ${entry.approved_head}`);
145
+ sha = await resolveLocal();
146
+ }
147
+ if (!sha) {
148
+ return {
149
+ sha: null,
150
+ reason: `approved head ${entry.approved_head} on ${entry.branch} could not be fetched from origin`,
151
+ };
152
+ }
153
+ return { sha };
154
+ }
155
+ async function resetCleanWorktree(worktreeDir, targetSha, runner, env) {
156
+ const co = await runner("git", ["-C", worktreeDir, "checkout", "--detach", "--force", targetSha], {
157
+ cwd: worktreeDir,
158
+ env,
159
+ timeoutMs: 60_000,
160
+ });
161
+ if (co.status !== 0) {
162
+ throw new Error(`git checkout --detach ${targetSha.slice(0, 9)} failed: ${(co.stderr || co.stdout).trim().slice(0, 300)}`);
163
+ }
164
+ await runner("git", ["-C", worktreeDir, "clean", "-fd", "-e", "artifacts/", "-e", "node_modules/"], {
165
+ cwd: worktreeDir,
166
+ env,
167
+ timeoutMs: 60_000,
168
+ });
169
+ }
170
+ async function mergeEntryIntoHead(worktreeDir, entry, resolvedSha, requireMergeCommit, runner, env) {
171
+ const alreadyMerged = await runner("git", ["-C", worktreeDir, "merge-base", "--is-ancestor", resolvedSha, "HEAD"], {
172
+ cwd: worktreeDir,
173
+ env,
174
+ timeoutMs: 15_000,
175
+ });
176
+ if (alreadyMerged.status === 0) {
177
+ return { ok: true };
178
+ }
179
+ const args = [
180
+ "-C",
181
+ worktreeDir,
182
+ "merge",
183
+ requireMergeCommit ? "--no-ff" : "--no-ff",
184
+ "-m",
185
+ `Merge WU #${entry.work_unit_number} (${entry.title.slice(0, 72)})`,
186
+ resolvedSha,
187
+ ];
188
+ const merged = await runner("git", args, {
189
+ cwd: worktreeDir,
190
+ env,
191
+ timeoutMs: 60_000,
192
+ });
193
+ if (merged.status !== 0) {
194
+ await runner("git", ["-C", worktreeDir, "merge", "--abort"], {
195
+ cwd: worktreeDir,
196
+ env,
197
+ timeoutMs: 30_000,
198
+ }).catch(() => { });
199
+ const detail = (merged.stderr || merged.stdout).trim().slice(0, 300) || "merge conflict";
200
+ return { ok: false, error: detail };
201
+ }
202
+ return { ok: true };
203
+ }
204
+ /**
205
+ * Executes a claimed merge-train gate job: merges queued approved heads onto origin/<target>
206
+ * in order, leaves conflicting units out, runs the configured gate under complete-suite lock,
207
+ * re-gates if target or approvals move mid-gate (never pushing an ungated merge), pushes on
208
+ * pass, and attributes failures by bisection or unit-attributed output.
209
+ */
210
+ export async function runMergeTrainWorkflow(job, trainRun, h) {
211
+ const gitEnv = withGitIdentityEnv(h.childEnv);
212
+ const activeEntries = trainRun.entries.map((entry) => ({ entry }));
213
+ const skippedUnits = [];
214
+ let retryCount = 0;
215
+ while (true) {
216
+ // 1. Fetch origin and check out current remote target.
217
+ const { baseSha } = await h.runStep("fetch target", async () => {
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}`], {
219
+ cwd: h.worktreeDir,
220
+ env: gitEnv,
221
+ timeoutMs: 120_000,
222
+ }), `fetch origin/${trainRun.target_branch}`);
223
+ if (fetchRes.status !== 0) {
224
+ throw new Error(`git fetch origin failed: ${(fetchRes.stderr || fetchRes.stdout).trim().slice(0, 300)}`);
225
+ }
226
+ const targetRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "--verify", `origin/${trainRun.target_branch}^{commit}`], {
227
+ cwd: h.worktreeDir,
228
+ env: gitEnv,
229
+ timeoutMs: 15_000,
230
+ });
231
+ if (targetRev.status !== 0) {
232
+ throw new Error(`target branch origin/${trainRun.target_branch} could not be resolved`);
233
+ }
234
+ const sha = targetRev.stdout.trim().toLowerCase();
235
+ await resetCleanWorktree(h.worktreeDir, sha, h.runner, gitEnv);
236
+ return { baseSha: sha };
237
+ }, () => 0);
238
+ // 2. Merge remaining active entries onto target in queue order, skipping conflicts & unfetchable heads.
239
+ const included = [];
240
+ await h.runStep("merge queued heads", async () => {
241
+ for (const item of [...activeEntries]) {
242
+ const { entry } = item;
243
+ const resolved = await resolveEntryCommitSha(h.worktreeDir, entry, h.runner, gitEnv);
244
+ if (!resolved.sha) {
245
+ skippedUnits.push({
246
+ unit_number: entry.work_unit_number,
247
+ approved_head: entry.approved_head,
248
+ outcome: "stale",
249
+ reason: resolved.reason ?? "approved head missing on origin",
250
+ });
251
+ const idx = activeEntries.indexOf(item);
252
+ if (idx >= 0)
253
+ activeEntries.splice(idx, 1);
254
+ continue;
255
+ }
256
+ item.resolvedSha = resolved.sha;
257
+ const merged = await mergeEntryIntoHead(h.worktreeDir, entry, resolved.sha, trainRun.require_merge_commit, h.runner, gitEnv);
258
+ if (!merged.ok) {
259
+ skippedUnits.push({
260
+ unit_number: entry.work_unit_number,
261
+ approved_head: resolved.sha,
262
+ outcome: "conflict",
263
+ reason: `merge conflict onto ${trainRun.target_branch}: ${merged.error}`,
264
+ });
265
+ const idx = activeEntries.indexOf(item);
266
+ if (idx >= 0)
267
+ activeEntries.splice(idx, 1);
268
+ continue;
269
+ }
270
+ included.push({ entry, resolvedSha: resolved.sha });
271
+ }
272
+ return 0;
273
+ }, () => 0);
274
+ if (included.length === 0) {
275
+ return {
276
+ status: "succeeded",
277
+ resolvedHead: baseSha,
278
+ trainResult: {
279
+ target_branch: trainRun.target_branch,
280
+ base_sha: baseSha,
281
+ merged_sha: null,
282
+ tested_tree_sha: null,
283
+ verified_baseline_sha: null,
284
+ push_verified: false,
285
+ included_units: [],
286
+ landed_units: [],
287
+ skipped_units: skippedUnits,
288
+ failed_step: null,
289
+ attributed_unit_number: null,
290
+ attribution_method: null,
291
+ attribution_reason: null,
292
+ retry_count: retryCount,
293
+ },
294
+ };
295
+ }
296
+ const headRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "HEAD"], {
297
+ cwd: h.worktreeDir,
298
+ env: gitEnv,
299
+ timeoutMs: 15_000,
300
+ });
301
+ if (headRev.status !== 0)
302
+ throw new Error("could not resolve merged HEAD commit SHA");
303
+ const candidateSha = headRev.stdout.trim().toLowerCase();
304
+ const treeRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "HEAD^{tree}"], {
305
+ cwd: h.worktreeDir,
306
+ env: gitEnv,
307
+ timeoutMs: 15_000,
308
+ });
309
+ const candidateTreeSha = treeRev.status === 0 ? treeRev.stdout.trim().toLowerCase() : null;
310
+ h.setResolvedHead(candidateSha);
311
+ // 3. Run configured gate under complete-suite lock (with bisection on failure).
312
+ const anchorUnit = included[0].entry.work_unit_number;
313
+ const gateSpec = resolveTrainGateCommand(trainRun.gate_command, anchorUnit, candidateSha, h.worktreeDir);
314
+ if (!gateSpec && trainRun.require_gate_receipt) {
315
+ throw new Error("project requires a gate receipt but has no merge.gate_command or scripts/gate.sh");
316
+ }
317
+ let gateVerifiedBaseline = null;
318
+ let gateTestedTree = candidateTreeSha;
319
+ let gateOutputText = "";
320
+ let failedStep = null;
321
+ let attributedUnitNumber = null;
322
+ let attributionMethod = null;
323
+ let attributionReason = null;
324
+ let gateExitCode = 0;
325
+ if (gateSpec) {
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)
373
+ return;
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) => {
378
+ throwIfHeartbeatFailed();
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`;
437
+ }
438
+ else {
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;
444
+ }
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
+ }
482
+ }
483
+ else {
484
+ attributedUnitNumber = included[lo].entry.work_unit_number;
485
+ attributionMethod = "bisect";
486
+ attributionReason = `bisect isolated failure at ${failedStep} to WU #${attributedUnitNumber}`;
487
+ }
488
+ }
489
+ }
490
+ }
491
+ return { exit_code: mainRun.status, ...scanResult };
492
+ }
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
+ }
528
+ }
529
+ if (gateExitCode !== 0) {
530
+ const stepLabel = failedStep ?? parseFailedGateStep(gateOutputText, h.stepTimeline);
531
+ const errText = `merge train failed at ${stepLabel}${attributedUnitNumber ? `; attributed to WU #${attributedUnitNumber} (${attributionMethod})` : ""}`;
532
+ return {
533
+ status: "failed",
534
+ resolvedHead: candidateSha,
535
+ error: errText,
536
+ trainResult: {
537
+ target_branch: trainRun.target_branch,
538
+ base_sha: baseSha,
539
+ merged_sha: candidateSha,
540
+ tested_tree_sha: gateTestedTree,
541
+ verified_baseline_sha: gateVerifiedBaseline,
542
+ push_verified: false,
543
+ included_units: included.map((i) => i.entry.work_unit_number),
544
+ landed_units: [],
545
+ skipped_units: skippedUnits,
546
+ failed_step: stepLabel,
547
+ attributed_unit_number: attributedUnitNumber,
548
+ attribution_method: attributionMethod ?? "unattributed",
549
+ attribution_reason: attributionReason ?? errText,
550
+ retry_count: retryCount,
551
+ },
552
+ };
553
+ }
554
+ // 4. Verify target did NOT move mid-gate before pushing.
555
+ const targetCheck = await h.runStep("verify target & preflight push", async () => {
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}`], {
557
+ cwd: h.worktreeDir,
558
+ env: gitEnv,
559
+ timeoutMs: 120_000,
560
+ }), `fetch origin/${trainRun.target_branch}`);
561
+ if (fetchTarget.status !== 0) {
562
+ throw new Error(`git fetch origin ${trainRun.target_branch} before push failed`);
563
+ }
564
+ const curRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "--verify", `origin/${trainRun.target_branch}^{commit}`], {
565
+ cwd: h.worktreeDir,
566
+ env: gitEnv,
567
+ timeoutMs: 15_000,
568
+ });
569
+ const currentRemoteSha = curRev.stdout.trim().toLowerCase();
570
+ if (currentRemoteSha !== baseSha) {
571
+ return { action: "re_gate_target_moved", currentRemoteSha };
572
+ }
573
+ const preflight = await h.machineClient.call("POST", `/machines/me/merge-train/runs/${encodeURIComponent(trainRun.id)}/preflight-push`, {
574
+ included_units: included.map((i) => i.entry.work_unit_number),
575
+ merged_sha: candidateSha,
576
+ base_sha: baseSha,
577
+ });
578
+ if (preflight?.ok !== true) {
579
+ if (Array.isArray(preflight?.stale_units) && preflight.stale_units.length > 0) {
580
+ return { action: "re_gate_stale", staleUnits: preflight.stale_units };
581
+ }
582
+ throw new Error(preflight?.reason || "merge train push preflight did not return ok: true; refusing push");
583
+ }
584
+ if (typeof preflight.push_lease_token !== "string" || !preflight.push_lease_token) {
585
+ throw new Error("merge train push preflight returned ok without a push_lease_token; refusing push");
586
+ }
587
+ const parsedExpiresAt = typeof preflight.push_lease_expires_at === "string"
588
+ ? Date.parse(preflight.push_lease_expires_at)
589
+ : NaN;
590
+ return {
591
+ action: "push",
592
+ pushLeaseToken: preflight.push_lease_token,
593
+ pushLeaseExpiresAtMs: Number.isFinite(parsedExpiresAt) ? parsedExpiresAt : null,
594
+ };
595
+ }, () => 0);
596
+ if (targetCheck.action === "re_gate_target_moved") {
597
+ retryCount++;
598
+ h.onLogLine(`merge-train ${trainRun.id}: target ${trainRun.target_branch} moved mid-gate (${baseSha.slice(0, 9)} -> ${targetCheck.currentRemoteSha.slice(0, 9)}); refusing ungated push`);
599
+ if (retryCount >= MAX_RE_GATE_ATTEMPTS) {
600
+ throw new Error(`target branch ${trainRun.target_branch} moved mid-gate ${retryCount} times; refusing to push ungated merge`);
601
+ }
602
+ continue;
603
+ }
604
+ if (targetCheck.action === "re_gate_stale") {
605
+ retryCount++;
606
+ const staleSet = new Set(targetCheck.staleUnits.map((s) => s.unit_number));
607
+ for (const stale of targetCheck.staleUnits) {
608
+ const idx = activeEntries.findIndex((item) => item.entry.work_unit_number === stale.unit_number);
609
+ const removedItem = idx >= 0 ? activeEntries.splice(idx, 1)[0] : undefined;
610
+ skippedUnits.push({
611
+ unit_number: stale.unit_number,
612
+ approved_head: removedItem?.entry.approved_head ?? candidateSha,
613
+ outcome: "stale",
614
+ reason: stale.reason,
615
+ });
616
+ }
617
+ h.onLogLine(`merge-train ${trainRun.id}: dropped stale/reopened unit(s) #${[...staleSet].join(", #")}; re-gating`);
618
+ if (retryCount >= MAX_RE_GATE_ATTEMPTS) {
619
+ throw new Error(`stale approvals changed repeatedly mid-gate; refusing to push ungated merge`);
620
+ }
621
+ continue;
622
+ }
623
+ const releasePushLease = async () => {
624
+ await h.machineClient.call("POST", `/machines/me/merge-train/runs/${encodeURIComponent(trainRun.id)}/release-push`, { push_lease_token: targetCheck.pushLeaseToken }).catch(() => { });
625
+ };
626
+ // 5. Fast-forward push candidateSha to origin/<target_branch> (never force-push).
627
+ // Renew advisory lease deadline while git push is active, and ONLY release the server push claim
628
+ // if remote verification proves candidateSha did NOT land on origin/<target> (merge-base --is-ancestor exit 1).
629
+ const rawRemainingMs = targetCheck.pushLeaseExpiresAtMs !== null
630
+ ? targetCheck.pushLeaseExpiresAtMs - Date.now()
631
+ : 60_000;
632
+ const pushTimeoutMs = Math.max(rawRemainingMs, 120_000);
633
+ const renewIntervalMs = Math.max(20, Math.min(15_000, Math.floor(Math.max(40, rawRemainingMs) / 2)));
634
+ let renewInFlight;
635
+ const renewTimer = setInterval(() => {
636
+ if (renewInFlight)
637
+ return;
638
+ 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; });
639
+ }, renewIntervalMs);
640
+ renewTimer.unref?.();
641
+ const includedNumbers = included.map((i) => i.entry.work_unit_number);
642
+ let pushStep;
643
+ try {
644
+ pushStep = await h.runStep("push merged target", async () => {
645
+ const pushRes = await h.runner("git", ["-C", h.worktreeDir, "push", "origin", `${candidateSha}:refs/heads/${trainRun.target_branch}`], {
646
+ cwd: h.worktreeDir,
647
+ env: gitEnv,
648
+ timeoutMs: pushTimeoutMs,
649
+ });
650
+ if (pushRes.status === 0)
651
+ return { kind: "pushed" };
652
+ // Push failed or timed out cleanly/ambiguously: verify actual state on origin/<target> before deciding.
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}`], {
654
+ cwd: h.worktreeDir,
655
+ env: gitEnv,
656
+ timeoutMs: 60_000,
657
+ }), `fetch origin/${trainRun.target_branch}`);
658
+ if (postFetch.status !== 0) {
659
+ return {
660
+ kind: "inconclusive",
661
+ error: `git push origin ${trainRun.target_branch} status ${pushRes.status ?? "timeout"} and post-push fetch failed (status ${postFetch.status ?? "timeout"}); keeping push claim locked until resolved`,
662
+ };
663
+ }
664
+ const postPushRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "--verify", `origin/${trainRun.target_branch}^{commit}`], {
665
+ cwd: h.worktreeDir,
666
+ env: gitEnv,
667
+ timeoutMs: 15_000,
668
+ });
669
+ if (postPushRev.status !== 0) {
670
+ return {
671
+ kind: "inconclusive",
672
+ error: `could not inspect origin/${trainRun.target_branch} (rev-parse status ${postPushRev.status ?? "timeout"}) after push failure; keeping push claim locked until resolved`,
673
+ };
674
+ }
675
+ const latestRemote = postPushRev.stdout.trim().toLowerCase();
676
+ // If remote already has candidateSha (or an ancestor check confirms it landed), treat ambiguous push as landed!
677
+ if (latestRemote === candidateSha) {
678
+ return { kind: "pushed" };
679
+ }
680
+ const ancestorCheck = await h.runner("git", ["-C", h.worktreeDir, "merge-base", "--is-ancestor", candidateSha, latestRemote], {
681
+ cwd: h.worktreeDir,
682
+ env: gitEnv,
683
+ timeoutMs: 15_000,
684
+ });
685
+ if (ancestorCheck.status === 0) {
686
+ return { kind: "pushed" };
687
+ }
688
+ if (ancestorCheck.status !== 1) {
689
+ return {
690
+ kind: "inconclusive",
691
+ error: `git merge-base --is-ancestor returned inconclusive status ${ancestorCheck.status ?? "timeout"}; keeping push claim locked until resolved`,
692
+ };
693
+ }
694
+ // Confirmed (merge-base --is-ancestor exited 1) that candidateSha did NOT reach origin/<target>; safe to release push claim.
695
+ await releasePushLease();
696
+ if (latestRemote && latestRemote !== baseSha) {
697
+ return { kind: "not_pushed", movedTo: latestRemote };
698
+ }
699
+ return {
700
+ kind: "not_pushed",
701
+ movedTo: null,
702
+ error: `git push origin ${trainRun.target_branch} failed: ${(pushRes.stderr || pushRes.stdout || pushRes.error?.message || "unknown error").trim().slice(0, 300)}`,
703
+ };
704
+ }, (r) => (r.kind === "pushed" ? 0 : 1));
705
+ }
706
+ catch (err) {
707
+ const msg = err instanceof Error ? err.message : String(err);
708
+ pushStep = {
709
+ kind: "inconclusive",
710
+ error: `${msg}; keeping push claim locked until resolved`,
711
+ };
712
+ }
713
+ finally {
714
+ clearInterval(renewTimer);
715
+ await renewInFlight;
716
+ }
717
+ if (pushStep.kind === "inconclusive") {
718
+ return {
719
+ status: "failed",
720
+ resolvedHead: candidateSha,
721
+ error: pushStep.error,
722
+ trainResult: {
723
+ target_branch: trainRun.target_branch,
724
+ base_sha: baseSha,
725
+ merged_sha: candidateSha,
726
+ tested_tree_sha: gateTestedTree,
727
+ verified_baseline_sha: gateVerifiedBaseline,
728
+ push_verified: false,
729
+ push_outcome: "inconclusive",
730
+ included_units: includedNumbers,
731
+ landed_units: [],
732
+ skipped_units: skippedUnits,
733
+ failed_step: "push merged target",
734
+ attributed_unit_number: null,
735
+ attribution_method: "unattributed",
736
+ attribution_reason: pushStep.error.slice(0, 500),
737
+ retry_count: retryCount,
738
+ },
739
+ };
740
+ }
741
+ if (pushStep.kind === "not_pushed") {
742
+ if (pushStep.movedTo) {
743
+ retryCount++;
744
+ h.onLogLine(`merge-train ${trainRun.id}: target ${trainRun.target_branch} moved at push time to ${pushStep.movedTo.slice(0, 9)}; re-gating`);
745
+ if (retryCount >= MAX_RE_GATE_ATTEMPTS) {
746
+ const msg = `target branch ${trainRun.target_branch} moved at push time ${retryCount} times`;
747
+ return {
748
+ status: "failed",
749
+ resolvedHead: candidateSha,
750
+ error: msg,
751
+ trainResult: {
752
+ target_branch: trainRun.target_branch,
753
+ base_sha: baseSha,
754
+ merged_sha: candidateSha,
755
+ tested_tree_sha: gateTestedTree,
756
+ verified_baseline_sha: gateVerifiedBaseline,
757
+ push_verified: false,
758
+ push_outcome: "not_pushed",
759
+ included_units: includedNumbers,
760
+ landed_units: [],
761
+ skipped_units: skippedUnits,
762
+ failed_step: "push merged target",
763
+ attributed_unit_number: null,
764
+ attribution_method: "unattributed",
765
+ attribution_reason: msg,
766
+ retry_count: retryCount,
767
+ },
768
+ };
769
+ }
770
+ continue;
771
+ }
772
+ const errMsg = pushStep.error ?? `git push origin ${trainRun.target_branch} failed`;
773
+ return {
774
+ status: "failed",
775
+ resolvedHead: candidateSha,
776
+ error: errMsg,
777
+ trainResult: {
778
+ target_branch: trainRun.target_branch,
779
+ base_sha: baseSha,
780
+ merged_sha: candidateSha,
781
+ tested_tree_sha: gateTestedTree,
782
+ verified_baseline_sha: gateVerifiedBaseline,
783
+ push_verified: false,
784
+ push_outcome: "not_pushed",
785
+ included_units: includedNumbers,
786
+ landed_units: [],
787
+ skipped_units: skippedUnits,
788
+ failed_step: "push merged target",
789
+ attributed_unit_number: null,
790
+ attribution_method: "unattributed",
791
+ attribution_reason: errMsg.slice(0, 500),
792
+ retry_count: retryCount,
793
+ },
794
+ };
795
+ }
796
+ // Push succeeded; return exact landed units whose heads reached target.
797
+ return {
798
+ status: "succeeded",
799
+ resolvedHead: candidateSha,
800
+ trainResult: {
801
+ target_branch: trainRun.target_branch,
802
+ base_sha: baseSha,
803
+ merged_sha: candidateSha,
804
+ tested_tree_sha: gateTestedTree,
805
+ verified_baseline_sha: gateVerifiedBaseline,
806
+ push_verified: true,
807
+ push_outcome: "pushed",
808
+ included_units: includedNumbers,
809
+ landed_units: includedNumbers,
810
+ skipped_units: skippedUnits,
811
+ failed_step: null,
812
+ attributed_unit_number: null,
813
+ attribution_method: null,
814
+ attribution_reason: null,
815
+ retry_count: retryCount,
816
+ },
817
+ };
818
+ }
819
+ }