diff --git a/.github/scripts/pr-review.mjs b/.github/scripts/pr-review.mjs index 632b1df..cea3a04 100644 --- a/.github/scripts/pr-review.mjs +++ b/.github/scripts/pr-review.mjs @@ -1,6 +1,7 @@ import { spawnSync } from "node:child_process"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { join } from "node:path"; +import { mkdtempSync, readFileSync, statSync } from "node:fs"; +import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises"; +import { basename, join } from "node:path"; import { chinese, english } from "./pr-review-language.mjs"; const FILES_PER_PAGE = 100; @@ -9,6 +10,9 @@ const MAX_FILE_LENGTH = 36_000; const MAX_INLINE_FINDINGS = 6; const MAX_PREVIOUS_COMMENTS = 8; const MARKER_PREFIX = "\r?\n?/, "").trim(), 1200), inlineFindings: reviewComments.slice(0, MAX_PREVIOUS_COMMENTS).map((comment) => ({ @@ -602,11 +607,95 @@ export function configureOCR({ binary, home, language, parentEnv = process.env, return { ...baseEnv, ...credentials }; } -export async function reviewWithOCR({ binary, repo, from, to, rule, background, home, profile, language, parentEnv = process.env, processRunner = runProcess }) { +// Where OCR keeps its own state for one PR, and where the run's checkout lives. +// The key carries the PR number: one checkout holds every PR number in turn, so +// the repository directory alone means "the last run, whoever it was". +export function resumeSessionDir(settings = process.env) { + const stateDirectory = settings.PR_REVIEW_STATE_DIR; + const home = settings.PR_REVIEW_SESSION_HOME?.trim(); + return join(home || (settings.LOCALAPPDATA ? join(settings.LOCALAPPDATA, "reims-go", "pr-review") : "pr-review"), + "sessions", stateKey(stateDirectory, settings)); +} + +function stateKey(stateDirectory, settings) { + try { + const owner = JSON.parse(readFileSync(join(stateDirectory, "state.json"), "utf8")); + if (typeof owner.repository === "string" && Number.isInteger(owner.pr)) { + if (!REPOSITORY.test(owner.repository)) throw new Error("Invalid GitHub repository name"); + return owner.repository.split("/").join("-") + "-" + owner.pr; + } + } catch { + // Fall through to the checkout name. + } + return basename(settings.GITHUB_WORKSPACE || process.cwd()); +} + +// OCR names each session directory after the repository path: it strips the +// volume, trims leading separators, turns each separator into a dash and then +// puts the volume back with its colon underscored. Mirroring that is what lets +// this script find the session file it just asked OCR to keep. +export function encodeRepoPath(path) { + const volume = /^[A-Za-z]:/.exec(path)?.[0] ?? ""; + const body = path.slice(volume.length).split(/[/\\]+/).filter(Boolean).join("-"); + return volume.replace(":", "_") + body || "empty"; +} + +// The last session this script asked OCR to keep, and the range it covers. +// A record that cannot be read simply starts a full review again. +export function readResumeState(stateDirectory) { + try { + const record = JSON.parse(readFileSync(join(stateDirectory, RESUME_STATE_FILE), "utf8")); + return record && typeof record.session === "string" && typeof record.from === "string" && typeof record.to === "string" ? record : null; + } catch { + return null; + } +} + +// The record names the session and the commit range it was computed over. The +// session file must still exist: a cleaned-up record must not send OCR looking +// for a session that is gone. +export function revalidationOf(record, range, home, repo) { + if (!record || record.from !== range.from || record.to !== range.to || typeof record.session !== "string" || !record.session) return null; + try { + if (!statSync(join(home, ".opencodereview", "sessions", encodeRepoPath(repo), record.session + ".jsonl")).isFile()) return null; + } catch { + return null; + } + return record.session; +} + +// Only the session this run leaves behind is worth keeping; older records of +// the same PR still hold reviewed file content. +async function deleteOldSessions(home, repo, session) { + const directory = join(home, ".opencodereview", "sessions", encodeRepoPath(repo)); + let names = []; + try { + names = await readdir(directory); + } catch { + return; + } + for (const name of names) { + if (name === session + ".jsonl" || name.endsWith(".lock")) continue; + await rm(join(directory, name), { force: true, recursive: true }); + } + // Earlier session files of this PR still hold reviewed file content. + if (process.env.PR_REVIEW_KEEP_SESSIONS === "true") return; + for (const name of names) { + if (/^[0-9a-f-]{36}\.jsonl$/.test(name) && name !== session + ".jsonl") await rm(join(directory, name), { force: true }); + } +} + +export async function writeResumeState(stateDirectory, record) { + await mkdir(stateDirectory, { recursive: true }); + await writeFile(join(stateDirectory, RESUME_STATE_FILE), JSON.stringify(record) + "\n"); +} + +export async function reviewWithOCR({ binary, repo, from, to, rule, background, home, profile, language, resume, parentEnv = process.env, processRunner = runProcess }) { const env = configureOCR({ binary, home, language, parentEnv, processRunner }); const args = ["review", "--repo", repo, "--from", from, "--to", to, "--rule", rule, "--background-file", background, "--format", "json", "--audience", "agent", "--effort", profile.effort, "--concurrency", String(profile.concurrency), "--timeout", "10", "--max-tokens-budget", String(profile.maxTokensBudget)]; + if (resume) args.push("--resume", resume); const result = processRunner(binary, args, { cwd: home, env, timeout: 1_500_000 }); if (result.error || result.status !== 0) { // OCR exits non-zero when any item hits a provider error or timeout, but still emits the completed items. @@ -669,8 +758,14 @@ async function prepareGitWorkspace({ repo, home, repository, number, pull, token if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) throw new Error("Invalid GitHub repository name"); const env = isolatedEnvironment(home); const fetchEnv = gitEnvironment(home, token); + const source = "https://github.com/" + repository + ".git"; git(repo, ["init", "--quiet", "--template="], env); - git(repo, ["remote", "add", "origin", "https://github.com/" + repository + ".git"], env); + // The checkout survives between runs, so the remote is usually already there. + if (git(repo, ["remote"], env).stdout.split(/\r?\n/).some((name) => name.trim() === "origin")) { + git(repo, ["remote", "set-url", "origin", source], env); + } else { + git(repo, ["remote", "add", "origin", source], env); + } let headRef = headSha; const fetchRange = (depth) => git(repo, ["fetch", "--no-tags", "--no-recurse-submodules", depth, "origin", baseSha, headRef], fetchEnv); try { @@ -767,6 +862,15 @@ export async function run() { return; } const isManual = !event.pull_request; + // A review that stopped short still settled some files, and its findings were + // already published. It can be continued only for the very same revision: a + // new push moves the range, and a resumed run must review exactly the range + // its checkpoints were computed over. Anything else starts a full review. + const resumePrevious = process.env.PR_REVIEW_REUSE_INCOMPLETE === "true" && history.previousReview?.incomplete === true + && (history.previousReview.headSha ?? "").toLowerCase() === pull.head.sha.toLowerCase(); + // An incomplete review never anchors an incremental run: it did not finish the + // range it started, so a later commit range would leave that work undone. + const rangePrevious = history.previousReview && (!history.previousReview.incomplete || resumePrevious) ? history.previousReview : null; const headCommitMessage = !isManual && pull.draft ? "" : await fetchHeadCommitMessage(github, repoPath, pull.head.sha); const skipReason = shouldSkipAutoReview({ isManual, draft: Boolean(pull.draft), commitMessage: headCommitMessage }); if (skipReason) { @@ -782,18 +886,29 @@ export async function run() { console.log("This PR revision has already been reviewed"); return; } - const runnerTemp = required("RUNNER_TEMP"); const trustedRoot = process.cwd(); const rule = join(trustedRoot, ".opencodereview", "rule.json"); const ruleConfig = JSON.parse(await readFile(rule, "utf8")); if (!Array.isArray(ruleConfig.exclude) || !ruleConfig.exclude.every((item) => typeof item === "string")) throw new Error("Invalid trusted OCR exclude rules"); - const repo = await mkdtemp(join(runnerTemp, "pr-repo-")); - let home; - try { - home = await mkdtemp(join(runnerTemp, "pr-review-home-")); + const stateDirectory = required("PR_REVIEW_STATE_DIR"); + await mkdir(stateDirectory, { recursive: true }); + await writeFile(join(stateDirectory, "state.json"), JSON.stringify({ repository, pr: number }) + "\n"); + // Whatever this run replaces goes first: an aborted run leaves a checkout + // whose worktree may not match the new commits. + if (process.env.PR_REVIEW_FRESH_STATE === "true") { + await rm(join(resumeSessionDir(), "repo"), { recursive: true, force: true }); + await rm(join(resumeSessionDir(), "home"), { recursive: true, force: true }); + } + // The checkout and the OCR home survive between runs so a review that stopped + // short continues instead of paying for the same files again. The OCR config + // records how to read the token (printenv), never the token itself. + const repo = join(resumeSessionDir(), "repo"); + const home = join(resumeSessionDir(), "home"); + await mkdir(repo, { recursive: true }); + await mkdir(home, { recursive: true }); const workspace = await prepareGitWorkspace({ repo, home, repository, number, pull, token }); const range = await selectReviewRange({ - previousReview: history.previousReview, isManual, baseSha: pull.base.sha, headSha: pull.head.sha, + previousReview: rangePrevious, isManual, baseSha: pull.base.sha, headSha: pull.head.sha, mergeBase: workspace.mergeBase, fetchCheckpoint: workspace.fetchCheckpoint, isAncestor: workspace.isAncestor, }); const stats = effectiveDiffStats(git(repo, ["diff", "--numstat", "--no-renames", "-z", range.from, range.to, "--"], workspace.env).stdout, ruleConfig.exclude); @@ -807,11 +922,31 @@ export async function run() { const background = join(home, "background.md"); await writeFile(background, backgroundText({ pull, mainline, goVersion, previousReview: history.previousReview, guidelines, designGuidelines }), { mode: 0o600 }); console.log("Running OpenCodeReview: " + profile.tier + ", " + stats.files + " effective files, " + stats.lines + " changed lines" + (range.incremental ? ", incremental" : "")); - const assessment = await reviewWithOCR({ - binary: required("PR_REVIEW_OCR_BIN"), repo, from: range.from, to: range.to, rule, background, home, profile, language, - }); - console.log("OpenCodeReview finished: " + assessment.status + ", " + (Number(assessment.summary?.total_tokens) || 0) - + " of " + profile.maxTokensBudget + " budgeted tokens"); + // A partial review records which files it settled. Continuing it reuses + // those verdicts and spends the next budget on the files it never reached. + // Resuming keeps the range, which is why an explicitly reused incomplete + // review continues over the range that produced it. + const earlier = resumePrevious ? revalidationOf(readResumeState(stateDirectory), range, home, repo) : null; + let assessment; + let resumed = 0; + for (;;) { + const session = resumed === 0 ? earlier : revalidationOf(readResumeState(stateDirectory), range, home, repo); + if (resumed > 0 && !session) break; + assessment = await reviewWithOCR({ + binary: required("PR_REVIEW_OCR_BIN"), repo, from: range.from, to: range.to, rule, background, home, profile, language, resume: session, + }); + console.log("OpenCodeReview finished: " + assessment.status + ", " + (Number(assessment.summary?.total_tokens) || 0) + + " of " + profile.maxTokensBudget + " budgeted tokens" + (session ? " (resumed)" : "")); + if (assessment.session_id) { + await writeResumeState(stateDirectory, { session: assessment.session_id, from: range.from, to: range.to }); + } + const settled = assessment.status === "complete" || assessment.status === "success"; + if (settled || resumed >= MAX_OCR_CONTINUATIONS || !assessment.session_id) break; + if (assessment.status === "skipped" || assessment.status === "failed") break; + resumed++; + console.log("Continuing the review from session " + assessment.session_id); + } + if (assessment.session_id) await deleteOldSessions(home, repo, assessment.session_id); const locations = new Map(); for (const file of files) { const anchors = diffAnchors(file.patch); @@ -869,9 +1004,6 @@ export async function run() { if (comments.length) review.comments = comments; await postReview(github, path, review, copy, currentPR); console.log("Review submitted"); - } finally { - await Promise.all([repo, home].filter(Boolean).map((directory) => rm(directory, { recursive: true, force: true }))); - } } if (process.argv[1]?.endsWith("pr-review.mjs")) { diff --git a/.github/scripts/pr-review.test.mjs b/.github/scripts/pr-review.test.mjs index b2e3577..c17c03c 100644 --- a/.github/scripts/pr-review.test.mjs +++ b/.github/scripts/pr-review.test.mjs @@ -15,7 +15,12 @@ import { githubRequest, hasSkipCIToken, normalizeLLMBaseURL, + encodeRepoPath, parseOCRJSON, + readResumeState, + resumeSessionDir, + revalidationOf, + writeResumeState, postReview, reviewProfile, reviewSummary, @@ -143,7 +148,9 @@ test("bot login is configurable and previous marker exposes the reviewed head an const defaultBot = extractPreviousReview(reviews.slice(0, 1)); assert.equal(defaultBot.headSha, A); const partial = { ...reviews[0], body: marker(A).replace("} -->", ",\"incomplete\":true} -->") + "\npartial review" }; - assert.equal(extractPreviousReview([partial]).headSha, null); + const partialReview = extractPreviousReview([partial]); + assert.equal(partialReview.incomplete, true); + assert.equal(partialReview.headSha, A); }); test("incremental checkpoint accepts linear history and compatible base advancement", async () => { @@ -460,3 +467,63 @@ test("GitHub non-422 failures are not swallowed", async () => { throw Object.assign(new Error("denied"), { status: 403 }); }, "/pulls/1", { comments: [{}] }, chinese), /denied/); }); + +test("a resumed OCR review passes the session id and keeps its full budget", async (t) => { + const fake = await fakeOCR(t); + await mkdir(join(fake.directory, "home"), { recursive: true }); + await reviewWithOCR(ocrOptions(fake, { resume: "11111111-2222-3333-4444-555555555555" })); + const review = (await recordedCalls(fake.record)).at(-1); + assert.deepEqual(review.args.slice(-2), ["--resume", "11111111-2222-3333-4444-555555555555"]); + assert.equal(review.args[review.args.indexOf("--max-tokens-budget") + 1], "400000"); + const fresh = await fakeOCR(t); + await mkdir(join(fresh.directory, "home"), { recursive: true }); + await reviewWithOCR(ocrOptions(fresh)); + assert.equal((await recordedCalls(fresh.record)).at(-1).args.includes("--resume"), false); +}); + +test("OCR session directories mirror the repository path", () => { + assert.equal(encodeRepoPath("/home/runner/work/repo"), "home-runner-work-repo"); + assert.equal(encodeRepoPath("D:\\a\\repo"), "D_a-repo"); + assert.equal(encodeRepoPath("D:/a/repo"), "D_a-repo"); + assert.equal(encodeRepoPath(""), "empty"); +}); + +test("a resume record applies only to the range and file it was computed over", async (t) => { + const home = await tempDirectory(t, "ocr-home-"); + const repo = join(home, "checkout"); + const session = "11111111-2222-3333-4444-555555555555"; + const directory = join(home, ".opencodereview", "sessions", encodeRepoPath(repo)); + await mkdir(directory, { recursive: true }); + const range = { from: A, to: B }; + const record = { session, from: A, to: B }; + assert.equal(revalidationOf(record, range, home, repo), null, "a record whose session file is gone must not resume"); + await writeFile(join(directory, session + ".jsonl"), "{}\n"); + assert.equal(revalidationOf(record, range, home, repo), session); + assert.equal(revalidationOf({ ...record, to: C }, range, home, repo), null); + assert.equal(revalidationOf({ ...record, from: C }, range, home, repo), null); + assert.equal(revalidationOf(null, range, home, repo), null); + await writeResumeState(join(home, "state"), record); + assert.deepEqual(readResumeState(join(home, "state")), record); + assert.equal(readResumeState(join(home, "missing")), null); +}); + +test("each pull request gets its own review state", async (t) => { + const directory = await tempDirectory(t, "ocr-state-"); + await writeFile(join(directory, "state.json"), JSON.stringify({ repository: "Nwflower/Reims-Go", pr: 163 })); + const dir = resumeSessionDir({ PR_REVIEW_STATE_DIR: directory, PR_REVIEW_SESSION_HOME: join(directory, "home") }); + assert.equal(dir, join(directory, "home", "sessions", "Nwflower-Reims-Go-163")); + const other = await tempDirectory(t, "ocr-state-"); + await writeFile(join(other, "state.json"), "not json"); + assert.equal(resumeSessionDir({ PR_REVIEW_STATE_DIR: other, PR_REVIEW_SESSION_HOME: join(other, "home"), GITHUB_WORKSPACE: "/w/repo" }), + join(other, "home", "sessions", "repo")); +}); + +test("an incomplete previous review is recognised and never anchors an incremental range", () => { + const marker = ''; + const reviews = [{ user: { login: "reims-go-reviewer[bot]" }, state: "COMMENTED", commit_id: B, body: marker + "\n## 自动代码审核" }]; + const previous = extractPreviousReview(reviews, [], "reims-go-reviewer[bot]"); + assert.equal(previous.incomplete, true); + assert.equal(previous.headSha, B); + const complete = [{ user: { login: "reims-go-reviewer[bot]" }, state: "COMMENTED", commit_id: B, body: marker.replace(',"incomplete":true', '') + "\n## 自动代码审核" }]; + assert.equal(extractPreviousReview(complete, [], "reims-go-reviewer[bot]").incomplete, false); +}); diff --git a/.github/workflows/pr-review.yml b/.github/workflows/pr-review.yml index 0d08873..d9f322b 100644 --- a/.github/workflows/pr-review.yml +++ b/.github/workflows/pr-review.yml @@ -59,6 +59,21 @@ jobs: path: ${{ runner.temp }}/ocr-bin key: opencodereview-${{ env.OCR_VERSION }}-${{ env.OCR_SHA256 }} + # Keep the OCR session records and the checkout between runs. A review + # that stops at its token budget continues from here on the next run + # instead of paying for the same files again. + - name: Cache PR review state + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4 + with: + path: ${{ runner.temp }}/pr-review-state + key: pr-review-state-${{ github.repository }}-${{ github.event.pull_request.number || inputs.pull_number }}-${{ github.run_id }} + restore-keys: | + pr-review-state-${{ github.repository }}-${{ github.event.pull_request.number || inputs.pull_number }}- + + - name: Ensure PR review state directories + shell: bash + run: mkdir -p "$RUNNER_TEMP/pr-review-state" "$RUNNER_TEMP/pr-review-state/sessions" "$RUNNER_TEMP/pr-review-state/repos" + - name: Download OpenCodeReview if: steps.ocr-cache.outputs.cache-hit != 'true' shell: bash @@ -86,4 +101,7 @@ jobs: PR_REVIEW_LLM_PROTOCOL: ${{ vars.PR_REVIEW_LLM_PROTOCOL || 'anthropic' }} PR_REVIEW_LLM_EXTRA_BODY: ${{ vars.PR_REVIEW_LLM_EXTRA_BODY }} PR_REVIEW_CODE_SUGGESTIONS: ${{ vars.PR_REVIEW_CODE_SUGGESTIONS }} + PR_REVIEW_STATE_DIR: ${{ runner.temp }}/pr-review-state + PR_REVIEW_SESSION_HOME: ${{ runner.temp }}/pr-review-state + PR_REVIEW_REUSE_INCOMPLETE: "true" run: node .github/scripts/pr-review.mjs