Skip to content

Commit 497a66e

Browse files
committed
fix(repair): merge concurrent router ledgers
1 parent 3f2bcaa commit 497a66e

6 files changed

Lines changed: 434 additions & 2 deletions

File tree

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
type JsonRecord = Record<string, unknown>;
2+
3+
const MAX_COMMANDS = 1000;
4+
5+
export function mergeCommentRouterLedgers(localText: string, remoteText: string): string {
6+
const local = parseLedger(localText, "local");
7+
const remote = parseLedger(remoteText, "remote");
8+
const byKey = new Map<string, JsonRecord>();
9+
10+
// A router run publishes a bounded snapshot. Unioning by durable command
11+
// identity prevents a later stale snapshot from erasing commands that a
12+
// concurrent run already committed.
13+
for (const entry of [...remote.commands, ...local.commands]) {
14+
const key = ledgerEntryKey(entry);
15+
const previous = byKey.get(key);
16+
if (!previous || compareEntries(previous, entry) < 0) byKey.set(key, entry);
17+
}
18+
19+
const commands = [...byKey.values()]
20+
.sort((left, right) => compareLedgerOrder(left, right))
21+
.slice(-MAX_COMMANDS);
22+
const updatedAt = latestTimestamp(local.updated_at, remote.updated_at);
23+
return `${JSON.stringify({ updated_at: updatedAt, commands }, null, 2)}\n`;
24+
}
25+
26+
function parseLedger(
27+
text: string,
28+
side: string,
29+
): { updated_at: string | null; commands: JsonRecord[] } {
30+
let value: unknown;
31+
try {
32+
value = JSON.parse(text);
33+
} catch (error) {
34+
throw new Error(`failed to parse ${side} comment router ledger`, { cause: error });
35+
}
36+
if (!isRecord(value) || !Array.isArray(value.commands) || !value.commands.every(isRecord)) {
37+
throw new Error(`${side} comment router ledger must contain a commands array`);
38+
}
39+
const updatedAt = typeof value.updated_at === "string" ? value.updated_at : null;
40+
return { updated_at: updatedAt, commands: value.commands };
41+
}
42+
43+
function ledgerEntryKey(entry: JsonRecord): string {
44+
if (
45+
!entry.comment_version_key &&
46+
entry.automation_source === "repair_loop_label_sweep" &&
47+
entry.idempotency_key
48+
) {
49+
return `idempotency:${String(entry.idempotency_key)}`;
50+
}
51+
return String(
52+
entry.comment_version_key ??
53+
`${String(entry.comment_id ?? "unknown")}:${String(entry.comment_updated_at ?? "unknown")}`,
54+
);
55+
}
56+
57+
function compareEntries(left: JsonRecord, right: JsonRecord): number {
58+
const status = statusRank(left.status) - statusRank(right.status);
59+
if (status !== 0) return status;
60+
const processed = timestamp(left.processed_at) - timestamp(right.processed_at);
61+
if (processed !== 0) return processed;
62+
return JSON.stringify(left).localeCompare(JSON.stringify(right));
63+
}
64+
65+
function compareLedgerOrder(left: JsonRecord, right: JsonRecord): number {
66+
const processed = timestamp(left.processed_at) - timestamp(right.processed_at);
67+
if (processed !== 0) return processed;
68+
return ledgerEntryKey(left).localeCompare(ledgerEntryKey(right));
69+
}
70+
71+
function statusRank(value: unknown): number {
72+
if (value === "executed") return 4;
73+
if (value === "skipped") return 3;
74+
if (value === "waiting") return 2;
75+
if (value === "claimed") return 1;
76+
return 0;
77+
}
78+
79+
function latestTimestamp(left: string | null, right: string | null): string | null {
80+
if (!left) return right;
81+
if (!right) return left;
82+
return timestamp(left) >= timestamp(right) ? left : right;
83+
}
84+
85+
function timestamp(value: unknown): number {
86+
const parsed = typeof value === "string" ? Date.parse(value) : Number.NaN;
87+
return Number.isFinite(parsed) ? parsed : 0;
88+
}
89+
90+
function isRecord(value: unknown): value is JsonRecord {
91+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
92+
}

‎src/repair/git-publish.ts‎

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import {
2828
type RecordTupleWinner,
2929
} from "./record-tuple.js";
3030
import { mergeSweepStatusJson } from "./sweep-status-merge.js";
31+
import { mergeCommentRouterLedgers } from "./comment-router-ledger-merge.js";
3132

