benignswarm 0.12.162 → 0.12.164
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/admin-index.js +0 -0
- package/dist/client.js +137 -36
- package/dist/commands/agent.js +2 -2
- package/dist/commands/lock-run.js +19 -4
- package/dist/commands/machine.js +4 -1
- package/dist/commands/ux.js +8 -0
- package/dist/commands/watch.js +7 -3
- package/dist/commands/wu.js +24 -3
- package/dist/harnesses.js +4 -3
- package/dist/help.js +3 -1
- package/dist/index.js +0 -0
- package/dist/merge-train.js +166 -6
- package/dist/output.js +4 -0
- package/dist/rebase-compare.js +301 -0
- package/dist/ux-jobs.js +124 -11
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/merge-train.js
CHANGED
|
@@ -5,6 +5,14 @@ import { createGateMarkerScanner } from "./commands/lock-run.js";
|
|
|
5
5
|
import { createLockHeartbeatReporter } from "./lock-heartbeat.js";
|
|
6
6
|
import { CliError } from "./errors.js";
|
|
7
7
|
import { retryGitFetch } from "./git-fetch.js";
|
|
8
|
+
export const CLI_VERSION_CONFLICT_FILES = [
|
|
9
|
+
"package-lock.json",
|
|
10
|
+
"packages/cli/package.json",
|
|
11
|
+
"packages/cli/src/version.ts",
|
|
12
|
+
];
|
|
13
|
+
export const MECHANICALLY_RESOLVABLE_CONFLICT_FILES = [
|
|
14
|
+
...CLI_VERSION_CONFLICT_FILES,
|
|
15
|
+
];
|
|
8
16
|
const MAX_RE_GATE_ATTEMPTS = 3;
|
|
9
17
|
const SHA_RE = /^[0-9a-f]{7,64}$/i;
|
|
10
18
|
export function shaMatches(left, right) {
|
|
@@ -60,11 +68,16 @@ export function parseFailedGateStep(output, stepTimeline) {
|
|
|
60
68
|
export function classifyRetryableGateFailure(output, exitCode) {
|
|
61
69
|
if (/^gate:\s+stale baseline:/im.test(output))
|
|
62
70
|
return "stale baseline";
|
|
63
|
-
const
|
|
64
|
-
const
|
|
65
|
-
const
|
|
71
|
+
const hasAssertionError = /\bAssertionError\b/i.test(output);
|
|
72
|
+
const hasFailedTestCount = /\bTests?\s+\d+\s+failed\b|\bTest Files?\s+\d+\s+failed\b/i.test(output);
|
|
73
|
+
const assertionFailure = hasAssertionError || hasFailedTestCount;
|
|
74
|
+
// When a test runner reports failing tests, scan only the failing test blocks so
|
|
75
|
+
// passing tests that intentionally exercise D1/DO error paths cannot mask real failures.
|
|
76
|
+
const failureScope = hasFailedTestCount ? failingTestText(output) : output;
|
|
77
|
+
const setupFailure = /\b(?:test setup error|setup file(?:s)?[^\n]*(?:failed|error)|failed (?:during|while) (?:the )?test setup|error (?:during|while) (?:the )?test setup)\b/i.test(failureScope);
|
|
78
|
+
const localD1Failure = /\bD1_ERROR:\s*[^\n]*\binternal error\b|\binternal error in Durable Object storage\b/i.test(failureScope);
|
|
66
79
|
const watchdogTimeout = (exitCode === 124 || /^gate:\s+.+\s+exit 124(?:\s+in\s+\d+\s+s)?\s*$/im.test(output)) && !assertionFailure;
|
|
67
|
-
if (setupFailure || localD1Failure || watchdogTimeout)
|
|
80
|
+
if (!hasAssertionError && (setupFailure || localD1Failure || watchdogTimeout))
|
|
68
81
|
return "infrastructure";
|
|
69
82
|
return null;
|
|
70
83
|
}
|
|
@@ -206,6 +219,140 @@ async function resetCleanWorktree(worktreeDir, targetSha, runner, env) {
|
|
|
206
219
|
timeoutMs: 60_000,
|
|
207
220
|
});
|
|
208
221
|
}
|
|
222
|
+
function stripVersionFieldsFromPackageJson(raw) {
|
|
223
|
+
try {
|
|
224
|
+
const parsed = JSON.parse(raw);
|
|
225
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
226
|
+
return null;
|
|
227
|
+
const clone = { ...parsed };
|
|
228
|
+
delete clone.version;
|
|
229
|
+
return clone;
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
return null;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
function stripCliVersionFieldsFromLockfile(raw) {
|
|
236
|
+
try {
|
|
237
|
+
const parsed = JSON.parse(raw);
|
|
238
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
|
|
239
|
+
return null;
|
|
240
|
+
const packages = parsed.packages && typeof parsed.packages === "object" ? { ...parsed.packages } : undefined;
|
|
241
|
+
if (packages) {
|
|
242
|
+
if (packages[""] && typeof packages[""] === "object") {
|
|
243
|
+
packages[""] = { ...packages[""] };
|
|
244
|
+
delete packages[""].version;
|
|
245
|
+
}
|
|
246
|
+
if (packages["packages/cli"] && typeof packages["packages/cli"] === "object") {
|
|
247
|
+
packages["packages/cli"] = { ...packages["packages/cli"] };
|
|
248
|
+
delete packages["packages/cli"].version;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
return {
|
|
252
|
+
...parsed,
|
|
253
|
+
...(packages ? { packages } : {}),
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
catch {
|
|
257
|
+
return null;
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
async function readConflictStage(worktreeDir, stage, file, runner, env) {
|
|
261
|
+
const res = await runner("git", ["-C", worktreeDir, "show", `:${stage}:${file}`], {
|
|
262
|
+
cwd: worktreeDir,
|
|
263
|
+
env,
|
|
264
|
+
timeoutMs: 15_000,
|
|
265
|
+
});
|
|
266
|
+
return res.status === 0 ? res.stdout : null;
|
|
267
|
+
}
|
|
268
|
+
async function isSafeMechanicalCliVersionConflict(worktreeDir, conflictingFiles, runner, env) {
|
|
269
|
+
if (conflictingFiles.includes("packages/cli/package.json")) {
|
|
270
|
+
const base = await readConflictStage(worktreeDir, 1, "packages/cli/package.json", runner, env);
|
|
271
|
+
const ours = await readConflictStage(worktreeDir, 2, "packages/cli/package.json", runner, env);
|
|
272
|
+
const theirs = await readConflictStage(worktreeDir, 3, "packages/cli/package.json", runner, env);
|
|
273
|
+
if (!base || !ours || !theirs)
|
|
274
|
+
return false;
|
|
275
|
+
const b = stripVersionFieldsFromPackageJson(base);
|
|
276
|
+
const o = stripVersionFieldsFromPackageJson(ours);
|
|
277
|
+
const t = stripVersionFieldsFromPackageJson(theirs);
|
|
278
|
+
if (!b || !o || !t)
|
|
279
|
+
return false;
|
|
280
|
+
if (JSON.stringify(b) !== JSON.stringify(t) && JSON.stringify(o) !== JSON.stringify(t))
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
if (conflictingFiles.includes("package-lock.json")) {
|
|
284
|
+
const base = await readConflictStage(worktreeDir, 1, "package-lock.json", runner, env);
|
|
285
|
+
const ours = await readConflictStage(worktreeDir, 2, "package-lock.json", runner, env);
|
|
286
|
+
const theirs = await readConflictStage(worktreeDir, 3, "package-lock.json", runner, env);
|
|
287
|
+
if (!base || !ours || !theirs)
|
|
288
|
+
return false;
|
|
289
|
+
const b = stripCliVersionFieldsFromLockfile(base);
|
|
290
|
+
const o = stripCliVersionFieldsFromLockfile(ours);
|
|
291
|
+
const t = stripCliVersionFieldsFromLockfile(theirs);
|
|
292
|
+
if (!b || !o || !t)
|
|
293
|
+
return false;
|
|
294
|
+
// Allow mechanical resolution when incoming changes to package-lock.json are CLI-version-only
|
|
295
|
+
// relative to its merge-base (or already equal to HEAD outside CLI version).
|
|
296
|
+
if (JSON.stringify(b) !== JSON.stringify(t) && JSON.stringify(o) !== JSON.stringify(t))
|
|
297
|
+
return false;
|
|
298
|
+
}
|
|
299
|
+
if (conflictingFiles.includes("packages/cli/src/version.ts")) {
|
|
300
|
+
const theirs = await readConflictStage(worktreeDir, 3, "packages/cli/src/version.ts", runner, env);
|
|
301
|
+
if (!theirs || !/^export const CLI_VERSION = "[^"\n]+";\s*$/.test(theirs))
|
|
302
|
+
return false;
|
|
303
|
+
}
|
|
304
|
+
return true;
|
|
305
|
+
}
|
|
306
|
+
async function tryResolveMechanicalMergeConflicts(worktreeDir, entry, conflictingFiles, runner, env) {
|
|
307
|
+
if (!conflictingFiles.length)
|
|
308
|
+
return false;
|
|
309
|
+
const allow = new Set(MECHANICALLY_RESOLVABLE_CONFLICT_FILES);
|
|
310
|
+
if (conflictingFiles.some((file) => !allow.has(file)))
|
|
311
|
+
return false;
|
|
312
|
+
const cliSet = new Set(CLI_VERSION_CONFLICT_FILES);
|
|
313
|
+
const cliConflicts = conflictingFiles.filter((file) => cliSet.has(file));
|
|
314
|
+
if (cliConflicts.length) {
|
|
315
|
+
const safeCli = await isSafeMechanicalCliVersionConflict(worktreeDir, cliConflicts, runner, env);
|
|
316
|
+
if (!safeCli)
|
|
317
|
+
return false;
|
|
318
|
+
// Take main's (HEAD / --ours) CLI version & lockfile, then re-run scripts/bump-cli.sh.
|
|
319
|
+
const co = await runner("git", ["-C", worktreeDir, "checkout", "--ours", "--", ...cliConflicts], {
|
|
320
|
+
cwd: worktreeDir,
|
|
321
|
+
env,
|
|
322
|
+
timeoutMs: 30_000,
|
|
323
|
+
});
|
|
324
|
+
if (co.status !== 0)
|
|
325
|
+
return false;
|
|
326
|
+
if (existsSync(join(worktreeDir, "scripts/bump-cli.sh"))) {
|
|
327
|
+
const bump = await runner("sh", ["scripts/bump-cli.sh"], {
|
|
328
|
+
cwd: worktreeDir,
|
|
329
|
+
env,
|
|
330
|
+
timeoutMs: 60_000,
|
|
331
|
+
});
|
|
332
|
+
if (bump.status !== 0)
|
|
333
|
+
return false;
|
|
334
|
+
}
|
|
335
|
+
const existingCliFiles = CLI_VERSION_CONFLICT_FILES.filter((file) => existsSync(join(worktreeDir, file)));
|
|
336
|
+
if (existingCliFiles.length) {
|
|
337
|
+
const add = await runner("git", ["-C", worktreeDir, "add", "--", ...existingCliFiles], {
|
|
338
|
+
cwd: worktreeDir,
|
|
339
|
+
env,
|
|
340
|
+
timeoutMs: 30_000,
|
|
341
|
+
});
|
|
342
|
+
if (add.status !== 0)
|
|
343
|
+
return false;
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
const remaining = await runner("git", ["-C", worktreeDir, "diff", "--name-only", "--diff-filter=U"], {
|
|
347
|
+
cwd: worktreeDir,
|
|
348
|
+
env,
|
|
349
|
+
timeoutMs: 15_000,
|
|
350
|
+
});
|
|
351
|
+
if (remaining.status !== 0 || remaining.stdout.trim())
|
|
352
|
+
return false;
|
|
353
|
+
const commit = await runner("git", ["-C", worktreeDir, "commit", "--no-verify", "-m", `Merge WU #${entry.work_unit_number} (${entry.title.slice(0, 72)})`], { cwd: worktreeDir, env, timeoutMs: 60_000 });
|
|
354
|
+
return commit.status === 0;
|
|
355
|
+
}
|
|
209
356
|
async function mergeEntryIntoHead(worktreeDir, entry, resolvedSha, requireMergeCommit, runner, env) {
|
|
210
357
|
const alreadyMerged = await runner("git", ["-C", worktreeDir, "merge-base", "--is-ancestor", resolvedSha, "HEAD"], {
|
|
211
358
|
cwd: worktreeDir,
|
|
@@ -230,13 +377,23 @@ async function mergeEntryIntoHead(worktreeDir, entry, resolvedSha, requireMergeC
|
|
|
230
377
|
timeoutMs: 60_000,
|
|
231
378
|
});
|
|
232
379
|
if (merged.status !== 0) {
|
|
380
|
+
const conflictsRes = await runner("git", ["-C", worktreeDir, "diff", "--name-only", "--diff-filter=U"], {
|
|
381
|
+
cwd: worktreeDir,
|
|
382
|
+
env,
|
|
383
|
+
timeoutMs: 15_000,
|
|
384
|
+
}).catch(() => ({ status: 1, stdout: "", stderr: "" }));
|
|
385
|
+
const conflictingFiles = [...new Set(conflictsRes.stdout.split(/\r?\n/).map((line) => line.trim()).filter(Boolean))].sort();
|
|
386
|
+
const resolvedMechanically = await tryResolveMechanicalMergeConflicts(worktreeDir, entry, conflictingFiles, runner, env).catch(() => false);
|
|
387
|
+
if (resolvedMechanically) {
|
|
388
|
+
return { ok: true, resolvedMechanicalFiles: conflictingFiles };
|
|
389
|
+
}
|
|
233
390
|
await runner("git", ["-C", worktreeDir, "merge", "--abort"], {
|
|
234
391
|
cwd: worktreeDir,
|
|
235
392
|
env,
|
|
236
393
|
timeoutMs: 30_000,
|
|
237
394
|
}).catch(() => { });
|
|
238
395
|
const detail = (merged.stderr || merged.stdout).trim().slice(0, 300) || "merge conflict";
|
|
239
|
-
return { ok: false, error: detail };
|
|
396
|
+
return { ok: false, error: detail, ...(conflictingFiles.length ? { conflictingFiles } : {}) };
|
|
240
397
|
}
|
|
241
398
|
return { ok: true };
|
|
242
399
|
}
|
|
@@ -301,6 +458,7 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
|
|
|
301
458
|
approved_head: resolved.sha,
|
|
302
459
|
outcome: "conflict",
|
|
303
460
|
reason: `merge conflict onto ${trainRun.target_branch}: ${merged.error}`,
|
|
461
|
+
...(merged.conflictingFiles?.length ? { conflicting_files: merged.conflictingFiles } : {}),
|
|
304
462
|
});
|
|
305
463
|
const idx = activeEntries.indexOf(item);
|
|
306
464
|
if (idx >= 0)
|
|
@@ -375,6 +533,7 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
|
|
|
375
533
|
note: `merge-train ${trainRun.id} (${included.map((i) => `#${i.entry.work_unit_number}`).join(",")}) @ ${candidateSha.slice(0, 9)}`,
|
|
376
534
|
commandLabel: gateSpec.commandLabel,
|
|
377
535
|
...(h.lockPollMs === undefined ? {} : { pollMs: h.lockPollMs }),
|
|
536
|
+
...(h.signal ? { signal: h.signal, remoteJobId: job.id } : {}),
|
|
378
537
|
run: async (lockContext) => {
|
|
379
538
|
const lockedEnv = { ...gitEnv };
|
|
380
539
|
if (lockContext?.jobId)
|
|
@@ -386,6 +545,7 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
|
|
|
386
545
|
lockedEnv.BSCHAT_UX_JOB_ARTIFACT_DIR = h.jobArtifactDir;
|
|
387
546
|
h.setFingerprint(await h.buildFingerprint(lockedEnv, lockContext));
|
|
388
547
|
const heartbeatController = new AbortController();
|
|
548
|
+
const commandSignal = lockContext?.signal ? AbortSignal.any([heartbeatController.signal, lockContext.signal]) : heartbeatController.signal;
|
|
389
549
|
let heartbeatTimer;
|
|
390
550
|
let heartbeatInFlight;
|
|
391
551
|
let heartbeatFailure;
|
|
@@ -427,7 +587,7 @@ export async function runMergeTrainWorkflow(job, trainRun, h) {
|
|
|
427
587
|
cwd: h.worktreeDir,
|
|
428
588
|
env: lockedEnv,
|
|
429
589
|
timeoutMs: 1_800_000,
|
|
430
|
-
signal:
|
|
590
|
+
signal: commandSignal,
|
|
431
591
|
onStdoutChunk: (chunk) => {
|
|
432
592
|
output += chunk;
|
|
433
593
|
if (stepName === "gate")
|
package/dist/output.js
CHANGED
|
@@ -66,9 +66,13 @@ export function fmtStatus(s) {
|
|
|
66
66
|
const parts = [
|
|
67
67
|
`${s.state === "benched" ? "BENCHED " : ""}${s.agent_name}${s.role_name ? `[${s.role_name}]` : ""}${s.away ? ` (away until ${s.away.until}: ${s.away.reason})` : s.usage_limit_until ? ` (usage limit until ${s.usage_limit_until})` : s.liveness === "quiet" ? " (quiet: harness went silent)" : s.liveness === "unknown" ? " (stale, harness unmonitored)" : s.liveness === "scheduled" ? ` (checks every ${s.checks_every} min, next ${(s.next_check_at ?? "").slice(11, 16)} UTC)` : s.liveness === "missed" ? ` (missed its ${s.checks_every}-min check)` : ""}`,
|
|
68
68
|
`state=${s.state ?? "-"}`,
|
|
69
|
+
s.watcher_state ? `watcher=${s.watcher_state}${s.watcher_state === "errored" && s.watcher?.last_error ? `(${s.watcher.last_error})` : ""}` : null,
|
|
69
70
|
s.goal ? `goal="${s.goal}"` : null,
|
|
70
71
|
s.task ? `task="${s.task}"` : null,
|
|
71
72
|
s.blocked_on ? `blocked_on="${s.blocked_on}"` : null,
|
|
73
|
+
s.blocked_kind ? `blocked_kind=${s.blocked_kind}${s.blocked_ref ? `(${s.blocked_ref})` : ""}` : null,
|
|
74
|
+
s.blocked_since ? `blocked_since=${s.blocked_since}` : null,
|
|
75
|
+
s.state_changed_at ? `state_since=${s.state_changed_at}` : null,
|
|
72
76
|
`model=${s.model ?? "-"}`,
|
|
73
77
|
s.machine ? `machine=${s.machine}` : null,
|
|
74
78
|
s.machine_pressure ? `machine_health=${s.machine_pressure.state ?? "unknown"} (sample_age=${typeof s.machine_pressure.age_seconds === "number" ? `${Math.floor(s.machine_pressure.age_seconds)}s` : "unknown"}${s.machine_pressure.reasons?.length ? `; reasons=${s.machine_pressure.reasons.join(",")}` : ""})` : null,
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
import { spawnSync } from "node:child_process";
|
|
2
|
+
export function parseRawDiffEntries(rawOut) {
|
|
3
|
+
const entries = new Map();
|
|
4
|
+
const tokens = rawOut.split("\0");
|
|
5
|
+
for (let i = 0; i + 1 < tokens.length; i += 2) {
|
|
6
|
+
const header = tokens[i];
|
|
7
|
+
const path = tokens[i + 1];
|
|
8
|
+
if (!header.startsWith(":") || !path)
|
|
9
|
+
continue;
|
|
10
|
+
const parts = header.slice(1).split(/\s+/);
|
|
11
|
+
if (parts.length < 5)
|
|
12
|
+
continue;
|
|
13
|
+
entries.set(path, {
|
|
14
|
+
oldMode: parts[0],
|
|
15
|
+
newMode: parts[1],
|
|
16
|
+
oldBlobSha: parts[2].toLowerCase(),
|
|
17
|
+
newBlobSha: parts[3].toLowerCase(),
|
|
18
|
+
status: parts[4],
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
return entries;
|
|
22
|
+
}
|
|
23
|
+
function runGit(args, cwd) {
|
|
24
|
+
const res = spawnSync("git", args, { cwd, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
|
|
25
|
+
return {
|
|
26
|
+
status: res.status ?? 1,
|
|
27
|
+
stdout: res.stdout ?? "",
|
|
28
|
+
stderr: res.stderr ?? "",
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
function resolveCommit(ref, cwd) {
|
|
32
|
+
const res = runGit(["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], cwd);
|
|
33
|
+
return res.status === 0 && res.stdout.trim() ? res.stdout.trim().toLowerCase() : null;
|
|
34
|
+
}
|
|
35
|
+
function resolveTargetRef(targetBranch, cwd) {
|
|
36
|
+
const remoteRef = `refs/remotes/origin/${targetBranch}`;
|
|
37
|
+
if (resolveCommit(remoteRef, cwd))
|
|
38
|
+
return remoteRef;
|
|
39
|
+
const localRef = `refs/heads/${targetBranch}`;
|
|
40
|
+
if (resolveCommit(localRef, cwd))
|
|
41
|
+
return localRef;
|
|
42
|
+
return resolveCommit(targetBranch, cwd) ? targetBranch : null;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Parse a `git diff --unified=0` patch per file, keeping only changed (`-` / `+`)
|
|
46
|
+
* hunk lines and structural metadata so surrounding context and shifted line numbers
|
|
47
|
+
* are ignored when verifying whether a rebased change matches the approved patch.
|
|
48
|
+
*/
|
|
49
|
+
export function parseZeroContextDiff(patch, rawEntries = new Map()) {
|
|
50
|
+
const files = new Map();
|
|
51
|
+
const lines = patch.split(/\r?\n/);
|
|
52
|
+
let currentFile = null;
|
|
53
|
+
let metaParts = [];
|
|
54
|
+
let isBinary = false;
|
|
55
|
+
let hunks = [];
|
|
56
|
+
let currentHunk = null;
|
|
57
|
+
const flushHunk = () => {
|
|
58
|
+
if (currentHunk) {
|
|
59
|
+
hunks.push({
|
|
60
|
+
header: currentHunk.header,
|
|
61
|
+
changes: currentHunk.changes,
|
|
62
|
+
bodyKey: currentHunk.changes.join("\n"),
|
|
63
|
+
});
|
|
64
|
+
currentHunk = null;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
const flushFile = () => {
|
|
68
|
+
flushHunk();
|
|
69
|
+
if (currentFile !== null) {
|
|
70
|
+
const raw = rawEntries.get(currentFile);
|
|
71
|
+
let binarySignature = null;
|
|
72
|
+
if (isBinary) {
|
|
73
|
+
binarySignature = raw && /^[0-9a-f]{40,}$/i.test(raw.oldBlobSha) && /^[0-9a-f]{40,}$/i.test(raw.newBlobSha)
|
|
74
|
+
? `${raw.oldMode}:${raw.newMode}:${raw.oldBlobSha}->${raw.newBlobSha}`
|
|
75
|
+
: "unhashed";
|
|
76
|
+
}
|
|
77
|
+
files.set(currentFile, { metaKey: metaParts.join("\n"), isBinary, binarySignature, hunks });
|
|
78
|
+
}
|
|
79
|
+
currentFile = null;
|
|
80
|
+
metaParts = [];
|
|
81
|
+
isBinary = false;
|
|
82
|
+
hunks = [];
|
|
83
|
+
};
|
|
84
|
+
for (const line of lines) {
|
|
85
|
+
if (line.startsWith("diff --git ")) {
|
|
86
|
+
flushFile();
|
|
87
|
+
const m = line.match(/^diff --git a\/(.+?) b\/(.+)$/);
|
|
88
|
+
currentFile = m ? m[2] : line.slice("diff --git ".length);
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (currentFile === null)
|
|
92
|
+
continue;
|
|
93
|
+
if (line.startsWith("@@ ")) {
|
|
94
|
+
flushHunk();
|
|
95
|
+
const end = line.indexOf(" @@", 3);
|
|
96
|
+
currentHunk = {
|
|
97
|
+
header: end >= 0 ? line.slice(0, end + 3) : line,
|
|
98
|
+
changes: [],
|
|
99
|
+
};
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (currentHunk) {
|
|
103
|
+
if (line.startsWith("+") || line.startsWith("-") || line === "\") {
|
|
104
|
+
currentHunk.changes.push(line);
|
|
105
|
+
}
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
if (line.startsWith("Binary files ") || line.startsWith("GIT binary patch")) {
|
|
109
|
+
isBinary = true;
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (line.startsWith("new file mode ")
|
|
113
|
+
|| line.startsWith("deleted file mode ")
|
|
114
|
+
|| line.startsWith("old mode ")
|
|
115
|
+
|| line.startsWith("new mode ")) {
|
|
116
|
+
metaParts.push(line);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
flushFile();
|
|
120
|
+
return files;
|
|
121
|
+
}
|
|
122
|
+
function previewLines(changes, prefix) {
|
|
123
|
+
return changes
|
|
124
|
+
.filter((line) => line.startsWith(prefix))
|
|
125
|
+
.slice(0, 5)
|
|
126
|
+
.map((line) => line.slice(0, 200));
|
|
127
|
+
}
|
|
128
|
+
export function diffParsedFileMaps(oldFiles, newFiles) {
|
|
129
|
+
const allPaths = [...new Set([...oldFiles.keys(), ...newFiles.keys()])].sort();
|
|
130
|
+
const changed = [];
|
|
131
|
+
for (const file of allPaths) {
|
|
132
|
+
const before = oldFiles.get(file);
|
|
133
|
+
const after = newFiles.get(file);
|
|
134
|
+
if (before?.isBinary || after?.isBinary) {
|
|
135
|
+
if (before?.isBinary
|
|
136
|
+
&& after?.isBinary
|
|
137
|
+
&& before.metaKey === after.metaKey
|
|
138
|
+
&& before.binarySignature
|
|
139
|
+
&& before.binarySignature !== "unhashed"
|
|
140
|
+
&& before.binarySignature === after.binarySignature) {
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
changed.push({
|
|
144
|
+
file,
|
|
145
|
+
before_header: before ? `binary (${before.binarySignature ?? (before.metaKey || "none")})` : null,
|
|
146
|
+
after_header: after ? `binary (${after.binarySignature ?? (after.metaKey || "none")})` : null,
|
|
147
|
+
removed_preview: [],
|
|
148
|
+
added_preview: [],
|
|
149
|
+
});
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
if (before
|
|
153
|
+
&& after
|
|
154
|
+
&& before.metaKey === after.metaKey
|
|
155
|
+
&& before.hunks.length === after.hunks.length
|
|
156
|
+
&& before.hunks.every((h, i) => h.bodyKey === after.hunks[i]?.bodyKey)) {
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const oldHunks = before?.hunks ?? [];
|
|
160
|
+
const newHunks = after?.hunks ?? [];
|
|
161
|
+
if (!oldHunks.length && !newHunks.length) {
|
|
162
|
+
changed.push({
|
|
163
|
+
file,
|
|
164
|
+
before_header: before?.metaKey || null,
|
|
165
|
+
after_header: after?.metaKey || null,
|
|
166
|
+
removed_preview: [],
|
|
167
|
+
added_preview: [],
|
|
168
|
+
});
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
// Match identical hunk bodies in order, reporting only hunks whose body or metadata differs.
|
|
172
|
+
const matchedNew = new Set();
|
|
173
|
+
const unmatchedOld = [];
|
|
174
|
+
for (const oldH of oldHunks) {
|
|
175
|
+
const idx = newHunks.findIndex((newH, i) => !matchedNew.has(i) && newH.bodyKey === oldH.bodyKey);
|
|
176
|
+
if (idx >= 0)
|
|
177
|
+
matchedNew.add(idx);
|
|
178
|
+
else
|
|
179
|
+
unmatchedOld.push(oldH);
|
|
180
|
+
}
|
|
181
|
+
const unmatchedNew = newHunks.filter((_, i) => !matchedNew.has(i));
|
|
182
|
+
const pairs = Math.max(unmatchedOld.length, unmatchedNew.length);
|
|
183
|
+
if (pairs === 0) {
|
|
184
|
+
changed.push({
|
|
185
|
+
file,
|
|
186
|
+
before_header: before?.metaKey || null,
|
|
187
|
+
after_header: after?.metaKey || null,
|
|
188
|
+
removed_preview: [],
|
|
189
|
+
added_preview: [],
|
|
190
|
+
});
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
for (let i = 0; i < pairs; i++) {
|
|
194
|
+
const oldH = unmatchedOld[i];
|
|
195
|
+
const newH = unmatchedNew[i];
|
|
196
|
+
changed.push({
|
|
197
|
+
file,
|
|
198
|
+
before_header: oldH?.header ?? null,
|
|
199
|
+
after_header: newH?.header ?? null,
|
|
200
|
+
removed_preview: oldH ? previewLines(oldH.changes, "-") : [],
|
|
201
|
+
added_preview: newH ? previewLines(newH.changes, "+") : [],
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return changed.slice(0, 200);
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Compare the approved change (`oldBase..priorApprovedHead`) against the rebased change
|
|
209
|
+
* (`newBase..HEAD`) using `--unified=0`, ignoring surrounding/resolved context and shifted line numbers.
|
|
210
|
+
*/
|
|
211
|
+
export function compareRebasedPatchAgainstApproved(targetBranch, priorApprovedHead, cwd = process.cwd()) {
|
|
212
|
+
const rebasedHead = resolveCommit("HEAD", cwd);
|
|
213
|
+
if (!priorApprovedHead || !rebasedHead) {
|
|
214
|
+
return {
|
|
215
|
+
unchanged: false,
|
|
216
|
+
ignored_context: true,
|
|
217
|
+
prior_approved_head: priorApprovedHead ?? null,
|
|
218
|
+
rebased_head: rebasedHead,
|
|
219
|
+
old_base_sha: null,
|
|
220
|
+
new_base_sha: null,
|
|
221
|
+
changed_hunks: [],
|
|
222
|
+
summary: "missing prior approved head or HEAD commit",
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
let resolvedPrior = resolveCommit(priorApprovedHead, cwd);
|
|
226
|
+
if (!resolvedPrior) {
|
|
227
|
+
runGit(["fetch", "--no-tags", "--quiet", "origin", priorApprovedHead], cwd);
|
|
228
|
+
resolvedPrior = resolveCommit(priorApprovedHead, cwd);
|
|
229
|
+
}
|
|
230
|
+
const targetRef = resolveTargetRef(targetBranch, cwd);
|
|
231
|
+
if (!resolvedPrior || !targetRef) {
|
|
232
|
+
return {
|
|
233
|
+
unchanged: false,
|
|
234
|
+
ignored_context: true,
|
|
235
|
+
prior_approved_head: priorApprovedHead.toLowerCase(),
|
|
236
|
+
rebased_head: rebasedHead,
|
|
237
|
+
old_base_sha: null,
|
|
238
|
+
new_base_sha: null,
|
|
239
|
+
changed_hunks: [],
|
|
240
|
+
summary: !resolvedPrior
|
|
241
|
+
? `prior approved commit ${priorApprovedHead.slice(0, 9)} is not available locally`
|
|
242
|
+
: `target ref for ${targetBranch} is not available locally`,
|
|
243
|
+
};
|
|
244
|
+
}
|
|
245
|
+
const oldBaseRes = runGit(["merge-base", targetRef, resolvedPrior], cwd);
|
|
246
|
+
const newBaseRes = runGit(["merge-base", targetRef, rebasedHead], cwd);
|
|
247
|
+
if (oldBaseRes.status !== 0 || newBaseRes.status !== 0 || !oldBaseRes.stdout.trim() || !newBaseRes.stdout.trim()) {
|
|
248
|
+
return {
|
|
249
|
+
unchanged: false,
|
|
250
|
+
ignored_context: true,
|
|
251
|
+
prior_approved_head: resolvedPrior,
|
|
252
|
+
rebased_head: rebasedHead,
|
|
253
|
+
old_base_sha: null,
|
|
254
|
+
new_base_sha: null,
|
|
255
|
+
changed_hunks: [],
|
|
256
|
+
summary: `could not determine merge-base against ${targetRef}`,
|
|
257
|
+
};
|
|
258
|
+
}
|
|
259
|
+
const oldBase = oldBaseRes.stdout.trim().toLowerCase();
|
|
260
|
+
const newBase = newBaseRes.stdout.trim().toLowerCase();
|
|
261
|
+
const diffArgs = (base, tip) => [
|
|
262
|
+
"diff", "--unified=0", "--no-color", "--no-ext-diff", "--no-renames", "--src-prefix=a/", "--dst-prefix=b/", base, tip,
|
|
263
|
+
];
|
|
264
|
+
const rawArgs = (base, tip) => [
|
|
265
|
+
"diff", "--raw", "-z", "--abbrev=40", "--full-index", "--no-renames", base, tip,
|
|
266
|
+
];
|
|
267
|
+
const oldDiff = runGit(diffArgs(oldBase, resolvedPrior), cwd);
|
|
268
|
+
const newDiff = runGit(diffArgs(newBase, rebasedHead), cwd);
|
|
269
|
+
const oldRaw = runGit(rawArgs(oldBase, resolvedPrior), cwd);
|
|
270
|
+
const newRaw = runGit(rawArgs(newBase, rebasedHead), cwd);
|
|
271
|
+
if (oldDiff.status !== 0 || newDiff.status !== 0 || oldRaw.status !== 0 || newRaw.status !== 0) {
|
|
272
|
+
return {
|
|
273
|
+
unchanged: false,
|
|
274
|
+
ignored_context: true,
|
|
275
|
+
prior_approved_head: resolvedPrior,
|
|
276
|
+
rebased_head: rebasedHead,
|
|
277
|
+
old_base_sha: oldBase,
|
|
278
|
+
new_base_sha: newBase,
|
|
279
|
+
changed_hunks: [],
|
|
280
|
+
summary: "git diff failed while comparing rebased patch",
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
const oldMap = parseZeroContextDiff(oldDiff.stdout, parseRawDiffEntries(oldRaw.stdout));
|
|
284
|
+
const newMap = parseZeroContextDiff(newDiff.stdout, parseRawDiffEntries(newRaw.stdout));
|
|
285
|
+
const changedHunks = diffParsedFileMaps(oldMap, newMap);
|
|
286
|
+
const unchanged = changedHunks.length === 0;
|
|
287
|
+
const touchedFiles = [...new Set(changedHunks.map((h) => h.file))];
|
|
288
|
+
const summary = unchanged
|
|
289
|
+
? "0 reviewed hunks changed (ignoring context and line offsets)"
|
|
290
|
+
: `${changedHunks.length} reviewed hunk${changedHunks.length === 1 ? "" : "s"} changed across ${touchedFiles.slice(0, 4).join(", ")}${touchedFiles.length > 4 ? `, +${touchedFiles.length - 4} more` : ""}`;
|
|
291
|
+
return {
|
|
292
|
+
unchanged,
|
|
293
|
+
ignored_context: true,
|
|
294
|
+
prior_approved_head: resolvedPrior,
|
|
295
|
+
rebased_head: rebasedHead,
|
|
296
|
+
old_base_sha: oldBase,
|
|
297
|
+
new_base_sha: newBase,
|
|
298
|
+
changed_hunks: changedHunks,
|
|
299
|
+
summary,
|
|
300
|
+
};
|
|
301
|
+
}
|