File size: 8,677 Bytes
9580dce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 | import { claude, parseClaudeJson } from "@/lib/claude";
import type {
CodeIssue,
RubricPoint,
CodeReviewProblem,
ArchitectureProblem,
CodingProblem,
} from "./types";
import type { CodeReviewVerdict, ArchitectureVerdict } from "./grade";
// ---------------------------------------------------------------------------
// LLM-as-judge for written submissions (code-review & architecture).
//
// Two implementations:
// - Claude judge (accurate, requires an API key) β resolves which known
// issues / rubric points the user's free-text answer actually covers.
// - Heuristic judge (pure, offline) β keyword overlap fallback used when no
// API key is configured or the Claude call fails. Keeps the feature usable
// and testable locally.
//
// Both produce the same verdict shape, which the pure graders in grade.ts turn
// into a quality score. The route decides whether to attempt the AI path.
// ---------------------------------------------------------------------------
// βββ Keyword heuristics (pure) βββββββββββββββββββββββββββββββββββββββββββββββ
const STOPWORDS = new Set([
"the", "and", "for", "with", "that", "this", "from", "into", "such", "like",
"when", "where", "your", "their", "would", "should", "could", "have", "they",
"what", "which", "while", "about", "uses", "use", "using", "via",
]);
/** Distinctive lowercase keywords (length β₯ 4, non-stopword) from a text. */
function keywordsOf(...texts: string[]): string[] {
const words = texts
.join(" ")
.toLowerCase()
.split(/[^a-z0-9]+/)
.filter((w) => w.length >= 4 && !STOPWORDS.has(w));
return Array.from(new Set(words));
}
/** True when `answer` covers enough of `target`'s keywords to count as a hit. */
function covers(answer: string, ...target: string[]): boolean {
const lower = answer.toLowerCase();
const keys = keywordsOf(...target);
if (keys.length === 0) return false;
const hits = keys.filter((k) => lower.includes(k)).length;
const threshold = Math.max(1, Math.ceil(keys.length * 0.34));
return hits >= threshold;
}
const CLAIM_WORDS = [
"bug", "issue", "error", "wrong", "incorrect", "broken", "crash",
"vulnerab", "problem", "fix", "fail", "leak", "unsafe",
];
const CLEAN_WORDS = [
"no issue", "no bug", "no problem", "looks correct", "looks good",
"is correct", "nothing wrong", "clean", "no errors", "correct and",
];
function claimsAnIssue(answer: string): boolean {
const lower = answer.toLowerCase();
const hasClaim = CLAIM_WORDS.some((w) => lower.includes(w));
const hasClean = CLEAN_WORDS.some((w) => lower.includes(w));
return hasClaim && !hasClean;
}
export function heuristicCodeReviewVerdict(
answer: string,
issues: CodeIssue[],
): CodeReviewVerdict {
if (issues.length === 0) {
return {
identifiedIssueIds: [],
falsePositives: claimsAnIssue(answer) ? 1 : 0,
};
}
const identifiedIssueIds = issues
.filter((iss) => covers(answer, iss.id.replace(/-/g, " "), iss.title))
.map((iss) => iss.id);
return { identifiedIssueIds, falsePositives: 0 };
}
export function heuristicArchitectureVerdict(
answer: string,
rubric: RubricPoint[],
): ArchitectureVerdict {
const coveredPointIds = rubric
.filter((p) => covers(answer, p.point))
.map((p) => p.id);
return { coveredPointIds };
}
// βββ Claude judge (impure) βββββββββββββββββββββββββββββββββββββββββββββββββββ
interface AIJudgeResult<V> {
verdict: V;
feedback: string;
}
const JUDGE_MODEL = "claude-haiku-4-5-20251001";
export async function claudeJudgeCodeReview(
problem: CodeReviewProblem,
answer: string,
): Promise<AIJudgeResult<CodeReviewVerdict>> {
const issueList = problem.issues
.map((i) => `- id="${i.id}" (${i.severity}): ${i.title} β ${i.description}`)
.join("\n");
const content = `You are grading a code review. A developer was shown this ${problem.language} code and asked to find every issue:
\`\`\`${problem.language}
${problem.code}
\`\`\`
The known issues in this code are:
${issueList || "(none β this code is actually correct and clean)"}
The developer's written review:
"""
${answer}
"""
Decide which of the known issue ids the developer correctly identified (the description must match the real issue, not a vague guess), and how many distinct issues they claimed that are NOT in the known list (false positives).
Respond ONLY with JSON (no markdown):
{ "identifiedIssueIds": ["id", ...], "falsePositives": N, "feedback": "one or two sentences" }`;
const message = await claude.messages.create({
model: JUDGE_MODEL,
max_tokens: 800,
messages: [{ role: "user", content }],
});
const text = message.content[0].type === "text" ? message.content[0].text : "";
const parsed = parseClaudeJson<{
identifiedIssueIds: string[];
falsePositives: number;
feedback: string;
}>(text);
// Defensive: only trust ids that are actually known issues.
const known = new Set(problem.issues.map((i) => i.id));
const identifiedIssueIds = (parsed.identifiedIssueIds ?? []).filter((id) =>
known.has(id),
);
return {
verdict: {
identifiedIssueIds,
falsePositives: Math.max(0, Math.round(parsed.falsePositives ?? 0)),
},
feedback: parsed.feedback ?? "",
};
}
export async function claudeJudgeArchitecture(
problem: ArchitectureProblem,
answer: string,
): Promise<AIJudgeResult<ArchitectureVerdict>> {
const rubricList = problem.rubric
.map((p) => `- id="${p.id}" (weight ${p.weight}): ${p.point}`)
.join("\n");
const content = `You are grading an architecture/design answer. The question was:
"""
${problem.prompt}
"""
A strong answer should address these rubric points:
${rubricList}
The developer's answer:
"""
${answer}
"""
Decide which rubric point ids the answer adequately addresses (a real, substantive treatment β not a passing mention).
Respond ONLY with JSON (no markdown):
{ "coveredPointIds": ["id", ...], "feedback": "one or two sentences" }`;
const message = await claude.messages.create({
model: JUDGE_MODEL,
max_tokens: 800,
messages: [{ role: "user", content }],
});
const text = message.content[0].type === "text" ? message.content[0].text : "";
const parsed = parseClaudeJson<{ coveredPointIds: string[]; feedback: string }>(
text,
);
const known = new Set(problem.rubric.map((p) => p.id));
const coveredPointIds = (parsed.coveredPointIds ?? []).filter((id) =>
known.has(id),
);
return { verdict: { coveredPointIds }, feedback: parsed.feedback ?? "" };
}
// βββ Dispatcher ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
export type WrittenVerdict = CodeReviewVerdict | ArchitectureVerdict;
export interface WrittenJudgement {
verdict: WrittenVerdict;
feedback: string;
usedAI: boolean;
}
export type AIJudgeFn = (
problem: CodingProblem,
answer: string,
) => Promise<AIJudgeResult<WrittenVerdict>>;
export interface JudgeOptions {
useAI?: boolean;
/** Injectable AI judge (defaults to the Claude implementation). */
aiJudge?: AIJudgeFn;
}
/** Default AI judge: routes to the right Claude judge by problem type. */
const defaultAIJudge: AIJudgeFn = async (problem, answer) => {
if (problem.type === "code-review") {
return claudeJudgeCodeReview(problem, answer);
}
if (problem.type === "architecture") {
return claudeJudgeArchitecture(problem, answer);
}
throw new Error(`Problem type ${problem.type} is not a written problem`);
};
function heuristicVerdict(
problem: CodeReviewProblem | ArchitectureProblem,
answer: string,
): WrittenVerdict {
return problem.type === "code-review"
? heuristicCodeReviewVerdict(answer, problem.issues)
: heuristicArchitectureVerdict(answer, problem.rubric);
}
export async function judgeWritten(
problem: CodeReviewProblem | ArchitectureProblem,
answer: string,
options: JudgeOptions = {},
): Promise<WrittenJudgement> {
const { useAI = false, aiJudge = defaultAIJudge } = options;
if (useAI) {
try {
const ai = await aiJudge(problem, answer);
return { verdict: ai.verdict, feedback: ai.feedback, usedAI: true };
} catch {
// Fall through to the heuristic on any AI failure (no key, parse, network).
}
}
return {
verdict: heuristicVerdict(problem, answer),
feedback: "",
usedAI: false,
};
}
|