From 16da4f27010ea0ec1b89ade4df19cc735d3d9027 Mon Sep 17 00:00:00 2001 From: aiongg <67543387+aiongg@users.noreply.github.com> Date: Tue, 3 Nov 2026 23:29:52 +0000 Subject: [PATCH] Harden post-merge review: record filing before the create call, never re-file for a PR with a follow-up, scope diffs to the PR, dedupe, clean public text --- docs/pipeline.md | 20 +-- src/dash/api/admin.ts | 2 +- src/dash/api/postmerge.ts | 30 ++-- src/github/write.ts | 27 +++- src/pilot.ts | 6 +- src/postmerge/file.ts | 168 ++++++++++++++++---- src/postmerge/index.ts | 20 ++- src/postmerge/parse.ts | 11 +- src/postmerge/review.ts | 60 ++++--- src/postmerge/select.ts | 90 +++++++++-- src/postmerge/template.ts | 36 ++++- src/prompts/index.ts | 5 +- src/review/diff.ts | 29 +++- src/runner/steps.ts | 4 +- src/schema.sql | 9 +- src/stages/registry.ts | 3 +- test/postmerge.test.ts | 242 ++++++++++++++++++++++++++++- web/src/api/mock/verifyFixtures.ts | 1 + web/src/api/types.ts | 18 ++- web/src/modules/item/PrWork.tsx | 17 +- 20 files changed, 675 insertions(+), 123 deletions(-) diff --git a/docs/pipeline.md b/docs/pipeline.md index 7d78745d9..7e0ae2a50 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -332,14 +332,15 @@ Makes the GitHub comments and closes that follow an operator's answer. No model. ## Post-merge review -A second Opus review of every PR the pipeline merged, to catch what the first review and the merge let through (for example a requested fix that a conflict merge dropped). Only merges recorded after the stage started, or since `autocraft postmerge backfill --since `, are reviewed, and only for PRs in the pilot. Each merged PR is reviewed once, oldest merge first; there is no daily limit on the model step. +A second Opus review of every PR the pipeline merged, to catch what the first review and the merge let through (for example a requested fix that a conflict merge dropped). Only merges recorded after the stage started, or since `autocraft postmerge backfill --since `, are reviewed, and only for PRs in the pilot. Each merged PR is reviewed once, oldest merge first; there is no daily limit on the model step. A backfill more than 14 days back needs `--yes`. -- **Input.** The PR's title, body and author; the merged diff (the merge commit against its first parent, kept to the files the PR changed, code files only, the same size cap as Review); the commits the pipeline added (conflict merges, fix-ups, parts carried over from duplicates); the PR's earlier Opus reviews; and the open issues and PRs that mention the PR number or one of its files, by number and title, to avoid duplicates. The call reads a checkout at the merge commit with the same read-only tools and reference mount as Review, and its reply goes through the same lint and fix turn. -- **Findings.** Each finding is a `defect` (wrong behaviour, a crash, data loss, a correctness bug) or `minor` (style, wording, commit titles, stale comments, test-only gaps), with a title, a public body, file and line, the number of an open item that already covers it, and two internal notes: the stage that should have caught it and why it did not. An empty list is a valid review. A reply that is not valid is asked again once, then stored as an error and tried again after an hour; a diff over the size cap is held. -- **Filing.** The `postmerge-file` step opens one GitHub issue for each defect that no open item covers, in repos approved for comments: title is the finding's title, the body is `Follow-up to #.` and the finding's text under the same AI-generated disclaimer line a review carries. Daily limit 20 issues; defects over the limit are filed by later runs. A defect is never filed twice, also when the PR is reviewed again. Minor findings and duplicates are stored and shown, never filed. -- **After filing.** The issue is mirrored, classified and fixed like any other issue. It counts as a pilot item when the PR it follows up is one. -- **Item page.** A merged PR shows its findings with severity, text, file and line, and the issue filed for each defect. Operators and maintainers also see which stage missed the finding and why. -- **Commands.** `autocraft postmerge review # [--again]` reviews one PR now; `autocraft postmerge backfill --since ` makes the step review the pipeline's merges since that date. Both are logged in the audit log. +- **Input.** The PR's title, body and author; the merged diff (the merge commit against its first parent, kept to the files the PR changed, code files only, the same size cap as Review; for a PR merged through an integration batch, the PR's own diff at the merged head, which includes the pipeline's pushes to the PR branch; when the PR's own diff cannot be read there is no diff and the review is tried again later); the commits the pipeline added (conflict merges, fix-ups, parts carried over from duplicates); the PR's earlier Opus reviews; the open issues and PRs, and those closed in the last 30 days, that mention the PR number or one of its files, by number, state and title, to avoid duplicates; and the follow-up issues earlier reviews of the PR filed (`filed_before`), with their state. The call reads a checkout at the merge commit with the same read-only tools and reference mount as Review, and its reply goes through the same lint and fix turn. +- **Findings.** Each finding is a `defect` (wrong behaviour, a crash, data loss, a correctness bug) or `minor` (style, wording, commit titles, stale comments, test-only gaps), with a title, a public body, file and line, the number of an open item that already covers it, and two internal notes: the stage that should have caught it and why it did not. An empty list is a valid review. A reply that is not valid is asked again once, then stored as an error and tried again after an hour, three times at most, after which the review is held; a diff over the size cap is held. +- **Filing.** The `postmerge-file` step opens one GitHub issue for each defect that no open item covers, in repos approved for comments: the title is the finding's title, the body is `Follow-up to #.` and the finding's text under the same AI-generated disclaimer line a review carries, then the `Location:` line when the finding names a file. Daily limit 20 issues; defects over the limit are filed by later runs, and every attempt counts against it. Public text outside code is cleaned: URLs go, Markdown links keep their text, issue references (`owner/repo#n`, `#n`) read "issue n", and mentions lose their `@`; code spans and blocks stay as written. A title or body that names the product or the pipeline's GitHub account is stored and never filed. +- **Safety.** Before the create call the step writes a follow-up row in state `filing`; after it, the row becomes `filed` with the issue number in a separate step. A row left in `filing` (crash, lost response, failed record) is never retried: the issue may exist, the item page says "Outcome unknown, check GitHub", and the run stops. A refusal from GitHub that cannot have created an issue (issues disabled, no permission) is stored as `failed` and tried again after 1 hour, then after 6 hours, three attempts at most. A defect whose cited file is no longer on the default branch is skipped as stale. Within one run, defects in the same file, within 20 lines and with a similar title are filed once (the first); the others are marked duplicates of it. A PR that already has a filed follow-up from an earlier review never files automatically again, and neither does a PR that itself fixes a follow-up issue: their findings are stored and shown as not filed. +- **After filing.** The issue is mirrored, classified and fixed like any other issue. It counts as a pilot item when the PR it follows up is one, and so does the Fix PR opened for it. +- **Item page.** A merged PR shows its findings with severity, text, file and line, and the issue filed for each defect, the duplicate it was marked as, why it was not filed, and the follow-ups of earlier reviews. Operators and maintainers also see which stage missed the finding and why. +- **Commands.** `autocraft postmerge review # [--again]` reviews one PR now (refused while the runner has a postmerge job running for the repo); `autocraft postmerge file # ` files one defect of the PR's latest review, counted from 0, whatever holds the PR's automatic filing back; `autocraft postmerge backfill --since [--yes]` makes the step review the pipeline's merges since that date. All are logged in the audit log. ## Conversations @@ -507,7 +508,8 @@ Automated work waits only for the reasons below. A stage that is not running sho | Batch PR runs awaiting approval | The batch PR comes from the pipeline account's fork, so GitHub may hold its workflow runs (`action_required`) until a maintainer approves them; the ci-approve step approves them when the repo's CI approval is on and every member was reviewed at its batched head | Until the runs are approved and finish (read again with each checks job) | Batch note "batch PR runs wait for a maintainer's approval" | | Batch push retry | Pushing the batch branch or opening its PR failed | 1, 2, 4, 8 minutes (at most 30); the batch fails after 5 failures and its PRs return to the queue | Batch state `checking` with the error | | Changes requested | A reviewer with write access has a formal review that blocks the merge | Until that reviewer approves or a maintainer dismisses the review; no timer. Blocked PRs are read again every merge run | Queue state `changes-requested` with the reviewer in its note | -| Failed post-merge review | The model gave no valid reply twice | 1 hour | Post-merge review on the item page: no review yet | +| Failed post-merge review | The model gave no valid reply twice | 1 hour, three tries in all | Post-merge review on the item page: no review yet | +| Failed post-merge filing | GitHub refused to create the issue | 1 hour, then 6 hours; stops after three attempts | Post-merge review on the item page: not filed, with the attempts | | Failed job | Retry a real failure without hammering | 1, 2, 4, 8, 16, then 30 minutes; ends on a release, and after a single failure also on a changed input | "failed N times in a row; retry at HH:MM UTC" | | Daily limit | Cost control | Until 00:00 UTC | "daily limit of N items reached; resumes at 00:00 UTC" | | Jev unavailable | Jev is switched off (`autocraft accounts jev off`), the `jev` command is missing, or its account fails: out of credit, or a missing or rejected key (status 401, 402, 403, or a message about credit, billing, quota or the key). Haiku does Jev's classify, priority and duplicate work through the Claude accounts. Off or not installed: no retry until it is switched on or the command exists (checked on each pass). Account failure: the first pass an hour after the last failure tries Jev again; no timer runs. Other Jev errors (timeouts, server errors, bad answers) are retried as before | 1 hour after an account failure | Accounts page and run logs | @@ -543,6 +545,6 @@ Dry run is the default for every writing command; `--apply` writes (and still re | `autocraft queue`, `merge --repo R`, `merge-hold\|merge-release `, `batch-remove `, `batch-stop ` | Merge queue | | `autocraft fasttrack add\|remove `, `fasttrack list` | Fast track | | `autocraft act --repo R` | Act | -| `autocraft postmerge review [--again]`, `postmerge backfill --since ` | Post-merge review | +| `autocraft postmerge review [--again]`, `postmerge file `, `postmerge backfill --since [--yes]` | Post-merge review | | `autocraft conversation show\|say\|do` | Conversations | | `autocraft pipeline on\|off\|limit`, `accounts list\|set\|jev` | Switch, limits, accounts | diff --git a/src/dash/api/admin.ts b/src/dash/api/admin.ts index babfee647..9b139be5c 100644 --- a/src/dash/api/admin.ts +++ b/src/dash/api/admin.ts @@ -38,7 +38,7 @@ export const AUDIT_ACTIONS = [ "session-revoke", "sign-in", "sign-in-refused", "account-add", "account-change", "account-login-start", "account-login-code", "account-login-cancel", "account-sign-out", "account-refresh", "repo-track", "repo-untrack", "reference-import", "labels-approve", "labels-revoke", "labels-apply", "merge-approve", "merge-revoke", "comment-approve", "comment-revoke", "act-comment", "act-close", "act-skip", "push-approve", "push-revoke", "fixup-push", "fixup-comment", "fixup-comment-edit", "fixissue-approve", "fixissue-revoke", "fixissue-push", "fixissue-pr", "fixissue-comment", "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", "postmerge-file", "postmerge-review", "postmerge-backfill", + "fasttrack-add", "fasttrack-remove", "merge-hold", "merge-release", "batch-remove", "batch-stop", "areas-edit", "areas-accept", "ci-approve", "ci-revoke", "ci-run-approve", "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", "duplicate-answer", "duplicate-group-ended", "duplicate-member-released", "duplicate-superseded", "env-change", "env-create", "env-rotate-key", "fix-again", "fixissue-check", "fixissue-claim", "fixup-check", "item-gone", "merge-answer-superseded", "merge-held-for-discussion", "merge-question-withdrawn", "merge-refused", "review-again", "task-cancel", "verify-again", "workspace-exclude", ]; diff --git a/src/dash/api/postmerge.ts b/src/dash/api/postmerge.ts index 42245a363..eb290e4be 100644 --- a/src/dash/api/postmerge.ts +++ b/src/dash/api/postmerge.ts @@ -1,28 +1,40 @@ // The post-merge review of a merged PR as the item page shows it. import type { DatabaseSync } from "node:sqlite"; -import type { ItemPostmerge, PostmergeFiling, PostmergeFinding } from "../../../web/src/api/types.ts"; -import { followupsOf, reviewOf } from "../../postmerge/select.ts"; +import type { ItemPostmerge, PostmergeEarlier, PostmergeFiling, PostmergeFinding } from "../../../web/src/api/types.ts"; +import { followupsOf, heldReason, reviewOf, type Followup } from "../../postmerge/select.ts"; import { itemState } from "./decisions.ts"; /** `staff`: operators and maintainers, who also read which stage missed a finding and why. */ export function postmergeOf(db: DatabaseSync, repo: string, n: number, staff: boolean): ItemPostmerge | null { const r = reviewOf(db, repo, n); if (!r) return null; - const follow = followupsOf(db, repo, n).filter((f) => f.review_at === r.at); + const all = followupsOf(db, repo, n); + const follow = all.filter((f) => f.review_at === r.at); const issueOf = db.prepare("SELECT state, title FROM items WHERE repo = ? AND number = ?"); + const filedIssue = (row: Followup) => { + const it = issueOf.get(repo, row.issue_number) as { state: string; title: string | null } | undefined; + return { number: row.issue_number!, url: row.url, state: it ? itemState(it.state) : null, title: it?.title ?? row.title }; + }; + const held = heldReason(db, repo, n, r.at); const findings = r.findings.map((f, i): PostmergeFinding => { const row = follow.find((x) => x.finding === i); let filing: PostmergeFiling; - if (row?.state === "filed" && row.issue_number !== null) { - const it = issueOf.get(repo, row.issue_number) as { state: string; title: string | null } | undefined; - filing = { state: "filed", issue: { number: row.issue_number, url: row.url, state: it ? itemState(it.state) : null, title: it?.title ?? row.title } }; - } else if (f.severity === "minor") filing = { state: "minor" }; - else if (f.duplicate_of !== null) filing = { state: "duplicate", duplicateOf: f.duplicate_of }; + if (row?.state === "filed" && row.issue_number !== null) filing = { state: "filed", issue: filedIssue(row) }; + else if (row?.state === "filing") filing = { state: "unknown" }; + else if (f.severity === "minor") filing = { state: "minor" }; + else if (row?.state === "skipped-duplicate" || f.duplicate_of !== null) filing = { state: "duplicate", duplicateOf: row?.duplicate_of ?? f.duplicate_of! }; + else if (row?.state === "skipped-stale") filing = { state: "stale" }; + else if (row?.state === "skipped-text") filing = { state: "refused" }; + else if (row?.state === "failed") filing = { state: "failed", attempts: row.attempts }; + else if (held) filing = { state: "held", reason: held }; else filing = row?.state === "skipped-limit" ? { state: "limit" } : { state: "pending" }; return { severity: f.severity, title: f.title, body: f.body, file: f.file, line: f.line, filing, ...(staff ? { missedBy: f.missed_by || null, missedWhy: f.missed_why || null } : {}), }; }); - return { at: r.at, model: r.model, mergeSha: r.merge_sha, error: r.error ? r.error.replace(/^(retry|held):\s*/, "") : null, findings }; + // Follow-ups of earlier reviews of the PR (`--again` replaces the review): a filed issue never shows as not filed. + const earlier = all.filter((f) => f.review_at !== r.at && (f.state === "filed" || f.state === "filing")).map((f): PostmergeEarlier => + f.state === "filed" && f.issue_number !== null ? { state: "filed", title: f.title, issue: filedIssue(f) } : { state: "unknown", title: f.title }); + return { at: r.at, model: r.model, mergeSha: r.merge_sha, error: r.error ? r.error.replace(/^(retry|held):\s*/, "") : null, findings, earlier }; } diff --git a/src/github/write.ts b/src/github/write.ts index f333010a8..eb5da0a43 100644 --- a/src/github/write.ts +++ b/src/github/write.ts @@ -182,12 +182,31 @@ export function ghFork(w: Writer, exec: Exec, repo: string, details: Details = { return viaGh(w, exec, "fork-create", repo, details, ["repo", "fork", `${ORG}/${repo}`, "--clone=false"]); } -/** Opens an issue; returns its number and URL. Throws when `gh` fails or prints no issue URL. `target` is the item the issue follows up. */ +/** `clear`: GitHub refused the request, so no issue can exist. Otherwise the outcome is unknown (a timeout, a lost response, a success without a URL). */ +export class IssueError extends Error { + clear: boolean; + constructor(message: string, clear: boolean) { super(message); this.clear = clear; } +} + +// gh's own wording when GitHub rejects the request before creating anything. +const REFUSED = /issues are disabled|has disabled issues|could not resolve to a repository|not found|forbidden|must have (?:admin|write|push)|permission|requires authentication|bad credentials|gh auth login|HTTP (?:401|403|404|410|422)|validation failed/i; + +/** + * Opens an issue; returns its number and URL. Throws an IssueError when `gh` fails or prints no issue URL; `clear` tells + * whether the failure certainly left no issue behind. `target` is the item the issue follows up. + */ export async function createIssue(w: Writer, exec: Exec, o: { repo: string; target: string; title: string; body: string }, details: Details = {}): Promise<{ number: number; url: string }> { - const r = await viaGh(w, exec, "postmerge-file", o.target, { ...details, title: o.title, text: o.body }, - ["issue", "create", "--repo", `${ORG}/${o.repo}`, "--title", o.title, "--body-file", "-"], o.body); + let r: ExecResult; + try { + r = await viaGh(w, exec, "postmerge-file", o.target, { ...details, title: o.title, text: o.body }, + ["issue", "create", "--repo", `${ORG}/${o.repo}`, "--title", o.title, "--body-file", "-"], o.body); + } catch (e) { + // exec rejects only when the command could not be started. + throw new IssueError(oneLine(String((e as Error).message ?? e)), true); + } const url = r.stdout.match(/https:\/\/github\.com\/\S+\/issues\/(\d+)/); - if (r.code !== 0 || !url) throw new Error(oneLine(r.stderr || r.stdout) || `exit code ${r.code}`); + if (r.code !== 0) { const m = oneLine(r.stderr || r.stdout) || `exit code ${r.code}`; throw new IssueError(m, REFUSED.test(m)); } + if (!url) throw new IssueError(oneLine(r.stderr || r.stdout) || "gh printed no issue URL", false); return { number: Number(url[1]), url: url[0] }; } diff --git a/src/pilot.ts b/src/pilot.ts index c8fd60430..d9a067b9b 100644 --- a/src/pilot.ts +++ b/src/pilot.ts @@ -1,6 +1,6 @@ // The scope of the pipeline. A repo takes part only while its pipeline flag (tracked_repos.pipeline) is on; off means sync only. // The pilot is an operator setting that narrows the enabled repos further to a list of items ("repo#number"). -// Empty or absent means no pilot. A Fix PR the pipeline opened for a pilot issue, and a follow-up issue it filed for a pilot PR, count as pilot items. +// Empty or absent means no pilot. A Fix PR the pipeline opened for a pilot issue, a follow-up issue it filed for a pilot PR, and a Fix PR it opened for such a follow-up issue count as pilot items. // A fast-tracked item (src/fasttrack.ts) is in scope whatever its repo's flag and the pilot say. // No Node imports besides the type, so candidate queries can use the SQL fragments. import type { DatabaseSync } from "node:sqlite"; @@ -87,7 +87,7 @@ export function setPilot(db: DatabaseSync, by: string, input: unknown): string[] const LIST = `(SELECT CASE WHEN json_valid(ps.value) THEN ps.value ELSE '[]' END FROM main.settings ps WHERE ps.key = '${PILOT_KEY}')`; -/** SQL condition on an item given by its repo and number expressions: it is fast-tracked, or its repo's pipeline flag is on and, with a pilot set, it is a pilot item or the Fix PR of a pilot issue. */ +/** SQL condition on an item given by its repo and number expressions: it is fast-tracked, or its repo's pipeline flag is on and, with a pilot set, it is a pilot item, the Fix PR of a pilot issue, a follow-up issue of a pilot PR or the Fix PR of such an issue. */ export const pilotSqlFor = (repo: string, number: string): string => `(EXISTS (SELECT 1 FROM main.fast_track pft WHERE pft.repo = ${repo} AND pft.number = ${number}) OR (EXISTS (SELECT 1 FROM main.tracked_repos pt WHERE pt.name = ${repo} AND pt.pipeline = 1) @@ -95,6 +95,8 @@ export const pilotSqlFor = (repo: string, number: string): string => OR EXISTS (SELECT 1 FROM json_each(${LIST}) pj WHERE pj.value = ${repo} || '#' || ${number}) OR EXISTS (SELECT 1 FROM main.fix_attempts pf, json_each(${LIST}) pj WHERE pf.repo = ${repo} AND pf.pr_url LIKE '%/pull/' || ${number} AND pj.value = pf.repo || '#' || pf.number) + OR EXISTS (SELECT 1 FROM main.fix_attempts pf2 JOIN main.postmerge_followups pm2 ON pm2.repo = pf2.repo AND pm2.issue_number = pf2.number, json_each(${LIST}) pj + WHERE pf2.repo = ${repo} AND pf2.pr_url LIKE '%/pull/' || ${number} AND pj.value = pm2.repo || '#' || pm2.number) OR EXISTS (SELECT 1 FROM main.postmerge_followups pm, json_each(${LIST}) pj WHERE pm.repo = ${repo} AND pm.issue_number = ${number} AND pj.value = pm.repo || '#' || pm.number))) OR EXISTS (SELECT 1 FROM main.fix_attempts pg JOIN main.fast_track pgt ON pgt.repo = pg.repo AND pgt.number = pg.number diff --git a/src/postmerge/file.ts b/src/postmerge/file.ts index bfab0ec69..440de3456 100644 --- a/src/postmerge/file.ts +++ b/src/postmerge/file.ts @@ -1,63 +1,169 @@ // Filing: each post-merge defect with no duplicate becomes one GitHub issue, in repos approved for comments. The issue then // goes through sync, classify and Fix like any other. The write is src/github/write.ts's `createIssue`. +// +// A row in state `filing` is written before the call. A create that succeeded on GitHub but whose answer was lost leaves +// that row behind: the issue may exist, so the finding is never filed again by this stage, and the dashboard says the +// outcome is unknown. Only a refusal from GitHub (no issue can exist) is recorded `failed` and tried again later. import type { DatabaseSync } from "node:sqlite"; import { commentApprovalOf } from "../act/approval.ts"; +import { audit } from "../dash/audit.ts"; import { exec, type Exec } from "../fixup/git.ts"; -import { createIssue, type Writer } from "../github/write.ts"; -import { issueBody, issueTitle } from "./template.ts"; -import { pendingDefects } from "./select.ts"; +import { createIssue, IssueError, type Writer } from "../github/write.ts"; +import { pipelineLogin } from "../review/discussion.ts"; +import { ghFileExists, type FileChecker } from "../review/diff.ts"; +import { issueBody, issueTitle, refusal } from "./template.ts"; +import { dedupeDefects, pendingDefects, reviewOf, followupsOf, type FollowupState, type PendingDefect } from "./select.ts"; export const ACTOR = "postmerge-file"; +const OPERATOR = "cli"; export type FileParams = { repo: string; limit?: number; onHandled?: (n: number) => void }; -export type FileDeps = { exec: Exec; now: () => Date }; -export type FileSummary = { repo: string; candidates: number; filed: { ref: string; issue: number }[]; limited: number; failed: { ref: string; reason: string }[]; note: string | null }; - -export const defaultFileDeps = (): FileDeps => ({ exec, now: () => new Date() }); - -const setFollowup = (db: DatabaseSync, d: { repo: string; number: number; review_at: string; finding: number; title: string }, state: "filed" | "skipped-limit", at: string, issue?: { number: number; url: string }): void => { - db.prepare(`INSERT OR REPLACE INTO postmerge_followups (repo, number, review_at, finding, title, issue_number, url, state, at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`) - .run(d.repo, d.number, d.review_at, d.finding, d.title, issue?.number ?? null, issue?.url ?? null, state, at); +export type FileDeps = { exec: Exec; now: () => Date; fileExists: FileChecker }; +export type FileSummary = { + repo: string; candidates: number; filed: { ref: string; issue: number }[]; limited: number; failed: { ref: string; reason: string }[]; + /** Attempts whose outcome is unknown: the issue may exist on GitHub. */ + unknown: { ref: string; reason: string }[]; skipped: number; note: string | null; }; +export const defaultFileDeps = (): FileDeps => ({ exec, now: () => new Date(), fileExists: ghFileExists }); + +type Row = { repo: string; number: number; review_at: string; finding: number; title: string }; +type Extra = { issue?: { number: number; url: string }; duplicateOf?: number | null; attempts?: number; note?: string | null }; + +const rowOf = (d: PendingDefect): Row => ({ repo: d.repo, number: d.number, review_at: d.review_at, finding: d.finding, title: d.f.title }); + +function setFollowup(db: DatabaseSync, d: Row, state: FollowupState, at: string, x: Extra = {}): void { + db.prepare(`INSERT OR REPLACE INTO postmerge_followups (repo, number, review_at, finding, title, issue_number, url, state, at, duplicate_of, attempts, note) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`) + .run(d.repo, d.number, d.review_at, d.finding, d.title, x.issue?.number ?? null, x.issue?.url ?? null, state, at, x.duplicateOf ?? null, x.attempts ?? 0, x.note ?? null); +} + +/** Writes the `filing` row unless another process already holds or finished this finding. */ +function claim(db: DatabaseSync, d: Row, at: string, attempts: number): boolean { + db.exec("BEGIN IMMEDIATE"); + try { + const cur = db.prepare("SELECT state FROM postmerge_followups WHERE repo = ? AND number = ? AND review_at = ? AND finding = ?").get(d.repo, d.number, d.review_at, d.finding) as { state: string } | undefined; + if (cur?.state === "filing" || cur?.state === "filed") { db.exec("ROLLBACK"); return false; } + setFollowup(db, d, "filing", at, { attempts }); + db.exec("COMMIT"); + return true; + } catch (e) { + try { db.exec("ROLLBACK"); } catch { /* nothing open */ } + throw e; + } +} + +const oneLine = (e: unknown): string => String((e as Error).message ?? e).replace(/\s+/g, " ").slice(0, 300); + +type Outcome = { kind: "filed"; issue: number } | { kind: "skipped" } | { kind: "failed" | "unknown"; reason: string }; + /** - * Files up to `limit` pending defects of the repo, oldest review first. The defects beyond the limit are marked skipped-limit - * and are filed by a later run. Nothing is filed in a repo without comment approval. + * One filing attempt: the stale-file and text checks (a skip, no write to GitHub), the `filing` row, the create, and the + * `filed` row as its own step. `onAttempt` runs once the create is about to be, or was, tried. + */ +async function fileDefect(db: DatabaseSync, deps: FileDeps, w: Writer, d: PendingDefect, log: (line: string) => void, onAttempt: () => void): Promise { + const { repo } = d, ref = `${repo}#${d.number}`, row = rowOf(d); + const at = () => deps.now().toISOString(); + if (d.f.file) { + const branch = (db.prepare("SELECT default_branch FROM repos WHERE name = ?").get(repo) as { default_branch: string | null } | undefined)?.default_branch ?? "main"; + if (await deps.fileExists(repo, branch, d.f.file) === false) { + setFollowup(db, row, "skipped-stale", at(), { note: `${d.f.file} is not on ${branch}` }); + log(` ${ref}: not filed: ${d.f.file} is no longer on ${branch}`); + return { kind: "skipped" }; + } + } + const title = issueTitle(d.f.title); + const body = issueBody({ number: d.number, model: d.model, body: d.f.body, file: d.f.file, line: d.f.line }); + const bad = refusal([d.f.title, d.f.body, title, body], pipelineLogin(db)); + if (bad) { + setFollowup(db, row, "skipped-text", at(), { note: bad }); + log(` ${ref}: not filed: ${bad}`); + return { kind: "skipped" }; + } + const attempts = d.attempts + 1; + if (!claim(db, row, at(), attempts)) return { kind: "skipped" }; + onAttempt(); + let made: { number: number; url: string }; + try { + made = await createIssue(w, deps.exec, { repo, target: ref, title, body }, { finding: d.finding, severity: d.f.severity }); + } catch (e) { + const reason = oneLine(e); + if (!(e instanceof IssueError) || !e.clear) return { kind: "unknown", reason }; + try { setFollowup(db, row, "failed", at(), { attempts, note: reason }); } catch { return { kind: "unknown", reason }; } + return { kind: "failed", reason }; + } + try { + setFollowup(db, row, "filed", at(), { issue: made, attempts }); + } catch (e) { + return { kind: "unknown", reason: `issue ${made.url} was created but not recorded: ${oneLine(e)}` }; + } + log(` ${ref}: filed ${made.url}`); + return { kind: "filed", issue: made.number }; +} + +/** + * Files up to `limit` pending defects of the repo, oldest review first. A defect that repeats an earlier one of the same + * run (same file, nearby line, similar title) is marked skipped-duplicate. The defects beyond the limit are marked + * skipped-limit and are filed by a later run. Nothing is filed in a repo without comment approval. After an attempt with + * an unknown outcome the run stops: the network or GitHub is likely failing. */ export async function runPostmergeFile(db: DatabaseSync, params: FileParams, log: (line: string) => void = console.log, deps: FileDeps = defaultFileDeps()): Promise { const { repo } = params; - const s: FileSummary = { repo, candidates: 0, filed: [], limited: 0, failed: [], note: null }; + const s: FileSummary = { repo, candidates: 0, filed: [], limited: 0, failed: [], unknown: [], skipped: 0, note: null }; if (!commentApprovalOf(db, repo)) { s.note = `commenting in ${repo} is not approved`; log(`postmerge-file ${repo}: ${s.note}; nothing filed`); return s; } - const todo = pendingDefects(db, repo); - s.candidates = todo.length; + const { keep, dupes } = dedupeDefects(pendingDefects(db, repo, deps.now().getTime())); + for (const { d, of } of dupes) { + setFollowup(db, rowOf(d), "skipped-duplicate", deps.now().toISOString(), { duplicateOf: of }); + log(` ${repo}#${d.number}: not filed: repeats a defect of ${repo}#${of}`); + s.skipped++; + } + s.candidates = keep.length; const w: Writer = { db, login: ACTOR }; let handled = 0; - for (const d of todo) { + for (const d of keep) { const ref = `${repo}#${d.number}`; if (params.limit !== undefined && handled >= params.limit) { - setFollowup(db, { ...d, title: d.f.title }, "skipped-limit", deps.now().toISOString()); + // A failed row keeps its state: its backoff and attempt count still apply. + if (!d.attempts) setFollowup(db, rowOf(d), "skipped-limit", deps.now().toISOString()); s.limited++; continue; } - handled++; - try { - const made = await createIssue(w, deps.exec, { repo, target: ref, title: issueTitle(d.f.title), body: issueBody({ number: d.number, model: d.model, body: d.f.body, file: d.f.file, line: d.f.line }) }, - { finding: d.finding, severity: d.f.severity }); - setFollowup(db, { ...d, title: d.f.title }, "filed", deps.now().toISOString(), made); - s.filed.push({ ref, issue: made.number }); - log(` ${ref}: filed ${made.url}`); - params.onHandled?.(handled); - } catch (e) { - const reason = String((e as Error).message ?? e).replace(/\s+/g, " ").slice(0, 300); - s.failed.push({ ref, reason }); - log(` ${ref}: not filed: ${reason}`); + const o = await fileDefect(db, deps, w, d, log, () => { handled++; params.onHandled?.(handled); }); + if (o.kind === "filed") s.filed.push({ ref, issue: o.issue }); + else if (o.kind === "skipped") s.skipped++; + else if (o.kind === "failed") { s.failed.push({ ref, reason: o.reason }); log(` ${ref}: not filed: ${o.reason}`); } + else { + s.unknown.push({ ref, reason: o.reason }); + log(` ${ref}: outcome unknown, check GitHub: ${o.reason}`); + break; } } - log(`postmerge-file ${repo}: ${s.filed.length} filed, ${s.limited} over the limit, ${s.failed.length} failed`); + log(`postmerge-file ${repo}: ${s.filed.length} filed, ${s.limited} over the limit, ${s.failed.length} failed, ${s.unknown.length} unknown, ${s.skipped} skipped`); return s; } +/** + * Files one finding of the PR's latest review on the operator's say, whatever holds the PR's automatic filing back + * (an earlier follow-up, a Fix PR of a follow-up). Refuses a finding that was filed or is in `filing`. + */ +export async function fileFinding(db: DatabaseSync, ref: string, index: number, log: (line: string) => void = console.log, deps: FileDeps = defaultFileDeps()): Promise { + const m = /^([A-Za-z0-9._-]+)#([1-9][0-9]*)$/.exec(ref); + if (!m) throw new Error(`not a repo#number: ${ref}`); + const repo = m[1]!, number = Number(m[2]); + const r = reviewOf(db, repo, number); + if (!r || r.error) throw new Error(`${ref} has no post-merge review`); + const f = r.findings[index]; + if (!f) throw new Error(`${ref} has no finding ${index}; its review has ${r.findings.length} (counted from 0)`); + if (f.severity !== "defect") throw new Error(`finding ${index} of ${ref} is minor; only defects are filed`); + if (!commentApprovalOf(db, repo)) throw new Error(`commenting in ${repo} is not approved`); + const have = followupsOf(db, repo, number).find((x) => x.review_at === r.at && x.finding === index); + if (have?.state === "filed" || have?.state === "filing") throw new Error(`finding ${index} of ${ref} is already ${have.state === "filed" ? `filed as issue ${have.issue_number}` : "being filed with an unknown outcome; check GitHub"}`); + audit(db, OPERATOR, "postmerge-file-one", ref, { finding: index }); + const d: PendingDefect = { repo, number, review_at: r.at, finding: index, f, model: r.model, attempts: have?.attempts ?? 0 }; + const o = await fileDefect(db, deps, { db, login: ACTOR }, d, log, () => {}); + log(o.kind === "filed" ? `${ref}: filed issue ${o.issue}` : `${ref}: finding ${index} not filed (${o.kind === "skipped" ? "see the log above" : o.reason})`); + return o; +} diff --git a/src/postmerge/index.ts b/src/postmerge/index.ts index 4d373a2c7..d92275ba6 100644 --- a/src/postmerge/index.ts +++ b/src/postmerge/index.ts @@ -1,11 +1,12 @@ -// CLI of the post-merge review stage: `autocraft postmerge review # [--again]` and -// `autocraft postmerge backfill --since `. Operator only: the box's shell is the operator's. +// CLI of the post-merge review stage: `autocraft postmerge review # [--again]`, +// `autocraft postmerge file # ` and `autocraft postmerge backfill --since [--yes]`. +// Operator only: the box's shell is the operator's. import type { DatabaseSync } from "node:sqlite"; import { audit } from "../dash/audit.ts"; import { mergedPr } from "./select.ts"; const ACTOR = "cli"; -const USAGE = "postmerge review # [--again] | postmerge backfill --since "; +const USAGE = "postmerge review # [--again] | postmerge file # | postmerge backfill --since [--yes]"; /** Reviews one merged PR now; refuses a PR the pipeline did not merge, and one that has a review unless `again`. */ export async function reviewOne(db: DatabaseSync, ref: string, again: boolean, log: (line: string) => void = console.log): Promise { @@ -14,6 +15,8 @@ export async function reviewOne(db: DatabaseSync, ref: string, again: boolean, l const repo = m[1]!, number = Number(m[2]); if (!mergedPr(db, repo, number)) throw new Error(`${ref} was not merged by the pipeline`); if (!again && db.prepare("SELECT 1 FROM postmerge_reviews WHERE repo = ? AND number = ? AND error IS NULL").get(repo, number)) throw new Error(`${ref} has a post-merge review; add --again to review it again`); + // The runner's job reviews any candidate of its repo; two reviews of one PR at once would replace each other's rows. + if (db.prepare("SELECT 1 FROM jobs WHERE step = 'postmerge' AND state = 'running' AND repo = ?").get(repo)) throw new Error(`a postmerge job is running for ${repo}; try again when it has finished`); audit(db, ACTOR, "postmerge-review", ref, { again }); const { runPostmerge } = await import("./review.ts"); await runPostmerge(db, { repo, only: [number] }, log); @@ -30,10 +33,17 @@ export const commands = { const refs = rest.filter((a) => a !== "--again"); if (refs.length !== 1 || refs[0]!.startsWith("--")) throw new Error(`usage: autocraft ${USAGE}`); await reviewOne(connect(), refs[0]!, again); + } else if (sub === "file") { + const idx = Number(rest[1]); + if (rest.length !== 2 || !Number.isInteger(idx) || idx < 0) throw new Error(`usage: autocraft ${USAGE}`); + const { fileFinding } = await import("./file.ts"); + await fileFinding(connect(), rest[0]!, idx); } else if (sub === "backfill") { - if (rest[0] !== "--since" || rest.length !== 2 || Number.isNaN(Date.parse(rest[1]!))) throw new Error("usage: autocraft postmerge backfill --since "); + const yes = rest.includes("--yes"); + const a = rest.filter((x) => x !== "--yes"); + if (a[0] !== "--since" || a.length !== 2 || Number.isNaN(Date.parse(a[1]!))) throw new Error("usage: autocraft postmerge backfill --since [--yes]"); const { queueBackfill } = await import("./review.ts"); - const n = queueBackfill(connect(), ACTOR, rest[1]!); + const n = queueBackfill(connect(), ACTOR, a[1]!, { yes }); console.log(`${n} merged PRs wait for a post-merge review; the postmerge step reviews them`); } else throw new Error(`usage: autocraft ${USAGE}`); }, diff --git a/src/postmerge/parse.ts b/src/postmerge/parse.ts index 42a3def8a..335d5441c 100644 --- a/src/postmerge/parse.ts +++ b/src/postmerge/parse.ts @@ -28,7 +28,9 @@ export type Finding = { export type PostmergeCommit = { kind: "conflict-merge" | "fix-up" | "duplicate-carry"; sha: string | null; note: string | null }; export type PostmergeReviewRow = { head: string; verdict: string; sure: boolean; reason: string; risks: string[]; fixes: { file: string; change: string }[]; at: string }; -export type RelatedItem = { number: number; kind: "issue" | "pr"; title: string }; +export type RelatedItem = { number: number; kind: "issue" | "pr"; state: "open" | "closed"; title: string }; +/** A follow-up issue this stage already filed for the PR (any state), or is filing with an unknown outcome. */ +export type FiledBefore = { number: number | null; state: "open" | "closed" | "unknown"; title: string }; /** One merged PR as the prompt shows it. Every string field is untrusted or derived from untrusted text. */ export type PostmergePr = { @@ -49,8 +51,10 @@ export type PostmergePr = { pipeline_commits: PostmergeCommit[]; /** Our reviews of the PR, oldest first. */ review_history: PostmergeReviewRow[]; - /** Open issues and PRs that mention this PR or its files: number and title only, for deduplication. */ + /** Issues and PRs that mention this PR or its files, open or closed in the last 30 days: number, kind, state and title only, for deduplication. */ related_open: RelatedItem[]; + /** Follow-up issues already filed for this PR by earlier reviews, with their current state. */ + filed_before: FiledBefore[]; diff: string; }; @@ -121,6 +125,7 @@ export const SAMPLE_POSTMERGE_PRS: PostmergePr[] = [{ merge_sha: "0123456789abcdef0123456789abcdef01234567", method: "merge", files: ["src/png.rs"], tests_omitted: ["tests/png16.rs"], lockfiles_omitted: [], pipeline_commits: [{ kind: "conflict-merge", sha: "89abcdef0123456789abcdef0123456789abcdef", note: "merged the base branch into the PR" }], review_history: [{ head: "fedcba9876543210fedcba9876543210fedcba98", verdict: "take-fix", sure: true, reason: "Rename tmp to stride.", risks: [], fixes: [{ file: "src/png.rs", change: "Rename `tmp` to `stride`." }], at: "2026-11-01T10:00:00.000Z" }], - related_open: [{ number: 14, kind: "issue", title: "Resize crops the last row of 16-bit PNGs" }], + related_open: [{ number: 14, kind: "issue", state: "open", title: "Resize crops the last row of 16-bit PNGs" }], + filed_before: [], diff: "diff --git a/src/png.rs b/src/png.rs\n--- a/src/png.rs\n+++ b/src/png.rs\n@@ -88,7 +88,7 @@ fn resize(img: &Image) -> Image {\n- let stride = img.width * 4;\n+ let stride = img.width * img.bytes_per_pixel();\n", }]; diff --git a/src/postmerge/review.ts b/src/postmerge/review.ts index bbfe156e9..bde0e8d28 100644 --- a/src/postmerge/review.ts +++ b/src/postmerge/review.ts @@ -13,8 +13,8 @@ import { codeDiff, ghMerged, type MergedFetcher } from "../review/diff.ts"; import { MAX_DIFF_CHARS } from "../review/opus.ts"; import { REPO_PATH } from "../sandbox/command.ts"; import { checkoutForCommit, checkoutForPr } from "../sandbox/index.ts"; -import { lintReply, MAX_MERGED_DIFF_CHARS, parseFindings, publicTexts, type Finding, type PostmergeCommit, type PostmergePr, type PostmergeReviewRow, type RelatedItem } from "./parse.ts"; -import { mergedPr, selectPostmerge, type MergedPr } from "./select.ts"; +import { lintReply, MAX_MERGED_DIFF_CHARS, parseFindings, publicTexts, type FiledBefore, type Finding, type PostmergeCommit, type PostmergePr, type PostmergeReviewRow, type RelatedItem } from "./parse.ts"; +import { followupsOf, MAX_RETRIES, mergedPr, selectPostmerge, type MergedPr } from "./select.ts"; const PROMPT = CLAUDE_PROMPTS["postmerge.opus"]; const now = () => new Date().toISOString(); @@ -65,23 +65,37 @@ function reviewHistory(db: DatabaseSync, repo: string, number: number): Postmerg .map((r) => ({ head: r.head_oid, verdict: r.verdict, sure: r.sure === 1, reason: r.reason, risks: list(r.risks), fixes: list(r.fixes), at: r.at })); } -/** Open items of the repo that mention the PR by number or one of its files by path: number, kind and title, for deduplication. */ -export function relatedOpen(db: DatabaseSync, repo: string, number: number, files: string[]): RelatedItem[] { +/** Items closed within this long still count as related: a defect reported and closed recently is not reported again. */ +export const RELATED_CLOSED_DAYS = 30; + +/** Items of the repo, open or closed in the last 30 days, that mention the PR by number or one of its files by path: number, kind, state and title, for deduplication. */ +export function relatedOpen(db: DatabaseSync, repo: string, number: number, files: string[], at = Date.now()): RelatedItem[] { const needles = [`#${number}`, ...files.slice(0, 30)]; const where = needles.map(() => "(i.title LIKE ? ESCAPE '\\' OR i.body LIKE ? ESCAPE '\\')").join(" OR "); const args = needles.flatMap((n) => { const like = `%${n.replace(/[\\%_]/g, "\\$&")}%`; return [like, like]; }); - const rows = db.prepare(`SELECT i.number, i.kind, i.title, i.body FROM items i WHERE i.repo = ? AND i.state = 'OPEN' AND i.number <> ? AND (${where}) ORDER BY i.number LIMIT 60`).all(repo, number, ...args) as - { number: number; kind: "issue" | "pr"; title: string | null; body: string | null }[]; + const since = new Date(at - RELATED_CLOSED_DAYS * 86400_000).toISOString(); + const rows = db.prepare(`SELECT i.number, i.kind, i.state, i.title, i.body FROM items i WHERE i.repo = ? + AND (i.state = 'OPEN' OR COALESCE(i.closed_at, i.merged_at, i.updated_at) >= ?) AND i.number <> ? AND (${where}) ORDER BY i.number LIMIT 60`).all(repo, since, number, ...args) as + { number: number; kind: "issue" | "pr"; state: string; title: string | null; body: string | null }[]; const byNumber = new RegExp(String.raw`(? { const text = `${r.title ?? ""}\n${r.body ?? ""}`; return byNumber.test(text) || files.some((f) => text.includes(f)); }) - .slice(0, 40).map((r) => ({ number: r.number, kind: r.kind, title: (r.title ?? "").slice(0, 160) })); + .slice(0, 40).map((r) => ({ number: r.number, kind: r.kind, state: r.state === "OPEN" ? "open" as const : "closed" as const, title: (r.title ?? "").slice(0, 160) })); +} + +/** Follow-up issues earlier reviews of the PR filed, with their current state; one still in `filing` has an unknown outcome. */ +export function filedBefore(db: DatabaseSync, repo: string, number: number): FiledBefore[] { + const stateOf = db.prepare("SELECT state FROM items WHERE repo = ? AND number = ?"); + return followupsOf(db, repo, number).filter((f) => f.state === "filed" || f.state === "filing").map((f) => { + const it = f.issue_number === null ? undefined : stateOf.get(repo, f.issue_number) as { state: string } | undefined; + return { number: f.issue_number, state: f.state === "filing" ? "unknown" as const : it?.state === "OPEN" || !it ? "open" as const : "closed" as const, title: f.title }; + }); } type Prepared = { kind: "ready"; input: PostmergePr; sha: string | null } | { kind: "error"; error: string }; async function prepare(db: DatabaseSync, c: MergedPr, deps: PostmergeDeps): Promise { - const d = await deps.fetchMerged(c.repo, c.number); + const d = await deps.fetchMerged(c.repo, c.number, { batch: c.batch === 1 }); if (!d.ok) return { kind: "error", error: d.tooLarge ? "held: too large to review automatically" : `retry: no merged diff: ${d.error}` }; let cd = codeDiff(d.text); if (!cd.files.length && cd.testsOmitted.length) cd = codeDiff(d.text, true); @@ -92,26 +106,31 @@ async function prepare(db: DatabaseSync, c: MergedPr, deps: PostmergeDeps): Prom ref: refOf(c), title: it?.title ?? "", body: it?.body ?? "", author: it?.author ?? null, merge_sha: d.sha ?? c.head_oid, method: c.method, files: cd.files, tests_omitted: cd.testsOmitted, lockfiles_omitted: cd.lockfilesOmitted, pipeline_commits: pipelineCommits(db, c.repo, c.number), review_history: reviewHistory(db, c.repo, c.number), - related_open: relatedOpen(db, c.repo, c.number, cd.files), diff: cd.text, + related_open: relatedOpen(db, c.repo, c.number, cd.files), filed_before: filedBefore(db, c.repo, c.number), diff: cd.text, }; return { kind: "ready", input, sha: d.sha }; } /** * Stores the review and one `postmerge_followups` row for each finding that is never filed: a minor one (skipped-minor) - * or a defect another open item already covers (skipped-duplicate). A review that replaces an earlier one keeps the - * earlier one's follow-up rows, so a defect filed before is not filed again. + * or a defect another item already covers (skipped-duplicate). A review that replaces an earlier one keeps the earlier + * one's follow-up rows, so the PR's filed follow-ups stay known. A `retry:` error is stored as held at the third try. */ export function saveReview(db: DatabaseSync, c: { repo: string; number: number }, r: { sha: string; runId: string | null; model: string | null; findings: Finding[] | null; error: string | null; at?: string }): void { const at = r.at ?? now(); // A failed second try never replaces a stored review. if (r.error && db.prepare("SELECT 1 FROM postmerge_reviews WHERE repo = ? AND number = ? AND error IS NULL").get(c.repo, c.number)) return; - db.prepare("INSERT OR REPLACE INTO postmerge_reviews (repo, number, merge_sha, at, model, run_id, findings, error) VALUES (?, ?, ?, ?, ?, ?, ?, ?)") - .run(c.repo, c.number, r.sha, at, r.model, r.runId, r.findings ? JSON.stringify(r.findings) : null, r.error); - const skip = db.prepare("INSERT OR IGNORE INTO postmerge_followups (repo, number, review_at, finding, title, issue_number, url, state, at) VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, ?)"); + let error = r.error, tries = 0; + if (error?.startsWith("retry:")) { + tries = ((db.prepare("SELECT tries FROM postmerge_reviews WHERE repo = ? AND number = ?").get(c.repo, c.number) as { tries: number } | undefined)?.tries ?? 0) + 1; + if (tries >= MAX_RETRIES) error = `held: gave up after ${tries} tries (${error.slice("retry:".length).trim()})`; + } + db.prepare("INSERT OR REPLACE INTO postmerge_reviews (repo, number, merge_sha, at, model, run_id, findings, error, tries) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)") + .run(c.repo, c.number, r.sha, at, r.model, r.runId, r.findings ? JSON.stringify(r.findings) : null, error, tries); + const skip = db.prepare("INSERT OR IGNORE INTO postmerge_followups (repo, number, review_at, finding, title, issue_number, url, state, at, duplicate_of) VALUES (?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?)"); (r.findings ?? []).forEach((f, i) => { - if (f.severity === "minor") skip.run(c.repo, c.number, at, i, f.title, "skipped-minor", at); - else if (f.duplicate_of !== null) skip.run(c.repo, c.number, at, i, f.title, "skipped-duplicate", at); + if (f.severity === "minor") skip.run(c.repo, c.number, at, i, f.title, "skipped-minor", at, null); + else if (f.duplicate_of !== null) skip.run(c.repo, c.number, at, i, f.title, "skipped-duplicate", at, f.duplicate_of); }); } @@ -166,10 +185,15 @@ export async function runPostmerge(db: DatabaseSync, params: PostmergeParams, lo return s; } -export function queueBackfill(db: DatabaseSync, by: string, since: string): number { +/** A backfill reaching further back than this needs the operator's confirmation. */ +export const BACKFILL_FREE_DAYS = 14; + +export function queueBackfill(db: DatabaseSync, by: string, since: string, o: { yes?: boolean; now?: number } = {}): number { const iso = new Date(since).toISOString(); + const days = ((o.now ?? Date.now()) - Date.parse(iso)) / 86400_000; + if (days > BACKFILL_FREE_DAYS && !o.yes) throw new Error(`--since is ${Math.floor(days)} days back; every merged PR since then gets a model review and its defects are filed publicly. Add --yes to confirm`); db.prepare("INSERT INTO settings (key, value) VALUES ('postmerge_since', ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value").run(iso); - audit(db, by, "postmerge-backfill", null, { since: iso }); + audit(db, by, "postmerge-backfill", null, { since: iso, confirmed: o.yes === true }); return (db.prepare(`SELECT COUNT(*) AS n FROM (SELECT DISTINCT m.repo, m.number FROM merges m WHERE m.outcome = 'merged' AND m.at >= ? AND NOT EXISTS (SELECT 1 FROM postmerge_reviews r WHERE r.repo = m.repo AND r.number = m.number))`).get(iso) as { n: number }).n; } diff --git a/src/postmerge/select.ts b/src/postmerge/select.ts index cb956ecd0..c4919aaab 100644 --- a/src/postmerge/select.ts +++ b/src/postmerge/select.ts @@ -7,20 +7,27 @@ import type { Finding } from "./parse.ts"; export const RETRY_AFTER_MS = 3600_000; export const SINCE_KEY = "postmerge_since"; -export type MergedPr = { repo: string; number: number; head_oid: string; merged_at: string; method: string | null }; +/** `batch`: the PR landed through a merged integration batch. */ +export type MergedPr = { repo: string; number: number; head_oid: string; merged_at: string; method: string | null; batch: number }; + +/** Re-reviews of a PR whose review ended in a `retry:` error stop after this many tries. */ +export const MAX_RETRIES = 3; + +const BATCH = `EXISTS (SELECT 1 FROM merge_batch_prs bp JOIN merge_batches mb ON mb.id = bp.batch_id WHERE mb.repo = m.repo AND bp.number = m.number AND mb.state = 'merged') AS batch`; export const sinceOf = (db: DatabaseSync): string => (db.prepare("SELECT value FROM settings WHERE key = ?").get(SINCE_KEY) as { value: string } | undefined)?.value ?? "9999"; /** * PRs a pipeline merge landed (`merges` rows with outcome merged) since the `postmerge_since` setting, in the pilot, without a - * stored review, oldest merge first. A review stored with a `retry:` error counts as missing an hour after it failed. + * stored review, oldest merge first. A review stored with a `retry:` error counts as missing an hour after it failed; the third such error is stored as held. */ export function selectPostmerge(db: DatabaseSync, repo: string, now = Date.now()): MergedPr[] { return db.prepare(`SELECT m.repo, m.number, (SELECT x.head_oid FROM merges x WHERE x.repo = m.repo AND x.number = m.number AND x.outcome = 'merged' ORDER BY x.at DESC, x.rowid DESC LIMIT 1) AS head_oid, MIN(m.at) AS merged_at, - (SELECT x.method FROM merges x WHERE x.repo = m.repo AND x.number = m.number AND x.outcome = 'merged' ORDER BY x.at DESC, x.rowid DESC LIMIT 1) AS method + (SELECT x.method FROM merges x WHERE x.repo = m.repo AND x.number = m.number AND x.outcome = 'merged' ORDER BY x.at DESC, x.rowid DESC LIMIT 1) AS method, + ${BATCH} FROM merges m WHERE m.repo = :repo AND m.outcome = 'merged' AND m.at >= :since AND ${pilotSqlFor("m.repo", "m.number")} AND NOT EXISTS (SELECT 1 FROM postmerge_reviews r WHERE r.repo = m.repo AND r.number = m.number @@ -33,7 +40,8 @@ export function mergedPr(db: DatabaseSync, repo: string, number: number): Merged return (db.prepare(`SELECT m.repo, m.number, (SELECT x.head_oid FROM merges x WHERE x.repo = m.repo AND x.number = m.number AND x.outcome = 'merged' ORDER BY x.at DESC, x.rowid DESC LIMIT 1) AS head_oid, MIN(m.at) AS merged_at, - (SELECT x.method FROM merges x WHERE x.repo = m.repo AND x.number = m.number AND x.outcome = 'merged' ORDER BY x.at DESC, x.rowid DESC LIMIT 1) AS method + (SELECT x.method FROM merges x WHERE x.repo = m.repo AND x.number = m.number AND x.outcome = 'merged' ORDER BY x.at DESC, x.rowid DESC LIMIT 1) AS method, + ${BATCH} FROM merges m WHERE m.repo = ? AND m.number = ? AND m.outcome = 'merged' GROUP BY m.repo, m.number`).get(repo, number) as MergedPr | undefined) ?? null; } @@ -52,32 +60,82 @@ export function reviewOf(db: DatabaseSync, repo: string, number: number): Stored return r ? { ...r, findings: parseStored(r.findings) } : null; } -export type FollowupState = "filed" | "skipped-duplicate" | "skipped-limit" | "skipped-minor"; -export type Followup = { repo: string; number: number; review_at: string; finding: number; title: string; issue_number: number | null; url: string | null; state: FollowupState; at: string }; +export type FollowupState = "filing" | "filed" | "failed" | "skipped-duplicate" | "skipped-limit" | "skipped-minor" | "skipped-stale" | "skipped-text"; +export type Followup = { repo: string; number: number; review_at: string; finding: number; title: string; issue_number: number | null; url: string | null; state: FollowupState; at: string; duplicate_of: number | null; attempts: number; note: string | null }; export function followupsOf(db: DatabaseSync, repo: string, number: number): Followup[] { - return db.prepare("SELECT repo, number, review_at, finding, title, issue_number, url, state, at FROM postmerge_followups WHERE repo = ? AND number = ? ORDER BY review_at, finding").all(repo, number) as Followup[]; + return db.prepare("SELECT repo, number, review_at, finding, title, issue_number, url, state, at, duplicate_of, attempts, note FROM postmerge_followups WHERE repo = ? AND number = ? ORDER BY review_at, finding").all(repo, number) as Followup[]; } -export type PendingDefect = { repo: string; number: number; review_at: string; finding: number; f: Finding; model: string | null }; +/** A failed filing is tried again this long after its attempt (1 h after the first, 6 h after the second); three attempts at most. */ +export const FAILED_BACKOFF_MS = [3600_000, 6 * 3600_000]; +export const MAX_ATTEMPTS = 3; + +export function retryDue(f: Pick, now = Date.now()): boolean { + if (f.state !== "failed") return false; + const wait = FAILED_BACKOFF_MS[f.attempts - 1]; + return wait !== undefined && f.attempts < MAX_ATTEMPTS && now - Date.parse(f.at) >= wait; +} + +/** The PR is the Fix PR of a follow-up issue this stage filed. */ +export function fixesFollowup(db: DatabaseSync, repo: string, number: number): boolean { + return db.prepare(`SELECT 1 FROM fix_attempts fa JOIN postmerge_followups pf ON pf.repo = fa.repo AND pf.issue_number = fa.number + WHERE fa.repo = ? AND fa.pr_url LIKE '%/pull/' || ?`).get(repo, String(number)) !== undefined; +} /** - * Defects with no duplicate that no issue was filed for yet, oldest review first. A PR whose review was replaced - * (`--again`) is judged by its latest review; a defect whose title an issue was already filed for is not filed again. + * Why the defects of the review `reviewAt` are never filed automatically: a follow-up of an earlier review of the PR + * exists (filed, or filing with an unknown outcome), or the PR itself fixes a follow-up issue. The operator files one + * with `postmerge file`. */ -export function pendingDefects(db: DatabaseSync, repo: string): PendingDefect[] { +export function heldReason(db: DatabaseSync, repo: string, number: number, reviewAt: string): "earlier" | "fix" | null { + if (followupsOf(db, repo, number).some((x) => (x.state === "filed" || x.state === "filing") && x.review_at !== reviewAt)) return "earlier"; + return fixesFollowup(db, repo, number) ? "fix" : null; +} + +export type PendingDefect = { repo: string; number: number; review_at: string; finding: number; f: Finding; model: string | null; attempts: number }; + +/** + * Defects of the latest review of each PR that the filing step may still try, oldest review first: no row yet, a + * skipped-limit row, or a failed row whose backoff has passed. A review held by `heldReason` has none. + */ +export function pendingDefects(db: DatabaseSync, repo: string, now = Date.now()): PendingDefect[] { const rows = db.prepare(`SELECT r.repo, r.number, r.at, r.model, r.findings FROM postmerge_reviews r WHERE r.repo = ? AND r.error IS NULL AND ${pilotSqlFor("r.repo", "r.number")} ORDER BY r.at, r.number`).all(repo) as { repo: string; number: number; at: string; model: string | null; findings: string | null }[]; const out: PendingDefect[] = []; for (const r of rows) { - const rows2 = followupsOf(db, r.repo, r.number); - const filedTitles = new Set(rows2.filter((x) => x.state === "filed").map((x) => x.title.toLowerCase())); + if (heldReason(db, r.repo, r.number, r.at)) continue; + const have = followupsOf(db, r.repo, r.number).filter((x) => x.review_at === r.at); parseStored(r.findings).forEach((f, i) => { if (f.severity !== "defect" || f.duplicate_of !== null) return; - if (rows2.some((x) => x.review_at === r.at && x.finding === i && x.state === "filed")) return; - if (filedTitles.has(f.title.toLowerCase())) return; - out.push({ repo: r.repo, number: r.number, review_at: r.at, finding: i, f, model: r.model }); + const row = have.find((x) => x.finding === i); + if (row && row.state !== "skipped-limit" && !retryDue(row, now)) return; + out.push({ repo: r.repo, number: r.number, review_at: r.at, finding: i, f, model: r.model, attempts: row?.attempts ?? 0 }); }); } return out; } + +const words = (t: string): Set => new Set(t.toLowerCase().replace(/[^a-z0-9]+/g, " ").split(" ").filter((w) => w.length > 2)); + +/** Titles that name mostly the same words, after lower-casing and dropping punctuation and short words. */ +export function similarTitles(a: string, b: string): boolean { + const x = words(a), y = words(b); + if (!x.size || !y.size) return a.trim().toLowerCase() === b.trim().toLowerCase(); + const common = [...x].filter((w) => y.has(w)).length; + return common / (x.size + y.size - common) >= 0.5; +} + +/** The same file, lines within 20 and similar titles: the defect of one cause found in overlapping PRs. */ +export const sameDefect = (a: Finding, b: Finding): boolean => + a.file !== null && a.file === b.file && a.line !== null && b.line !== null && Math.abs(a.line - b.line) <= 20 && similarTitles(a.title, b.title); + +/** Keeps the first of each group of same defects (list order) and names, for each other, the PR number of the one kept. */ +export function dedupeDefects(list: PendingDefect[]): { keep: PendingDefect[]; dupes: { d: PendingDefect; of: number }[] } { + const keep: PendingDefect[] = [], dupes: { d: PendingDefect; of: number }[] = []; + for (const d of list) { + const k = keep.find((x) => sameDefect(x.f, d.f)); + if (k) dupes.push({ d, of: k.number }); else keep.push(d); + } + return { keep, dupes }; +} diff --git a/src/postmerge/template.ts b/src/postmerge/template.ts index f98d317fb..9ae2875e8 100644 --- a/src/postmerge/template.ts +++ b/src/postmerge/template.ts @@ -5,15 +5,41 @@ import { cleanLine, modelLabel } from "../review/post-template.ts"; export const ISSUE_TITLE_MAX = 120; export const ISSUE_BODY_MAX = 6000; -export const ISSUE_TEMPLATE = "_AI-generated review ({model}). Not a maintainer decision._\n\nFollow-up to #{number}.\n\n{body}"; +export const ISSUE_TEMPLATE = "_AI-generated review ({model}). Not a maintainer decision._\n\nFollow-up to #{number}.\n\n{body}\n\nLocation: `{file}:{line}` (only when the finding names a file)"; -/** Raw HTML tags and mentions out (nobody gets pinged); Markdown and line breaks stay. */ -function cleanBody(s: string): string { - return s.replace(/(^|[^A-Za-z0-9_])@(?=[A-Za-z0-9_])/g, "$1").replace(/<\/?[A-Za-z][^>]*>/g, "").trim(); +/** Fenced blocks and inline code spans; the capturing group makes split() keep them at odd indices. */ +const CODE = /(```[\s\S]*?(?:```|$)|`[^`\n]*`)/; + +/** `fix` runs on the text outside code only: code keeps its URLs, references and `@`. */ +function outsideCode(s: string, fix: (t: string) => string): string { + return s.split(CODE).map((part, i) => (i % 2 ? part : fix(part))).join(""); } +/** + * Public text outside code: no raw HTML, no mentions, no URLs, Markdown links reduced to their text, and no issue + * references (`owner/repo#n`, `#n`), which would link or notify other threads. A reference reads "issue n". + */ +function cleanOutsideCode(t: string): string { + return t + .replace(/!?\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/<\/?[A-Za-z][^>]*>/g, "") + .replace(/]*>?/gi, "") + .replace(/(^|[^A-Za-z0-9_])@(?=[A-Za-z0-9_])/g, "$1") + .replace(/(\b(?:issues?|pull requests?|PRs?)\s+)?(? (pre ? `${pre}${n}` : `issue ${n}`)); +} + +const cleanBody = (s: string): string => outsideCode(s, cleanOutsideCode).trim(); + export function issueTitle(title: string): string { - return cleanLine(title, ISSUE_TITLE_MAX); + return cleanLine(outsideCode(title, cleanOutsideCode), ISSUE_TITLE_MAX); +} + +/** Why a title or body must not be filed: it names the product or the pipeline's account. Null when it is fine. */ +export function refusal(texts: string[], login: string): string | null { + const all = texts.join("\n"); + if (/autocraft/i.test(all)) return "the text names the product"; + if (login && new RegExp(`(? { return { ok: true, text: diff.out }; }; -/** What a merged PR landed: the commit read (null when GitHub names none) and its diff restricted to the files of the PR's own diff. */ +/** What a merged PR landed: the commit read (null when the diff is the PR's own) and its diff restricted to the files of the PR's own diff. */ export type MergedDiff = { ok: true; sha: string | null; text: string } | { ok: false; tooLarge: boolean; error: string }; -export type MergedFetcher = (repo: string, number: number) => Promise; +/** `batch`: the PR landed through an integration batch, whose merge commit carries every member. */ +export type MergedFetcher = (repo: string, number: number, opts?: { batch?: boolean }) => Promise; /** - * The merge commit's diff against its first parent, kept to the files the PR changed (an integration batch's merge commit - * carries other PRs too). Without a merge commit, or when that diff is unreadable or empty, the PR's own diff. + * The merge commit's diff against its first parent, kept to the files the PR changed. A PR merged through an integration + * batch, or one without a merge commit, is read as its own diff at the merged head (it includes the pipeline's pushes to + * the PR branch). When the PR's own diff cannot be read there is no diff: the merge commit alone would carry other PRs. */ -export const ghMerged: MergedFetcher = async (repo, number) => { +export const ghMerged: MergedFetcher = async (repo, number, opts = {}) => { const own = await ghDiff(repo, number); + if (!own.ok) return own; + if (opts.batch) return { ok: true, sha: null, text: own.text }; const view = await gh(["pr", "view", String(number), "--repo", `${ORG}/${repo}`, "--json", "mergeCommit", "--jq", ".mergeCommit.oid // empty"]); const sha = view.code === 0 && /^[0-9a-f]{40}$/.test(view.out.trim()) ? view.out.trim() : null; - const fallback: MergedDiff = own.ok ? { ok: true, sha, text: own.text } : own; + const fallback: MergedDiff = { ok: true, sha, text: own.text }; if (!sha) return fallback; const c = await gh(["api", "-H", "Accept: application/vnd.github.diff", `repos/${ORG}/${repo}/commits/${sha}`]); if (c.code !== 0) return fallback; - const keep = own.ok ? new Set(splitDiff(own.text).map((f) => f.path)) : null; - const text = keep ? splitDiff(c.out).filter((f) => keep.has(f.path)).map((f) => f.text).join("") : c.out; + const keep = new Set(splitDiff(own.text).map((f) => f.path)); + const text = splitDiff(c.out).filter((f) => keep.has(f.path)).map((f) => f.text).join(""); return text ? { ok: true, sha, text } : fallback; }; + +/** Whether `path` exists on `ref` of the repo; null when GitHub could not say (anything but a plain not-found). */ +export type FileChecker = (repo: string, ref: string, path: string) => Promise; + +export const ghFileExists: FileChecker = async (repo, ref, path) => { + const r = await gh(["api", `repos/${ORG}/${repo}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(ref)}`, "--jq", ".type"]); + if (r.code === 0) return r.out.trim().length > 0; + return /\b404\b|Not Found/i.test(r.err) ? false : null; +}; diff --git a/src/runner/steps.ts b/src/runner/steps.ts index 2adfc2df4..8547984b6 100644 --- a/src/runner/steps.ts +++ b/src/runner/steps.ts @@ -564,8 +564,8 @@ export const STEPS: StepDef[] = [ const refused = await checkCommentApproved(ctx.db, ctx.params); if (refused) throw new Error(refused); const r = await runPostmergeFile(ctx.db, { repo: String(ctx.params.repo), limit: Number(ctx.params.limit), onHandled: ctx.handled }, ctx.log); - ctx.acted(r.filed.length + r.failed.length); - return `${r.repo}: ${r.filed.length} issues filed, ${r.limited} over the limit, ${r.failed.length} failed`; + ctx.acted(r.filed.length + r.failed.length + r.unknown.length); + return `${r.repo}: ${r.filed.length} issues filed, ${r.limited} over the limit, ${r.failed.length} failed${r.unknown.length ? `, ${r.unknown.length} with an unknown outcome (check GitHub)` : ""}`; }, }, { diff --git a/src/schema.sql b/src/schema.sql index a30f0d5cc..3eee90ea0 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -1065,9 +1065,13 @@ CREATE TABLE IF NOT EXISTS postmerge_reviews ( run_id TEXT, findings TEXT, error TEXT, + tries INTEGER NOT NULL DEFAULT 0, -- consecutive reviews that ended in a retry: error; the third becomes held PRIMARY KEY (repo, number) ); --- What the filing step did with each finding of a review (review_at identifies the review). state: filed | skipped-duplicate | skipped-limit | skipped-minor. +-- What the filing step did with each finding of a review (review_at identifies the review). +-- state: filing (written before gh issue create runs; one left in this state has an unknown outcome and is never retried) | filed | +-- failed (gh refused with no possible side effect; attempts counts the tries, retried after 1 h and then 6 h, three at most) | +-- skipped-duplicate (duplicate_of: the PR or issue number that covers it) | skipped-limit | skipped-minor | skipped-stale (the cited file is gone). -- A skipped-limit row is replaced when the finding is filed later. CREATE TABLE IF NOT EXISTS postmerge_followups ( repo TEXT NOT NULL, number INTEGER NOT NULL, @@ -1078,6 +1082,9 @@ CREATE TABLE IF NOT EXISTS postmerge_followups ( url TEXT, state TEXT NOT NULL, at TEXT NOT NULL, + duplicate_of INTEGER, + attempts INTEGER NOT NULL DEFAULT 0, + note TEXT, -- one line: why a failed attempt failed PRIMARY KEY (repo, number, review_at, finding) ); CREATE INDEX IF NOT EXISTS postmerge_followups_issue ON postmerge_followups(repo, issue_number); diff --git a/src/stages/registry.ts b/src/stages/registry.ts index a9a2ad9a2..884831257 100644 --- a/src/stages/registry.ts +++ b/src/stages/registry.ts @@ -424,7 +424,8 @@ export const STAGES: StageDef[] = [ models: [{ model: "opus", use: "Reviews each merged PR", remark: "Reads the merge commit and lists findings; the reply is linted like the Review stage's" }], promptIds: ["postmerge.opus"], promptStage: "Post-merge review", waits: [ - { name: "Failed post-merge review", why: "The model gave no valid reply twice", howLong: "1 hour", showsAs: "Post-merge review on the item page: no review yet", kind: "backoff" }, + { name: "Failed post-merge review", why: "The model gave no valid reply twice", howLong: "1 hour, three tries in all", showsAs: "Post-merge review on the item page: no review yet", kind: "backoff" }, + { name: "Failed post-merge filing", why: "GitHub refused to create the issue", howLong: "1 hour, then 6 hours; stops after three attempts", showsAs: "Post-merge review on the item page: not filed, with the attempts", kind: "backoff" }, ], writes: [{ what: "Follow-up issue", approval: "comment" }], person: "Per-repo approval", diff --git a/test/postmerge.test.ts b/test/postmerge.test.ts index 017b5476d..8e98fbc8e 100644 --- a/test/postmerge.test.ts +++ b/test/postmerge.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict"; -import { mkdirSync, mkdtempSync } from "node:fs"; +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { describe, test } from "node:test"; import type { DatabaseSync } from "node:sqlite"; @@ -9,9 +9,11 @@ import { postmergeOf } from "../src/dash/api/postmerge.ts"; import { connect } from "../src/db.ts"; import type { Exec } from "../src/fixup/git.ts"; import { inPilot, setPilot } from "../src/pilot.ts"; -import { runPostmergeFile, type FileDeps } from "../src/postmerge/file.ts"; +import { fileFinding, runPostmergeFile, type FileDeps } from "../src/postmerge/file.ts"; import { reviewOne } from "../src/postmerge/index.ts"; -import { runPostmerge, type PostmergeDeps } from "../src/postmerge/review.ts"; +import { queueBackfill, relatedOpen, runPostmerge, type PostmergeDeps } from "../src/postmerge/review.ts"; +import { issueBody, issueTitle } from "../src/postmerge/template.ts"; +import { ghMerged } from "../src/review/diff.ts"; import { selectPostmerge, type FollowupState } from "../src/postmerge/select.ts"; import { useTestAccount } from "./accounts-fixture.ts"; import { SCRATCH } from "./scratch.ts"; @@ -20,7 +22,7 @@ mkdirSync(SCRATCH, { recursive: true }); const dir = mkdtempSync(join(SCRATCH, "postmerge-test-")); const DIFF = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -1,1 +1,1 @@\n-let a = 1;\n+let a = 2;\n"; -type F = { severity: string; title: string; body?: string; duplicate_of?: number | null }; +type F = { severity: string; title: string; body?: string; duplicate_of?: number | null; file?: string | null; line?: number | null }; const finding = (f: F) => ({ file: "src/lib.rs", line: 1, missed_by: "review", missed_why: "not read", body: `${f.title}: body`, duplicate_of: null, ...f }); /** Repo `app` with PR 1 merged by the pipeline, commenting approved. */ @@ -50,6 +52,7 @@ function fakeGh(created: Created[], first = 50): FileDeps { let next = first; return { now: () => new Date(), + fileExists: async () => true, exec: (async (_cmd, args, opts) => { created.push({ args, input: opts?.input }); return { code: 0, stdout: `https://github.com/storytold/app/issues/${next++}\n`, stderr: "" }; @@ -187,3 +190,234 @@ describe("item API", () => { assert.equal(other.findings[0]!.filing.state, "pending"); }); }); + +const nowIn = (deps: FileDeps, ms: number): FileDeps => ({ ...deps, now: () => new Date(Date.now() + ms) }); +const lost: Exec = async () => ({ code: 1, stdout: "", stderr: "error connecting to api.github.com" }); +const refused: Exec = async () => ({ code: 1, stdout: "", stderr: "GraphQL: Repository has disabled issues. (HTTP 410)" }); +const withExec = (created: Created[], exec: Exec): FileDeps => ({ ...fakeGh(created), exec: (async (c, a, o) => { created.push({ args: a, input: o?.input }); return exec(c, a, o); }) as Exec }); + +async function reviewedWith(findings: F[]): Promise { + const db = fresh(); + const restore = setRunner(fakeModel([], findings)); + try { await runPostmerge(db, { repo: "app" }, () => {}, deps); } finally { restore(); } + return db; +} + +describe("filing safety", () => { + test("a lost response leaves the row in filing: never filed again, counted, shown as unknown", async () => { + const db = await reviewedWith([{ severity: "defect", title: "Stride is wrong" }]); + const created: Created[] = []; + let handled = 0; + const s = await runPostmergeFile(db, { repo: "app", onHandled: (n) => { handled = n; } }, () => {}, withExec(created, lost)); + assert.equal(created.length, 1); + assert.equal(handled, 1); + assert.equal(s.unknown.length, 1); + assert.deepEqual(states(db), ["0:filing"]); + await runPostmergeFile(db, { repo: "app" }, () => {}, nowIn(fakeGh(created), 48 * 3600_000)); + assert.equal(created.length, 1, "not tried again"); + assert.equal(postmergeOf(db, "app", 1, false)!.findings[0]!.filing.state, "unknown"); + }); + + test("a record failure after a successful create leaves filing", async () => { + const db = await reviewedWith([{ severity: "defect", title: "Stride is wrong" }]); + const created: Created[] = []; + const real = fakeGh(created); + db.exec("CREATE TRIGGER no_filed BEFORE UPDATE ON postmerge_followups WHEN NEW.state = 'filed' BEGIN SELECT RAISE(ABORT, 'disk full'); END"); + db.exec("CREATE TRIGGER no_filed2 BEFORE INSERT ON postmerge_followups WHEN NEW.state = 'filed' BEGIN SELECT RAISE(ABORT, 'disk full'); END"); + const s = await runPostmergeFile(db, { repo: "app" }, () => {}, real); + assert.equal(s.unknown.length, 1); + assert.deepEqual(states(db), ["0:filing"]); + }); + + test("a refusal by GitHub is failed with a backoff of 1 h, then 6 h, then stops after three tries", async () => { + const db = await reviewedWith([{ severity: "defect", title: "Stride is wrong" }]); + const created: Created[] = []; + await runPostmergeFile(db, { repo: "app" }, () => {}, withExec(created, refused)); + assert.deepEqual(states(db), ["0:failed"]); + await runPostmergeFile(db, { repo: "app" }, () => {}, withExec(created, refused)); + assert.equal(created.length, 1, "not retried at once"); + await runPostmergeFile(db, { repo: "app" }, () => {}, nowIn(withExec(created, refused), 2 * 3600_000)); + assert.equal(created.length, 2); + await runPostmergeFile(db, { repo: "app" }, () => {}, nowIn(withExec(created, refused), 4 * 3600_000)); + assert.equal(created.length, 2, "the second backoff is 6 h"); + await runPostmergeFile(db, { repo: "app" }, () => {}, nowIn(withExec(created, refused), 9 * 3600_000)); + assert.equal(created.length, 3); + await runPostmergeFile(db, { repo: "app" }, () => {}, nowIn(withExec(created, refused), 400 * 3600_000)); + assert.equal(created.length, 3, "stops after three"); + assert.equal(db.prepare("SELECT attempts FROM postmerge_followups").get()!.attempts, 3); + }); + + test("--again files nothing for a PR with a filed follow-up; the file command files one and the prompt lists the earlier ones", async () => { + const db = await reviewedWith([{ severity: "defect", title: "Stride is wrong" }]); + const created: Created[] = []; + await runPostmergeFile(db, { repo: "app" }, () => {}, fakeGh(created)); + const prompts: string[] = []; + const restore = setRunner(fakeModel(prompts, [{ severity: "defect", title: "Rows are cropped" }, { severity: "defect", title: "Header is skipped", file: "src/other.rs" }])); + try { await runPostmerge(db, { repo: "app", only: [1] }, () => {}, deps); } finally { restore(); } + assert.match(prompts[0]!, /"filed_before": \[\s*\{\s*"number": 50,\s*"state": "open",\s*"title": "Stride is wrong"/); + await runPostmergeFile(db, { repo: "app" }, () => {}, fakeGh(created, 60)); + assert.equal(created.length, 1); + const shown = postmergeOf(db, "app", 1, false)!; + assert.deepEqual(shown.findings.map((f) => f.filing), [{ state: "held", reason: "earlier" }, { state: "held", reason: "earlier" }]); + assert.equal(shown.earlier.length, 1); + await assert.rejects(fileFinding(db, "app#1", 5, () => {}, fakeGh(created, 60)), /no finding 5/); + const o = await fileFinding(db, "app#1", 1, () => {}, fakeGh(created, 60)); + assert.equal(o.kind, "filed"); + assert.equal(created.length, 2); + assert.equal(created[1]!.args[5], "Header is skipped"); + await assert.rejects(fileFinding(db, "app#1", 1, () => {}, fakeGh(created, 60)), /already filed/); + assert.equal(db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action = 'postmerge-file-one'").get()!.n, 1); + }); + + test("the review command refuses while a postmerge job runs for the repo", async () => { + const db = fresh(); + db.prepare("INSERT INTO jobs (step, params, requested_by, requested_at, state, repo) VALUES ('postmerge', '{}', 'pipeline', ?, 'running', 'app')").run(new Date().toISOString()); + await assert.rejects(reviewOne(db, "app#1", true, () => {}), /job is running/); + }); + + test("a defect that repeats another one in the same file, near the line, with a similar title is filed once", async () => { + const db = await reviewedWith([{ severity: "defect", title: "Stride is wrong in decode" }]); + const now = new Date().toISOString(); + db.prepare("INSERT INTO items (repo, number, kind, state, title, created_at, updated_at) VALUES ('app', 2, 'pr', 'MERGED', 'Other', ?, ?)").run(now, now); + db.prepare("INSERT INTO merges (repo, number, head_oid, run_id, at, path, method, outcome) VALUES ('app', 2, 'head2', 'm1', ?, 'rule', 'merge', 'merged')").run(now); + const f2 = [finding({ severity: "defect", title: "decode: wrong stride", line: 15 }), finding({ severity: "defect", title: "Stride is wrong in decode", line: 400 })]; + db.prepare("INSERT INTO postmerge_reviews (repo, number, merge_sha, at, model, findings) VALUES ('app', 2, 'x', ?, 'opus', ?)").run(new Date(Date.now() + 1000).toISOString(), JSON.stringify(f2)); + const created: Created[] = []; + await runPostmergeFile(db, { repo: "app" }, () => {}, fakeGh(created)); + assert.deepEqual(created.map((c) => c.args[5]), ["Stride is wrong in decode", "Stride is wrong in decode"], "the one at line 400 is a separate defect"); + const dup = db.prepare("SELECT state, duplicate_of FROM postmerge_followups WHERE number = 2 AND finding = 0").get()!; + assert.deepEqual([dup.state, dup.duplicate_of], ["skipped-duplicate", 1]); + }); + + test("a cited file that is gone from the default branch is skipped as stale", async () => { + const db = await reviewedWith([{ severity: "defect", title: "Stride is wrong" }]); + const created: Created[] = []; + await runPostmergeFile(db, { repo: "app" }, () => {}, { ...fakeGh(created), fileExists: async () => false }); + assert.equal(created.length, 0); + assert.deepEqual(states(db), ["0:skipped-stale"]); + }); + + test("a body that names the product or the pipeline account is stored and not filed", async () => { + const db = await reviewedWith([{ severity: "defect", title: "One", body: "AutoCraft left this open." }, { severity: "defect", title: "Two", body: "pipeline-bot wrote this." }, { severity: "defect", title: "Three", body: "Fine." }]); + db.prepare("INSERT INTO settings (key, value) VALUES ('pipeline_login', 'pipeline-bot')").run(); + const created: Created[] = []; + await runPostmergeFile(db, { repo: "app" }, () => {}, fakeGh(created)); + assert.deepEqual(created.map((c) => c.args[5]), ["Three"]); + assert.deepEqual(states(db), ["0:skipped-text", "1:skipped-text", "2:filed#50"]); + }); + + test("a PR that fixes a follow-up issue is not filed for automatically", async () => { + const db = await reviewedWith([{ severity: "defect", title: "Stride is wrong" }]); + const created: Created[] = []; + await runPostmergeFile(db, { repo: "app" }, () => {}, fakeGh(created)); + const now = new Date().toISOString(); + db.prepare("INSERT INTO items (repo, number, kind, state, title, created_at, updated_at) VALUES ('app', 2, 'pr', 'MERGED', 'Fix', ?, ?)").run(now, now); + db.prepare("INSERT INTO merges (repo, number, head_oid, run_id, at, path, method, outcome) VALUES ('app', 2, 'head2', 'm1', ?, 'rule', 'merge', 'merged')").run(now); + db.prepare("INSERT INTO fix_attempts (repo, number, main_sha, text_hash, state, pr_url, created_at, updated_at) VALUES ('app', 50, 'm', 'h', 'pr-opened', 'https://github.com/storytold/app/pull/2', ?, ?)").run(now, now); + const restore = setRunner(fakeModel([], [{ severity: "defect", title: "New problem" }])); + try { await runPostmerge(db, { repo: "app" }, () => {}, deps); } finally { restore(); } + await runPostmergeFile(db, { repo: "app" }, () => {}, fakeGh(created, 60)); + assert.equal(created.length, 1); + assert.deepEqual(postmergeOf(db, "app", 2, false)!.findings[0]!.filing, { state: "held", reason: "fix" }); + }); + + test("a Fix PR of a follow-up issue of a pilot PR is a pilot item", async () => { + const db = await reviewedWith([{ severity: "defect", title: "Stride is wrong" }]); + await runPostmergeFile(db, { repo: "app" }, () => {}, fakeGh([])); + setPilot(db, "op", ["app#1"]); + assert.equal(inPilot(db, "app", 2), false); + const now = new Date().toISOString(); + db.prepare("INSERT INTO fix_attempts (repo, number, main_sha, text_hash, state, pr_url, created_at, updated_at) VALUES ('app', 50, 'm', 'h', 'pr-opened', 'https://github.com/storytold/app/pull/2', ?, ?)").run(now, now); + assert.equal(inPilot(db, "app", 2), true); + assert.equal(inPilot(db, "app", 3), false); + }); +}); + +describe("review inputs", () => { + test("a failed review is given up on after three tries", async () => { + const db = fresh(); + const bad = { ...deps, fetchMerged: async () => ({ ok: false as const, tooLarge: false, error: "boom" }) }; + for (let i = 0; i < 3; i++) await runPostmerge(db, { repo: "app", only: [1] }, () => {}, bad); + assert.match(db.prepare("SELECT error FROM postmerge_reviews").get()!.error as string, /^held: gave up after 3 tries/); + assert.deepEqual(selectPostmerge(db, "app", Date.now() + 99 * 3600_000), []); + }); + + test("a batch member is asked for with the batch flag", async () => { + const db = fresh(); + const now = new Date().toISOString(); + db.prepare("INSERT INTO merge_batches (id, repo, branch, state, base_sha, commit_sha, created_at, updated_at) VALUES (1, 'app', 'integration-app-1', 'merged', 'b', 'c', ?, ?)").run(now, now); + db.prepare("INSERT INTO merge_batch_prs (batch_id, number, head_oid, position) VALUES (1, 1, 'head1', 0)").run(); + const seen: unknown[] = []; + const restore = setRunner(fakeModel([], [])); + try { await runPostmerge(db, { repo: "app" }, () => {}, { ...deps, fetchMerged: async (_r, _n, o) => { seen.push(o); return { ok: true, sha: null, text: DIFF }; } }); } finally { restore(); } + assert.deepEqual(seen, [{ batch: true }]); + }); + + test("related items include ones closed in the last 30 days, with their state", () => { + const db = fresh(); + const day = (n: number) => new Date(Date.now() - n * 86400_000).toISOString(); + const add = db.prepare("INSERT INTO items (repo, number, kind, state, title, body, closed_at, created_at, updated_at) VALUES ('app', ?, 'issue', ?, ?, 'about #1', ?, 'z', 'z')"); + add.run(5, "OPEN", "Open one", null); + add.run(6, "CLOSED", "Closed lately", day(3)); + add.run(7, "CLOSED", "Closed long ago", day(90)); + assert.deepEqual(relatedOpen(db, "app", 1, []).map((r) => [r.number, r.state]), [[5, "open"], [6, "closed"]]); + }); + + test("a backfill more than 14 days back needs --yes", () => { + const db = fresh(); + const back = (d: number) => new Date(Date.now() - d * 86400_000).toISOString(); + assert.throws(() => queueBackfill(db, "cli", back(20)), /--yes/); + assert.equal(db.prepare("SELECT value FROM settings WHERE key = 'postmerge_since'").get()!.value !== back(20), true); + assert.equal(queueBackfill(db, "cli", back(10)), 1); + assert.equal(queueBackfill(db, "cli", back(20), { yes: true }), 1); + }); +}); + +describe("merged diff", () => { + /** A fake `gh` first on PATH: `pr diff` fails when FAIL_OWN is set; everything else answers. Calls are logged. */ + function withFakeGh(failOwn: boolean, f: (log: string) => Promise): Promise { + const bin = mkdtempSync(join(dir, "bin-")), log = join(bin, "calls"); + writeFileSync(join(bin, "gh"), `#!/bin/sh +echo "$@" >> ${log} +case "$1 $2" in + "pr diff") ${failOwn ? 'echo "no diff" >&2; exit 1' : `printf '%s' 'diff --git a/src/a.rs b/src/a.rs\n--- a/src/a.rs\n+++ b/src/a.rs\n@@ -1 +1 @@\n-1\n+2\n'`} ;; + "pr view") echo ${"a".repeat(40)} ;; + *) printf '%s' 'diff --git a/src/a.rs b/src/a.rs\n--- a/src/a.rs\n+++ b/src/a.rs\n@@ -1 +1 @@\n-1\n+3\ndiff --git a/src/other.rs b/src/other.rs\n--- a/src/other.rs\n+++ b/src/other.rs\n@@ -1 +1 @@\n-1\n+2\n' ;; +esac +`); + chmodSync(join(bin, "gh"), 0o755); + const old = process.env.PATH; + process.env.PATH = `${bin}:${old}`; + return f(log).finally(() => { process.env.PATH = old; }); + } + + test("when the PR's own diff fails there is no diff, not the whole merge commit", async () => { + const r = await withFakeGh(true, () => ghMerged("app", 1)); + assert.equal(r.ok, false); + const db = fresh(); + await runPostmerge(db, { repo: "app" }, () => {}, { ...deps, fetchMerged: async () => r }); + assert.match(db.prepare("SELECT error FROM postmerge_reviews").get()!.error as string, /^retry: no merged diff/); + }); + + test("the merge commit's diff is kept to the PR's own files; a batch member is read as its own diff", async () => { + const plain = await withFakeGh(false, () => ghMerged("app", 1)); + assert.ok(plain.ok && plain.sha === "a".repeat(40)); + assert.ok(plain.ok && plain.text.includes("+3") && !plain.text.includes("other.rs")); + const member = await withFakeGh(false, async (log) => { const r = await ghMerged("app", 1, { batch: true }); return { r, calls: readFileSync(log, "utf8") }; }); + assert.ok(member.r.ok && member.r.sha === null && member.r.text.includes("+2")); + assert.doesNotMatch(member.calls, /commits\//); + }); +}); + +describe("public text", () => { + test("URLs, links, issue references and mentions go outside code and stay inside it", () => { + const body = issueBody({ number: 4, model: "opus", file: "src/a.rs", line: 3, body: + "See [the docs](https://example.com/x) or https://example.com/y and storytold/app#12, also #7 and issue #8. Ping @someone.\n\n`@keep https://example.com/z #9`\n\n```\nlet a = \"#10 @x\";\n```" }); + assert.match(body, /^_AI-generated review \(Opus\)\. Not a maintainer decision\._\n\nFollow-up to #4\.\n\n/); + assert.match(body, /See the docs or\s+and issue 12, also issue 7 and issue 8\. Ping someone\./); + assert.match(body, /`@keep https:\/\/example\.com\/z #9`/); + assert.match(body, /let a = "#10 @x";/); + assert.match(body, /Location: `src\/a\.rs:3`/); + assert.equal(issueTitle("Fix #5 in storytold/app#6 at https://x.y"), "Fix issue 5 in issue 6 at"); + }); +}); diff --git a/web/src/api/mock/verifyFixtures.ts b/web/src/api/mock/verifyFixtures.ts index bccca12de..4d591fa88 100644 --- a/web/src/api/mock/verifyFixtures.ts +++ b/web/src/api/mock/verifyFixtures.ts @@ -89,6 +89,7 @@ export function postmergeFor(n: number, kind: Item["kind"], staff: boolean): Ite return { at: iso(3 * H), model: "claude-opus-5-5", mergeSha: sha(n + 3), error: null, + earlier: [], findings: [ { severity: "defect", title: "Stride is read before the image is checked for 16-bit data", diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 8d9c72066..f1fc58418 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -317,7 +317,21 @@ export type PostmergeFiling = | { state: "duplicate"; duplicateOf: number } | { state: "limit" } | { state: "minor" } - | { state: "pending" }; + | { state: "pending" } + /** `gh issue create` was started and its answer is not recorded: the issue may exist. */ + | { state: "unknown" } + | { state: "failed"; attempts: number } + /** The file the finding cites is no longer on the default branch. */ + | { state: "stale" } + /** The text names the product or the pipeline's account. */ + | { state: "refused" } + /** Never filed automatically: `earlier` follow-ups of the PR exist, or `fix`: the PR itself fixes a follow-up issue. */ + | { state: "held"; reason: "earlier" | "fix" }; + +/** A follow-up issue filed for the PR by an earlier review of it. */ +export type PostmergeEarlier = + | { state: "filed"; title: string; issue: { number: number; url: string | null; state: ItemState | null; title: string | null } } + | { state: "unknown"; title: string }; export interface PostmergeFinding { severity: PostmergeSeverity; @@ -341,6 +355,8 @@ export interface ItemPostmerge { /** Why there is no review yet (for example too large to review); null when there is one. */ error: string | null; findings: PostmergeFinding[]; + /** Follow-ups of earlier reviews of the PR. */ + earlier: PostmergeEarlier[]; } export type FixupState = "pushed" | "failed" | "refused" | "cannot-push" | "too-large" | "asked" | "rejected"; diff --git a/web/src/modules/item/PrWork.tsx b/web/src/modules/item/PrWork.tsx index c0a8cf8c9..78f39d218 100644 --- a/web/src/modules/item/PrWork.tsx +++ b/web/src/modules/item/PrWork.tsx @@ -194,9 +194,16 @@ function Finding({ f, repo }: { f: PostmergeFinding; repo: string }) { {defect && (
{x.state === "filed" && } - {x.state === "duplicate" && Not filed: duplicate of #{x.duplicateOf}} + {x.state === "duplicate" && ( + Not filed: duplicate of + )} {x.state === "limit" && Not filed: daily limit} {x.state === "pending" && Not filed yet} + {x.state === "unknown" && Outcome unknown, check GitHub} + {x.state === "failed" && Not filed: GitHub refused it ({x.attempts} {x.attempts === 1 ? "try" : "tries"}){x.attempts < 3 ? "; tried again later" : ""}} + {x.state === "stale" && Not filed: the file is no longer on the default branch} + {x.state === "refused" && Not filed: the text names the product or the pipeline} + {x.state === "held" && {x.reason === "earlier" ? "Not filed: earlier follow-ups exist" : "Not filed: this PR fixes a follow-up issue"}}
)} {(f.missedBy || f.missedWhy) && ( @@ -229,6 +236,14 @@ function Postmerge({ p, repo }: { p: ItemPostmerge; repo: string }) { {p.mergeSha.slice(0, 7)} {ago(p.at)} ago + {p.earlier.length > 0 && ( +
+ Follow-ups of earlier reviews: + {p.earlier.map((e, i) => e.state === "filed" + ? + : {e.title}: outcome unknown, check GitHub)} +
+ )} {p.findings.length > 0 && (
    {p.findings.map((f, i) => )}