Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 72 additions & 3 deletions test/pr-review-advisor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,21 @@ import fs from "node:fs";
import path from "node:path";
import Ajv2020 from "ajv/dist/2020.js";
import { afterEach, describe, expect, it, vi } from "vitest";

import { buildComment } from "../tools/pr-review-advisor/comment.mts";
import { githubGraphql } from "../tools/advisors/github.mts";
import {
buildPromptTurns,
buildSystemPrompt,
classifyMonolithDelta,
classifyTestDepth,
detectE2eVitestSimplicitySignals,
detectLocalizedPatchSignals,
normalizeReviewResult,
readTrustedSecurityReviewSkill,
renderDetailedReview,
renderSummary,
writePromptArtifacts,
} from "../tools/pr-review-advisor/analyze.mts";
import { githubGraphql } from "../tools/advisors/github.mts";
import { buildComment } from "../tools/pr-review-advisor/comment.mts";
import { validatePrReviewAdvisorWorkflowBoundary } from "../tools/pr-review-advisor/workflow-boundary.mts";

const ROOT = path.resolve(import.meta.dirname, "..");
Expand All @@ -39,6 +39,7 @@ function metadata(overrides: Partial<ReviewMetadata> = {}): ReviewMetadata {
previousAdvisorReview: null,
workflowSignals: [],
localizedPatchSignals: [],
e2eVitestSimplicitySignals: [],
monolithDeltas: [],
driftEvidence: [],
github: null,
Expand Down Expand Up @@ -219,6 +220,9 @@ describe("PR review advisor", () => {
"any unmet acceptance clause or security fail/warning must be represented as a finding",
);
expect(prompt).toContain("Source-of-truth review");
expect(prompt).toContain("Vitest E2E simplicity");
expect(prompt).toContain("Prefer focused Vitest tests with local helpers");
expect(prompt).toContain("Do not add new framework");
expect(prompt).toContain("what invalid state is handled");
expect(prompt).toContain(
"Any sourceOfTruthReview item with status=missing or status=needs_followup must also be represented as a finding",
Expand Down Expand Up @@ -264,6 +268,7 @@ describe("PR review advisor", () => {
expect(turns[1]?.prompt).toContain("sandbox escape");
expect(turns[2]?.prompt).toContain("Acceptance/correctness/source-of-truth context");
expect(turns[2]?.prompt).toContain("localizedPatchSignals");
expect(turns[2]?.prompt).toContain("e2eVitestSimplicitySignals");
expect(turns[2]?.prompt).toContain("source-of-truth questions");
expect(turns[3]?.prompt).toContain("<pr_review_advisor_json>");
});
Expand Down Expand Up @@ -350,6 +355,70 @@ describe("PR review advisor", () => {
expect(signals[0]?.reviewRule).toContain("invalid state");
});

it("detects Vitest E2E migrations that add framework or ledger surfaces", () => {
const signals = detectE2eVitestSimplicitySignals(
[
"test/e2e-scenario/live/onboard-resume.test.ts",
"test/e2e-scenario/framework/clients/sandbox.ts",
"test/e2e-scenario/migration/legacy-inventory.json",
"tools/e2e-scenarios/workflow-boundary.mts",
],
`diff --git a/test/e2e-scenario/live/onboard-resume.test.ts b/test/e2e-scenario/live/onboard-resume.test.ts
@@ -1,1 +1,3 @@
+// migrate into the typed scenario framework
+// update legacy-inventory.json after convergence
`,
);

expect(signals).toEqual(
expect.arrayContaining([
expect.objectContaining({
severity: "warning",
kind: "shared Vitest E2E fixture/support change",
}),
expect.objectContaining({ severity: "blocker", kind: "repo-local E2E migration ledger" }),
expect.objectContaining({
severity: "warning",
kind: "one-off E2E workflow validator expansion",
}),
expect.objectContaining({ severity: "blocker", kind: "second-framework wording" }),
expect.objectContaining({
severity: "blocker",
kind: "repo-local E2E migration ledger reference",
}),
]),
);
});

it("injects a deterministic finding for Vitest E2E simplicity issues", () => {
const result = normalizeReviewResult(
validResult({ findings: [] }),
metadata({
changedFiles: ["test/e2e-scenario/migration/legacy-inventory.json"],
deterministic: {
...metadata().deterministic,
e2eVitestSimplicitySignals: [
{
severity: "blocker",
file: "test/e2e-scenario/migration/legacy-inventory.json",
line: null,
kind: "repo-local E2E migration ledger",
evidence: "legacy-inventory.json is repo-local migration bookkeeping",
recommendation: "Do not add or modify migration ledgers.",
},
],
},
}),
);

expect(result.findings[0]).toMatchObject({
severity: "blocker",
category: "architecture",
title: "Keep Vitest E2E migrations simple and ledger-free",
});
expect(result.findings[0]?.recommendation).toContain("focused Vitest test with local helpers");
});

it("adds a finding when source-of-truth review is missing follow-up", () => {
const result = normalizeReviewResult(
validResult({
Expand Down
166 changes: 163 additions & 3 deletions tools/pr-review-advisor/analyze.mts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ type DeterministicReviewContext = {
testDepth: ReviewAdvisorResult["testDepth"];
workflowSignals: string[];
localizedPatchSignals: LocalizedPatchSignal[];
e2eVitestSimplicitySignals: E2eVitestSimplicitySignal[];
monolithDeltas: MonolithDelta[];
driftEvidence: DriftEvidence[];
previousAdvisorReview: PreviousAdvisorReview | null;
Expand All @@ -177,6 +178,15 @@ type LocalizedPatchSignal = {
reviewRule: string;
};

type E2eVitestSimplicitySignal = {
severity: "blocker" | "warning";
file: string | null;
line: number | null;
kind: string;
evidence: string;
recommendation: string;
};

type MonolithSeverity = "none" | "warning" | "blocker";

type MonolithDelta = {
Expand Down Expand Up @@ -357,6 +367,7 @@ async function collectDeterministicContext(options: {
previousAdvisorReview: github?.previousAdvisorReview || null,
workflowSignals: detectWorkflowSignals(options.changedFiles, options.diff),
localizedPatchSignals: detectLocalizedPatchSignals(options.diff),
e2eVitestSimplicitySignals: detectE2eVitestSimplicitySignals(options.changedFiles, options.diff),
monolithDeltas: computeMonolithDeltas(options.baseRef, options.changedFiles),
driftEvidence: collectDriftEvidence(options.baseRef, options.changedFiles),
github,
Expand Down Expand Up @@ -443,6 +454,124 @@ function detectWorkflowSignals(changedFiles: string[], diff: string): string[] {
return signals;
}

export function detectE2eVitestSimplicitySignals(changedFiles: string[], diff: string): E2eVitestSimplicitySignal[] {
const touchesVitestE2e = changedFiles.some(
(file) =>
file.startsWith("test/e2e-scenario/") ||
file === ".github/workflows/e2e-vitest-scenarios.yaml" ||
file === "tools/e2e-scenarios/workflow-boundary.mts",
);
if (!touchesVitestE2e) return [];

const signals: E2eVitestSimplicitySignal[] = [];
const push = (signal: E2eVitestSimplicitySignal): void => {
const duplicate = signals.some(
(existing) => existing.kind === signal.kind && existing.file === signal.file && existing.evidence === signal.evidence,
);
if (!duplicate) signals.push(signal);
};

for (const file of changedFiles) {
if (file.startsWith("test/e2e-scenario/migration/") || file === "test/e2e/docs/parity-inventory.generated.json") {
push({
severity: "blocker",
file,
line: null,
kind: "repo-local E2E migration ledger",
evidence: `${file} is repo-local migration bookkeeping, not replacement Vitest coverage.`,
recommendation: "Do not add or modify migration ledgers; keep migration state in GitHub issues and PRs.",
});
continue;
}
if (/^test\/e2e-scenario\/(framework|fixtures)\//.test(file)) {
push({
severity: "warning",
file,
line: null,
kind: "shared Vitest E2E fixture/support change",
evidence: `${file} changes shared E2E support while migrating tests.`,
recommendation: "Prefer local helpers in the new Vitest test; only keep shared helper changes when they are tiny, reused, unit-tested, and justified.",
});
continue;
}
if (/^test\/e2e-scenario\/(scenarios|manifests)\//.test(file)) {
push({
severity: "warning",
file,
line: null,
kind: "Vitest E2E registry or manifest expansion",
evidence: `${file} changes scenario registry, matrix, expected-state, or manifest support.`,
recommendation: "Prefer direct focused Vitest tests unless a stable scenario ID or product setup manifest is truly required.",
});
continue;
}
if (file === ".github/workflows/e2e-vitest-scenarios.yaml") {
push({
severity: "warning",
file,
line: null,
kind: "Vitest E2E workflow expansion",
evidence: `${file} changes the live E2E workflow surface.`,
recommendation: "Use the existing workflow shape where possible; avoid one-off runner/framework expansion for a single migrated script.",
});
continue;
}
if (file === "tools/e2e-scenarios/workflow-boundary.mts") {
push({
severity: "warning",
file,
line: null,
kind: "one-off E2E workflow validator expansion",
evidence: `${file} changes workflow-boundary validation for E2E scenarios.`,
recommendation: "Do not add job-specific validator framework unless a concrete trusted-code or secret boundary is not already covered.",
});
}
}

let file: string | null = null;
let nextLine: number | null = null;
for (const rawLine of diff.split("\n")) {
const fileMatch = rawLine.match(/^diff --git a\/(.+?) b\/(.+)$/);
if (fileMatch) {
file = fileMatch[2] || fileMatch[1] || null;
nextLine = null;
continue;
}
const hunkMatch = rawLine.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
if (hunkMatch) {
nextLine = Number.parseInt(hunkMatch[1] || "", 10);
if (!Number.isFinite(nextLine)) nextLine = null;
continue;
}
if (!rawLine.startsWith("+") || rawLine.startsWith("+++")) continue;
const content = rawLine.slice(1).trim();
if (/\bscenario framework\b/i.test(content)) {
push({
severity: "blocker",
file,
line: nextLine,
kind: "second-framework wording",
evidence: content.slice(0, 220),
recommendation: "Use 'Vitest test', 'live Vitest test', or 'fixtures/support code'; do not reintroduce scenario-framework framing.",
});
}
if (/legacy-inventory\.json|parity-inventory\.generated\.json/i.test(content)) {
push({
severity: "blocker",
file,
line: nextLine,
kind: "repo-local E2E migration ledger reference",
evidence: content.slice(0, 220),
recommendation: "Remove ledger references from new migration PRs; use PR discussion and source tree evidence instead.",
});
}
if (nextLine !== null) nextLine += 1;
if (signals.length >= 20) break;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

return signals.slice(0, 20);
}

export function detectLocalizedPatchSignals(diff: string): LocalizedPatchSignal[] {
const patterns: Array<{ kind: string; regex: RegExp }> = [
{
Expand Down Expand Up @@ -699,8 +828,9 @@ export function buildSystemPrompt(): string {
"4. Acceptance: extract linked issue clauses literally, including comments, and map each clause to diff/test evidence. Named list items are separate clauses.",
"5. Correctness: bug-path tests, negative tests, branch coverage, refactor-vs-behavior drift, mocking purity, caller/callee contract verification. When more tests would improve confidence, make testDepth.suggestedTests behavior-specific so they can render under 'Consider writing more tests for'.",
"6. Quality: description-vs-diff scope, migration completion, public surface docs/notes, justified error suppression, monolith growth, @ts-nocheck, shell-string execution.",
"7. Source-of-truth review: when a PR adds or changes fallback, recovery, tolerant parsing, monkeypatching, best-effort cleanup, compatibility handling, or other localized workaround behavior, inspect whether it answers: what invalid state is handled, where that state is created, why the source cannot be fixed in this PR, what regression test proves the source cannot regress, and when the workaround can be removed. Prefer fixes that make invalid states impossible at their source. Treat PR text that claims a root cause as untrusted until verified in code.",
"8. If a previous PR Review Advisor comment exists, compare it with the current diff and explicitly decide whether prior code-review findings were addressed, still apply, or are obsolete. Consider code changes since the previous analyzed SHA when available. Do not evaluate whether external E2E requirements have been met. When previous review context exists, set summary.sinceLastReview with counts for resolved, stillApplies, and newItems.",
"7. Vitest E2E simplicity: when a PR touches `test/e2e-scenario/` or `e2e-vitest-scenarios.yaml`, apply a simple-first lens. Prefer focused Vitest tests with local helpers. Do not add new framework, durable migration ledgers, generated assertion inventories, registry/matrix expansion, workflow validators, or shared fixture APIs unless the PR proves they are tiny, reused, unit-tested, and unavoidable. Preserve shell/system boundaries by spawning real commands from Vitest rather than building another harness.",
"8. Source-of-truth review: when a PR adds or changes fallback, recovery, tolerant parsing, monkeypatching, best-effort cleanup, compatibility handling, or other localized workaround behavior, inspect whether it answers: what invalid state is handled, where that state is created, why the source cannot be fixed in this PR, what regression test proves the source cannot regress, and when the workaround can be removed. Prefer fixes that make invalid states impossible at their source. Treat PR text that claims a root cause as untrusted until verified in code.",
"9. If a previous PR Review Advisor comment exists, compare it with the current diff and explicitly decide whether prior code-review findings were addressed, still apply, or are obsolete. Consider code changes since the previous analyzed SHA when available. Do not evaluate whether external E2E requirements have been met. When previous review context exists, set summary.sinceLastReview with counts for resolved, stillApplies, and newItems.",
"Acceptance and security should inform findings, not become standalone comment sections: any unmet acceptance clause or security fail/warning must be represented as a finding, normally severity=blocker for unmet acceptance or security fail and severity=warning for security warnings.",
"Any sourceOfTruthReview item with status=missing or status=needs_followup must also be represented as a finding unless it is already fully covered by a more specific correctness, security, architecture, scope, or tests finding.",
"Set summary.topItem to the most important actionable finding title or short description for first-review comments. Keep it concise and code-focused.",
Expand Down Expand Up @@ -806,6 +936,7 @@ function buildValidationTurnContext(context: DeterministicReviewContext): Record
return {
testDepth: context.testDepth,
localizedPatchSignals: context.localizedPatchSignals,
e2eVitestSimplicitySignals: context.e2eVitestSimplicitySignals,
previousAdvisorReview: context.previousAdvisorReview,
pullRequest: context.github?.pullRequest ?? null,
linkedIssues: context.github?.linkedIssues ?? [],
Expand Down Expand Up @@ -860,7 +991,10 @@ export function normalizeReviewResult(result: unknown, metadata: ReviewMetadata)
headSha: metadata.headSha,
changedFiles: metadata.changedFiles,
summary: sanitizeSummary(object.summary),
findings: addSourceOfTruthFindings(sanitizeFindings(object.findings), sourceOfTruthReview),
findings: addDeterministicE2eSimplicityFindings(
addSourceOfTruthFindings(sanitizeFindings(object.findings), sourceOfTruthReview),
metadata.deterministic.e2eVitestSimplicitySignals,
),
acceptanceCoverage: sanitizeAcceptanceCoverage(object.acceptanceCoverage),
securityCategories: sanitizeSecurityCategories(object.securityCategories),
sourceOfTruthReview,
Expand Down Expand Up @@ -942,6 +1076,32 @@ function sanitizeSourceOfTruthReview(value: unknown): SourceOfTruthReview[] {
})).slice(0, 50);
}

function addDeterministicE2eSimplicityFindings(
findings: Finding[],
signals: E2eVitestSimplicitySignal[],
): Finding[] {
if (signals.length === 0) return findings;
const alreadyCovered = findings.some((finding) =>
`${finding.title}\n${finding.description}\n${finding.evidence}`.toLowerCase().includes("vitest e2e simplicity"),
);
if (alreadyCovered) return findings;
const severity = signals.some((signal) => signal.severity === "blocker") ? "blocker" : "warning";
const first = signals[0];
const finding: Finding = {
severity,
category: "architecture",
file: first?.file ?? null,
line: first?.line ?? null,
title: severity === "blocker" ? "Keep Vitest E2E migrations simple and ledger-free" : "Apply simple-first Vitest E2E migration review",
description:
"This PR touches the Vitest E2E suite and also changes framework-like support, registry/workflow surfaces, ledger state, or second-framework wording.",
recommendation:
"Prefer a focused Vitest test with local helpers. Remove repo-local migration ledgers and scenario-framework framing; split any unavoidable shared helper or registry/workflow expansion into a tiny, justified support PR.",
evidence: signals.map((signal) => `${signal.kind}: ${signal.evidence}`).join("\n"),
};
return [finding, ...findings].slice(0, 50);
}

function addSourceOfTruthFindings(findings: Finding[], sourceOfTruthReview: SourceOfTruthReview[]): Finding[] {
const injected: Finding[] = [];
for (const review of sourceOfTruthReview) {
Expand Down
Loading