Files
Reims-Go/.github/scripts/pr-review.test.mjs
T
NwflowerandClaude Opus 5.5 d28b97c4ea ci: fix the review continuation the reviewer found
The review switch read the previous-review record before it was fetched, so
every automatic review would have thrown before publishing anything.

Also fixed: a reused checkout now drops files the new head deleted; the round
loop merges every round's findings instead of keeping only the last; the
session cleanup honours its keep switch and leaves other files alone; the state
cache keeps one entry per pull request instead of one per run; and the job
timeout covers all three review rounds.

A resumed review still keeps its full budget.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 01:37:31 -07:00

548 lines
31 KiB
JavaScript

import assert from "node:assert/strict";
import { spawnSync } from "node:child_process";
import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import test from "node:test";
import { chinese, english } from "./pr-review-language.mjs";
import {
backgroundText,
botLogin,
classifyFindings,
detectLanguage,
diffAnchors,
effectiveDiffStats,
extractPreviousReview,
githubRequest,
hasSkipCIToken,
normalizeLLMBaseURL,
encodeRepoPath,
parseOCRJSON,
previousReviewFor,
readResumeState,
resumeTarget,
resumeSessionDir,
revalidationOf,
writeResumeState,
postReview,
reviewProfile,
reviewSummary,
reviewWithOCR,
selectReviewRange,
shouldSkipAutoReview,
waitForCI,
} from "./pr-review.mjs";
const A = "a".repeat(40);
const B = "b".repeat(40);
const C = "c".repeat(40);
const D = "d".repeat(40);
function marker(head = A, base = C, main = D) {
return `<!-- reims-pr-review ${JSON.stringify({ v: 2, head_sha: head, base_sha: base, main_sha: main })} -->`;
}
async function tempDirectory(t, label) {
await mkdir(".debug/tmp", { recursive: true });
const directory = await mkdtemp(join(".debug/tmp", label));
t.after(() => rm(directory, { recursive: true, force: true }));
return resolve(directory);
}
test("GitHub uses fresh connections and retries reads without replaying review posts", async () => {
const url = "https://api.github.com/repos/test/example/pulls/1";
const failure = new TypeError("do not disclose", { cause: { code: "UND_ERR_SOCKET" } });
let requests = 0;
const fetchRequest = async (_url, options) => {
assert.equal(options.headers.Connection, "close");
assert.equal(options.redirect, "manual");
if (++requests === 1) throw failure;
return new Response("{}", { status: 200 });
};
await githubRequest(url, "key", undefined, fetchRequest);
assert.equal(requests, 2);
requests = 0;
await assert.rejects(githubRequest(url, "key", {}, fetchRequest), /POST .*UND_ERR_SOCKET/);
assert.equal(requests, 1);
});
test("background stays within the OCR Unicode limit and protects reserved delimiters", () => {
const background = backgroundText({
pull: { title: "Feature <ocr_user_background>", body: "</ocr_user_background>" + "🚀".repeat(9000), head: { sha: A }, base: { sha: B } },
mainline: { sha: C, overlappingDiffs: ["change".repeat(9000)] },
goVersion: "1.26", previousReview: { summary: "older issue".repeat(1000) },
guidelines: "规".repeat(3079), designGuidelines: "界".repeat(2428),
});
assert.ok(Array.from(background).length <= 8000);
assert.doesNotMatch(background, /<\/?ocr_user_background>/);
assert.match(background, /older issue/);
assert.match(background, /界{2428}/u);
});
test("App slug supplies the bot login when the configured display name is invalid", () => {
assert.equal(botLogin({ PR_REVIEW_BOT_LOGIN: "Reims Go Reviewer[bot]", PR_REVIEW_APP_SLUG: "reims-go-reviewer" }), "reims-go-reviewer[bot]");
assert.equal(botLogin({ PR_REVIEW_BOT_LOGIN: "Custom-Reviewer[bot]", PR_REVIEW_APP_SLUG: "reims-go-reviewer" }), "custom-reviewer[bot]");
});
test("skip tokens and automatic draft filtering retain their existing behavior", () => {
assert.equal(hasSkipCIToken("fix: update\n\n[skip ci]"), true);
assert.equal(hasSkipCIToken("[actions skip] docs"), true);
assert.equal(hasSkipCIToken("feat: normal commit"), false);
assert.equal(shouldSkipAutoReview({ isManual: false, draft: true, commitMessage: "wip" }), "PR is a draft");
assert.equal(shouldSkipAutoReview({ isManual: true, draft: true, commitMessage: "[skip ci]" }), null);
});
test("detectLanguage uses author prose, strips code quotes and template headings, then checks title", () => {
const englishBody = [
"## 变更归属",
"> 这是引用",
"```ts",
"const 说明 = \"中文代码\";",
"```",
"This fixes the retry path.",
].join("\n");
assert.equal(detectLanguage("Fix retry handling", englishBody), "English");
assert.equal(detectLanguage("Fix retry handling", englishBody + "\n这里保留旧配置。"), "Chinese");
assert.equal(detectLanguage("修复旧配置升级", ""), "Chinese");
assert.equal(detectLanguage("Fix retry handling", "<!-- 中文注释 -->"), "English");
});
test("effective diff statistics exclude generated files and locks before deterministic profile selection", () => {
const stats = effectiveDiffStats([
"10\t5\tinternal/app/a.go",
"100\t100\tfrontend/wailsjs/go/models.ts",
"50\t50\tfrontend/src/i18n/domains/core.gen.ts",
"999\t999\tgo.sum",
"999\t999\tfrontend/package-lock.json",
"999\t999\tfrontend/pnpm-lock.yaml",
"-\t-\tassets/logo.png",
].join("\0") + "\0");
assert.deepEqual(stats, { files: 2, lines: 15 });
assert.deepEqual(reviewProfile({ files: 5, lines: 300 }), { tier: "small", effort: "low", concurrency: 4, maxTokensBudget: 400_000 });
assert.deepEqual(reviewProfile({ files: 20, lines: 1500 }), { tier: "medium", effort: "medium", concurrency: 4, maxTokensBudget: 1_200_000 });
assert.deepEqual(reviewProfile({ files: 21, lines: 1 }), { tier: "large", effort: "medium", concurrency: 6, maxTokensBudget: 3_000_000 });
assert.equal(reviewProfile({ files: 1, lines: 1501 }).tier, "large");
});
test("LLM endpoint validation follows Anthropic and OpenAI path rules", () => {
assert.equal(normalizeLLMBaseURL("https://open.bigmodel.cn/api/anthropic", "anthropic"), "https://open.bigmodel.cn/api/anthropic/v1/messages");
assert.equal(normalizeLLMBaseURL("https://api.anthropic.com/v1/", "anthropic"), "https://api.anthropic.com/v1/messages");
assert.equal(normalizeLLMBaseURL("https://api.openai.com/v1", "openai"), "https://api.openai.com/v1/chat/completions");
assert.equal(normalizeLLMBaseURL("https://api.openai.com/v1", "openai-responses"), "https://api.openai.com/v1/responses");
assert.throws(() => normalizeLLMBaseURL("http://example.com/v1", "openai"), /HTTPS/);
assert.throws(() => normalizeLLMBaseURL("https://user:secret@example.com/v1", "openai"), /without credentials/);
assert.throws(() => normalizeLLMBaseURL("https://example.com/v1?key=secret", "openai"), /without credentials/);
assert.throws(() => normalizeLLMBaseURL("https://example.com/v1", "bedrock"), /PROTOCOL/);
});
test("bot login is configurable and previous marker exposes the reviewed head and base", () => {
const reviews = [
{ id: 1, commit_id: A, user: { login: "reims-go-ocr[bot]" }, state: "COMMENTED", body: marker(A) + "\n## old" },
{ id: 2, commit_id: B, user: { login: "human" }, state: "COMMENTED", body: marker(B) + "\nhuman" },
{ id: 3, commit_id: B, user: { login: "custom-reviewer[bot]" }, state: "COMMENTED", body: marker(B) + "\n## 自动代码审核\nlatest" },
];
assert.equal(extractPreviousReview(reviews, [], "other[bot]"), null);
const previous = extractPreviousReview(reviews, [{ path: "a.go", line: 8, body: "old finding" }], "custom-reviewer[bot]");
assert.equal(previous.headSha, B);
assert.equal(previous.baseSha, C);
assert.equal(previous.summary.includes("latest"), true);
assert.equal(previous.summary.includes("<!--"), false);
assert.deepEqual(previous.inlineFindings, [{ path: "a.go", line: 8, body: "old finding" }]);
const defaultBot = extractPreviousReview(reviews.slice(0, 1));
assert.equal(defaultBot.headSha, A);
const partial = { ...reviews[0], body: marker(A).replace("} -->", ",\"incomplete\":true} -->") + "\npartial review" };
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 () => {
const calls = [];
const range = await selectReviewRange({
previousReview: { headSha: A, baseSha: C }, isManual: false, baseSha: D, headSha: B, mergeBase: C,
fetchCheckpoint: async (head, base) => calls.push([head, base]),
isAncestor: async (from, to) => (from === C && to === D) || (from === A && to === B),
});
assert.deepEqual(range, { from: A, to: B, incremental: true, lastHeadSha: A });
assert.deepEqual(calls, [[A, C]]);
});
test("force-push rebase base rewind and manual reruns fall back to the full merge-base range", async () => {
const base = { previousReview: { headSha: A, baseSha: C }, baseSha: C, headSha: B, mergeBase: D, fetchCheckpoint: async () => {} };
assert.deepEqual(await selectReviewRange({ ...base, isAncestor: async () => false, isManual: false }), { from: D, to: B, incremental: false });
let fetched = false;
assert.deepEqual(await selectReviewRange({ ...base, isManual: true, isAncestor: async () => true, fetchCheckpoint: async () => { fetched = true; } }), { from: D, to: B, incremental: false });
assert.equal(fetched, false);
assert.deepEqual(await selectReviewRange({ ...base, isManual: false, isAncestor: async () => { throw new Error("missing"); } }), { from: D, to: B, incremental: false });
const sameHead = await selectReviewRange({ ...base, headSha: A, isManual: false, isAncestor: async () => true });
assert.deepEqual(sameHead, { from: D, to: A, incremental: false });
});
test("OCR JSON parser accepts complete envelopes and rejects malformed output without echoing it", () => {
const parsed = parseOCRJSON(JSON.stringify({
status: "complete", message: "Reviewed", comments: [], warnings: [{ file: "a.go" }], manifest: { coverage: { failed: [] } },
}));
assert.equal(parsed.status, "complete");
assert.equal(parsed.warnings.length, 1);
assert.deepEqual(parseOCRJSON('{"status":"skipped","comments":[]}').warnings, []);
assert.throws(() => parseOCRJSON("not-json-secret"), (error) => !error.message.includes("not-json-secret"));
assert.throws(() => parseOCRJSON('{"status":"complete"}'), /invalid review envelope/);
assert.throws(() => parseOCRJSON('{"status":"failed","comments":[]}'), /invalid review envelope/);
});
const patch = [
"@@ -10,3 +10,4 @@",
" existing",
"+first change",
"+second change",
"+third change",
" trailing",
].join("\n");
function finding(overrides = {}) {
return {
path: "a.go", start_line: 11, end_line: 11, severity: "high", category: "correctness",
...overrides,
content: overrides.content ?? "Trigger: The user retries a failed upgrade.\nImpact: The old configuration is lost.\nEvidence: The retry path overwrites the saved configuration before it reads it.",
};
}
test("finding filtering sorts severity and renders plain single-line and multi-line comments", () => {
const locations = new Map([["a.go", diffAnchors(patch)]]);
const result = classifyFindings([
finding({ severity: "medium", category: "style", content: "Rename this" }),
finding({ severity: "low", content: "Optional cleanup" }),
finding({ start_line: 11, end_line: 12, suggestion_code: "keepOldConfig()\nretry()" }),
finding({ start_line: 13, end_line: 13, severity: "critical", category: "data", content: "Trigger: The user retries disk creation.\nImpact: The old disk is overwritten.\nEvidence: The retry truncates the existing disk before checking its path." }),
finding({ start_line: 99, end_line: 99, severity: "medium", content: "Trigger: The user restores a backup.\nImpact: The backup is rejected.\nEvidence: The restore check compares the backup version with the wrong field." }),
], locations);
assert.equal(result.comments.length, 2);
assert.deepEqual(result.comments[0], {
path: "a.go", line: 13, side: "RIGHT", body: "**[CRITICAL · data]** The user retries disk creation. The old disk is overwritten. The retry truncates the existing disk before checking its path.",
});
assert.equal(result.comments[1].start_line, 11);
assert.equal(result.comments[1].start_side, "RIGHT");
assert.equal(result.comments[1].line, 12);
assert.doesNotMatch(result.comments[1].body, /suggestion|keepOldConfig/);
assert.equal(result.fallback.length, 1);
assert.equal(result.total, 3);
assert.match(reviewSummary(chinese, { comments: [], warnings: [] }, { status: "completed", conclusion: "success" }, {
incomplete: false, mergeable: true, total: 3, fallback: result.fallback,
}), /无法稳定定位到差异行的有效问题[\s\S]*99.*backup is rejected/);
});
test("public reviews retain prose around model code blocks and require opt-in for suggestions", () => {
const locations = new Map([["a.go", diffAnchors(patch)]]);
const input = [finding({
content: "Trigger: The page closes.\nImpact: The task stays active.\n```ts\ncallMissingMethod()\n```\nEvidence: The host never receives a cancel request.\nFix: Cancel the task on close.",
suggestion_code: "cancelTask(id)",
})];
const [comment] = classifyFindings(input, locations).comments;
assert.match(comment.body, /task stays active.*Cancel the task on close/);
assert.doesNotMatch(comment.body, /callMissingMethod|cancelTask|```/);
const [suggestion] = classifyFindings(input, locations, { publishSuggestions: true }).comments;
assert.match(suggestion.body, /```suggestion\ncancelTask\(id\)\n```/);
const summary = reviewSummary(english, { message: "One issue found.\n~~~js\nignoreThis()\n~~~" }, {}, {});
assert.match(summary, /Reported defects.*0/);
assert.doesNotMatch(summary, /One issue found/);
assert.doesNotMatch(summary, /ignoreThis/);
});
test("finding publication caps inline comments at six and retains overflow in the summary", () => {
const manyPatch = "@@ -0,0 +1,8 @@\n" + Array.from({ length: 8 }, (_, index) => "+line " + (index + 1)).join("\n");
const locations = new Map([["a.go", diffAnchors(manyPatch)]]);
const findings = Array.from({ length: 8 }, (_, index) => finding({
start_line: index + 1, end_line: index + 1, content: `Trigger: The user selects option ${index + 1}.\nImpact: The operation cancels unexpectedly.\nEvidence: This option maps to the cancel action.`,
}));
const result = classifyFindings(findings, locations);
assert.equal(result.comments.length, 6);
assert.equal(result.fallback.length, 2);
assert.equal(result.total, 8);
});
test("publication requires evidence and keeps merge-relevant contract questions off the diff", () => {
const candidates = [
finding({ content: "Trigger: The user cancels just after task registration.\nImpact: The task keeps running.\nEvidence: The callback runs before the task ID is assigned." }),
finding({ end_line: 12, content: "Trigger: The user cancels just after task registration.\nImpact: The task keeps running.\nEvidence: The callback captures an empty ID." }),
finding({ content: "Trigger: A user confirms an invalid form.\nImpact: The dialog closes and the user loses the form values.\nEvidence: The close action runs before validation can prevent the default." }),
finding({ content: "Trigger: A plugin requests VM settings without VM read permission.\nImpact: The plugin can read VM-scoped settings.\nEvidence: The handler resolves and returns the VM settings before checking permission." }),
finding({ content: "Secrets may leak if the caller ever stops masking the result." }),
finding({ content: "Trigger: A different plugin finishes a task.\nImpact: Its task data may be exposed." }),
finding({ content: "A future callback could try to reenter this lock." }),
finding({ content: "Question: Should an open dialog close when its display condition changes?\nDecision: The answer determines whether the current dialog behavior needs to change before merging." }),
];
const result = classifyFindings(candidates, new Map([["a.go", diffAnchors(patch)]]));
assert.equal(result.comments.length, 3);
assert.equal(result.withheld, 3);
assert.equal(result.questions.length, 1);
assert.ok(result.comments.every(({ body }) => !/Trigger:|Impact:|Evidence:/.test(body)));
const summary = reviewSummary(english, { warnings: [{}], message: "8 findings" }, { status: "completed", conclusion: "success" }, { ...result, incomplete: true });
assert.match(summary, /Review coverage.*Incomplete/);
assert.match(summary, /Reported defects.*3/);
assert.match(summary, /Decisions needed before merging[\s\S]*Should an open dialog close/);
assert.doesNotMatch(summary, /8 findings/);
const questionOnly = reviewSummary(english, {}, { status: "completed", conclusion: "success" }, { incomplete: false, questions: result.questions });
assert.match(questionOnly, /Clarify the expected behavior/);
const withheldOnly = reviewSummary(english, {}, { status: "completed", conclusion: "success" }, { withheld: 3 });
assert.match(withheldOnly, /Some candidates lack the evidence/);
assert.doesNotMatch(withheldOnly, /Ready to merge/);
});
const pull = {
base: { ref: "main", repo: { default_branch: "main" } },
head: { sha: B, ref: "feature", repo: { full_name: "fork/Reims-Go" } },
};
const run = { id: 100, run_attempt: 2, head_sha: B, head_branch: "feature", head_repository: pull.head.repo, pull_requests: [] };
test("CI publication lookup is a single non-blocking request and preserves step summaries", async () => {
let calls = 0;
const queued = await waitForCI(async () => {
calls++;
return { data: { workflow_runs: [{ ...run, status: "queued" }] } };
}, "/repos/test/Reims-Go", pull, 42, { wait: false });
assert.equal(queued.status, "queued");
assert.equal(calls, 1);
const passed = await waitForCI(async (route) => route.endsWith("/100/attempts/2/jobs")
? { data: { jobs: [{ name: "verify", conclusion: "success", steps: [{ name: "Go test", conclusion: "success" }] }] } }
: { data: { workflow_runs: [{ ...run, status: "completed", conclusion: "success", html_url: "https://github.com/test/run/100" }] } },
"/repos/test/Reims-Go", pull, 42, { wait: false });
const summary = reviewSummary(english, { message: "No issues", comments: [], warnings: [] }, passed, { incomplete: false, mergeable: true, hasFindings: false });
assert.match(summary, /Go test · success/);
assert.match(summary, /Ready to merge/);
const waiting = reviewSummary(chinese, { comments: [], warnings: [] }, queued, { incomplete: false, mergeable: true, hasFindings: false });
assert.match(waiting, /代码未见阻塞,等待 CI/);
});
test("CI failures and incomplete OCR results affect the final recommendation independently", () => {
const failed = reviewSummary(chinese, { comments: [], warnings: [] }, { status: "completed", conclusion: "failure" }, { incomplete: false, mergeable: true, hasFindings: false });
assert.match(failed, /修改后再审/);
assert.match(failed, /处理 CI 失败项/);
const partial = reviewSummary(chinese, { comments: [], warnings: [{}] }, { status: "completed", conclusion: "success" }, { incomplete: true, mergeable: true, hasFindings: false });
assert.match(partial, /先审完剩余改动/);
assert.match(partial, /未完成的审查任务/);
});
async function fakeOCR(t, { exitCode = 0, stdout = null } = {}) {
const directory = await tempDirectory(t, "ocr-fake-");
const record = join(directory, "calls.jsonl");
const script = join(directory, "fake.cjs");
const output = stdout ?? JSON.stringify({ status: "complete", message: "Reviewed", comments: [], warnings: [], manifest: {} });
const source = [
"const fs = require(\"node:fs\");",
`fs.appendFileSync(${JSON.stringify(record)}, JSON.stringify({ args: process.argv.slice(2), env: process.env }) + "\\n");`,
"if (process.argv[2] === \"review\") {",
` process.stdout.write(${JSON.stringify(output)});`,
" process.stderr.write(\"diagnostic llm-secret github-secret\");",
` process.exitCode = ${exitCode};`,
"}",
].join("\n");
await writeFile(script, source);
let binary;
if (process.platform === "win32") {
binary = script;
} else {
binary = join(directory, "ocr");
await writeFile(binary, `#!/bin/sh\nexec "${process.execPath}" "${script}" "$@"\n`);
await chmod(binary, 0o700);
}
return { directory, binary, record };
}
function ocrOptions(fake, overrides = {}) {
return {
binary: fake.binary, repo: join(fake.directory, "repo"), from: A, to: B,
rule: join(fake.directory, "trusted-rule.json"), background: join(fake.directory, "background.md"),
home: join(fake.directory, "home"), profile: reviewProfile({ files: 2, lines: 20 }), language: "Chinese",
...(process.platform === "win32" ? { processRunner: (binary, args, options) => spawnSync(process.execPath, [binary, ...args], { encoding: "utf8", ...options }) } : {}),
parentEnv: {
PATH: process.env.PATH, SystemRoot: process.env.SystemRoot, ComSpec: process.env.ComSpec,
GITHUB_TOKEN: "github-secret", OCR_APP_PRIVATE_KEY: "app-secret", ACTIONS_RUNTIME_TOKEN: "runtime-secret",
PR_REVIEW_LLM_KEY: "llm-secret", PR_REVIEW_LLM_BASE_URL: "https://open.bigmodel.cn/api/anthropic",
PR_REVIEW_LLM_MODEL: "glm-5.4", PR_REVIEW_LLM_PROTOCOL: "anthropic",
},
...overrides,
};
}
async function recordedCalls(path) {
return (await readFile(path, "utf8")).trim().split("\n").map((line) => JSON.parse(line));
}
test("fake OCR executable receives complete arguments and an isolated credential environment", async (t) => {
const fake = await fakeOCR(t);
await mkdir(join(fake.directory, "home"), { recursive: true });
const result = await reviewWithOCR(ocrOptions(fake));
assert.equal(result.status, "complete");
const calls = await recordedCalls(fake.record);
assert.equal(calls.length, 7);
assert.deepEqual(calls[0].args, ["config", "set", "language", "Chinese"]);
assert.deepEqual(calls[1].args, ["config", "set", "llm.url", "https://open.bigmodel.cn/api/anthropic/v1/messages"]);
assert.deepEqual(calls[2].args, ["config", "set", "llm.model", "glm-5.4"]);
assert.deepEqual(calls[3].args, ["config", "set", "llm.protocol", "anthropic"]);
assert.deepEqual(calls[4].args, ["config", "set", "llm.extra_body", '{"thinking":{"type":"disabled"}}']);
assert.deepEqual(calls[5].args, ["config", "set", "llm.auth_token_cmd", "printenv OCR_LLM_TOKEN"]);
const options = ocrOptions(fake);
const reviewCall = calls[6];
assert.deepEqual(reviewCall.args, [
"review", "--repo", options.repo, "--from", A, "--to", B, "--rule", options.rule,
"--background-file", options.background, "--format", "json", "--audience", "agent", "--effort", "low",
"--concurrency", "4", "--timeout", "10", "--max-tokens-budget", "400000",
]);
for (const call of calls) {
assert.equal(call.env.HOME, options.home);
assert.equal(call.env.XDG_CONFIG_HOME, join(options.home, "config"));
assert.equal(call.env.GIT_CONFIG_NOSYSTEM, "1");
assert.equal(call.env.GIT_CONFIG_GLOBAL, "/dev/null");
assert.equal(call.env.GIT_CONFIG_KEY_0, "core.hooksPath");
assert.equal(call.env.GIT_CONFIG_VALUE_0, "/dev/null");
assert.equal(call.env.GITHUB_TOKEN, undefined);
assert.equal(call.env.PR_REVIEW_LLM_KEY, undefined);
assert.equal(call.env.OCR_APP_PRIVATE_KEY, undefined);
assert.equal(call.env.ACTIONS_RUNTIME_TOKEN, undefined);
}
assert.equal(calls[0].env.OCR_LLM_TOKEN, undefined);
assert.equal(reviewCall.env.OCR_LLM_TOKEN, "llm-secret");
assert.equal(reviewCall.env.OCR_LLM_URL, "https://open.bigmodel.cn/api/anthropic/v1/messages");
assert.equal(reviewCall.env.OCR_LLM_MODEL, "glm-5.4");
assert.equal(reviewCall.env.OCR_LLM_PROTOCOL, "anthropic");
assert.equal(reviewCall.env.OCR_USE_ANTHROPIC, "true");
assert.equal(reviewCall.env.OCR_LLM_TIMEOUT, "180");
const allowed = new Set(["path", "systemroot", "comspec", "homedrive", "homepath", "home", "tmpdir", "temp", "tmp", "xdg_config_home",
"xdg_data_home", "xdg_cache_home", "xdg_state_home", "git_config_nosystem", "git_config_global", "git_config_count",
"git_config_key_0", "git_config_value_0", "git_terminal_prompt", "lc_all", "no_color", "term", "ocr_llm_url",
"ocr_llm_token", "ocr_llm_model", "ocr_llm_protocol", "ocr_use_anthropic", "ocr_llm_timeout"]);
// Windows may add session variables while starting a native process; CI asserts the exact Linux allowlist.
if (process.platform !== "win32") {
for (const key of Object.keys(reviewCall.env)) assert.equal(allowed.has(key.toLowerCase()), true, "unexpected child env " + key);
}
});
test("a nonzero OCR exit keeps the partial result it emitted", async (t) => {
const fake = await fakeOCR(t, { exitCode: 1, stdout: JSON.stringify({ status: "partial", comments: [{ path: "a.go" }], manifest: {} }) });
await mkdir(join(fake.directory, "home"), { recursive: true });
const result = await reviewWithOCR(ocrOptions(fake));
assert.equal(result.status, "partial");
assert.equal(result.comments.length, 1);
});
test("a fully failed OCR review reports why its items failed", async (t) => {
const failed = [{ classification: "budget" }, { classification: "budget" }, { classification: "llm-secret 1" }];
const fake = await fakeOCR(t, { exitCode: 1, stdout: JSON.stringify({ status: "failed", comments: [], manifest: { coverage: { failed } } }) });
await mkdir(join(fake.directory, "home"), { recursive: true });
await assert.rejects(reviewWithOCR(ocrOptions(fake)), /exit 1; failed items: budget; /);
});
test("fake OCR nonzero exits and invalid JSON fail with sanitized diagnostics", async (t) => {
const failed = await fakeOCR(t, { exitCode: 7 });
await mkdir(join(failed.directory, "home"), { recursive: true });
await assert.rejects(reviewWithOCR(ocrOptions(failed)), (error) => {
assert.match(error.message, /exit 7/);
assert.doesNotMatch(error.message, /llm-secret|github-secret|app-secret/);
return true;
});
const malformed = await fakeOCR(t, { stdout: "invalid-json-llm-secret" });
await mkdir(join(malformed.directory, "home"), { recursive: true });
await assert.rejects(reviewWithOCR(ocrOptions(malformed)), (error) => {
assert.match(error.message, /valid JSON/);
assert.doesNotMatch(error.message, /llm-secret/);
return true;
});
});
test("GitHub 422 retries as a summary-only review without losing inline findings", async () => {
const comment = { path: "a.go", line: 12, start_line: 11, side: "RIGHT", body: "**[HIGH]** Keep old config\n\n```suggestion\nkeepConfig()\n```" };
const review = { event: "COMMENT", body: "summary", comments: [comment] };
const bodies = [];
await postReview(async (route, body) => {
bodies.push(body);
if (body.comments) throw Object.assign(new Error("unprocessable"), { status: 422 });
return { data: {} };
}, "/repos/test/Reims-Go/pulls/1", review, chinese);
assert.equal(bodies.length, 2);
assert.equal(bodies[1].comments, undefined);
assert.match(bodies[1].body, /GitHub 未能附加行内评论/);
assert.match(bodies[1].body, /a\.go.*11-12.*Keep old config/);
assert.doesNotMatch(bodies[1].body, /keepConfig|```/);
});
test("GitHub non-422 failures are not swallowed", async () => {
await assert.rejects(postReview(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 = '<!-- reims-pr-review {"v":2,"head_sha":"' + B + '","base_sha":"' + A + '","main_sha":"' + A + '","incomplete":true} -->';
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);
});
test("only the same revision may continue an incomplete review", () => {
const incomplete = { incomplete: true, headSha: B };
assert.equal(resumeTarget(incomplete, B, true), true);
assert.equal(resumeTarget(incomplete, B.toUpperCase(), true), true);
assert.equal(resumeTarget(incomplete, B, false), false, "the switch is off by default");
assert.equal(resumeTarget(incomplete, A, true), false, "a new push starts a full review");
assert.equal(resumeTarget({ incomplete: false, headSha: B }, B, true), false);
assert.equal(resumeTarget(null, B, true), false);
assert.equal(previousReviewFor(incomplete, false), null, "an unfinished review cannot anchor an incremental range");
assert.equal(previousReviewFor(incomplete, true), incomplete);
assert.equal(previousReviewFor({ incomplete: false }, false)?.incomplete, false);
assert.equal(previousReviewFor(null, true), null);
const range = previousReviewFor(incomplete, resumeTarget(incomplete, B, true));
assert.equal(range, incomplete, "continuing keeps the range the review was computed over");
});