Download src/lib/coding/judge.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 8.68 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/coding/judge.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/lib/coding/judge.ts
-
curl -L -o judge.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/coding/judge.ts
8.68 kB
| 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, | |
| }; | |
| } | |