File size: 3,972 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
import { NextRequest, NextResponse } from "next/server";
import { withApiError, ApiError } from "@/lib/api-error";
import { resolveProblem } from "@/lib/coding/store";
import { gradeCodeReview, gradeArchitecture } from "@/lib/coding/grade";
import { judgeWritten } from "@/lib/coding/judge";
import { awardCodingXp } from "@/lib/coding/award";
import { isWrittenProblem, type CodingDifficulty } from "@/lib/coding/types";
import { isLlmAvailable } from "@/lib/claude";
import type { CodeReviewVerdict, ArchitectureVerdict } from "@/lib/coding/grade";

interface SubmitWrittenBody {
  instanceId?: string;
  answer?: string;
  durationSecs?: number;
  userId?: number;
}

/**
 * POST /api/coding/submit-written
 * Body: { instanceId, answer, durationSecs? }
 *
 * Grades a written answer (code-review or architecture) with the LLM-as-judge
 * (or the offline heuristic when no API key is configured). Awards "written"
 * XP — separate from code XP — when the answer is judged correct.
 */
export const POST = withApiError(async (request: NextRequest) => {
  let body: SubmitWrittenBody;
  try {
    body = await request.json();
  } catch {
    throw new ApiError(400, "Invalid JSON body");
  }

  const { instanceId, answer, durationSecs } = body;
  const userId = body.userId ?? 1;

  if (!instanceId || typeof answer !== "string" || answer.trim().length === 0) {
    throw new ApiError(400, "instanceId and a non-empty answer are required");
  }

  const problem = resolveProblem(instanceId);
  if (!problem) {
    throw new ApiError(404, "Problem not found (it may have expired — regenerate it).");
  }
  if (!isWrittenProblem(problem)) {
    throw new ApiError(400, "This problem type is graded by running code, not a written answer.");
  }

  // AI judge when any LLM is reachable for this request (the visitor's HF
  // token, an env HF token, or an Anthropic key); else the offline heuristic.
  const useAI = isLlmAvailable();
  const judgement = await judgeWritten(problem, answer, { useAI });

  const grade =
    problem.type === "code-review"
      ? gradeCodeReview(
          problem.issues.length,
          judgement.verdict as CodeReviewVerdict,
        )
      : gradeArchitecture(
          problem.rubric,
          judgement.verdict as ArchitectureVerdict,
        );

  // Build hints about what a strong answer should have covered (post-submit).
  const expectations =
    problem.type === "code-review"
      ? problem.issues.map((i) => ({ id: i.id, title: i.title, severity: i.severity }))
      : problem.rubric.map((p) => ({ id: p.id, point: p.point }));

  const verdictDetail =
    problem.type === "code-review"
      ? { identified: (judgement.verdict as CodeReviewVerdict).identifiedIssueIds }
      : { covered: (judgement.verdict as ArchitectureVerdict).coveredPointIds };

  const baseResponse = {
    correct: grade.isCorrect,
    qualityScore: grade.qualityScore,
    gradedBy: judgement.usedAI ? "llm-judge" : "heuristic",
    feedback: judgement.feedback,
    expectations,
    verdict: verdictDetail,
  };

  if (!grade.isCorrect) {
    return NextResponse.json({
      ...baseResponse,
      awarded: false,
      message: "Not quite — review the expected points and try again.",
    });
  }

  const award = await awardCodingXp({
    userId,
    exerciseType: "written",
    description: `Solved ${problem.difficulty} ${problem.type} "${problem.title}" (written)`,
    qualityScore: grade.qualityScore,
    difficulty: problem.difficulty as CodingDifficulty,
    durationSecs,
    metadata: {
      problemId: problem.id,
      problemType: problem.type,
      language: problem.language,
      difficulty: problem.difficulty,
      gradedBy: baseResponse.gradedBy,
      kind: "written",
    },
  });

  return NextResponse.json({
    ...baseResponse,
    awarded: true,
    ...award,
    message: award.isCriticalHit
      ? "Critical Hit! Strong written answer!"
      : "Correct — written answer accepted!",
  });
});