From 44ca5d41ae19fcb8355be88e4ec22489101f625e Mon Sep 17 00:00:00 2001
From: aiongg <67543387+aiongg@users.noreply.github.com>
Date: Thu, 5 Nov 2026 06:55:50 +0000
Subject: [PATCH] Edit the earlier conflict note instead of posting a new one
when it is the newest comment
---
docs/pipeline.md | 2 +-
src/dash/api/admin.ts | 2 +-
src/dash/api/github-detail.ts | 2 +-
src/fixup/conflict.ts | 40 ++++++++++++++++++++++++++++++---
src/fixup/template.ts | 24 +++++++++++++++++---
src/github/actions.ts | 1 +
test/conflict-note-edit.test.ts | 29 ++++++++++++++++++++++++
7 files changed, 91 insertions(+), 9 deletions(-)
create mode 100644 test/conflict-note-edit.test.ts
diff --git a/docs/pipeline.md b/docs/pipeline.md
index 4deab0694..cde17e022 100644
--- a/docs/pipeline.md
+++ b/docs/pipeline.md
@@ -243,7 +243,7 @@ For a take-fix review, Sonnet applies the listed small fixes to the contributor'
- **Assignment.** A PR is assigned to the pipeline account when the stage starts work on it (after the cheap checks pass, before the model call; a conflict merge before the base merge), only when nobody is assigned. See Merge queue, "Assignment" for when it is released. No "in progress" comment is posted: the comment after the push covers it.
- **Live check.** The PR is read from GitHub before the model calls and again after the Opus check. If it is no longer open, is a draft or its head moved, nothing is assigned or pushed and the PR is tried again on a later run.
- **Push.** One commit "Apply review fixes", pushed with a lease so a branch that moved is left alone, plus one comment from a fixed template.
-- **Conflicts.** An open, non-draft PR whose final review at the current head is take or take-fix and that GitHub reports as conflicting gets the default branch merged into its branch (same scope, push approval and pushable rule as above; the PR need not be take-fix). Nothing is checked out. `git merge-tree` computes the merge. A clean merge becomes a commit with two parents (the PR head first), "Merge into ", pushed with a lease; there is no rebase and no force-push. With conflicts, Sonnet (sandboxed, read-only tools) gets each conflicted file as numbered conflict sections, not whole: for each section its id and start line, about 30 lines before and after (shared out where sections are close), the pull request's side and the default branch's side (each with its newlines, so no lines and one blank line differ; the start line is the one in the PR head's file), plus the file's path and line count, quoted as untrusted with the PR title, description and review summary. It returns one resolution text per section id. Our code accepts the reply only when every section is answered exactly once and no other id appears, with no conflict markers. It splices the answers into the merge-tree file, so text outside the sections cannot change. Each answer may use lines from the two sides plus at most 3 others, none of which adds an import, declaration, unsafe code or a dependency; files with CRLF line endings or invalid UTF-8 are refused. Merge-tree and the file reads use the plain two-sided marker style, ignoring user and system git config. Opus then checks the resolution: it gets each section (about 10 lines of context, both sides, our resolution) and the PR's own diff, not the diff of the merge, which also holds everything the default branch changed. A reject pushes nothing and counts as a try; so does a resolution so long that the check's input goes over its limit. A resolution with Rust files is stored and linted before it is pushed (one build task: rustfmt on those files, clippy on the merged tree); the formatter's whitespace changes are folded in by the harness. Clippy findings on lines the resolution changed go back to Sonnet with the earlier resolution's diff, and the new resolution gets the same validation, Opus check and lint; the stored row keeps the state `linting` between rounds, and the next collect picks the re-lint up. After 2 lint rounds with findings left, the try is recorded as rejected with the first finding as its reason. Afterwards one comment from a fixed template ("Merged into this branch to resolve the conflict."). The PR is assigned to the pipeline account only once the checks that need no model pass (conflicted paths, markers, line endings, section sizes). A refusal that the same head always gets again (those checks, the conflict sections over the size limit of 120,000 characters shown to Sonnet or 40,000 for one section, or the conflict sections over the check's 80,000 character limit, measured as the check receives them with the longer side of each section standing in for its resolution; that bound is computed before the claim) is recorded once as held for that head: no second try, and no assignment when it was found before the model call. A model-dependent failure (Sonnet's answer fails our validation, Opus rejects) counts as a try, at most 2 per head; tries count against the daily limit. A PR we can't push to gets, in a repo with comment approval, one comment per head asking the contributor to merge or rebase ; without the approval it is held with no write. The new head goes through Review (Opus reads the PR's full diff for a merge commit of ours, not a delta that would include the base branch's changes) and Verify like any new head.
+- **Conflicts.** An open, non-draft PR whose final review at the current head is take or take-fix and that GitHub reports as conflicting gets the default branch merged into its branch (same scope, push approval and pushable rule as above; the PR need not be take-fix). Nothing is checked out. `git merge-tree` computes the merge. A clean merge becomes a commit with two parents (the PR head first), "Merge into ", pushed with a lease; there is no rebase and no force-push. With conflicts, Sonnet (sandboxed, read-only tools) gets each conflicted file as numbered conflict sections, not whole: for each section its id and start line, about 30 lines before and after (shared out where sections are close), the pull request's side and the default branch's side (each with its newlines, so no lines and one blank line differ; the start line is the one in the PR head's file), plus the file's path and line count, quoted as untrusted with the PR title, description and review summary. It returns one resolution text per section id. Our code accepts the reply only when every section is answered exactly once and no other id appears, with no conflict markers. It splices the answers into the merge-tree file, so text outside the sections cannot change. Each answer may use lines from the two sides plus at most 3 others, none of which adds an import, declaration, unsafe code or a dependency; files with CRLF line endings or invalid UTF-8 are refused. Merge-tree and the file reads use the plain two-sided marker style, ignoring user and system git config. Opus then checks the resolution: it gets each section (about 10 lines of context, both sides, our resolution) and the PR's own diff, not the diff of the merge, which also holds everything the default branch changed. A reject pushes nothing and counts as a try; so does a resolution so long that the check's input goes over its limit. A resolution with Rust files is stored and linted before it is pushed (one build task: rustfmt on those files, clippy on the merged tree); the formatter's whitespace changes are folded in by the harness. Clippy findings on lines the resolution changed go back to Sonnet with the earlier resolution's diff, and the new resolution gets the same validation, Opus check and lint; the stored row keeps the state `linting` between rounds, and the next collect picks the re-lint up. After 2 lint rounds with findings left, the try is recorded as rejected with the first finding as its reason. Afterwards one comment from a fixed template ("Merged into this branch to resolve the conflict."). When the newest comment on the PR, read live, is our own earlier conflict note and no comment or review came after it, that comment is edited instead ("Merged into this branch to resolve conflicts (3 times, last at 04:47 UTC)."), with the note line of the latest merge; if the read fails, a new comment is posted. The PR is assigned to the pipeline account only once the checks that need no model pass (conflicted paths, markers, line endings, section sizes). A refusal that the same head always gets again (those checks, the conflict sections over the size limit of 120,000 characters shown to Sonnet or 40,000 for one section, or the conflict sections over the check's 80,000 character limit, measured as the check receives them with the longer side of each section standing in for its resolution; that bound is computed before the claim) is recorded once as held for that head: no second try, and no assignment when it was found before the model call. A model-dependent failure (Sonnet's answer fails our validation, Opus rejects) counts as a try, at most 2 per head; tries count against the daily limit. A PR we can't push to gets, in a repo with comment approval, one comment per head asking the contributor to merge or rebase ; without the approval it is held with no write. The new head goes through Review (Opus reads the PR's full diff for a merge commit of ours, not a delta that would include the base branch's changes) and Verify like any new head.
- **Live read.** What the live read shows (conflicting, closed, draft, head moved) is written to the checks table, so a PR that is no longer a candidate is not selected again until the checks sync changes it. A PR that reads as conflicting goes to the conflict merge.
- **Hand-off.** The new head is reviewed again. At most 2 tries per PR. Daily limit 20 PRs, pushes and comments together.
diff --git a/src/dash/api/admin.ts b/src/dash/api/admin.ts
index 76860e114..fa2e5cd91 100644
--- a/src/dash/api/admin.ts
+++ b/src/dash/api/admin.ts
@@ -41,7 +41,7 @@ export const AUDIT_ACTIONS = [
"job-request", "job-cancel", "pipeline-switch", "stage-limit", "limit-reset", "pilot-set", "pilot-clear", "repo-pipeline", "review-post", "review-edit", "batch-again", "reopen", "backlog-bulk", "withdraw",
"single-merge-max", "label-create", "batch-pr-close", "fork-create", "assign", "unassign", "merge", "batch-push", "batch-pr", "shared-repos",
"fasttrack-add", "fasttrack-remove", "merge-hold", "merge-release", "batch-remove", "batch-stop", "areas-edit", "areas-accept", "ci-approve", "ci-revoke", "ci-run-approve", "ci-rerun", "cifix-push", "cifix-comment", "cifix-check", "postmerge-file", "postmerge-file-one", "postmerge-review", "postmerge-backfill",
- "act-group-applied", "answer-used", "batch-end-too-late", "batch-hold", "batch-merged-after-end", "batch-start", "carry-queued", "classify-run", "compare-again", "conflict-comment", "conflict-push", "conversation-card", "conversation-card-dismiss", "conversation-card-edit", "decision-withdrawn", "duplicate-answer", "duplicate-group-ended", "duplicate-member-released", "duplicate-superseded", "env-change", "env-create", "env-rotate-key", "fix-again", "fixissue-check", "fixissue-claim", "fixissue-unclaim", "fixup-check", "item-gone", "merge-answer-superseded", "merge-held-for-discussion", "merge-question-withdrawn", "merge-refused", "preapproval", "operator-fixup", "review-again", "task-cancel", "verify-again", "workspace-exclude",
+ "act-group-applied", "answer-used", "batch-end-too-late", "batch-hold", "batch-merged-after-end", "batch-start", "carry-queued", "classify-run", "compare-again", "conflict-comment", "conflict-comment-edit", "conflict-push", "conversation-card", "conversation-card-dismiss", "conversation-card-edit", "decision-withdrawn", "duplicate-answer", "duplicate-group-ended", "duplicate-member-released", "duplicate-superseded", "env-change", "env-create", "env-rotate-key", "fix-again", "fixissue-check", "fixissue-claim", "fixissue-unclaim", "fixup-check", "item-gone", "merge-answer-superseded", "merge-held-for-discussion", "merge-question-withdrawn", "merge-refused", "preapproval", "operator-fixup", "review-again", "task-cancel", "verify-again", "workspace-exclude",
];
const isOperator = (req: Req): boolean => req.user.role === "operator";
diff --git a/src/dash/api/github-detail.ts b/src/dash/api/github-detail.ts
index cee6b50d0..88ecaca0d 100644
--- a/src/dash/api/github-detail.ts
+++ b/src/dash/api/github-detail.ts
@@ -7,7 +7,7 @@ export function detailOf(action: string, d: Record): string {
switch (action) {
case "labels-apply": return list;
case "label-create": return String(d.name ?? "");
- case "act-comment": case "fixup-comment": case "fixup-comment-edit": case "fixissue-comment": return clip(String(d.text ?? ""), 160);
+ case "act-comment": case "fixup-comment": case "fixup-comment-edit": case "conflict-comment-edit": case "fixissue-comment": return clip(String(d.text ?? ""), 160);
case "batch-pr-close": return clip(String(d.text ?? ""), 160);
case "merge": return [d.method, d.commit ? short(d.commit) : "", d.batch ? `in ${d.batch}` : ""].filter(Boolean).join(" ");
case "assign": case "unassign": return String(d.assignee ?? "");
diff --git a/src/fixup/conflict.ts b/src/fixup/conflict.ts
index cca228e92..599f8702a 100644
--- a/src/fixup/conflict.ts
+++ b/src/fixup/conflict.ts
@@ -9,7 +9,8 @@ import { REPO_PATH } from "../sandbox/command.ts";
import { audit } from "../dash/audit.ts";
import type { By } from "../core/gates.ts";
import { guard, liveOf } from "../core/guard.ts";
-import { ghAskComment, ghComment, pushBranch, type Writer } from "../github/write.ts";
+import type { Note } from "../github/note.ts";
+import { ghAskComment, ghComment, ghEditComment, pushBranch, type Writer } from "../github/write.ts";
import { LINT_MAX_ROUNDS } from "../core/rules.ts";
import { foldFormat, queueLint, readLint } from "../prepush/index.ts";
import { cachedDiff } from "../review/diff.ts";
@@ -22,7 +23,7 @@ import { dropSessions, sessionAsk, storeSessions, type Kept, type SessionLedger
import { noteLive, type FixupDeps, type FixupSummary, type PrNode, type Who } from "./index.ts";
import { answerText, conflictView, endNewline, hasMarkers, locateInHead, parseResolution, resolvablePath, spliceSections, type ConflictFile, type ConflictSection } from "./patch.ts";
import { BASE_ORG, longLivedOf, pushable } from "./pushable.ts";
-import { conflictAskText, conflictCommentText, mergeMessage } from "./template.ts";
+import { conflictAskText, conflictCommentCount, conflictCommentText, mergeMessage } from "./template.ts";
const CHECK = CLAUDE_PROMPTS["fixup.check"];
const CONFLICT = CLAUDE_PROMPTS["fixup.conflict"];
@@ -88,6 +89,35 @@ async function live(db: DatabaseSync, x: ConflictRun, c: ConflictCandidate): Pro
return pr;
}
+const NEWEST_QUERY = `query($name: String!, $n: Int!) {
+ repository(name: $name, owner: "${BASE_ORG}") { pullRequest(number: $n) {
+ comments(last: 1) { nodes { databaseId body createdAt author { login } } }
+ reviews(last: 1) { nodes { submittedAt } }
+ } }
+}`;
+
+/**
+ * Our own conflict note when it is the newest comment on the PR and no review came after it, read live in one call
+ * (the number of merges it reports and its comment id); null otherwise, and when the read fails.
+ */
+export async function newestConflictNote(x: ConflictRun, c: ConflictCandidate): Promise<{ id: string; count: number } | null> {
+ try {
+ const r = await x.d.querier.query(NEWEST_QUERY, { name: x.repo, n: c.number }) as { repository?: { pullRequest?: {
+ comments?: { nodes?: { databaseId: number; body: string; createdAt: string; author: { login: string } | null }[] };
+ reviews?: { nodes?: { submittedAt: string | null }[] };
+ } | null } };
+ const pr = r.repository?.pullRequest;
+ const last = pr?.comments?.nodes?.[0];
+ if (!pr || !last || last.author?.login !== (await x.who()).login) return null;
+ const count = conflictCommentCount(last.body, c.base);
+ if (count === null) return null;
+ const posted = last.createdAt;
+ const review = pr.reviews?.nodes?.[0]?.submittedAt;
+ if (review && (!posted || review > posted)) return null;
+ return { id: String(last.databaseId), count };
+ } catch { return null; }
+}
+
/** One comment per head asking the contributor to bring the base branch in, for a branch we can't push to. */
export async function askConflict(db: DatabaseSync, x: ConflictRun, c: ConflictCandidate): Promise {
const ref = refOf(c);
@@ -288,7 +318,11 @@ export async function mergeConflict(db: DatabaseSync, x: ConflictRun, c: Conflic
record(db, x.at(), c, "merged", null, files, baseSha, commit);
x.summary.pushed.push(ref);
x.log(` ${ref}: merged ${c.base} into the branch: ${short(commit)} on ${short(head)}${files.length ? `, resolved ${files.join(", ")}` : ""}`);
- const cm = await ghComment(x.gw, g, x.d.exec, "conflict-comment", { repo: x.repo, number: c.number, pr: true }, files.length ? { by: "model", kind: "comment", model: CONFLICT.models[0] } : { by: "fixed" }, conflictCommentText(c.base), { run: x.runId });
+ const note: Note = files.length ? { by: "model", kind: "comment", model: CONFLICT.models[0] } : { by: "fixed" };
+ const prev = await newestConflictNote(x, c);
+ const cm = prev
+ ? await ghEditComment(x.gw, g, x.d.exec, "conflict-comment-edit", { repo: x.repo, number: c.number, commentId: prev.id }, note, conflictCommentText(c.base, prev.count + 1, x.at()), { run: x.runId })
+ : await ghComment(x.gw, g, x.d.exec, "conflict-comment", { repo: x.repo, number: c.number, pr: true }, note, conflictCommentText(c.base), { run: x.runId });
if (cm.code !== 0) x.log(` ${ref}: comment failed: ${oneLine(cm.stderr)}`);
} catch (e) {
fail("failed", oneLine(String((e as Error).message ?? e)));
diff --git a/src/fixup/template.ts b/src/fixup/template.ts
index 3ead403db..5727570e3 100644
--- a/src/fixup/template.ts
+++ b/src/fixup/template.ts
@@ -59,10 +59,28 @@ export function carryAskText(sources: { number: number; points: string[] }[]): s
return CARRY_ASK_TEMPLATE.replace("{{points}}", lines.join("\n"));
}
-/** The one comment posted on the PR after the default branch was merged into it; `{{base}}` is the branch name. */
+/** The comment posted on the PR after the default branch was merged into it; `{{base}}` is the branch name. */
export const CONFLICT_COMMENT_TEMPLATE = "Merged {{base}} into this branch to resolve the conflict.";
-export function conflictCommentText(base: string): string {
- return CONFLICT_COMMENT_TEMPLATE.replace("{{base}}", base);
+/** The same comment edited after further merges; `{{count}}` is the number of merges, `{{time}}` the time of the last one (HH:MM). */
+export const CONFLICT_COMMENT_REPEAT_TEMPLATE = "Merged {{base}} into this branch to resolve conflicts ({{count}} times, last at {{time}} UTC).";
+/** `count` merges so far, the last at ISO time `at`. One merge gives the plain text. */
+export function conflictCommentText(base: string, count = 1, at = ""): string {
+ if (count < 2) return CONFLICT_COMMENT_TEMPLATE.replace("{{base}}", base);
+ return CONFLICT_COMMENT_REPEAT_TEMPLATE.replace("{{base}}", base).replace("{{count}}", String(count)).replace("{{time}}", at.slice(11, 16));
+}
+
+/**
+ * The number of merges a comment body reports, or null when the body (after its note line) is not our conflict comment for `base`.
+ * A repeat text whose count can't be read counts as 2.
+ */
+export function conflictCommentCount(body: string, base: string): number | null {
+ const text = body.replace(/^_[^\n]*_\n\n/, "");
+ if (text === conflictCommentText(base)) return 1;
+ const esc = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const m = new RegExp(`^${esc(CONFLICT_COMMENT_REPEAT_TEMPLATE).replace(esc("{{base}}"), esc(base)).replace(esc("{{count}}"), "(\\d+)").replace(esc("{{time}}"), ".*")}$`).exec(text);
+ if (!m) return null;
+ const n = Number(m[1]);
+ return Number.isInteger(n) && n >= 2 ? n : 2;
}
/** The one comment per head on a conflicted PR we can't resolve ourselves. */
diff --git a/src/github/actions.ts b/src/github/actions.ts
index 4fe38c479..8d54f1d05 100644
--- a/src/github/actions.ts
+++ b/src/github/actions.ts
@@ -21,6 +21,7 @@ export const GITHUB_ACTIONS: Record = {
"fixup-push": "Pushed",
"conflict-push": "Pushed",
"conflict-comment": "Commented",
+ "conflict-comment-edit": "Edited comment",
"fixissue-claim": "Commented",
"fixissue-unclaim": "Deleted comment",
"batch-push": "Pushed",
diff --git a/test/conflict-note-edit.test.ts b/test/conflict-note-edit.test.ts
new file mode 100644
index 000000000..23e4c0c98
--- /dev/null
+++ b/test/conflict-note-edit.test.ts
@@ -0,0 +1,29 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { newestConflictNote, type ConflictRun } from "../src/fixup/conflict.ts";
+import type { ConflictCandidate } from "../src/fixup/conflict-state.ts";
+import { withNote } from "../src/github/note.ts";
+import { conflictCommentCount, conflictCommentText } from "../src/fixup/template.ts";
+
+const c = { repo: "app", number: 7, base: "main" } as ConflictCandidate;
+const run = (pr: object | Error): ConflictRun => ({
+ repo: "app",
+ who: async () => ({ login: "bot", nodeId: "U", email: "e" }),
+ d: { querier: { async query() { if (pr instanceof Error) throw pr; return { repository: { pullRequest: pr } }; } } },
+}) as unknown as ConflictRun;
+const ours = (text: string, login = "bot") => ({ databaseId: 55, body: withNote({ by: "fixed" }, text), createdAt: "2026-01-01T00:00:00Z", author: { login } });
+
+test("the conflict note is edited only when ours is the newest comment and no review followed", async () => {
+ const first = conflictCommentText("main");
+ assert.deepEqual(await newestConflictNote(run({ comments: { nodes: [ours(first)] }, reviews: { nodes: [] } }), c), { id: "55", count: 1 });
+ const third = conflictCommentText("main", 3, "2026-01-01T04:47:00Z");
+ assert.match(third, /\(3 times, last at 04:47 UTC\)/);
+ assert.equal(conflictCommentCount(withNote({ by: "fixed" }, third), "main"), 3);
+ assert.equal(conflictCommentCount(withNote({ by: "fixed" }, "Merged main into this branch to resolve conflicts (many times, last at x UTC)."), "main"), null);
+ assert.equal((await newestConflictNote(run({ comments: { nodes: [ours(third)] }, reviews: { nodes: [] } }), c))?.count, 3);
+ // A review after it, another author, other text, or a failed read: post a new note.
+ assert.equal(await newestConflictNote(run({ comments: { nodes: [ours(first)] }, reviews: { nodes: [{ submittedAt: "2026-01-02T00:00:00Z" }] } }), c), null);
+ assert.equal(await newestConflictNote(run({ comments: { nodes: [ours(first, "someone")] }, reviews: { nodes: [] } }), c), null);
+ assert.equal(await newestConflictNote(run({ comments: { nodes: [ours("Looks good")] }, reviews: { nodes: [] } }), c), null);
+ assert.equal(await newestConflictNote(run(new Error("down")), c), null);
+});