import { createHash } from "node:crypto"; import { mkdtemp, readFile, rm } from "node:fs/promises"; import { join } from "node:path"; import { pathToFileURL } from "node:url"; import { askModel, repositoryClient } from "./issue-triage.mjs"; import { configureOCR, parseOCRJSON, plainMarkdown, required, reviewEvidence, runProcess, safeExit, shortText, validFinding } from "./pr-review.mjs"; // Each run scans the next area, so the whole client is covered over successive runs. export const AREAS = [ "internal/app", "internal/guesttools", "internal/plugin", "internal/macos", "internal/host,internal/driver,internal/vmstart,internal/lifecycle", "internal/packetbridge,internal/netproxy,internal/networkmsg,internal/qmp,internal/console,internal/control", "internal/runtime,internal/selfupdate,internal/fetch,internal/downloader,internal/datamigrate,internal/cli", "frontend/src", ]; const MARKER = "`, "由定期代码诊断自动生成,经模型复核,未经真机验证。处理前请先确认问题真实存在。", part("触发条件", trigger), part("影响", impact), part("证据", evidence), ...(fix ? [part("修复方向", fix)] : []), `[查看代码](https://github.com/${repository}/blob/${sha}/${finding.path.split("/").map(encodeURIComponent).join("/")}${line})`, ].join("\n\n"), }; } export async function selectFindings(comments, { known, readSource, ask }) { const candidates = comments .filter((finding) => validFinding(finding) && finding.severity in RANK && reviewEvidence(finding.content)?.trigger && !["style", "documentation"].includes(String(finding.category ?? "").toLowerCase())) .sort((a, b) => RANK[a.severity] - RANK[b.severity]); const selected = []; let withheld = 0; let verified = 0; for (const finding of candidates) { if (selected.length >= MAX_NEW_ISSUES || verified >= MAX_VERIFIED) break; if (String(finding.category ?? "").toLowerCase() === "security") { withheld++; continue; } const code = squash(finding.existing_code); const id = fingerprint(finding); if (code.length < 8 || known.has(id)) continue; const source = await readSource(finding.path); if (!source || !squash(source).includes(code)) continue; verified++; const { path, content, existing_code } = finding; const answer = await ask(VERIFY, { finding: { path, content, existing_code }, source: source.slice(0, 200_000) }); if (answer.security_sensitive !== false) withheld++; else if (answer.verdict === "confirmed") { known.add(id); selected.push(finding); } } return { selected, withheld }; } export async function previousDiagnoses(github) { const issues = []; for (let page = 1; ; page++) { const { data } = await github("GET", `/issues?state=all&per_page=100&creator=${encodeURIComponent(BOT)}&page=${page}`); issues.push(...data.filter((issue) => issue.body?.startsWith(MARKER))); if (data.length < 100) return issues; } } async function main() { if (!process.env.PR_REVIEW_LLM_KEY?.trim()) { console.log("Code diagnosis skipped: set the PR_REVIEW_LLM_KEY repository secret"); return; } const repository = required("GITHUB_REPOSITORY"); const event = JSON.parse(await readFile(required("GITHUB_EVENT_PATH"), "utf8")); const publish = process.env.GITHUB_EVENT_NAME === "schedule" || String(event.inputs?.publish) === "true"; const github = repositoryClient({ apiUrl: required("GITHUB_API_URL"), repository, token: required("GITHUB_TOKEN") }); const previous = await previousDiagnoses(github); if (publish && previous.filter((issue) => issue.state === "open").length >= MAX_OPEN_ISSUES) { console.log("Code diagnosis skipped: handle the open diagnosis issues first"); return; } const known = new Set(previous.map((issue) => issue.body.slice(MARKER.length, MARKER.length + 16))); const repo = process.cwd(); const area = AREAS[Number(required("GITHUB_RUN_NUMBER")) % AREAS.length]; const binary = required("PR_REVIEW_OCR_BIN"); const home = await mkdtemp(join(required("RUNNER_TEMP"), "diagnosis-home-")); let scan; try { const env = configureOCR({ binary, home, language: "Chinese" }); const result = runProcess(binary, ["scan", "--repo", repo, "--path", area, "--exclude", EXCLUDES, "--rule", join(repo, ".opencodereview", "rule.json"), "--format", "json", "--audience", "agent", "--no-summary", "--concurrency", "6", "--timeout", "10", "--max-tokens-budget", String(TOKEN_BUDGET)], { cwd: home, env, timeout: 3_000_000 }); if (result.error || result.status !== 0) throw new Error("OCR scan failed (" + safeExit(result) + ")"); scan = parseOCRJSON(result.stdout ?? ""); } finally { await rm(home, { recursive: true, force: true }); } const readSource = async (path) => { try { return await readFile(join(repo, path), "utf8"); } catch (error) { console.warn("Could not read a reported file: " + error.code); return null; } }; const { selected, withheld } = await selectFindings(scan.comments, { known, readSource, ask: askModel }); console.log(`Scanned ${area}: ${scan.status}, ${Number(scan.summary?.total_tokens) || 0} tokens, ${scan.comments.length} findings, ${selected.length} confirmed`); if (withheld) console.log(`::warning::${withheld} security-sensitive finding(s) were not published. Run the scan locally to inspect ${area}.`); for (const finding of selected) { const issue = diagnosisIssue(finding, { repository, sha: required("GITHUB_SHA") }); if (publish) { const { data } = await github("POST", "/issues", issue); console.log("Created issue #" + data.number); } else { console.log(issue.title + "\n" + issue.body + "\n"); } } } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { main().catch((error) => { console.error(error.message); process.exitCode = 1; }); }