3233
export type GitRunResult = {
3334
status: number;
@@ -979,16 +980,24 @@ export function pushCommit(options: {
979980
}
980981
const remoteCommit = runGit(["rev-parse", `${remote}/${branch}`], { quiet: true }).trim();
981982
const statusMerges = planSweepStatusMerges({ localCommit, remoteCommit });
983+
const ledgerMerge = planCommentRouterLedgerMerge({ localCommit, remoteCommit });
982984
const rebaseArgs =
983985
rebaseStrategy === "theirs" || rebaseStrategy === "apply-records"
984986
? ["rebase", "-X", "theirs", `${remote}/${branch}`]
985987
: ["rebase", `${remote}/${branch}`];
986988
if (spawnGit(rebaseArgs).status === 0) {
987989
applySweepStatusMerges({ statusMerges, remoteCommit, localCommitMessage });
990+
applyCommentRouterLedgerMerge({ ledgerMerge, remoteCommit, localCommitMessage });
991+
continue;
992+
}
993+
if (resolveCommentRouterLedgerConflict(ledgerMerge)) {
994+
applySweepStatusMerges({ statusMerges, remoteCommit, localCommitMessage });
995+
applyCommentRouterLedgerMerge({ ledgerMerge, remoteCommit, localCommitMessage });
988996
continue;
989997
}
990998
if (rebaseStrategy === "apply-records" && resolveApplyRecordConflicts(statusMerges)) {
991999
applySweepStatusMerges({ statusMerges, remoteCommit, localCommitMessage });
1000+
applyCommentRouterLedgerMerge({ ledgerMerge, remoteCommit, localCommitMessage });
9921001
continue;
9931002
} else {
9941003
runGit(["rebase", "--abort"], { allowFailure: true });
@@ -1430,6 +1439,13 @@ function rebuildPublishCommit(options: {
14301439
includeIndependent: true,
14311440
pathspecs: options.paths,
14321441
});
1442+
const ledgerMerge = planCommentRouterLedgerMerge({
1443+
baseCommit: runGit(["rev-parse", `${options.sourceCommit}^`], { quiet: true }).trim(),
1444+
localCommit: options.sourceCommit,
1445+
remoteCommit,
1446+
includeIndependent: true,
1447+
pathspecs: options.paths,
1448+
});
14331449
runGit(["reset", "--hard", remoteCommit]);
14341450

14351451
for (const path of uniqueNonEmpty(options.paths)) {
@@ -1446,6 +1462,7 @@ function rebuildPublishCommit(options: {
14461462
}
14471463

14481464
applySweepStatusMergeFiles(statusMerges);
1465+
applyCommentRouterLedgerMergeFiles(ledgerMerge ? [ledgerMerge] : []);
14491466
stagePaths(options.paths);
14501467
if (!hasStagedChanges()) {
14511468
console.log("No publish changes after syncing remote");
@@ -1564,6 +1581,90 @@ function readGitPath(commit: string, path: string): string | null {
15641581
return result.status === 0 ? result.stdout : null;
15651582
}
15661583

1584+
type CommentRouterLedgerMerge = { path: string; content: string };
1585+
1586+
function planCommentRouterLedgerMerge(options: {
1587+
baseCommit?: string;
1588+
localCommit: string;
1589+
remoteCommit: string;
1590+
includeIndependent?: boolean;
1591+
pathspecs?: readonly string[];
1592+
}): CommentRouterLedgerMerge | null {
1593+
const path = "results/comment-router.json";
1594+
if (options.pathspecs && !gitPathspecsInclude(options.pathspecs, path)) {
1595+
return null;
1596+
}
1597+
const baseCommit =
1598+
options.baseCommit ??
1599+
runGit(["merge-base", options.localCommit, options.remoteCommit], { quiet: true }).trim();
1600+
if (!baseCommit)
1601+
throw new Error("Refusing comment router ledger merge without a common Git base");
1602+
const base = readGitPath(baseCommit, path);
1603+
const local = readGitPath(options.localCommit, path);
1604+
const remote = readGitPath(options.remoteCommit, path);
1605+
if (!local || !remote) return null;
1606+
const localChanged = local !== base;
1607+
const remoteChanged = remote !== base;
1608+
if (!localChanged || (!options.includeIndependent && !remoteChanged)) return null;
1609+
return { path, content: mergeCommentRouterLedgers(local, remote) };
1610+
}
1611+
1612+
function gitPathspecsInclude(pathspecs: readonly string[], path: string): boolean {
1613+
// Publish accepts Git pathspec syntax, including root and magic forms. Ask
1614+
// Git to evaluate that contract so semantic merges cannot be bypassed by a
1615+
// broader spelling than the literal generated path.
1616+
return runGit(["ls-files", "-z", "--", ...uniqueNonEmpty(pathspecs)], { quiet: true })
1617+
.split("\0")
1618+
.includes(path);
1619+
}
1620+
1621+
function applyCommentRouterLedgerMergeFiles(merges: readonly CommentRouterLedgerMerge[]): void {
1622+
const root = publishRoot() ?? resolve(".");
1623+
for (const merge of merges) {
1624+
const destination = resolve(root, merge.path);
1625+
if (!isPathInsideOrEqual(root, destination)) {
1626+
throw new Error(
1627+
`Refusing to merge comment router ledger outside publish root: ${merge.path}`,
1628+
);
1629+
}
1630+
mkdirSync(dirname(destination), { recursive: true });
1631+
writeFileSync(destination, merge.content, "utf8");
1632+
runGit(["add", "--", merge.path]);
1633+
}
1634+
}
1635+
1636+
function resolveCommentRouterLedgerConflict(ledgerMerge: CommentRouterLedgerMerge | null): boolean {
1637+
if (!ledgerMerge) return false;
1638+
const conflicts = runGit(["diff", "--name-only", "--diff-filter=U"], { allowFailure: true })
1639+
.split(/\r?\n/)
1640+
.map((path) => path.trim())
1641+
.filter(Boolean);
1642+
if (!conflicts.includes(ledgerMerge.path)) return false;
1643+
applyCommentRouterLedgerMergeFiles([ledgerMerge]);
1644+
if (conflicts.length > 1) return false;
1645+
return spawnGit(["-c", "core.editor=true", "rebase", "--continue"]).status === 0;
1646+
}
1647+
1648+
function applyCommentRouterLedgerMerge(options: {
1649+
ledgerMerge: CommentRouterLedgerMerge | null;
1650+
remoteCommit: string;
1651+
localCommitMessage: string;
1652+
}): void {
1653+
if (!options.ledgerMerge) return;
1654+
applyCommentRouterLedgerMergeFiles([options.ledgerMerge]);
1655+
if (!hasStagedChanges()) return;
1656+
if (spawnGit(["diff", "--cached", "--quiet", options.remoteCommit]).status === 0) {
1657+
runGit(["reset", "--hard", options.remoteCommit]);
1658+
return;
1659+
}
1660+
const commitsAhead = Number(
1661+
runGit(["rev-list", "--count", `${options.remoteCommit}..HEAD`], { quiet: true }).trim(),
1662+
);
1663+
if (Number.isInteger(commitsAhead) && commitsAhead > 0)
1664+
runGit(["commit", "--amend", "--no-edit"]);
1665+
else runGit(["commit", "-m", options.localCommitMessage]);
1666+
}
1667+
15671668
function applySweepStatusMergeFiles(statusMerges: readonly SweepStatusMerge[]): void {
15681669
const root = publishRoot() ?? resolve(".");
15691670
for (const statusMerge of statusMerges) {

‎test/e2e/automerge/fake-gh.mjs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,10 @@ function handleApi() {
166166
assertReadToken();
167167
respondJson({ default_branch: state.pr.baseRef });
168168
}
169+
if (endpoint === `repos/${state.repo}/collaborators/fixture-maintainer/permission`) {
170+
assertReadToken();
171+
respondJson({ permission: "maintain", user: { id: 2, login: "fixture-maintainer" } });
172+
}
169173
if (/^repos\/openclaw\/clawsweeper\/actions\/workflows\/[^/]+\/runs\?/.test(endpoint)) {
170174
assertReadToken();
171175
respondJson([]);

‎test/e2e/automerge/run.mjs‎

Lines changed: 91 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export const AUTOMERGE_E2E_SCENARIOS = [
1616
"happy-path",
1717
"pending-checks",
1818
"planning-head-drift",
19+
"resume-intent-persistence",
1920
"verdict-head-drift",
2021
"ci-regression-29623139111",
2122
];
@@ -232,7 +233,41 @@ export function runAutomergeE2E({
232233

233234
const repairedHead = currentRef(targetFixture.remote, targetFixture.headRef);
234235
assertFixturePostRepair(targetFixture, repairedHead);
235-
addExactHeadVerdict(statePath, repairedHead);
236+
if (scenario === "resume-intent-persistence") {
237+
const activeJob = path.join(
238+
runtimeRoot,
239+
"jobs/openclaw/inbox/automerge-openclaw-openclaw-42.md",
240+
);
241+
fs.mkdirSync(path.dirname(activeJob), { recursive: true });
242+
fs.copyFileSync(jobPath, activeJob);
243+
addMaintainerAutomergeCommand(statePath);
244+
runCommentRouter(runtimeRoot, baseEnv, artifacts, "08-comment-router-resume-command");
245+
const resumeReport = readRouterReport(runtimeRoot);
246+
const resume = resumeReport.commands.find(
247+
(command) => command.intent === "automerge" && command.trusted_bot === false,
248+
);
249+
assert.equal(
250+
resume?.status,
251+
"executed",
252+
"maintainer replay must record active resume intent",
253+
);
254+
const persistedLedger = JSON.parse(
255+
fs.readFileSync(path.join(runtimeRoot, "results", "comment-router.json"), "utf8"),
256+
);
257+
assert.equal(
258+
persistedLedger.commands.some(
259+
(command) =>
260+
command.intent === "automerge" &&
261+
command.status === "executed" &&
262+
command.author === "fixture-maintainer",
263+
),
264+
true,
265+
"a later router invocation must be able to hydrate the resume command",
266+
);
267+
addCanonicalNeedsHumanVerdict(statePath, repairedHead);
268+
} else {
269+
addExactHeadVerdict(statePath, repairedHead);
270+
}
236271
if (scenario === "verdict-head-drift") {
237272
const driftedHead = advanceRemoteContributorHead(root, targetFixture, "verdict head drift");
238273
runCommentRouter(runtimeRoot, baseEnv, artifacts, "08-comment-router-stale-verdict");
@@ -313,8 +348,11 @@ export function runAutomergeE2E({
313348
assert.equal(fixReport.actions.at(-1)?.status, "pushed");
314349
assert.equal(repairPostFlight.actions.at(-1)?.status, "blocked");
315350
assert.equal(repairPostFlight.actions.at(-1)?.reason, "job does not allow merge");
351+
const mergedCommand = routerReport.commands.find((command) =>
352+
command.actions.some((action) => action.action === "merge"),
353+
);
316354
assert.equal(
317-
routerReport.commands.at(-1)?.actions.find((action) => action.action === "merge")?.status,
355+
mergedCommand?.actions.find((action) => action.action === "merge")?.status,
318356
"executed",
319357
);
320358
assert.equal(idempotentRouterReport.actionable, 0);
@@ -405,6 +443,57 @@ function addExactHeadVerdict(statePath, headSha) {
405443
writeJson(statePath, state);
406444
}
407445

446+
function addMaintainerAutomergeCommand(statePath) {
447+
const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
448+
addFixtureComment(statePath, {
449+
author: "clawsweeper[bot]",
450+
authorId: 1,
451+
body: `Automerge is already active.\n<!-- clawsweeper-command-status:${state.pr.number}:automerge:active -->`,
452+
});
453+
addFixtureComment(statePath, {
454+
author: "fixture-maintainer",
455+
authorId: 2,
456+
body: "@clawsweeper automerge\n\nResume the exact current head after the repair fix landed.",
457+
});
458+
}
459+
460+
function addCanonicalNeedsHumanVerdict(statePath, headSha) {
461+
const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
462+
const now = new Date(Date.now() + 1000).toISOString();
463+
addFixtureComment(statePath, {
464+
author: "clawsweeper[bot]",
465+
authorId: 1,
466+
body: [
467+
"ClawSweeper needs maintainer judgment.",
468+
"",
469+
"**Next step before merge**",
470+
"The PR is an active automerge candidate with no code finding, but missing real behavior proof needs maintainer handling.",
471+
"",
472+
`<!-- clawsweeper-verdict:needs-human item=${state.pr.number} sha=${headSha} reviewed_at=${now} -->`,
473+
].join("\n"),
474+
timestamp: now,
475+
});
476+
}
477+
478+
function addFixtureComment(
479+
statePath,
480+
{ author, authorId, body, timestamp = new Date().toISOString() },
481+
) {
482+
const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
483+
const id = state.nextCommentId++;
484+
state.comments.push({
485+
id,
486+
body,
487+
issue_url: `https://api.github.com/repos/${state.repo}/issues/${state.pr.number}`,
488+
html_url: `https://github.com/${state.repo}/pull/${state.pr.number}#issuecomment-${id}`,
489+
user: { id: authorId, login: author },
490+
author_association: "MEMBER",
491+
created_at: timestamp,
492+
updated_at: timestamp,
493+
});
494+
writeJson(statePath, state);
495+
}
496+
408497
function runPlanningHeadDriftScenario({
409498
artifacts,
410499
baseEnv,

0 commit comments

Comments
 (0)