benignswarm 0.12.157 → 0.12.158
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/args.js +2 -2
- package/dist/commands/admin.js +32 -2
- package/dist/commands/operator.js +1 -1
- package/dist/commands/ux.js +19 -2
- package/dist/commands/wu.js +116 -2
- package/dist/git.js +52 -14
- package/dist/help.js +11 -1
- package/dist/merge-train.js +736 -0
- package/dist/ux-jobs.js +80 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,736 @@
|
|
|
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 { CliError } from "./errors.js";
|
|
6
|
+
const MAX_RE_GATE_ATTEMPTS = 3;
|
|
7
|
+
const SHA_RE = /^[0-9a-f]{7,64}$/i;
|
|
8
|
+
export function shaMatches(left, right) {
|
|
9
|
+
if (!left || !right)
|
|
10
|
+
return false;
|
|
11
|
+
const a = left.trim().toLowerCase();
|
|
12
|
+
const b = right.trim().toLowerCase();
|
|
13
|
+
if (!SHA_RE.test(a) || !SHA_RE.test(b))
|
|
14
|
+
return false;
|
|
15
|
+
return a.startsWith(b) || b.startsWith(a);
|
|
16
|
+
}
|
|
17
|
+
/** Resolve the shell command and complete-suite lock label from merge.gate_command. */
|
|
18
|
+
export function resolveTrainGateCommand(gateCommand, anchorUnitNumber, candidateSha, worktreeDir) {
|
|
19
|
+
let resolved = gateCommand ? gateCommand.trim() : null;
|
|
20
|
+
if (resolved) {
|
|
21
|
+
resolved = resolved.replaceAll("{unit}", String(anchorUnitNumber)).replaceAll("{head}", candidateSha);
|
|
22
|
+
const stripped = resolved.replace(/^b9s\s+lock\s+run\s+complete-suite\b(?:\s+--\S+(?:\s+(?!--)\S+)?)*\s+--\s+/, "");
|
|
23
|
+
resolved = stripped.trim();
|
|
24
|
+
}
|
|
25
|
+
else if (existsSync(join(worktreeDir, "scripts", "gate.sh"))) {
|
|
26
|
+
resolved = `scripts/gate.sh ${candidateSha}`;
|
|
27
|
+
}
|
|
28
|
+
else {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
const parts = resolved.split(/\s+/).filter(Boolean);
|
|
32
|
+
if (parts.length >= 1 && parts[0] === "scripts/gate.sh") {
|
|
33
|
+
return {
|
|
34
|
+
commandLine: resolved,
|
|
35
|
+
commandLabel: parts,
|
|
36
|
+
execCmd: "/bin/sh",
|
|
37
|
+
execArgs: parts,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
commandLine: resolved,
|
|
42
|
+
commandLabel: parts,
|
|
43
|
+
execCmd: "/bin/sh",
|
|
44
|
+
execArgs: ["-c", resolved],
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
export function parseFailedGateStep(output, stepTimeline) {
|
|
48
|
+
const failedAt = [...output.matchAll(/^gate:\s+FAILED at\s+(.+?)\s+\([0-9a-f]{7,40}\)\s*$/gmi)].at(-1);
|
|
49
|
+
if (failedAt?.[1]?.trim())
|
|
50
|
+
return failedAt[1].trim();
|
|
51
|
+
const stageExit = [...output.matchAll(/^gate:\s+(.+?)\s+exit\s+[1-9]\d*(?:\s+in\s+\d+\s+s)?\s*$/gmi)].at(-1);
|
|
52
|
+
if (stageExit?.[1]?.trim())
|
|
53
|
+
return stageExit[1].trim();
|
|
54
|
+
const failedTimelineStep = [...stepTimeline].reverse().find((s) => s.exit_code !== null && s.exit_code !== 0);
|
|
55
|
+
return failedTimelineStep?.name ?? "gate";
|
|
56
|
+
}
|
|
57
|
+
export function detectUnitAttributedFailureFromOutput(output, entries) {
|
|
58
|
+
const unitSet = new Set(entries.map((e) => e.work_unit_number));
|
|
59
|
+
const matches = new Set();
|
|
60
|
+
for (const m of output.matchAll(/\b(?:WU\s*#?|unit\s*#?)(\d+)\b/gi)) {
|
|
61
|
+
const n = Number(m[1]);
|
|
62
|
+
if (unitSet.has(n))
|
|
63
|
+
matches.add(n);
|
|
64
|
+
}
|
|
65
|
+
if (matches.size === 1) {
|
|
66
|
+
const unitNumber = [...matches][0];
|
|
67
|
+
return { unitNumber, reason: `gate output directly attributed failure to WU #${unitNumber}` };
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
function withGitIdentityEnv(env) {
|
|
72
|
+
return {
|
|
73
|
+
...env,
|
|
74
|
+
GIT_AUTHOR_NAME: env.GIT_AUTHOR_NAME ?? "BenignSwarm Merge Train",
|
|
75
|
+
GIT_AUTHOR_EMAIL: env.GIT_AUTHOR_EMAIL ?? "merge-train@benignswarm.org",
|
|
76
|
+
GIT_COMMITTER_NAME: env.GIT_COMMITTER_NAME ?? "BenignSwarm Merge Train",
|
|
77
|
+
GIT_COMMITTER_EMAIL: env.GIT_COMMITTER_EMAIL ?? "merge-train@benignswarm.org",
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
async function resolveEntryCommitSha(worktreeDir, entry, runner, env) {
|
|
81
|
+
const resolveLocal = async () => {
|
|
82
|
+
const rev = await runner("git", ["-C", worktreeDir, "rev-parse", "--verify", `${entry.approved_head}^{commit}`], {
|
|
83
|
+
cwd: worktreeDir,
|
|
84
|
+
env,
|
|
85
|
+
timeoutMs: 15_000,
|
|
86
|
+
});
|
|
87
|
+
if (rev.status === 0) {
|
|
88
|
+
const sha = rev.stdout.trim().toLowerCase();
|
|
89
|
+
if (shaMatches(sha, entry.approved_head))
|
|
90
|
+
return sha;
|
|
91
|
+
}
|
|
92
|
+
return null;
|
|
93
|
+
};
|
|
94
|
+
let sha = await resolveLocal();
|
|
95
|
+
if (!sha) {
|
|
96
|
+
await runner("git", ["-C", worktreeDir, "fetch", "--no-tags", "origin", entry.branch], {
|
|
97
|
+
cwd: worktreeDir,
|
|
98
|
+
env,
|
|
99
|
+
timeoutMs: 120_000,
|
|
100
|
+
});
|
|
101
|
+
sha = await resolveLocal();
|
|
102
|
+
}
|
|
103
|
+
if (!sha) {
|
|
104
|
+
await runner("git", ["-C", worktreeDir, "fetch", "--no-tags", "origin", entry.approved_head], {
|
|
105
|
+
cwd: worktreeDir,
|
|
106
|
+
env,
|
|
107
|
+
timeoutMs: 120_000,
|
|
108
|
+
});
|
|
109
|
+
sha = await resolveLocal();
|
|
110
|
+
}
|
|
111
|
+
if (!sha) {
|
|
112
|
+
return {
|
|
113
|
+
sha: null,
|
|
114
|
+
reason: `approved head ${entry.approved_head} on ${entry.branch} could not be fetched from origin`,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
return { sha };
|
|
118
|
+
}
|
|
119
|
+
async function resetCleanWorktree(worktreeDir, targetSha, runner, env) {
|
|
120
|
+
const co = await runner("git", ["-C", worktreeDir, "checkout", "--detach", "--force", targetSha], {
|
|
121
|
+
cwd: worktreeDir,
|
|
122
|
+
env,
|
|
123
|
+
timeoutMs: 60_000,
|
|
124
|
+
});
|
|
125
|
+
if (co.status !== 0) {
|
|
126
|
+
throw new Error(`git checkout --detach ${targetSha.slice(0, 9)} failed: ${(co.stderr || co.stdout).trim().slice(0, 300)}`);
|
|
127
|
+
}
|
|
128
|
+
await runner("git", ["-C", worktreeDir, "clean", "-fd", "-e", "artifacts/", "-e", "node_modules/"], {
|
|
129
|
+
cwd: worktreeDir,
|
|
130
|
+
env,
|
|
131
|
+
timeoutMs: 60_000,
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
async function mergeEntryIntoHead(worktreeDir, entry, resolvedSha, requireMergeCommit, runner, env) {
|
|
135
|
+
const alreadyMerged = await runner("git", ["-C", worktreeDir, "merge-base", "--is-ancestor", resolvedSha, "HEAD"], {
|
|
136
|
+
cwd: worktreeDir,
|
|
137
|
+
env,
|
|
138
|
+
timeoutMs: 15_000,
|
|
139
|
+
});
|
|
140
|
+
if (alreadyMerged.status === 0) {
|
|
141
|
+
return { ok: true };
|
|
142
|
+
}
|
|
143
|
+
const args = [
|
|
144
|
+
"-C",
|
|
145
|
+
worktreeDir,
|
|
146
|
+
"merge",
|
|
147
|
+
requireMergeCommit ? "--no-ff" : "--no-ff",
|
|
148
|
+
"-m",
|
|
149
|
+
`Merge WU #${entry.work_unit_number} (${entry.title.slice(0, 72)})`,
|
|
150
|
+
resolvedSha,
|
|
151
|
+
];
|
|
152
|
+
const merged = await runner("git", args, {
|
|
153
|
+
cwd: worktreeDir,
|
|
154
|
+
env,
|
|
155
|
+
timeoutMs: 60_000,
|
|
156
|
+
});
|
|
157
|
+
if (merged.status !== 0) {
|
|
158
|
+
await runner("git", ["-C", worktreeDir, "merge", "--abort"], {
|
|
159
|
+
cwd: worktreeDir,
|
|
160
|
+
env,
|
|
161
|
+
timeoutMs: 30_000,
|
|
162
|
+
}).catch(() => { });
|
|
163
|
+
const detail = (merged.stderr || merged.stdout).trim().slice(0, 300) || "merge conflict";
|
|
164
|
+
return { ok: false, error: detail };
|
|
165
|
+
}
|
|
166
|
+
return { ok: true };
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Executes a claimed merge-train gate job: merges queued approved heads onto origin/<target>
|
|
170
|
+
* in order, leaves conflicting units out, runs the configured gate under complete-suite lock,
|
|
171
|
+
* re-gates if target or approvals move mid-gate (never pushing an ungated merge), pushes on
|
|
172
|
+
* pass, and attributes failures by bisection or unit-attributed output.
|
|
173
|
+
*/
|
|
174
|
+
export async function runMergeTrainWorkflow(job, trainRun, h) {
|
|
175
|
+
const gitEnv = withGitIdentityEnv(h.childEnv);
|
|
176
|
+
const activeEntries = trainRun.entries.map((entry) => ({ entry }));
|
|
177
|
+
const skippedUnits = [];
|
|
178
|
+
let retryCount = 0;
|
|
179
|
+
while (true) {
|
|
180
|
+
// 1. Fetch origin and check out current remote target.
|
|
181
|
+
const { baseSha } = await h.runStep("fetch target", async () => {
|
|
182
|
+
const fetchRes = await h.runner("git", ["-C", h.worktreeDir, "fetch", "--prune", "--no-tags", "origin"], {
|
|
183
|
+
cwd: h.worktreeDir,
|
|
184
|
+
env: gitEnv,
|
|
185
|
+
timeoutMs: 120_000,
|
|
186
|
+
});
|
|
187
|
+
if (fetchRes.status !== 0) {
|
|
188
|
+
throw new Error(`git fetch origin failed: ${(fetchRes.stderr || fetchRes.stdout).trim().slice(0, 300)}`);
|
|
189
|
+
}
|
|
190
|
+
const targetRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "--verify", `origin/${trainRun.target_branch}^{commit}`], {
|
|
191
|
+
cwd: h.worktreeDir,
|
|
192
|
+
env: gitEnv,
|
|
193
|
+
timeoutMs: 15_000,
|
|
194
|
+
});
|
|
195
|
+
if (targetRev.status !== 0) {
|
|
196
|
+
throw new Error(`target branch origin/${trainRun.target_branch} could not be resolved`);
|
|
197
|
+
}
|
|
198
|
+
const sha = targetRev.stdout.trim().toLowerCase();
|
|
199
|
+
await resetCleanWorktree(h.worktreeDir, sha, h.runner, gitEnv);
|
|
200
|
+
return { baseSha: sha };
|
|
201
|
+
}, () => 0);
|
|
202
|
+
// 2. Merge remaining active entries onto target in queue order, skipping conflicts & unfetchable heads.
|
|
203
|
+
const included = [];
|
|
204
|
+
await h.runStep("merge queued heads", async () => {
|
|
205
|
+
for (const item of [...activeEntries]) {
|
|
206
|
+
const { entry } = item;
|
|
207
|
+
const resolved = await resolveEntryCommitSha(h.worktreeDir, entry, h.runner, gitEnv);
|
|
208
|
+
if (!resolved.sha) {
|
|
209
|
+
skippedUnits.push({
|
|
210
|
+
unit_number: entry.work_unit_number,
|
|
211
|
+
approved_head: entry.approved_head,
|
|
212
|
+
outcome: "stale",
|
|
213
|
+
reason: resolved.reason ?? "approved head missing on origin",
|
|
214
|
+
});
|
|
215
|
+
const idx = activeEntries.indexOf(item);
|
|
216
|
+
if (idx >= 0)
|
|
217
|
+
activeEntries.splice(idx, 1);
|
|
218
|
+
continue;
|
|
219
|
+
}
|
|
220
|
+
item.resolvedSha = resolved.sha;
|
|
221
|
+
const merged = await mergeEntryIntoHead(h.worktreeDir, entry, resolved.sha, trainRun.require_merge_commit, h.runner, gitEnv);
|
|
222
|
+
if (!merged.ok) {
|
|
223
|
+
skippedUnits.push({
|
|
224
|
+
unit_number: entry.work_unit_number,
|
|
225
|
+
approved_head: resolved.sha,
|
|
226
|
+
outcome: "conflict",
|
|
227
|
+
reason: `merge conflict onto ${trainRun.target_branch}: ${merged.error}`,
|
|
228
|
+
});
|
|
229
|
+
const idx = activeEntries.indexOf(item);
|
|
230
|
+
if (idx >= 0)
|
|
231
|
+
activeEntries.splice(idx, 1);
|
|
232
|
+
continue;
|
|
233
|
+
}
|
|
234
|
+
included.push({ entry, resolvedSha: resolved.sha });
|
|
235
|
+
}
|
|
236
|
+
return 0;
|
|
237
|
+
}, () => 0);
|
|
238
|
+
if (included.length === 0) {
|
|
239
|
+
return {
|
|
240
|
+
status: "succeeded",
|
|
241
|
+
resolvedHead: baseSha,
|
|
242
|
+
trainResult: {
|
|
243
|
+
target_branch: trainRun.target_branch,
|
|
244
|
+
base_sha: baseSha,
|
|
245
|
+
merged_sha: null,
|
|
246
|
+
tested_tree_sha: null,
|
|
247
|
+
verified_baseline_sha: null,
|
|
248
|
+
push_verified: false,
|
|
249
|
+
included_units: [],
|
|
250
|
+
landed_units: [],
|
|
251
|
+
skipped_units: skippedUnits,
|
|
252
|
+
failed_step: null,
|
|
253
|
+
attributed_unit_number: null,
|
|
254
|
+
attribution_method: null,
|
|
255
|
+
attribution_reason: null,
|
|
256
|
+
retry_count: retryCount,
|
|
257
|
+
},
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
const headRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "HEAD"], {
|
|
261
|
+
cwd: h.worktreeDir,
|
|
262
|
+
env: gitEnv,
|
|
263
|
+
timeoutMs: 15_000,
|
|
264
|
+
});
|
|
265
|
+
if (headRev.status !== 0)
|
|
266
|
+
throw new Error("could not resolve merged HEAD commit SHA");
|
|
267
|
+
const candidateSha = headRev.stdout.trim().toLowerCase();
|
|
268
|
+
const treeRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "HEAD^{tree}"], {
|
|
269
|
+
cwd: h.worktreeDir,
|
|
270
|
+
env: gitEnv,
|
|
271
|
+
timeoutMs: 15_000,
|
|
272
|
+
});
|
|
273
|
+
const candidateTreeSha = treeRev.status === 0 ? treeRev.stdout.trim().toLowerCase() : null;
|
|
274
|
+
h.setResolvedHead(candidateSha);
|
|
275
|
+
// 3. Run configured gate under complete-suite lock (with bisection on failure).
|
|
276
|
+
const anchorUnit = included[0].entry.work_unit_number;
|
|
277
|
+
const gateSpec = resolveTrainGateCommand(trainRun.gate_command, anchorUnit, candidateSha, h.worktreeDir);
|
|
278
|
+
if (!gateSpec && trainRun.require_gate_receipt) {
|
|
279
|
+
throw new Error("project requires a gate receipt but has no merge.gate_command or scripts/gate.sh");
|
|
280
|
+
}
|
|
281
|
+
let gateVerifiedBaseline = null;
|
|
282
|
+
let gateTestedTree = candidateTreeSha;
|
|
283
|
+
let gateOutputText = "";
|
|
284
|
+
let failedStep = null;
|
|
285
|
+
let attributedUnitNumber = null;
|
|
286
|
+
let attributionMethod = null;
|
|
287
|
+
let attributionReason = null;
|
|
288
|
+
let gateExitCode = 0;
|
|
289
|
+
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)
|
|
317
|
+
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`;
|
|
360
|
+
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;
|
|
388
|
+
}
|
|
389
|
+
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;
|
|
411
|
+
}
|
|
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}`;
|
|
420
|
+
}
|
|
421
|
+
else {
|
|
422
|
+
attributedUnitNumber = included[0].entry.work_unit_number;
|
|
423
|
+
attributionMethod = "bisect";
|
|
424
|
+
attributionReason = `bisect confirmed ${trainRun.target_branch} passes and WU #${attributedUnitNumber} fails ${failedStep}`;
|
|
425
|
+
}
|
|
426
|
+
}
|
|
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
|
+
}
|
|
433
|
+
}
|
|
434
|
+
}
|
|
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);
|
|
445
|
+
}
|
|
446
|
+
if (gateExitCode !== 0) {
|
|
447
|
+
const stepLabel = failedStep ?? parseFailedGateStep(gateOutputText, h.stepTimeline);
|
|
448
|
+
const errText = `merge train failed at ${stepLabel}${attributedUnitNumber ? `; attributed to WU #${attributedUnitNumber} (${attributionMethod})` : ""}`;
|
|
449
|
+
return {
|
|
450
|
+
status: "failed",
|
|
451
|
+
resolvedHead: candidateSha,
|
|
452
|
+
error: errText,
|
|
453
|
+
trainResult: {
|
|
454
|
+
target_branch: trainRun.target_branch,
|
|
455
|
+
base_sha: baseSha,
|
|
456
|
+
merged_sha: candidateSha,
|
|
457
|
+
tested_tree_sha: gateTestedTree,
|
|
458
|
+
verified_baseline_sha: gateVerifiedBaseline,
|
|
459
|
+
push_verified: false,
|
|
460
|
+
included_units: included.map((i) => i.entry.work_unit_number),
|
|
461
|
+
landed_units: [],
|
|
462
|
+
skipped_units: skippedUnits,
|
|
463
|
+
failed_step: stepLabel,
|
|
464
|
+
attributed_unit_number: attributedUnitNumber,
|
|
465
|
+
attribution_method: attributionMethod ?? "unattributed",
|
|
466
|
+
attribution_reason: attributionReason ?? errText,
|
|
467
|
+
retry_count: retryCount,
|
|
468
|
+
},
|
|
469
|
+
};
|
|
470
|
+
}
|
|
471
|
+
// 4. Verify target did NOT move mid-gate before pushing.
|
|
472
|
+
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], {
|
|
474
|
+
cwd: h.worktreeDir,
|
|
475
|
+
env: gitEnv,
|
|
476
|
+
timeoutMs: 120_000,
|
|
477
|
+
});
|
|
478
|
+
if (fetchTarget.status !== 0) {
|
|
479
|
+
throw new Error(`git fetch origin ${trainRun.target_branch} before push failed`);
|
|
480
|
+
}
|
|
481
|
+
const curRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "--verify", `origin/${trainRun.target_branch}^{commit}`], {
|
|
482
|
+
cwd: h.worktreeDir,
|
|
483
|
+
env: gitEnv,
|
|
484
|
+
timeoutMs: 15_000,
|
|
485
|
+
});
|
|
486
|
+
const currentRemoteSha = curRev.stdout.trim().toLowerCase();
|
|
487
|
+
if (currentRemoteSha !== baseSha) {
|
|
488
|
+
return { action: "re_gate_target_moved", currentRemoteSha };
|
|
489
|
+
}
|
|
490
|
+
const preflight = await h.machineClient.call("POST", `/machines/me/merge-train/runs/${encodeURIComponent(trainRun.id)}/preflight-push`, {
|
|
491
|
+
included_units: included.map((i) => i.entry.work_unit_number),
|
|
492
|
+
merged_sha: candidateSha,
|
|
493
|
+
base_sha: baseSha,
|
|
494
|
+
});
|
|
495
|
+
if (preflight?.ok !== true) {
|
|
496
|
+
if (Array.isArray(preflight?.stale_units) && preflight.stale_units.length > 0) {
|
|
497
|
+
return { action: "re_gate_stale", staleUnits: preflight.stale_units };
|
|
498
|
+
}
|
|
499
|
+
throw new Error(preflight?.reason || "merge train push preflight did not return ok: true; refusing push");
|
|
500
|
+
}
|
|
501
|
+
if (typeof preflight.push_lease_token !== "string" || !preflight.push_lease_token) {
|
|
502
|
+
throw new Error("merge train push preflight returned ok without a push_lease_token; refusing push");
|
|
503
|
+
}
|
|
504
|
+
const parsedExpiresAt = typeof preflight.push_lease_expires_at === "string"
|
|
505
|
+
? Date.parse(preflight.push_lease_expires_at)
|
|
506
|
+
: NaN;
|
|
507
|
+
return {
|
|
508
|
+
action: "push",
|
|
509
|
+
pushLeaseToken: preflight.push_lease_token,
|
|
510
|
+
pushLeaseExpiresAtMs: Number.isFinite(parsedExpiresAt) ? parsedExpiresAt : null,
|
|
511
|
+
};
|
|
512
|
+
}, () => 0);
|
|
513
|
+
if (targetCheck.action === "re_gate_target_moved") {
|
|
514
|
+
retryCount++;
|
|
515
|
+
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`);
|
|
516
|
+
if (retryCount >= MAX_RE_GATE_ATTEMPTS) {
|
|
517
|
+
throw new Error(`target branch ${trainRun.target_branch} moved mid-gate ${retryCount} times; refusing to push ungated merge`);
|
|
518
|
+
}
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (targetCheck.action === "re_gate_stale") {
|
|
522
|
+
retryCount++;
|
|
523
|
+
const staleSet = new Set(targetCheck.staleUnits.map((s) => s.unit_number));
|
|
524
|
+
for (const stale of targetCheck.staleUnits) {
|
|
525
|
+
const idx = activeEntries.findIndex((item) => item.entry.work_unit_number === stale.unit_number);
|
|
526
|
+
const removedItem = idx >= 0 ? activeEntries.splice(idx, 1)[0] : undefined;
|
|
527
|
+
skippedUnits.push({
|
|
528
|
+
unit_number: stale.unit_number,
|
|
529
|
+
approved_head: removedItem?.entry.approved_head ?? candidateSha,
|
|
530
|
+
outcome: "stale",
|
|
531
|
+
reason: stale.reason,
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
h.onLogLine(`merge-train ${trainRun.id}: dropped stale/reopened unit(s) #${[...staleSet].join(", #")}; re-gating`);
|
|
535
|
+
if (retryCount >= MAX_RE_GATE_ATTEMPTS) {
|
|
536
|
+
throw new Error(`stale approvals changed repeatedly mid-gate; refusing to push ungated merge`);
|
|
537
|
+
}
|
|
538
|
+
continue;
|
|
539
|
+
}
|
|
540
|
+
const releasePushLease = async () => {
|
|
541
|
+
await h.machineClient.call("POST", `/machines/me/merge-train/runs/${encodeURIComponent(trainRun.id)}/release-push`, { push_lease_token: targetCheck.pushLeaseToken }).catch(() => { });
|
|
542
|
+
};
|
|
543
|
+
// 5. Fast-forward push candidateSha to origin/<target_branch> (never force-push).
|
|
544
|
+
// Renew advisory lease deadline while git push is active, and ONLY release the server push claim
|
|
545
|
+
// if remote verification proves candidateSha did NOT land on origin/<target> (merge-base --is-ancestor exit 1).
|
|
546
|
+
const rawRemainingMs = targetCheck.pushLeaseExpiresAtMs !== null
|
|
547
|
+
? targetCheck.pushLeaseExpiresAtMs - Date.now()
|
|
548
|
+
: 60_000;
|
|
549
|
+
const pushTimeoutMs = Math.max(rawRemainingMs, 120_000);
|
|
550
|
+
const renewIntervalMs = Math.max(20, Math.min(15_000, Math.floor(Math.max(40, rawRemainingMs) / 2)));
|
|
551
|
+
let renewInFlight;
|
|
552
|
+
const renewTimer = setInterval(() => {
|
|
553
|
+
if (renewInFlight)
|
|
554
|
+
return;
|
|
555
|
+
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; });
|
|
556
|
+
}, renewIntervalMs);
|
|
557
|
+
renewTimer.unref?.();
|
|
558
|
+
const includedNumbers = included.map((i) => i.entry.work_unit_number);
|
|
559
|
+
let pushStep;
|
|
560
|
+
try {
|
|
561
|
+
pushStep = await h.runStep("push merged target", async () => {
|
|
562
|
+
const pushRes = await h.runner("git", ["-C", h.worktreeDir, "push", "origin", `${candidateSha}:refs/heads/${trainRun.target_branch}`], {
|
|
563
|
+
cwd: h.worktreeDir,
|
|
564
|
+
env: gitEnv,
|
|
565
|
+
timeoutMs: pushTimeoutMs,
|
|
566
|
+
});
|
|
567
|
+
if (pushRes.status === 0)
|
|
568
|
+
return { kind: "pushed" };
|
|
569
|
+
// 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], {
|
|
571
|
+
cwd: h.worktreeDir,
|
|
572
|
+
env: gitEnv,
|
|
573
|
+
timeoutMs: 60_000,
|
|
574
|
+
});
|
|
575
|
+
if (postFetch.status !== 0) {
|
|
576
|
+
return {
|
|
577
|
+
kind: "inconclusive",
|
|
578
|
+
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`,
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
const postPushRev = await h.runner("git", ["-C", h.worktreeDir, "rev-parse", "--verify", `origin/${trainRun.target_branch}^{commit}`], {
|
|
582
|
+
cwd: h.worktreeDir,
|
|
583
|
+
env: gitEnv,
|
|
584
|
+
timeoutMs: 15_000,
|
|
585
|
+
});
|
|
586
|
+
if (postPushRev.status !== 0) {
|
|
587
|
+
return {
|
|
588
|
+
kind: "inconclusive",
|
|
589
|
+
error: `could not inspect origin/${trainRun.target_branch} (rev-parse status ${postPushRev.status ?? "timeout"}) after push failure; keeping push claim locked until resolved`,
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
const latestRemote = postPushRev.stdout.trim().toLowerCase();
|
|
593
|
+
// If remote already has candidateSha (or an ancestor check confirms it landed), treat ambiguous push as landed!
|
|
594
|
+
if (latestRemote === candidateSha) {
|
|
595
|
+
return { kind: "pushed" };
|
|
596
|
+
}
|
|
597
|
+
const ancestorCheck = await h.runner("git", ["-C", h.worktreeDir, "merge-base", "--is-ancestor", candidateSha, latestRemote], {
|
|
598
|
+
cwd: h.worktreeDir,
|
|
599
|
+
env: gitEnv,
|
|
600
|
+
timeoutMs: 15_000,
|
|
601
|
+
});
|
|
602
|
+
if (ancestorCheck.status === 0) {
|
|
603
|
+
return { kind: "pushed" };
|
|
604
|
+
}
|
|
605
|
+
if (ancestorCheck.status !== 1) {
|
|
606
|
+
return {
|
|
607
|
+
kind: "inconclusive",
|
|
608
|
+
error: `git merge-base --is-ancestor returned inconclusive status ${ancestorCheck.status ?? "timeout"}; keeping push claim locked until resolved`,
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
// Confirmed (merge-base --is-ancestor exited 1) that candidateSha did NOT reach origin/<target>; safe to release push claim.
|
|
612
|
+
await releasePushLease();
|
|
613
|
+
if (latestRemote && latestRemote !== baseSha) {
|
|
614
|
+
return { kind: "not_pushed", movedTo: latestRemote };
|
|
615
|
+
}
|
|
616
|
+
return {
|
|
617
|
+
kind: "not_pushed",
|
|
618
|
+
movedTo: null,
|
|
619
|
+
error: `git push origin ${trainRun.target_branch} failed: ${(pushRes.stderr || pushRes.stdout || pushRes.error?.message || "unknown error").trim().slice(0, 300)}`,
|
|
620
|
+
};
|
|
621
|
+
}, (r) => (r.kind === "pushed" ? 0 : 1));
|
|
622
|
+
}
|
|
623
|
+
catch (err) {
|
|
624
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
625
|
+
pushStep = {
|
|
626
|
+
kind: "inconclusive",
|
|
627
|
+
error: `${msg}; keeping push claim locked until resolved`,
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
finally {
|
|
631
|
+
clearInterval(renewTimer);
|
|
632
|
+
await renewInFlight;
|
|
633
|
+
}
|
|
634
|
+
if (pushStep.kind === "inconclusive") {
|
|
635
|
+
return {
|
|
636
|
+
status: "failed",
|
|
637
|
+
resolvedHead: candidateSha,
|
|
638
|
+
error: pushStep.error,
|
|
639
|
+
trainResult: {
|
|
640
|
+
target_branch: trainRun.target_branch,
|
|
641
|
+
base_sha: baseSha,
|
|
642
|
+
merged_sha: candidateSha,
|
|
643
|
+
tested_tree_sha: gateTestedTree,
|
|
644
|
+
verified_baseline_sha: gateVerifiedBaseline,
|
|
645
|
+
push_verified: false,
|
|
646
|
+
push_outcome: "inconclusive",
|
|
647
|
+
included_units: includedNumbers,
|
|
648
|
+
landed_units: [],
|
|
649
|
+
skipped_units: skippedUnits,
|
|
650
|
+
failed_step: "push merged target",
|
|
651
|
+
attributed_unit_number: null,
|
|
652
|
+
attribution_method: "unattributed",
|
|
653
|
+
attribution_reason: pushStep.error.slice(0, 500),
|
|
654
|
+
retry_count: retryCount,
|
|
655
|
+
},
|
|
656
|
+
};
|
|
657
|
+
}
|
|
658
|
+
if (pushStep.kind === "not_pushed") {
|
|
659
|
+
if (pushStep.movedTo) {
|
|
660
|
+
retryCount++;
|
|
661
|
+
h.onLogLine(`merge-train ${trainRun.id}: target ${trainRun.target_branch} moved at push time to ${pushStep.movedTo.slice(0, 9)}; re-gating`);
|
|
662
|
+
if (retryCount >= MAX_RE_GATE_ATTEMPTS) {
|
|
663
|
+
const msg = `target branch ${trainRun.target_branch} moved at push time ${retryCount} times`;
|
|
664
|
+
return {
|
|
665
|
+
status: "failed",
|
|
666
|
+
resolvedHead: candidateSha,
|
|
667
|
+
error: msg,
|
|
668
|
+
trainResult: {
|
|
669
|
+
target_branch: trainRun.target_branch,
|
|
670
|
+
base_sha: baseSha,
|
|
671
|
+
merged_sha: candidateSha,
|
|
672
|
+
tested_tree_sha: gateTestedTree,
|
|
673
|
+
verified_baseline_sha: gateVerifiedBaseline,
|
|
674
|
+
push_verified: false,
|
|
675
|
+
push_outcome: "not_pushed",
|
|
676
|
+
included_units: includedNumbers,
|
|
677
|
+
landed_units: [],
|
|
678
|
+
skipped_units: skippedUnits,
|
|
679
|
+
failed_step: "push merged target",
|
|
680
|
+
attributed_unit_number: null,
|
|
681
|
+
attribution_method: "unattributed",
|
|
682
|
+
attribution_reason: msg,
|
|
683
|
+
retry_count: retryCount,
|
|
684
|
+
},
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
continue;
|
|
688
|
+
}
|
|
689
|
+
const errMsg = pushStep.error ?? `git push origin ${trainRun.target_branch} failed`;
|
|
690
|
+
return {
|
|
691
|
+
status: "failed",
|
|
692
|
+
resolvedHead: candidateSha,
|
|
693
|
+
error: errMsg,
|
|
694
|
+
trainResult: {
|
|
695
|
+
target_branch: trainRun.target_branch,
|
|
696
|
+
base_sha: baseSha,
|
|
697
|
+
merged_sha: candidateSha,
|
|
698
|
+
tested_tree_sha: gateTestedTree,
|
|
699
|
+
verified_baseline_sha: gateVerifiedBaseline,
|
|
700
|
+
push_verified: false,
|
|
701
|
+
push_outcome: "not_pushed",
|
|
702
|
+
included_units: includedNumbers,
|
|
703
|
+
landed_units: [],
|
|
704
|
+
skipped_units: skippedUnits,
|
|
705
|
+
failed_step: "push merged target",
|
|
706
|
+
attributed_unit_number: null,
|
|
707
|
+
attribution_method: "unattributed",
|
|
708
|
+
attribution_reason: errMsg.slice(0, 500),
|
|
709
|
+
retry_count: retryCount,
|
|
710
|
+
},
|
|
711
|
+
};
|
|
712
|
+
}
|
|
713
|
+
// Push succeeded; return exact landed units whose heads reached target.
|
|
714
|
+
return {
|
|
715
|
+
status: "succeeded",
|
|
716
|
+
resolvedHead: candidateSha,
|
|
717
|
+
trainResult: {
|
|
718
|
+
target_branch: trainRun.target_branch,
|
|
719
|
+
base_sha: baseSha,
|
|
720
|
+
merged_sha: candidateSha,
|
|
721
|
+
tested_tree_sha: gateTestedTree,
|
|
722
|
+
verified_baseline_sha: gateVerifiedBaseline,
|
|
723
|
+
push_verified: true,
|
|
724
|
+
push_outcome: "pushed",
|
|
725
|
+
included_units: includedNumbers,
|
|
726
|
+
landed_units: includedNumbers,
|
|
727
|
+
skipped_units: skippedUnits,
|
|
728
|
+
failed_step: null,
|
|
729
|
+
attributed_unit_number: null,
|
|
730
|
+
attribution_method: null,
|
|
731
|
+
attribution_reason: null,
|
|
732
|
+
retry_count: retryCount,
|
|
733
|
+
},
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
}
|