From ec29d2d818bc108a4e9dd721d88d088a961030f4 Mon Sep 17 00:00:00 2001 From: Rahul Singh Khokhar Date: Mon, 11 May 2026 02:34:56 -0700 Subject: [PATCH 1/7] chore(project): pick STORY-039d LLM-judge spec-clarity rubric [STORY-039d] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes AC #3 of STORY-039 — adds a second LLM call (Haiku) after the structural Zod gate that scores variants 1-5 on instruction_clarity / example_quality / concept_match and drops the variant when min(scores) < 3. Co-Authored-By: Claude Opus 4.7 --- .../STORY-039d-variant-spec-clarity-judge.md | 120 ++++++++++++++++++ 1 file changed, 120 insertions(+) create mode 100644 project/stories/STORY-039d-variant-spec-clarity-judge.md diff --git a/project/stories/STORY-039d-variant-spec-clarity-judge.md b/project/stories/STORY-039d-variant-spec-clarity-judge.md new file mode 100644 index 0000000..6516e71 --- /dev/null +++ b/project/stories/STORY-039d-variant-spec-clarity-judge.md @@ -0,0 +1,120 @@ +--- +id: STORY-039d +title: LLM-judge spec-clarity rubric for LLM-generated problem variants +type: story +status: in-progress +priority: P2 +estimate: S +parent: EPIC-007 +phase: v1-followup +tags: [problems, llm, content, quality, v1-followup] +created: 2026-05-11 +updated: 2026-05-11 +--- + +## Description + +STORY-039 follow-up — wires a second LLM call (a "spec-clarity judge") into the variant +pipeline so a structurally valid variant whose problem statement is ambiguous, whose examples +contradict the spec, or whose declared concept tags don't actually match the exercise is +dropped before being cached or surfaced to a user. + +STORY-039 ships a structural Zod gate (`ProblemDefSchema.parse`) plus identity checks +(language / difficulty / concept_tags / track / kind / slug-prefix / variant_of). STORY-039a +adds a Piston self-validation gate (reference_solution must pass own hidden_tests). Those +two guards catch structural drift and reference-solution bugs, but they don't catch: + +- Ambiguous statements ("Given a list of items, return the result") that pass schema but + leave the learner guessing. +- Examples whose inputs and outputs disagree with the spec ("statement says positive + integers; example uses negative numbers"). +- Concept-tag mismatches ("`concept_tags: [recursion]` but the reference_solution uses a + flat for-loop"). + +AC #3 of STORY-039 flagged this gap; this Story closes it by adding a Haiku-call judge that +scores the variant 1-5 on three criteria — `instruction_clarity` / `example_quality` / +`concept_match` — and drops the variant when `min(scores) < 3`. + +The judge is gated by `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE=1` (default ON when +`ANTHROPIC_API_KEY` is set, OFF otherwise) so operators can disable the cost in environments +that don't want the round-trip (~$0.01 per variant). + +## Acceptance criteria + +- [ ] New versioned prompt `packages/prompts/src/variant-spec-clarity-prompt.ts` with + version tag `variant-spec-clarity-v1`. System prompt embeds the rubric (1-5 per + criterion + one-sentence reasoning). Forbidden-phrase test on the system prompt. +- [ ] New judge `packages/agent/src/variant-spec-clarity-judge.ts` exposes + `runVariantSpecClarityJudge({ llm, variant })` returning + `{ instruction_clarity, example_quality, concept_match, reasoning, pass }` where + `pass = min(scores) >= 3`. Pure function — no DB / no telemetry inside. Zod-validated + response with a single retry on parse failure; persistent failure → `{ pass: false }` + (best-effort, never throws). +- [ ] `generateProblemVariant` accepts an optional `judge?: SpecClarityJudge` parameter. + When provided, after the structural Zod gate passes AND (when configured) Piston + self-validation passes, run the judge. On `judge.pass === false`, drop the variant + and increment a new `variants_dropped_spec_clarity` telemetry counter (added to + `ProblemVariantsTelemetry`). Caller-controlled — existing callers don't break. +- [ ] `apps/api/src/problem-variants.ts` route honors `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE` + env flag (default ON when ANTHROPIC_API_KEY is set, otherwise OFF). When ON, passes + `runVariantSpecClarityJudge` as the `judge` to `generateProblemVariant`. +- [ ] Unit tests: passing scores → `pass: true`, one failing score → `pass: false`, + malformed JSON → retry once then `pass: false`, forbidden-phrase test on the system + prompt. ~8-10 tests. +- [ ] Unit tests in `problem-variants.test.ts`: stub judge returning `pass: false` → variant + dropped + `variants_dropped_spec_clarity` counter fired. Stub judge returning + `pass: true` → variant returned as before. ~3-4 new tests. + +## Deferred / explicitly-skipped + +- Admin surface for inspecting failed-judge variants (matches STORY-039 AC #4 — same + defer rationale). +- Embedding-based novelty score (STORY-039 AC unrelated to spec clarity). + +## Implementation outline + +1. `packages/prompts/src/variant-spec-clarity-prompt.ts`: + - System prompt: "You judge a coding-problem variant on spec clarity. Score 1-5 per + criterion; output strict JSON." + - User prompt: variant `title` + `problem_statement` + `examples` + `constraints` + + `concept_tags` + `hidden_tests`. + - Forbidden-phrase test on the system prompt. +2. `packages/agent/src/variant-spec-clarity-judge.ts`: + - Pure function `runVariantSpecClarityJudge({ llm, variant })`. + - Zod schema for the response; single retry on parse failure. + - Returns `{ pass: false }` on persistent failure (never throws). +3. Wire optional `judge` parameter into `generateProblemVariant`. Add + `variants_dropped_spec_clarity` to `ProblemVariantsTelemetry`. Update unit tests. +4. `apps/api/src/problem-variants.ts`: read env flag, pass `runVariantSpecClarityJudge` as + the `judge` when enabled. + +## Pattern (commits) + +1. STORY-039d story file pick-up commit. +2. Prompt + judge file + judge tests. +3. Wire judge into agent + agent tests. +4. Wire judge into Fastify route + env flag. +5. Mark STORY-039d done + update BOARD.md + STORY-039 AC tick. + +## Dependencies + +- Blocked by: [STORY-039](STORY-039-llm-problem-variants.md) (provides the agent + route + + cache). +- Builds on: [STORY-039a](STORY-039a-variant-piston-self-validation.md) (the agent's + optional-gate pattern is reused here). + +## Notes + +- The judge runs AFTER the structural Zod gate and (when wired) after Piston self- + validation. This ordering minimizes cost — variants that fail cheaper gates never reach + the LLM judge. +- Cost: ~$0.01 per variant (Haiku in/out at small token budgets). 100 variants ≈ $1. +- The judge is `Haiku` not `Sonnet` — the rubric is concrete enough that Haiku is reliable. +- Pure / no DB / no telemetry inside the judge. The caller fires the + `variants_dropped_spec_clarity` counter when `pass: false` and the agent drops the + variant. Keeps the judge module trivial to test. + +## Activity log + +- 2026-05-11 — created +- 2026-05-11 — picked up From bf7ae9e7bd5dc19d292935e0ddb70e21b795247c Mon Sep 17 00:00:00 2001 From: Rahul Singh Khokhar Date: Mon, 11 May 2026 02:38:27 -0700 Subject: [PATCH 2/7] feat(agent): variant spec-clarity LLM judge [STORY-039d] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a Haiku LLM-judge that scores LLM-generated problem variants on a 1-5 spec-clarity rubric with three criteria — instruction_clarity / example_quality / concept_match. Computes pass = min(scores) >= 3. Pure / never throws / single retry on parse failure / synthetic { pass: false } on persistent failure so the caller can use a single drop-if-not-pass pattern. - packages/prompts/src/variant-spec-clarity-prompt.ts — versioned v1 prompt with rubric anchors at 1/3/5 per criterion + forbidden-phrase guards on the system prompt itself - packages/agent/src/variant-spec-clarity-judge.ts — pure judge with Zod-validated response + parseVariantSpecClarityResponse exported for direct use - 12 prompt tests + 25 judge tests pass Co-Authored-By: Claude Opus 4.7 --- packages/agent/src/index.ts | 13 + .../src/variant-spec-clarity-judge.test.ts | 366 ++++++++++++++++++ .../agent/src/variant-spec-clarity-judge.ts | 177 +++++++++ packages/prompts/src/index.ts | 7 + .../src/variant-spec-clarity-prompt.test.ts | 125 ++++++ .../src/variant-spec-clarity-prompt.ts | 101 +++++ 6 files changed, 789 insertions(+) create mode 100644 packages/agent/src/variant-spec-clarity-judge.test.ts create mode 100644 packages/agent/src/variant-spec-clarity-judge.ts create mode 100644 packages/prompts/src/variant-spec-clarity-prompt.test.ts create mode 100644 packages/prompts/src/variant-spec-clarity-prompt.ts diff --git a/packages/agent/src/index.ts b/packages/agent/src/index.ts index 6692eb7..be0900c 100644 --- a/packages/agent/src/index.ts +++ b/packages/agent/src/index.ts @@ -268,3 +268,16 @@ export { type SeedVariantsTelemetry, type VariantCacheStore, } from "./seed-variants.js"; + +export { + parseVariantSpecClarityResponse, + runVariantSpecClarityJudge, + VARIANT_SPEC_CLARITY_MIN_PASSING, + VariantSpecClarityReasoningSchema, + VariantSpecClarityResultSchema, + type RunVariantSpecClarityJudgeInput, + type SpecClarityJudge, + type VariantSpecClarityReasoning, + type VariantSpecClarityResult, + type VariantSpecClarityScore, +} from "./variant-spec-clarity-judge.js"; diff --git a/packages/agent/src/variant-spec-clarity-judge.test.ts b/packages/agent/src/variant-spec-clarity-judge.test.ts new file mode 100644 index 0000000..90a0e98 --- /dev/null +++ b/packages/agent/src/variant-spec-clarity-judge.test.ts @@ -0,0 +1,366 @@ +import { describe, expect, it } from "vitest"; +import type { + CompleteRequest, + CompleteResponse, + EmbedRequest, + EmbedResponse, + LLMProvider, + StreamChunk, + ToolCallRequest, + ToolCallResponse, +} from "@learnpro/llm"; +import { + ImplementProblemDefSchema, + type ImplementProblemDef, + type ProblemDef, +} from "@learnpro/problems"; +import { VARIANT_SPEC_CLARITY_PROMPT_VERSION } from "@learnpro/prompts"; +import { + parseVariantSpecClarityResponse, + runVariantSpecClarityJudge, + VARIANT_SPEC_CLARITY_MIN_PASSING, +} from "./variant-spec-clarity-judge.js"; + +// STORY-039d — tests cover: +// - Pure parser: clean JSON / fenced JSON / garbage / schema-failing / out-of-range scores +// - Pass/fail computation: min(scores) >= 3 +// - runVariantSpecClarityJudge happy path: prompt version, model, role, user_id wiring +// - One failing score → pass:false +// - Malformed first response → single retry → pass on second attempt +// - Persistent malformed response → pass:false (best-effort synthetic result) +// - Transient LLM error → retry → synthetic failure if still failing +// - Non-implement variant → fails soft (synthetic failure, no LLM call) + +const VALID_VARIANT: ImplementProblemDef = ImplementProblemDefSchema.parse({ + kind: "implement", + slug: "sum-even-numbers-variant-1", + name: "Product of odd numbers", + language: "python", + difficulty: 2, + track: "python-fundamentals", + concept_tags: ["loops", "arithmetic"], + statement: + "Given a list of integers, return the product of all odd numbers in the list. If there are no odd numbers, return 1.", + starter_code: "def solve(nums):\n pass\n", + reference_solution: + "def solve(nums):\n result = 1\n for n in nums:\n if n % 2 != 0:\n result *= n\n return result\n", + public_examples: [{ input: [1, 2, 3, 4, 5], expected: 15 }], + hidden_tests: [ + { input: [], expected: 1 }, + { input: [2, 4, 6], expected: 1 }, + { input: [1, 3, 5], expected: 15 }, + ], + expected_median_time_to_solve_ms: 60_000, + variant_of: "sum-even-numbers", +}); + +function fakeLLM(responses: string[]): LLMProvider & { calls: CompleteRequest[] } { + const calls: CompleteRequest[] = []; + let idx = 0; + return { + name: "fake", + calls, + async complete(req: CompleteRequest): Promise { + calls.push(req); + const text = responses[Math.min(idx, responses.length - 1)] ?? ""; + idx += 1; + return { + text, + model: req.model ?? "claude-haiku-4-5-20251001", + finish_reason: "end_turn", + usage: { input_tokens: 200, output_tokens: 80 }, + }; + }, + async *stream(_req: CompleteRequest): AsyncIterable { + yield { delta: "", done: true }; + }, + async embed(_req: EmbedRequest): Promise { + return { vector: [], model: "voyage-3", usage: {} }; + }, + async toolCall(_req: ToolCallRequest): Promise { + return { + text: "", + tool_calls: [], + model: "fake", + finish_reason: "end_turn", + usage: { input_tokens: 0, output_tokens: 0 }, + }; + }, + }; +} + +function failingLLM(error: Error): LLMProvider { + return { + name: "failing", + async complete(_req: CompleteRequest): Promise { + throw error; + }, + async *stream(_req: CompleteRequest): AsyncIterable { + yield { delta: "", done: true }; + }, + async embed(_req: EmbedRequest): Promise { + return { vector: [], model: "voyage-3", usage: {} }; + }, + async toolCall(_req: ToolCallRequest): Promise { + return { + text: "", + tool_calls: [], + model: "fake", + finish_reason: "end_turn", + usage: { input_tokens: 0, output_tokens: 0 }, + }; + }, + }; +} + +function judgePayload(overrides: Record = {}): Record { + return { + instruction_clarity: 5, + example_quality: 4, + concept_match: 5, + reasoning: { + instruction_clarity: "Statement names inputs, outputs, and empty-input behavior.", + example_quality: "Examples cover happy path and empty input.", + concept_match: "Reference solution iterates with a for-loop and arithmetic check.", + }, + ...overrides, + }; +} + +describe("parseVariantSpecClarityResponse — STORY-039d", () => { + it("parses a clean JSON response with all-passing scores", () => { + const out = parseVariantSpecClarityResponse(JSON.stringify(judgePayload())); + expect(out).not.toBeNull(); + expect(out?.instruction_clarity).toBe(5); + expect(out?.example_quality).toBe(4); + expect(out?.concept_match).toBe(5); + expect(out?.pass).toBe(true); + }); + + it("strips ```json fences before parsing", () => { + const out = parseVariantSpecClarityResponse( + "```json\n" + JSON.stringify(judgePayload()) + "\n```", + ); + expect(out).not.toBeNull(); + expect(out?.pass).toBe(true); + }); + + it("strips bare ``` fences before parsing", () => { + const out = parseVariantSpecClarityResponse("```\n" + JSON.stringify(judgePayload()) + "\n```"); + expect(out).not.toBeNull(); + }); + + it("returns null on garbage", () => { + expect(parseVariantSpecClarityResponse("not json")).toBeNull(); + expect(parseVariantSpecClarityResponse("")).toBeNull(); + expect(parseVariantSpecClarityResponse(" ")).toBeNull(); + }); + + it("returns null on partial JSON (missing field)", () => { + const partial = judgePayload(); + delete partial.example_quality; + expect(parseVariantSpecClarityResponse(JSON.stringify(partial))).toBeNull(); + }); + + it("returns null when a score is out of 1-5 range", () => { + expect( + parseVariantSpecClarityResponse(JSON.stringify(judgePayload({ instruction_clarity: 0 }))), + ).toBeNull(); + expect( + parseVariantSpecClarityResponse(JSON.stringify(judgePayload({ instruction_clarity: 6 }))), + ).toBeNull(); + }); + + it("returns null when a score isn't an integer", () => { + expect( + parseVariantSpecClarityResponse(JSON.stringify(judgePayload({ example_quality: 2.5 }))), + ).toBeNull(); + }); + + it("returns null when reasoning has an empty string", () => { + const broken = judgePayload({ + reasoning: { + instruction_clarity: "", + example_quality: "fine", + concept_match: "fine", + }, + }); + expect(parseVariantSpecClarityResponse(JSON.stringify(broken))).toBeNull(); + }); + + it("sets pass=true when every score >= MIN_PASSING (3)", () => { + expect(VARIANT_SPEC_CLARITY_MIN_PASSING).toBe(3); + const out = parseVariantSpecClarityResponse( + JSON.stringify( + judgePayload({ instruction_clarity: 3, example_quality: 3, concept_match: 3 }), + ), + ); + expect(out?.pass).toBe(true); + }); + + it("sets pass=false when instruction_clarity < 3", () => { + const out = parseVariantSpecClarityResponse( + JSON.stringify(judgePayload({ instruction_clarity: 2 })), + ); + expect(out?.pass).toBe(false); + }); + + it("sets pass=false when example_quality < 3", () => { + const out = parseVariantSpecClarityResponse( + JSON.stringify(judgePayload({ example_quality: 1 })), + ); + expect(out?.pass).toBe(false); + }); + + it("sets pass=false when concept_match < 3", () => { + const out = parseVariantSpecClarityResponse(JSON.stringify(judgePayload({ concept_match: 2 }))); + expect(out?.pass).toBe(false); + }); + + it("sets pass=false even when the LLM emits a `pass: true` field (we compute it ourselves)", () => { + // The wrapper trusts only the three integer scores; a model that tries to override the + // computed pass flag is ignored. The response schema strips the extra field on parse. + const out = parseVariantSpecClarityResponse( + JSON.stringify(judgePayload({ instruction_clarity: 2, pass: true })), + ); + expect(out?.pass).toBe(false); + }); +}); + +describe("runVariantSpecClarityJudge — STORY-039d", () => { + it("calls Haiku with the v1 prompt version + reflection role + correct user_id", async () => { + const llm = fakeLLM([JSON.stringify(judgePayload())]); + await runVariantSpecClarityJudge({ + llm, + user_id: "u-123", + variant: VALID_VARIANT, + }); + expect(llm.calls).toHaveLength(1); + expect(llm.calls[0]?.role).toBe("reflection"); + expect(llm.calls[0]?.model).toMatch(/haiku/); + expect(llm.calls[0]?.prompt_version).toBe(VARIANT_SPEC_CLARITY_PROMPT_VERSION); + expect(llm.calls[0]?.user_id).toBe("u-123"); + }); + + it("uses a tight max_tokens budget (rubric output is small)", async () => { + const llm = fakeLLM([JSON.stringify(judgePayload())]); + await runVariantSpecClarityJudge({ llm, variant: VALID_VARIANT }); + expect(llm.calls[0]?.max_tokens).toBeLessThanOrEqual(800); + }); + + it("uses temperature 0 for deterministic rubric scoring", async () => { + const llm = fakeLLM([JSON.stringify(judgePayload())]); + await runVariantSpecClarityJudge({ llm, variant: VALID_VARIANT }); + expect(llm.calls[0]?.temperature).toBe(0); + }); + + it("happy path: all scores >= 3 → pass:true", async () => { + const llm = fakeLLM([JSON.stringify(judgePayload())]); + const out = await runVariantSpecClarityJudge({ llm, variant: VALID_VARIANT }); + expect(out.pass).toBe(true); + expect(out.instruction_clarity).toBe(5); + }); + + it("one failing score: returns pass:false without retry", async () => { + const llm = fakeLLM([JSON.stringify(judgePayload({ instruction_clarity: 2 }))]); + const out = await runVariantSpecClarityJudge({ llm, variant: VALID_VARIANT }); + expect(out.pass).toBe(false); + expect(llm.calls).toHaveLength(1); + }); + + it("malformed first response: retries once, returns parsed result on second attempt", async () => { + const llm = fakeLLM(["not json", JSON.stringify(judgePayload())]); + const out = await runVariantSpecClarityJudge({ llm, variant: VALID_VARIANT }); + expect(llm.calls).toHaveLength(2); + expect(out.pass).toBe(true); + }); + + it("persistent malformed responses: returns synthetic pass:false (best-effort, no throw)", async () => { + const llm = fakeLLM(["not json", "still not json"]); + const out = await runVariantSpecClarityJudge({ llm, variant: VALID_VARIANT }); + expect(llm.calls).toHaveLength(2); + expect(out.pass).toBe(false); + expect(out.instruction_clarity).toBe(1); + expect(out.example_quality).toBe(1); + expect(out.concept_match).toBe(1); + expect(out.reasoning.instruction_clarity).toMatch(/did not parse/); + }); + + it("LLM throws on every attempt: returns synthetic pass:false (never throws to caller)", async () => { + const llm = failingLLM(new Error("transient")); + const out = await runVariantSpecClarityJudge({ llm, variant: VALID_VARIANT }); + expect(out.pass).toBe(false); + }); + + it("LLM throws once then succeeds on retry: returns the parsed result", async () => { + let attempt = 0; + const responses = [JSON.stringify(judgePayload())]; + const llm: LLMProvider = { + name: "flaky", + async complete(req: CompleteRequest): Promise { + attempt += 1; + if (attempt === 1) throw new Error("simulated transient"); + return { + text: responses[0]!, + model: req.model ?? "claude-haiku-4-5-20251001", + finish_reason: "end_turn", + usage: { input_tokens: 100, output_tokens: 50 }, + }; + }, + async *stream(_req: CompleteRequest): AsyncIterable { + yield { delta: "", done: true }; + }, + async embed(_req: EmbedRequest): Promise { + return { vector: [], model: "voyage-3", usage: {} }; + }, + async toolCall(_req: ToolCallRequest): Promise { + return { + text: "", + tool_calls: [], + model: "fake", + finish_reason: "end_turn", + usage: { input_tokens: 0, output_tokens: 0 }, + }; + }, + }; + const out = await runVariantSpecClarityJudge({ llm, variant: VALID_VARIANT }); + expect(out.pass).toBe(true); + expect(attempt).toBe(2); + }); + + it("respects an explicit model override", async () => { + const llm = fakeLLM([JSON.stringify(judgePayload())]); + await runVariantSpecClarityJudge({ + llm, + variant: VALID_VARIANT, + model: "claude-sonnet-4-5", + }); + expect(llm.calls[0]?.model).toBe("claude-sonnet-4-5"); + }); + + it("passes the variant statement + concept_tags + examples through to the user prompt", async () => { + const llm = fakeLLM([JSON.stringify(judgePayload())]); + await runVariantSpecClarityJudge({ llm, variant: VALID_VARIANT }); + const userMessage = llm.calls[0]?.messages[0]?.content ?? ""; + expect(userMessage).toContain("Product of odd numbers"); + expect(userMessage).toContain("loops"); + expect(userMessage).toContain("arithmetic"); + // Hidden tests appear as JSON in the prompt — guards against the user prompt builder + // silently dropping fields. + expect(userMessage).toContain("Hidden tests:"); + }); + + it("non-implement variant: returns synthetic pass:false WITHOUT calling the LLM", async () => { + const llm = fakeLLM([JSON.stringify(judgePayload())]); + // Simulate a comprehension variant by shape — out-of-scope for the judge. The cast is + // intentional — the test exercises the runtime guard, not the type system. + const fakeVariant = { + ...VALID_VARIANT, + kind: "comprehension", + } as unknown as ProblemDef; + const out = await runVariantSpecClarityJudge({ llm, variant: fakeVariant }); + expect(out.pass).toBe(false); + expect(llm.calls).toHaveLength(0); + expect(out.reasoning.instruction_clarity).toMatch(/not supported/); + }); +}); diff --git a/packages/agent/src/variant-spec-clarity-judge.ts b/packages/agent/src/variant-spec-clarity-judge.ts new file mode 100644 index 0000000..49572d9 --- /dev/null +++ b/packages/agent/src/variant-spec-clarity-judge.ts @@ -0,0 +1,177 @@ +// STORY-039d — pure agent that runs a Haiku-based LLM judge over a structurally valid +// problem variant and returns 1-5 scores on three spec-clarity criteria. +// +// The judge runs AFTER the structural Zod gate (STORY-039) and AFTER (when wired) Piston +// self-validation (STORY-039a). It catches the failure modes those cheaper gates miss: +// - ambiguous statements that pass the schema but leave the learner guessing +// - examples that contradict the spec +// - concept_tag mismatches between the declared tags and what the exercise actually +// measures +// +// Design intent: +// - Pure: no DB, no telemetry, no side effects. The caller (the agent's variant pipeline) +// decides what to do with `{ pass: false }`. +// - Best-effort: never throws. Parse failure / Zod failure / transient LLM error → single +// retry → on persistent failure return `{ pass: false }` with a synthetic reasoning. A +// judge outage must never block the variant pipeline from returning what it has. +// - `pass = min(instruction_clarity, example_quality, concept_match) >= 3`. A single +// low-clarity score is enough to drop the variant. + +import { z } from "zod"; +import type { LLMProvider } from "@learnpro/llm"; +import { ANTHROPIC_HAIKU } from "@learnpro/llm"; +import { isImplementProblem, type ProblemDef } from "@learnpro/problems"; +import { + VARIANT_SPEC_CLARITY_PROMPT_VERSION, + buildVariantSpecClaritySystemPrompt, + buildVariantSpecClarityUserPrompt, + type VariantSpecClarityPromptVariant, +} from "@learnpro/prompts"; + +// Minimum per-criterion score required to keep a variant. A single score below this drops +// the variant. +export const VARIANT_SPEC_CLARITY_MIN_PASSING = 3; + +const MAX_RETRIES = 1; + +const RubricScoreSchema = z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4), z.literal(5)]); + +export const VariantSpecClarityReasoningSchema = z.object({ + instruction_clarity: z.string().min(1), + example_quality: z.string().min(1), + concept_match: z.string().min(1), +}); + +export const VariantSpecClarityResultSchema = z.object({ + instruction_clarity: RubricScoreSchema, + example_quality: RubricScoreSchema, + concept_match: RubricScoreSchema, + reasoning: VariantSpecClarityReasoningSchema, + pass: z.boolean(), +}); + +export type VariantSpecClarityScore = z.infer; +export type VariantSpecClarityReasoning = z.infer; +export type VariantSpecClarityResult = z.infer; + +// Internal schema for the raw LLM response (no `pass` field — the wrapper computes it from +// the three scores). +const ResponseSchema = z.object({ + instruction_clarity: RubricScoreSchema, + example_quality: RubricScoreSchema, + concept_match: RubricScoreSchema, + reasoning: VariantSpecClarityReasoningSchema, +}); + +export interface RunVariantSpecClarityJudgeInput { + llm: LLMProvider; + variant: ProblemDef; + user_id?: string; + // Override the default Haiku model — used by tests + future operator tuning. + model?: string; +} + +// Pure judge call. Returns `{ pass: false }` synthetically on any parse / Zod / LLM failure +// so the caller can use a single drop-if-not-pass pattern. Never throws. +export async function runVariantSpecClarityJudge( + input: RunVariantSpecClarityJudgeInput, +): Promise { + // Defensive guard — the prompt only fits implement-kind variants. Comprehension / debug + // variants are out of v1 scope for the variant pipeline, but if a future caller passes + // one we fail soft. + if (!isImplementProblem(input.variant)) { + return synthesizeFailureResult("variant kind not supported by the spec-clarity judge"); + } + + const promptVariant: VariantSpecClarityPromptVariant = { + name: input.variant.name, + statement: input.variant.statement, + concept_tags: input.variant.concept_tags, + public_examples: input.variant.public_examples, + hidden_tests: input.variant.hidden_tests, + }; + + const system = buildVariantSpecClaritySystemPrompt(); + const user = buildVariantSpecClarityUserPrompt({ variant: promptVariant }); + + for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { + let res; + try { + res = await input.llm.complete({ + messages: [{ role: "user", content: user }], + system, + model: input.model ?? ANTHROPIC_HAIKU, + role: "reflection", + max_tokens: 400, + temperature: 0, + prompt_version: VARIANT_SPEC_CLARITY_PROMPT_VERSION, + ...(input.user_id !== undefined ? { user_id: input.user_id } : {}), + }); + } catch { + // Transient LLM failure — let the loop retry. If we exhaust retries we fall through + // to the synthesized failure below. + continue; + } + + const parsed = parseVariantSpecClarityResponse(res.text); + if (parsed !== null) return parsed; + } + + return synthesizeFailureResult("judge response did not parse"); +} + +// Pure parser. Strips optional markdown fences, runs JSON.parse + Zod, and computes the +// `pass` flag from the three scores. Returns null on any failure so the caller can retry. +export function parseVariantSpecClarityResponse(text: string): VariantSpecClarityResult | null { + const stripped = text + .trim() + .replace(/^```(?:json)?\s*/i, "") + .replace(/```\s*$/i, "") + .trim(); + if (stripped.length === 0) return null; + + let raw: unknown; + try { + raw = JSON.parse(stripped); + } catch { + return null; + } + + const parsed = ResponseSchema.safeParse(raw); + if (!parsed.success) return null; + + const { instruction_clarity, example_quality, concept_match, reasoning } = parsed.data; + const pass = + Math.min(instruction_clarity, example_quality, concept_match) >= VARIANT_SPEC_CLARITY_MIN_PASSING; + + return { + instruction_clarity, + example_quality, + concept_match, + reasoning, + pass, + }; +} + +// Synthesize a failure result used when the LLM is unreachable or returns garbage. The +// `pass: false` is what the caller acts on; the rubric scores carry the minimum so that any +// downstream consumer that aggregates judge scores doesn't pull in a misleading high score. +function synthesizeFailureResult(reason: string): VariantSpecClarityResult { + return { + instruction_clarity: 1, + example_quality: 1, + concept_match: 1, + reasoning: { + instruction_clarity: reason, + example_quality: reason, + concept_match: reason, + }, + pass: false, + }; +} + +// Convenience type for the optional `judge` parameter passed to `generateProblemVariant`. +// The agent calls `judge(variant)` and inspects only `result.pass`; this lets a future +// caller swap in a stub / deterministic judge for tests without re-deriving the full +// LLMProvider surface. +export type SpecClarityJudge = (variant: ProblemDef) => Promise; diff --git a/packages/prompts/src/index.ts b/packages/prompts/src/index.ts index 50b8228..c52886e 100644 --- a/packages/prompts/src/index.ts +++ b/packages/prompts/src/index.ts @@ -86,3 +86,10 @@ export { type WeeklyThemePromptConcept, type WeeklyThemePromptOptions, } from "./weekly-theme-prompt.js"; +export { + VARIANT_SPEC_CLARITY_PROMPT_VERSION, + buildVariantSpecClaritySystemPrompt, + buildVariantSpecClarityUserPrompt, + type VariantSpecClarityPromptOptions, + type VariantSpecClarityPromptVariant, +} from "./variant-spec-clarity-prompt.js"; diff --git a/packages/prompts/src/variant-spec-clarity-prompt.test.ts b/packages/prompts/src/variant-spec-clarity-prompt.test.ts new file mode 100644 index 0000000..8dfdedf --- /dev/null +++ b/packages/prompts/src/variant-spec-clarity-prompt.test.ts @@ -0,0 +1,125 @@ +import { describe, expect, it } from "vitest"; +import { + VARIANT_SPEC_CLARITY_PROMPT_VERSION, + buildVariantSpecClaritySystemPrompt, + buildVariantSpecClarityUserPrompt, +} from "./variant-spec-clarity-prompt.js"; + +// STORY-039d — coach-voice forbidden-phrase test on the system prompt. The judge is internal +// (its output is never shown to a learner) so the register is "code reviewer", but we still +// guard against FOMO / streak / fire-emoji slipping in via a later edit. The list mirrors +// the rest of the user-visible-copy enforcement across notifications + dashboard. +const FORBIDDEN_SUBSTRINGS = [ + "DON'T LOSE", + "lose your streak", + "fall behind", + "DAY ", + "🔥", // 🔥 + "⚠️", // ⚠️ + "leaderboard", + "you've got this", + "level up", + "fomo", + "crush it", + "beat the clock", +]; + +describe("VARIANT_SPEC_CLARITY_PROMPT_VERSION — STORY-039d", () => { + it("is versioned with the v1 tag", () => { + expect(VARIANT_SPEC_CLARITY_PROMPT_VERSION).toBe("variant-spec-clarity-v1"); + }); +}); + +describe("buildVariantSpecClaritySystemPrompt — STORY-039d", () => { + it("names all three rubric criteria", () => { + const sys = buildVariantSpecClaritySystemPrompt(); + expect(sys).toContain("instruction_clarity"); + expect(sys).toContain("example_quality"); + expect(sys).toContain("concept_match"); + }); + + it("specifies a 1-5 integer scale per criterion", () => { + const sys = buildVariantSpecClaritySystemPrompt(); + expect(sys).toMatch(/1-5/); + expect(sys.toLowerCase()).toContain("integer scores only"); + }); + + it("requires reasoning per criterion in the output schema", () => { + const sys = buildVariantSpecClaritySystemPrompt(); + expect(sys).toContain('"reasoning"'); + }); + + it("instructs the model to output JSON only (no fences, no prose)", () => { + const sys = buildVariantSpecClaritySystemPrompt(); + expect(sys.toLowerCase()).toContain("no markdown fences"); + expect(sys.toLowerCase()).toContain("no prose"); + }); + + it("anchors a code-reviewer register (factual, neutral)", () => { + const sys = buildVariantSpecClaritySystemPrompt().toLowerCase(); + expect(sys).toContain("code-reviewer"); + }); + + it("has no forbidden coach-voice phrases", () => { + const sys = buildVariantSpecClaritySystemPrompt().toLowerCase(); + for (const phrase of FORBIDDEN_SUBSTRINGS) { + expect(sys.includes(phrase.toLowerCase()), `system prompt contains "${phrase}"`).toBe(false); + } + }); + + it("explicitly forbids motivational filler + emoji + exclamation in the output reasoning", () => { + const sys = buildVariantSpecClaritySystemPrompt().toLowerCase(); + expect(sys).toContain("no motivational filler"); + expect(sys).toContain("no emoji"); + expect(sys).toContain("no exclamation"); + }); + + it("rubric anchor scores explain what 1 / 3 / 5 mean per criterion", () => { + const sys = buildVariantSpecClaritySystemPrompt(); + // Each criterion gets at least one bulleted anchor for 1 + 3 + 5. + const criteria = ["instruction_clarity", "example_quality", "concept_match"]; + for (const c of criteria) { + const section = sys.slice(sys.indexOf(c)); + expect(section, `criterion ${c} should have a 1-anchor`).toMatch(/-\s*1:/); + expect(section, `criterion ${c} should have a 3-anchor`).toMatch(/-\s*3:/); + expect(section, `criterion ${c} should have a 5-anchor`).toMatch(/-\s*5:/); + } + }); +}); + +describe("buildVariantSpecClarityUserPrompt — STORY-039d", () => { + function exampleVariant() { + return { + name: "Product of odd numbers", + statement: "Given a list of integers, return the product of all odd numbers.", + concept_tags: ["loops", "arithmetic"], + public_examples: [{ input: [1, 2, 3, 4, 5], expected: 15 }], + hidden_tests: [ + { input: [], expected: 1 }, + { input: [2, 4, 6], expected: 1 }, + ], + }; + } + + it("renders the variant name + statement + concept_tags", () => { + const out = buildVariantSpecClarityUserPrompt({ variant: exampleVariant() }); + expect(out).toContain("Product of odd numbers"); + expect(out).toContain("Given a list of integers"); + expect(out).toContain("loops"); + expect(out).toContain("arithmetic"); + }); + + it("renders public examples + hidden tests verbatim as JSON", () => { + const out = buildVariantSpecClarityUserPrompt({ variant: exampleVariant() }); + expect(out).toContain("Public examples:"); + expect(out).toContain("Hidden tests:"); + // The hidden tests array shape should round-trip through JSON.stringify. + expect(out).toContain('"input":[]'); + expect(out).toContain('"expected":1'); + }); + + it("instructs the model to output JSON only with no markdown fences", () => { + const out = buildVariantSpecClarityUserPrompt({ variant: exampleVariant() }); + expect(out.toLowerCase()).toContain("no markdown fences"); + }); +}); diff --git a/packages/prompts/src/variant-spec-clarity-prompt.ts b/packages/prompts/src/variant-spec-clarity-prompt.ts new file mode 100644 index 0000000..9773f42 --- /dev/null +++ b/packages/prompts/src/variant-spec-clarity-prompt.ts @@ -0,0 +1,101 @@ +// STORY-039d — LLM-judge spec-clarity rubric for LLM-generated problem variants. +// +// STORY-039 ships variants through a structural Zod gate (`ProblemDefSchema.parse`) plus +// identity checks (language / difficulty / concept_tags / track / kind / slug-prefix / +// variant_of). STORY-039a adds a Piston self-validation gate (reference_solution must pass +// own hidden_tests). Those guards catch structural drift and reference-solution bugs, but +// they don't catch ambiguous statements, examples that disagree with the spec, or concept +// tags that don't actually match the exercise. This prompt scores a variant 1-5 on three +// criteria — instruction_clarity / example_quality / concept_match — and the caller drops +// the variant when min(scores) < 3. +// +// Tone rules: factual + analytical. The judge prompt is internal — its output isn't shown +// to a learner — so the register is "code reviewer" rather than "coach". Forbidden-phrase +// tests still guard against FOMO / streak / fire-emoji slipping into the system prompt +// (defense-in-depth: if a later edit accidentally seeds coach-voice into the rubric, the +// test catches it). + +export const VARIANT_SPEC_CLARITY_PROMPT_VERSION = "variant-spec-clarity-v1"; + +const VARIANT_SPEC_CLARITY_SYSTEM = `You are LearnPro's spec-clarity reviewer. You evaluate a single coding-problem variant on how clear and consistent its problem statement is. You do NOT critique the algorithm, the variable names, the code style, or the difficulty calibration — only how unambiguous the spec is and how well the examples + concept_tags match it. + +# Rubric (score each 1-5) + +instruction_clarity +- 1: The statement is so ambiguous a competent learner could not infer the inputs, outputs, or constraints. +- 3: The statement is workable but has one ambiguous edge case (e.g. unspecified empty-input behavior). +- 5: The statement names every input, every output, every constraint, and resolves all edge cases unambiguously. + +example_quality +- 1: The examples contradict the statement, OR there are no examples beyond the trivial happy path. +- 3: Examples cover the happy path and one edge case, all consistent with the statement. +- 5: Examples cover the happy path, an edge case (empty / single-element / boundary), and the input/output types are explicit. Hidden tests reinforce these without contradiction. + +concept_match +- 1: The declared concept_tags don't match what the problem actually exercises (e.g. tags say "recursion" but the reference_solution uses a flat for-loop). +- 3: The tags loosely match — the problem could be solved without exercising the tagged concept, but the canonical solution does exercise it. +- 5: The problem cannot be solved cleanly without exercising every declared concept_tag. + +# Output schema (JSON object — no prose, no markdown fences) +{ + "instruction_clarity": 1 | 2 | 3 | 4 | 5, + "example_quality": 1 | 2 | 3 | 4 | 5, + "concept_match": 1 | 2 | 3 | 4 | 5, + "reasoning": { + "instruction_clarity": string, // one sentence + "example_quality": string, // one sentence + "concept_match": string // one sentence + } +} + +# Hard rules +- Score each criterion independently. A weak statement does not drag down example_quality if the examples themselves are good. +- Integer scores only (1-5). +- Each reasoning line is one sentence (under 30 words). Factual, observational — no motivational filler, no second-person warmth, no marketing language. +- Output JSON only. No preamble, no markdown fences, no trailing prose. + +# Tone +- Code-reviewer register. Direct, neutral, specific. +- No exclamation points. No emoji. No second-person dares. +- Reference concrete details from the variant when explaining a score (e.g. "the empty-input case is undefined"). +`; + +export interface VariantSpecClarityPromptVariant { + name: string; + statement: string; + concept_tags: ReadonlyArray; + // `input` and `expected` are unknown because the problems schema's `TestCaseValueSchema` + // accepts any JSON-serialisable value. We pass through verbatim so the judge can reason + // about literal-value mismatches between the statement and the examples. + public_examples: ReadonlyArray<{ input?: unknown; expected?: unknown }>; + hidden_tests: ReadonlyArray<{ input?: unknown; expected?: unknown; weight?: number }>; +} + +export interface VariantSpecClarityPromptOptions { + variant: VariantSpecClarityPromptVariant; +} + +export function buildVariantSpecClaritySystemPrompt(): string { + return VARIANT_SPEC_CLARITY_SYSTEM; +} + +export function buildVariantSpecClarityUserPrompt(opts: VariantSpecClarityPromptOptions): string { + const v = opts.variant; + const lines: string[] = [ + "Variant under review:", + `- name: ${v.name}`, + `- concept_tags: ${JSON.stringify(v.concept_tags)}`, + "", + "Statement:", + v.statement, + "", + "Public examples:", + JSON.stringify(v.public_examples), + "", + "Hidden tests:", + JSON.stringify(v.hidden_tests), + "", + "Score now. Output JSON only — no markdown fences, no prose.", + ]; + return lines.join("\n"); +} From c795a722508921a45618cca3b17cab888daae585 Mon Sep 17 00:00:00 2001 From: Rahul Singh Khokhar Date: Mon, 11 May 2026 02:42:32 -0700 Subject: [PATCH 3/7] feat(agent): gate problem variants through spec-clarity judge [STORY-039d] Wires `runVariantSpecClarityJudge` into `generateProblemVariant` as a second gate (alongside STORY-039's Zod structural gate and STORY-039a's Piston self-validation gate). The judge runs after sandbox validation; a `pass:false` result drops the variant, fires `variants_dropped_spec_clarity` telemetry, and counts toward the same retry budget. The retry call carries an augmented prompt that points the model at the lowest-scoring rubric criterion. - `judge?: SpecClarityJudge` parameter on `GenerateProblemVariantInput` - new `variants_dropped_spec_clarity` counter on `ProblemVariantsTelemetry` - `PreviousFailure` is now a discriminated union (`self_validation` | `spec_clarity`) so the retry prompt picks the right corrective phrasing - 9 new tests covering happy path / drop+retry / drop-twice / sandbox+judge ordering / throwing-judge / throwing-sink Co-Authored-By: Claude Opus 4.7 --- packages/agent/src/problem-variants.test.ts | 257 ++++++++++++++++++++ packages/agent/src/problem-variants.ts | 242 +++++++++++++----- 2 files changed, 441 insertions(+), 58 deletions(-) diff --git a/packages/agent/src/problem-variants.test.ts b/packages/agent/src/problem-variants.test.ts index 132cd6d..1fe2863 100644 --- a/packages/agent/src/problem-variants.test.ts +++ b/packages/agent/src/problem-variants.test.ts @@ -32,6 +32,7 @@ import { parseProblemVariantResponse, type ProblemVariantsTelemetry, } from "./problem-variants.js"; +import type { SpecClarityJudge, VariantSpecClarityResult } from "./variant-spec-clarity-judge.js"; // STORY-039 — tests cover: // - The `variant_of` field validates correctly through ProblemDefSchema @@ -457,10 +458,60 @@ function recordingTelemetry(): { events.push({ kind: "validated_pass", slug: e.slug, attempt: e.attempt }), variants_dropped_fail: (e) => events.push({ kind: "dropped_fail", slug: e.slug, attempt: e.attempt }), + variants_dropped_spec_clarity: (e) => + events.push({ kind: "dropped_spec_clarity", slug: e.slug, attempt: e.attempt }), }; return { events, cb }; } +// STORY-039d — stub judges for testing. +function passingJudge(): SpecClarityJudge & { calls: number } { + const judge = ((async () => { + judge.calls += 1; + return { + instruction_clarity: 5, + example_quality: 4, + concept_match: 5, + reasoning: { + instruction_clarity: "clear", + example_quality: "good examples", + concept_match: "tags match", + }, + pass: true, + } satisfies VariantSpecClarityResult; + }) as SpecClarityJudge & { calls: number }); + judge.calls = 0; + return judge; +} + +function failingJudge(scoreOverride = 2): SpecClarityJudge & { calls: number } { + const judge = ((async () => { + judge.calls += 1; + return { + instruction_clarity: scoreOverride, + example_quality: 4, + concept_match: 5, + reasoning: { + instruction_clarity: "the empty-input behavior is undefined", + example_quality: "fine", + concept_match: "fine", + }, + pass: false, + } satisfies VariantSpecClarityResult; + }) as SpecClarityJudge & { calls: number }); + judge.calls = 0; + return judge; +} + +function throwingJudge(): SpecClarityJudge & { calls: number } { + const judge = ((async () => { + judge.calls += 1; + throw new Error("judge boom"); + }) as SpecClarityJudge & { calls: number }); + judge.calls = 0; + return judge; +} + describe("generateProblemVariant — STORY-039a self-validation gate", () => { it("happy path: passing sandbox + valid variant → returns variant + emits validated_pass", async () => { const llm = fakeLLM([JSON.stringify(validVariantPayload())]); @@ -645,6 +696,212 @@ describe("generateProblemVariant — STORY-039a self-validation gate", () => { }); }); +// ============================================================================ +// STORY-039d — LLM-judge spec-clarity rubric. The agent now optionally accepts a +// `SpecClarityJudge`; when wired, every parsed variant must score >= 3 on each +// rubric criterion (instruction_clarity / example_quality / concept_match) +// before being returned. Failure → augmented retry → on second failure, drop. +// A new `variants_dropped_spec_clarity` counter fires per drop. +// ============================================================================ + +describe("generateProblemVariant — STORY-039d spec-clarity judge gate", () => { + it("happy path: passing judge → returns variant + emits validated_pass (no dropped_spec_clarity)", async () => { + const llm = fakeLLM([JSON.stringify(validVariantPayload())]); + const judge = passingJudge(); + const { events, cb } = recordingTelemetry(); + const out = await generateProblemVariant({ + llm, + user_id: "u", + source: SOURCE_PROBLEM, + judge, + onTelemetry: cb, + }); + expect(out.variants).toHaveLength(1); + expect(out.fallback_used).toBe(false); + expect(judge.calls).toBe(1); + expect(events).toEqual([ + { kind: "generated", slug: "sum-even-numbers-variant-1", attempt: 1 }, + { kind: "validated_pass", slug: "sum-even-numbers-variant-1", attempt: 1 }, + ]); + }); + + it("failing judge: drops the variant, retries once, then returns empty + 2 dropped_spec_clarity events", async () => { + const llm = fakeLLM([ + JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-1" })), + JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-2" })), + ]); + const judge = failingJudge(); + const { events, cb } = recordingTelemetry(); + const out = await generateProblemVariant({ + llm, + user_id: "u", + source: SOURCE_PROBLEM, + judge, + onTelemetry: cb, + }); + expect(out.variants).toEqual([]); + expect(out.fallback_used).toBe(true); + expect(judge.calls).toBe(2); + expect(events.filter((e) => e.kind === "dropped_spec_clarity")).toHaveLength(2); + expect(events.filter((e) => e.kind === "validated_pass")).toHaveLength(0); + }); + + it("retry call carries an augmented prompt referencing the lowest-scoring criterion", async () => { + const llm = fakeLLM([ + JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-1" })), + JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-2" })), + ]); + await generateProblemVariant({ + llm, + user_id: "u", + source: SOURCE_PROBLEM, + judge: failingJudge(), + }); + expect(llm.calls).toHaveLength(2); + const secondMessage = llm.calls[1]?.messages[0]?.content ?? ""; + expect(secondMessage).toContain("failed the spec-clarity"); + expect(secondMessage).toContain("instruction_clarity"); + expect(secondMessage).toContain("the empty-input behavior is undefined"); + }); + + it("first attempt fails judge, second attempt passes → returns the second variant", async () => { + let judgeCalls = 0; + const stubJudge: SpecClarityJudge = async () => { + judgeCalls += 1; + if (judgeCalls === 1) { + return { + instruction_clarity: 2, + example_quality: 4, + concept_match: 5, + reasoning: { + instruction_clarity: "ambiguous empty case", + example_quality: "ok", + concept_match: "ok", + }, + pass: false, + }; + } + return { + instruction_clarity: 5, + example_quality: 5, + concept_match: 5, + reasoning: { + instruction_clarity: "clear", + example_quality: "good", + concept_match: "good", + }, + pass: true, + }; + }; + const llm = fakeLLM([ + JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-1" })), + JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-2" })), + ]); + const { events, cb } = recordingTelemetry(); + const out = await generateProblemVariant({ + llm, + user_id: "u", + source: SOURCE_PROBLEM, + judge: stubJudge, + onTelemetry: cb, + }); + expect(out.variants).toHaveLength(1); + expect(out.variants[0]?.slug).toBe("sum-even-numbers-variant-2"); + expect(out.fallback_used).toBe(false); + expect(events.map((e) => e.kind)).toEqual([ + "generated", + "dropped_spec_clarity", + "generated", + "validated_pass", + ]); + }); + + it("judge throws → treated as a drop (does not crash the agent)", async () => { + const llm = fakeLLM([ + JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-1" })), + JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-2" })), + ]); + const judge = throwingJudge(); + const { events, cb } = recordingTelemetry(); + const out = await generateProblemVariant({ + llm, + user_id: "u", + source: SOURCE_PROBLEM, + judge, + onTelemetry: cb, + }); + expect(out.variants).toEqual([]); + expect(out.fallback_used).toBe(true); + expect(events.filter((e) => e.kind === "dropped_spec_clarity").length).toBeGreaterThan(0); + }); + + it("judge AND sandbox both wired: sandbox fail short-circuits before judge runs", async () => { + const llm = fakeLLM([ + JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-1" })), + JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-2" })), + ]); + const sandbox = new StubFailingSandbox(); + const judge = passingJudge(); + await generateProblemVariant({ + llm, + user_id: "u", + source: SOURCE_PROBLEM, + sandbox, + judge, + }); + // Sandbox failed → judge should never run. + expect(judge.calls).toBe(0); + }); + + it("judge AND sandbox both wired: sandbox pass + judge pass → returns variant", async () => { + const llm = fakeLLM([JSON.stringify(validVariantPayload())]); + const sandbox = new StubPassingSandbox(); + const judge = passingJudge(); + const out = await generateProblemVariant({ + llm, + user_id: "u", + source: SOURCE_PROBLEM, + sandbox, + judge, + }); + expect(out.variants).toHaveLength(1); + expect(sandbox.calls.length).toBeGreaterThan(0); + expect(judge.calls).toBe(1); + }); + + it("no judge wired: validated_pass still fires (behaves as STORY-039a)", async () => { + const llm = fakeLLM([JSON.stringify(validVariantPayload())]); + const { events, cb } = recordingTelemetry(); + const out = await generateProblemVariant({ + llm, + user_id: "u", + source: SOURCE_PROBLEM, + onTelemetry: cb, + }); + expect(out.variants).toHaveLength(1); + expect(events.filter((e) => e.kind === "dropped_spec_clarity")).toHaveLength(0); + expect(events.filter((e) => e.kind === "validated_pass")).toHaveLength(1); + }); + + it("a throwing dropped_spec_clarity sink does not block variant generation", async () => { + const llm = fakeLLM([JSON.stringify(validVariantPayload())]); + const out = await generateProblemVariant({ + llm, + user_id: "u", + source: SOURCE_PROBLEM, + judge: failingJudge(), + onTelemetry: { + variants_dropped_spec_clarity: () => { + throw new Error("sink boom"); + }, + }, + }); + // failingJudge always returns pass:false → empty variants but no thrown error. + expect(out.variants).toEqual([]); + expect(out.fallback_used).toBe(true); + }); +}); + describe("problem-variants prompt — STORY-039 forbidden-phrase test", () => { // Coach-voice rules: no FOMO / loss-aversion / streak-shaming / coercive copy in the // user-facing variant statement. The system prompt sets the register; the test guards diff --git a/packages/agent/src/problem-variants.ts b/packages/agent/src/problem-variants.ts index 459a99e..ef6d0ac 100644 --- a/packages/agent/src/problem-variants.ts +++ b/packages/agent/src/problem-variants.ts @@ -2,26 +2,38 @@ // STORY-039a — wires `validateProblem` from `@learnpro/problems` into the pipeline so a // variant whose `reference_solution` doesn't pass its own `hidden_tests` is dropped before // it can be cached or surfaced to a user. +// STORY-039d — wires an optional LLM-judge spec-clarity rubric: after the structural Zod +// gate (STORY-039) and (when wired) Piston self-validation (STORY-039a), the judge scores +// the variant 1-5 on instruction_clarity / example_quality / concept_match. Variants with +// `min(scores) < 3` are dropped via a new `variants_dropped_spec_clarity` telemetry +// counter. // // `generateProblemVariant` is a pure function: given an LLMProvider (and optionally a -// SandboxProvider), it asks Haiku for a variant, parses the JSON output, validates against -// `ProblemDefSchema`, optionally runs the variant's reference solution against its own -// hidden_tests through the sandbox, and returns the parsed list. Failed parses (invalid JSON, +// SandboxProvider + spec-clarity judge), it asks Haiku for a variant, parses the JSON +// output, validates against `ProblemDefSchema`, optionally runs the variant's reference +// solution against its own hidden_tests through the sandbox, optionally runs a second LLM +// judge for spec clarity, and returns the parsed list. Failed parses (invalid JSON, // schema-failing variants) are dropped — the agent retries once with an augmented "fix the // previous variant" prompt and then returns whatever passed validation, which may be empty. // -// Design intent (STORY-039 + STORY-039a): -// - Cheap: Haiku, capped output tokens, single retry per source. +// Design intent (STORY-039 + STORY-039a + STORY-039d): +// - Cheap: Haiku, capped output tokens, single retry per source. The spec-clarity judge +// adds at most one extra Haiku call per variant (~$0.01) when wired. // - Pure: doesn't talk to the DB. The route handler owns persistence and decides whether -// to wire the sandbox (the env flag `LEARNPRO_VARIANT_SELF_VALIDATE` lives in the route). +// to wire the sandbox (the env flag `LEARNPRO_VARIANT_SELF_VALIDATE` lives in the route) +// or the judge (`LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE`). // - Strict at the boundary: the LLM output is run through `ProblemDefSchema.parse` so a // row that lands in the `problem_variants` cache is interchangeable with a YAML. // - Self-validating: when a sandbox is wired, the variant's reference_solution must pass // all of its own hidden_tests before being returned. This is AC #3 of STORY-039 and the // reason malformed variants no longer ship. +// - Spec-clarity-judged: when a judge is wired, the variant's statement + examples + +// concept_tags must score >= 3 on each rubric criterion. Closes AC #3's spec-clarity +// gap (the part the Zod + Piston gates don't cover). // - Best-effort: the function never throws. On every failure mode (LLM blank, JSON fail, -// Zod fail, validator fail twice) the result is `{ variants: [], fallback_used: true }` -// and the route returns 200 with an empty list so the UI can show an empty state. +// Zod fail, validator fail twice, judge drop twice) the result is +// `{ variants: [], fallback_used: true }` and the route returns 200 with an empty list +// so the UI can show an empty state. import type { LLMProvider } from "@learnpro/llm"; import { ANTHROPIC_HAIKU } from "@learnpro/llm"; @@ -40,16 +52,24 @@ import { type ProblemVariantsPromptSourceShape, } from "@learnpro/prompts"; import type { SandboxProvider } from "@learnpro/sandbox"; +import type { + SpecClarityJudge, + VariantSpecClarityResult, +} from "./variant-spec-clarity-judge.js"; // STORY-039a — telemetry callback. The route surfaces these counts to logs / metrics; the -// agent stays pure (no global state). All three counters are per-source (one call to +// agent stays pure (no global state). All counters are per-source (one call to // `generateProblemVariant`); the route may aggregate over a session if it wishes. +// +// STORY-039d adds `variants_dropped_spec_clarity` — emitted when the LLM-judge spec-clarity +// rubric drops the variant. Separate from `variants_dropped_fail` (which is for sandbox +// self-validation failures) so operators can attribute drops to the right gate. export interface ProblemVariantsTelemetry { // Emitted once per source-problem call when the LLM produced a structurally valid variant // (passed `parseProblemVariantResponse`). Counts both attempts that reached this point. variants_generated: (event: { slug: string; source_slug: string; attempt: number }) => void; // Emitted when a structurally valid variant also passed self-validation (reference_solution - // ran against hidden_tests in the sandbox). + // ran against hidden_tests in the sandbox) AND (when wired) the spec-clarity judge. variants_validated_pass: (event: { slug: string; source_slug: string; attempt: number }) => void; // Emitted when self-validation failed. The dropped variant + first failure detail are // surfaced so an operator can inspect later (no DB persistence in v1 — log-only). @@ -59,6 +79,14 @@ export interface ProblemVariantsTelemetry { attempt: number; failures: ProblemValidationResult["failures"]; }) => void; + // STORY-039d — emitted when the LLM-judge spec-clarity rubric drops the variant. The + // judge's per-criterion scores + reasoning are surfaced so an operator can inspect later. + variants_dropped_spec_clarity: (event: { + slug: string; + source_slug: string; + attempt: number; + judge: VariantSpecClarityResult; + }) => void; } export interface GenerateProblemVariantInput { @@ -77,6 +105,12 @@ export interface GenerateProblemVariantInput { // STORY-039a — optional time budget per hidden-test execution (passed straight through to // `validateProblem`). Defaults to the validate.ts default (5_000 ms) when omitted. validation_time_limit_ms?: number; + // STORY-039d — optional LLM-judge spec-clarity rubric. When wired, every parsed variant + // is scored 1-5 on instruction_clarity / example_quality / concept_match. Variants where + // `min(scores) < 3` are dropped and a `variants_dropped_spec_clarity` counter fires. + // Caller-controlled (route reads `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE`). Omit to skip the + // judge entirely and behave as STORY-039a. + judge?: SpecClarityJudge; // STORY-039a — optional structured telemetry callbacks. Each is called best-effort; throws // are swallowed so a sink hiccup never blocks variant generation. onTelemetry?: Partial; @@ -115,6 +149,7 @@ export async function generateProblemVariant( already_used_slugs: usedSlugs, sandbox: input.sandbox, validation_time_limit_ms: input.validation_time_limit_ms, + judge: input.judge, onTelemetry: input.onTelemetry, }); if (variant) { @@ -138,11 +173,15 @@ interface TryGenerateOneInput { already_used_slugs: Set; sandbox?: SandboxProvider; validation_time_limit_ms?: number; + judge?: SpecClarityJudge; onTelemetry?: Partial; } // STORY-039a — the retry loop carries the previous attempt's failing variant + reason so the // second LLM call can be steered with a "fix the bug in your previous variant" prompt. +// STORY-039d — adds a second gate (the spec-clarity judge) that runs after sandbox +// self-validation. A judge drop counts toward the same retry budget; persistent failure +// drops the variant entirely. async function tryGenerateOne(input: TryGenerateOneInput): Promise { let previousFailure: PreviousFailure | null = null; @@ -165,52 +204,72 @@ async function tryGenerateOne(input: TryGenerateOneInput): Promise { + try { + return await judge(variant); + } catch { + return { + instruction_clarity: 1, + example_quality: 1, + concept_match: 1, + reasoning: { + instruction_clarity: "spec-clarity judge threw", + example_quality: "spec-clarity judge threw", + concept_match: "spec-clarity judge threw", + }, + pass: false, + }; + } +} + +function lowestCriterion(j: VariantSpecClarityResult): { + name: "instruction_clarity" | "example_quality" | "concept_match"; + score: number; + reasoning: string; +} { + const items: Array<{ + name: "instruction_clarity" | "example_quality" | "concept_match"; + score: number; + reasoning: string; + }> = [ + { + name: "instruction_clarity", + score: j.instruction_clarity, + reasoning: j.reasoning.instruction_clarity, + }, + { name: "example_quality", score: j.example_quality, reasoning: j.reasoning.example_quality }, + { name: "concept_match", score: j.concept_match, reasoning: j.reasoning.concept_match }, + ]; + return items.reduce((lo, cur) => (cur.score < lo.score ? cur : lo)); +} + // Parses the LLM output and runs it through `ProblemDefSchema.parse`. Returns null on any // failure (invalid JSON, schema-failing variant, or — defense-in-depth — a variant that // drifted in language / difficulty / concept_tags away from the source). The caller retries From a1e20276964c2e993a7ea9ba67b6f70d441d8bba Mon Sep 17 00:00:00 2001 From: Rahul Singh Khokhar Date: Mon, 11 May 2026 02:45:33 -0700 Subject: [PATCH 4/7] feat(api): wire spec-clarity judge into problem-variants route [STORY-039d] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - New `buildVariantSpecClarityJudgeFromEnv` reads `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE` and returns a `SpecClarityJudge` only when enabled. Default is ON when `ANTHROPIC_API_KEY` is set, OFF otherwise (cost-safe default — judge costs ~$0.01 per variant). Disable values: 0 / false / off / no. - New optional `variantSpecClarityJudge` field on `BuildServerOptions`; the problem-variants route passes it through to `generateProblemVariant`. - `defaultsFromEnv` wires the env builder alongside the existing route. The wiring uses the same `llm` instance the rest of the API uses (no extra transport). - 8 new route tests cover env-flag enable/disable cases + judge-pass-through on a passing stub + drop-on-failing-stub + no-judge-default. Co-Authored-By: Claude Opus 4.7 --- apps/api/src/index.ts | 22 ++- apps/api/src/problem-variants.test.ts | 184 ++++++++++++++++++++++++++ apps/api/src/problem-variants.ts | 43 +++++- 3 files changed, 247 insertions(+), 2 deletions(-) diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index 5aeff7a..e8c3064 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -62,7 +62,10 @@ import { registerCheatsheetRoutes, type CheatsheetEpisodeFetcher, } from "./cheatsheet.js"; -import { registerProblemVariantsRoutes } from "./problem-variants.js"; +import { + buildVariantSpecClarityJudgeFromEnv, + registerProblemVariantsRoutes, +} from "./problem-variants.js"; import { loadExportWindowMs, noDbExporter, @@ -245,6 +248,12 @@ export interface BuildServerOptions { // registers `POST /v1/problem-variants`. Tests inject a fake DB; production wires the // same `db` instance via `defaultsFromEnv()`. problemVariantsDb?: import("@learnpro/db").LearnProDb; + // STORY-039d — optional LLM-judge spec-clarity rubric for the problem-variants route. + // When supplied, every generated variant is scored 1-5 on instruction_clarity / + // example_quality / concept_match before being persisted. `defaultsFromEnv` wires + // `buildVariantSpecClarityJudgeFromEnv` (default ON when ANTHROPIC_API_KEY is set; + // operator-disable via `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE=0`). + variantSpecClarityJudge?: import("@learnpro/agent").SpecClarityJudge; } // Default impl when no store is provided — drops events on the floor. Useful for tests and @@ -585,11 +594,15 @@ export function buildServer(opts: BuildServerOptions = {}) { // STORY-039 — LLM-generated problem-variants route. Wired only when a DB is supplied; // defaultsFromEnv forwards the same `db` instance the rest of the API uses. + // STORY-039d — optional spec-clarity judge from `defaultsFromEnv` is passed through here. if (opts.problemVariantsDb) { registerProblemVariantsRoutes(app, { db: opts.problemVariantsDb, llm, sessionResolver, + ...(opts.variantSpecClarityJudge !== undefined + ? { judge: opts.variantSpecClarityJudge } + : {}), }); } @@ -653,6 +666,7 @@ function defaultsFromEnv(): { cheatsheetDb?: import("@learnpro/db").LearnProDb; cheatsheetEpisodeFetcher?: CheatsheetEpisodeFetcher; problemVariantsDb?: import("@learnpro/db").LearnProDb; + variantSpecClarityJudge?: import("@learnpro/agent").SpecClarityJudge; } { const exportRateLimiter = buildExportRateLimiterFromEnv(process.env); const url = process.env["DATABASE_URL"]; @@ -758,6 +772,12 @@ function defaultsFromEnv(): { cheatsheetDb: db, cheatsheetEpisodeFetcher: buildDbCheatsheetEpisodeFetcher(db), problemVariantsDb: db, + // STORY-039d — wire the spec-clarity judge only when enabled (default on with API key). + // The judge adds ~$0.01 per generated variant; the env flag lets operators turn it off. + ...(() => { + const judge = buildVariantSpecClarityJudgeFromEnv({ llm, env: process.env }); + return judge ? { variantSpecClarityJudge: judge } : {}; + })(), ...(exportRateLimiter ? { exportRateLimiter } : {}), // STORY-033 — async profile-update agent. Build the BullMQ cron from REDIS_URL (returns null // when unset, in which case the enqueue helper is a soft no-op). Wire the session-end hook diff --git a/apps/api/src/problem-variants.test.ts b/apps/api/src/problem-variants.test.ts index aeaadd7..218461c 100644 --- a/apps/api/src/problem-variants.test.ts +++ b/apps/api/src/problem-variants.test.ts @@ -412,3 +412,187 @@ describe("Problem-variants route wiring — STORY-039", () => { await app.close(); }); }); + +describe("buildVariantSpecClarityJudgeFromEnv — STORY-039d env flag", () => { + const fakeLLM: LLMProvider = { + name: "fake", + async complete(_req: CompleteRequest): Promise { + return { + text: "", + model: "claude-haiku-4-5-20251001", + finish_reason: "end_turn", + usage: { input_tokens: 0, output_tokens: 0 }, + }; + }, + async *stream(_req: CompleteRequest): AsyncIterable { + yield { delta: "", done: true }; + }, + async embed(_req: EmbedRequest): Promise { + return { vector: [], model: "voyage-3", usage: {} }; + }, + async toolCall(_req: ToolCallRequest): Promise { + return { + text: "", + tool_calls: [], + model: "fake", + finish_reason: "end_turn", + usage: { input_tokens: 0, output_tokens: 0 }, + }; + }, + }; + + it("returns a judge when LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE=1", async () => { + const { buildVariantSpecClarityJudgeFromEnv } = await import("./problem-variants.js"); + const judge = buildVariantSpecClarityJudgeFromEnv({ + llm: fakeLLM, + env: { LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE: "1" }, + }); + expect(judge).toBeDefined(); + }); + + it("returns a judge by default when ANTHROPIC_API_KEY is set", async () => { + const { buildVariantSpecClarityJudgeFromEnv } = await import("./problem-variants.js"); + const judge = buildVariantSpecClarityJudgeFromEnv({ + llm: fakeLLM, + env: { ANTHROPIC_API_KEY: "sk-test" }, + }); + expect(judge).toBeDefined(); + }); + + it("returns undefined when LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE=0", async () => { + const { buildVariantSpecClarityJudgeFromEnv } = await import("./problem-variants.js"); + const judge = buildVariantSpecClarityJudgeFromEnv({ + llm: fakeLLM, + env: { ANTHROPIC_API_KEY: "sk-test", LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE: "0" }, + }); + expect(judge).toBeUndefined(); + }); + + it("returns undefined when LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE=false", async () => { + const { buildVariantSpecClarityJudgeFromEnv } = await import("./problem-variants.js"); + const judge = buildVariantSpecClarityJudgeFromEnv({ + llm: fakeLLM, + env: { ANTHROPIC_API_KEY: "sk-test", LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE: "false" }, + }); + expect(judge).toBeUndefined(); + }); + + it("returns undefined when LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE=off", async () => { + const { buildVariantSpecClarityJudgeFromEnv } = await import("./problem-variants.js"); + const judge = buildVariantSpecClarityJudgeFromEnv({ + llm: fakeLLM, + env: { ANTHROPIC_API_KEY: "sk-test", LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE: "OFF" }, + }); + expect(judge).toBeUndefined(); + }); + + it("returns undefined by default when ANTHROPIC_API_KEY is NOT set (cost-safe default)", async () => { + const { buildVariantSpecClarityJudgeFromEnv } = await import("./problem-variants.js"); + const judge = buildVariantSpecClarityJudgeFromEnv({ llm: fakeLLM, env: {} }); + expect(judge).toBeUndefined(); + }); +}); + +describe("POST /v1/problem-variants — STORY-039d judge wiring", () => { + it("passes the judge through to generateProblemVariant when wired (variant returned on judge pass)", async () => { + // Use a stub judge that returns pass:true so the variant flows through. + const stubJudge = vi.fn(async () => ({ + instruction_clarity: 5 as const, + example_quality: 5 as const, + concept_match: 5 as const, + reasoning: { + instruction_clarity: "clear", + example_quality: "good", + concept_match: "tags match", + }, + pass: true, + })); + listProblemVariants.mockResolvedValue([]); + insertProblemVariant.mockImplementation(async (_db: LearnProDb, args: { variant_def: unknown }) => ({ + id: "row-1", + org_id: "self", + source_problem_id: SOURCE_PROBLEM_ID, + variant_def: args.variant_def, + created_at: new Date(), + })); + const llm = fakeLlm([JSON.stringify(VALID_VARIANT_PAYLOAD)]); + const db = fakeDbWithProblem([SOURCE_PROBLEM_ROW]); + const app = buildServer({ + sessionResolver: userSession(USER_ID), + llm, + problemVariantsDb: db, + variantSpecClarityJudge: stubJudge, + }); + const res = await app.inject({ + method: "POST", + url: "/v1/problem-variants", + payload: { source_problem_id: SOURCE_PROBLEM_ID, count: 1 }, + }); + expect(res.statusCode).toBe(200); + expect(res.json().variants).toHaveLength(1); + expect(stubJudge).toHaveBeenCalledTimes(1); + await app.close(); + }); + + it("drops variants when the judge fails (returns empty variants list on persistent fail)", async () => { + const stubJudge = vi.fn(async () => ({ + instruction_clarity: 1 as const, + example_quality: 4 as const, + concept_match: 5 as const, + reasoning: { + instruction_clarity: "the empty case is undefined", + example_quality: "fine", + concept_match: "fine", + }, + pass: false, + })); + listProblemVariants.mockResolvedValue([]); + const llm = fakeLlm([ + JSON.stringify({ ...VALID_VARIANT_PAYLOAD, slug: "sum-even-numbers-variant-1" }), + JSON.stringify({ ...VALID_VARIANT_PAYLOAD, slug: "sum-even-numbers-variant-2" }), + ]); + const db = fakeDbWithProblem([SOURCE_PROBLEM_ROW]); + const app = buildServer({ + sessionResolver: userSession(USER_ID), + llm, + problemVariantsDb: db, + variantSpecClarityJudge: stubJudge, + }); + const res = await app.inject({ + method: "POST", + url: "/v1/problem-variants", + payload: { source_problem_id: SOURCE_PROBLEM_ID, count: 1 }, + }); + expect(res.statusCode).toBe(200); + expect(res.json().variants).toEqual([]); + expect(insertProblemVariant).not.toHaveBeenCalled(); + expect(stubJudge).toHaveBeenCalled(); + await app.close(); + }); + + it("behaves as STORY-039 when no judge is supplied (variant returned without judge call)", async () => { + listProblemVariants.mockResolvedValue([]); + insertProblemVariant.mockImplementation(async (_db: LearnProDb, args: { variant_def: unknown }) => ({ + id: "row-1", + org_id: "self", + source_problem_id: SOURCE_PROBLEM_ID, + variant_def: args.variant_def, + created_at: new Date(), + })); + const llm = fakeLlm([JSON.stringify(VALID_VARIANT_PAYLOAD)]); + const db = fakeDbWithProblem([SOURCE_PROBLEM_ROW]); + const app = buildServer({ + sessionResolver: userSession(USER_ID), + llm, + problemVariantsDb: db, + }); + const res = await app.inject({ + method: "POST", + url: "/v1/problem-variants", + payload: { source_problem_id: SOURCE_PROBLEM_ID, count: 1 }, + }); + expect(res.statusCode).toBe(200); + expect(res.json().variants).toHaveLength(1); + await app.close(); + }); +}); diff --git a/apps/api/src/problem-variants.ts b/apps/api/src/problem-variants.ts index 456b508..b5844dc 100644 --- a/apps/api/src/problem-variants.ts +++ b/apps/api/src/problem-variants.ts @@ -1,7 +1,11 @@ import { and, eq } from "drizzle-orm"; import type { FastifyInstance } from "fastify"; import { z } from "zod"; -import { generateProblemVariant } from "@learnpro/agent"; +import { + generateProblemVariant, + runVariantSpecClarityJudge, + type SpecClarityJudge, +} from "@learnpro/agent"; import { insertProblemVariant, listProblemVariants, @@ -46,6 +50,12 @@ export interface ProblemVariantsRouteOptions { sessionResolver: SessionResolver; // Override the agent's model — production defaults to Haiku via the agent itself. model?: string; + // STORY-039d — optional LLM-judge spec-clarity rubric. When supplied, every generated + // variant is scored 1-5 on instruction_clarity / example_quality / concept_match before + // being persisted; `min(scores) < 3` drops the variant. Production wiring goes through + // `buildVariantSpecClarityJudgeFromEnv` so the `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE` env + // flag can disable the round-trip. + judge?: SpecClarityJudge; } export function registerProblemVariantsRoutes( @@ -106,6 +116,7 @@ export function registerProblemVariantsRoutes( source: sourceImplement, count: need, ...(opts.model !== undefined ? { model: opts.model } : {}), + ...(opts.judge !== undefined ? { judge: opts.judge } : {}), }); } catch (err) { req.log.warn({ err }, "problem-variant agent failed — surfacing 503"); @@ -227,3 +238,33 @@ function difficultyTextToInt(text: string): number { return 3; } } + +// STORY-039d — env-flag builder for the spec-clarity judge. Mirrors `buildWeeklyThemeGenerator +// FromEnv` (STORY-046c). Reads `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE` and returns a +// `SpecClarityJudge` only when the flag is enabled. Default is ON when `ANTHROPIC_API_KEY` +// is set, OFF otherwise (so dev / self-host without an API key never accidentally fires the +// judge — the judge costs ~$0.01 per variant). +// +// Disable values (case-insensitive): "0", "false", "off", "no". Anything else (including +// unset when `ANTHROPIC_API_KEY` is present) enables the judge. +export function buildVariantSpecClarityJudgeFromEnv(opts: { + llm: LLMProvider; + env: NodeJS.ProcessEnv; +}): SpecClarityJudge | undefined { + const raw = opts.env["LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE"]; + if (raw !== undefined) { + const normalized = raw.toLowerCase().trim(); + const disabled = + normalized === "0" || normalized === "false" || normalized === "off" || normalized === "no"; + if (disabled) return undefined; + return buildJudgeFn(opts.llm); + } + // Default: enable only when an API key is wired. Self-host without a key never fires the + // judge. + if (!opts.env["ANTHROPIC_API_KEY"]) return undefined; + return buildJudgeFn(opts.llm); +} + +function buildJudgeFn(llm: LLMProvider): SpecClarityJudge { + return async (variant) => runVariantSpecClarityJudge({ llm, variant }); +} From e8fa91733d3db8238bb8ae0ee4fa40e80cd2ee4b Mon Sep 17 00:00:00 2001 From: Rahul Singh Khokhar Date: Mon, 11 May 2026 02:47:19 -0700 Subject: [PATCH 5/7] chore(project): mark STORY-039d done + update BOARD [STORY-039d] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - STORY-039d status → done, AC #1-6 → [x], activity log appended - STORY-039 AC #3 (LLM-judge spec-clarity rubric) → [x], activity log appended - BOARD.md: Last updated header leads with STORY-039d; new row in Recently Done table before STORY-039a Co-Authored-By: Claude Opus 4.7 --- apps/api/src/problem-variants.test.ts | 32 +++++++++-------- packages/agent/src/problem-variants.test.ts | 12 +++---- packages/agent/src/problem-variants.ts | 5 +-- .../agent/src/variant-spec-clarity-judge.ts | 11 ++++-- project/BOARD.md | 13 +++---- .../stories/STORY-039-llm-problem-variants.md | 3 +- .../STORY-039d-variant-spec-clarity-judge.md | 34 ++++++++++++++----- 7 files changed, 68 insertions(+), 42 deletions(-) diff --git a/apps/api/src/problem-variants.test.ts b/apps/api/src/problem-variants.test.ts index 218461c..81a701d 100644 --- a/apps/api/src/problem-variants.test.ts +++ b/apps/api/src/problem-variants.test.ts @@ -508,13 +508,15 @@ describe("POST /v1/problem-variants — STORY-039d judge wiring", () => { pass: true, })); listProblemVariants.mockResolvedValue([]); - insertProblemVariant.mockImplementation(async (_db: LearnProDb, args: { variant_def: unknown }) => ({ - id: "row-1", - org_id: "self", - source_problem_id: SOURCE_PROBLEM_ID, - variant_def: args.variant_def, - created_at: new Date(), - })); + insertProblemVariant.mockImplementation( + async (_db: LearnProDb, args: { variant_def: unknown }) => ({ + id: "row-1", + org_id: "self", + source_problem_id: SOURCE_PROBLEM_ID, + variant_def: args.variant_def, + created_at: new Date(), + }), + ); const llm = fakeLlm([JSON.stringify(VALID_VARIANT_PAYLOAD)]); const db = fakeDbWithProblem([SOURCE_PROBLEM_ROW]); const app = buildServer({ @@ -572,13 +574,15 @@ describe("POST /v1/problem-variants — STORY-039d judge wiring", () => { it("behaves as STORY-039 when no judge is supplied (variant returned without judge call)", async () => { listProblemVariants.mockResolvedValue([]); - insertProblemVariant.mockImplementation(async (_db: LearnProDb, args: { variant_def: unknown }) => ({ - id: "row-1", - org_id: "self", - source_problem_id: SOURCE_PROBLEM_ID, - variant_def: args.variant_def, - created_at: new Date(), - })); + insertProblemVariant.mockImplementation( + async (_db: LearnProDb, args: { variant_def: unknown }) => ({ + id: "row-1", + org_id: "self", + source_problem_id: SOURCE_PROBLEM_ID, + variant_def: args.variant_def, + created_at: new Date(), + }), + ); const llm = fakeLlm([JSON.stringify(VALID_VARIANT_PAYLOAD)]); const db = fakeDbWithProblem([SOURCE_PROBLEM_ROW]); const app = buildServer({ diff --git a/packages/agent/src/problem-variants.test.ts b/packages/agent/src/problem-variants.test.ts index 1fe2863..a5b7f35 100644 --- a/packages/agent/src/problem-variants.test.ts +++ b/packages/agent/src/problem-variants.test.ts @@ -466,7 +466,7 @@ function recordingTelemetry(): { // STORY-039d — stub judges for testing. function passingJudge(): SpecClarityJudge & { calls: number } { - const judge = ((async () => { + const judge = (async () => { judge.calls += 1; return { instruction_clarity: 5, @@ -479,13 +479,13 @@ function passingJudge(): SpecClarityJudge & { calls: number } { }, pass: true, } satisfies VariantSpecClarityResult; - }) as SpecClarityJudge & { calls: number }); + }) as SpecClarityJudge & { calls: number }; judge.calls = 0; return judge; } function failingJudge(scoreOverride = 2): SpecClarityJudge & { calls: number } { - const judge = ((async () => { + const judge = (async () => { judge.calls += 1; return { instruction_clarity: scoreOverride, @@ -498,16 +498,16 @@ function failingJudge(scoreOverride = 2): SpecClarityJudge & { calls: number } { }, pass: false, } satisfies VariantSpecClarityResult; - }) as SpecClarityJudge & { calls: number }); + }) as SpecClarityJudge & { calls: number }; judge.calls = 0; return judge; } function throwingJudge(): SpecClarityJudge & { calls: number } { - const judge = ((async () => { + const judge = (async () => { judge.calls += 1; throw new Error("judge boom"); - }) as SpecClarityJudge & { calls: number }); + }) as SpecClarityJudge & { calls: number }; judge.calls = 0; return judge; } diff --git a/packages/agent/src/problem-variants.ts b/packages/agent/src/problem-variants.ts index ef6d0ac..9368262 100644 --- a/packages/agent/src/problem-variants.ts +++ b/packages/agent/src/problem-variants.ts @@ -52,10 +52,7 @@ import { type ProblemVariantsPromptSourceShape, } from "@learnpro/prompts"; import type { SandboxProvider } from "@learnpro/sandbox"; -import type { - SpecClarityJudge, - VariantSpecClarityResult, -} from "./variant-spec-clarity-judge.js"; +import type { SpecClarityJudge, VariantSpecClarityResult } from "./variant-spec-clarity-judge.js"; // STORY-039a — telemetry callback. The route surfaces these counts to logs / metrics; the // agent stays pure (no global state). All counters are per-source (one call to diff --git a/packages/agent/src/variant-spec-clarity-judge.ts b/packages/agent/src/variant-spec-clarity-judge.ts index 49572d9..5137bda 100644 --- a/packages/agent/src/variant-spec-clarity-judge.ts +++ b/packages/agent/src/variant-spec-clarity-judge.ts @@ -34,7 +34,13 @@ export const VARIANT_SPEC_CLARITY_MIN_PASSING = 3; const MAX_RETRIES = 1; -const RubricScoreSchema = z.union([z.literal(1), z.literal(2), z.literal(3), z.literal(4), z.literal(5)]); +const RubricScoreSchema = z.union([ + z.literal(1), + z.literal(2), + z.literal(3), + z.literal(4), + z.literal(5), +]); export const VariantSpecClarityReasoningSchema = z.object({ instruction_clarity: z.string().min(1), @@ -142,7 +148,8 @@ export function parseVariantSpecClarityResponse(text: string): VariantSpecClarit const { instruction_clarity, example_quality, concept_match, reasoning } = parsed.data; const pass = - Math.min(instruction_clarity, example_quality, concept_match) >= VARIANT_SPEC_CLARITY_MIN_PASSING; + Math.min(instruction_clarity, example_quality, concept_match) >= + VARIANT_SPEC_CLARITY_MIN_PASSING; return { instruction_clarity, diff --git a/project/BOARD.md b/project/BOARD.md index 23ce93b..89ae621 100644 --- a/project/BOARD.md +++ b/project/BOARD.md @@ -1,6 +1,6 @@ # LearnPro Board -> **Last updated:** 2026-05-11 (STORY-038b done — Comprehension difficulty calibration (STORY-038 follow-up). `packages/scoring/src/difficulty.ts` gains `comprehensionEpisodeSuccessScore` + `comprehensionDifficultySignal` + `nextComprehensionDifficulty` keyed off a new `ComprehensionEpisodeSignalInputSchema` Zod discriminated union on `comprehension_format`. Multiple-choice success ladder: 1.0 first-try clean / 0.6 with one hint or two attempts / 0.3 with 2+ hints or 3+ attempts / 0.0 incorrect. Free-text maps `rubric_score` 1-5 to [0, 1] via `clamp((score - 1) / 4, 0, 1)`. Time signal uses per-problem `expected_time_sec` with format-specific defaults (60s MC, 180s free-text). Existing `kind: "implement"` / `kind: "debug"` branch byte-for-byte unchanged. Grade tool's comprehension dispatch (STORY-038a) surfaces a calibrated `comprehension_signal` on `GradeOutput` when `GradeEpisodeContext` carries runtime metadata (started_at_ms / hints_used / attempt_count). 27 new tests (22 in scoring, 5 in grade tool). Earlier: STORY-039c done — Per-user "already seen the seed" tracking (STORY-039 AC #6 follow-up). Migration `0024_episode_variant_of.sql` adds nullable `episodes.is_variant_of_problem_id uuid`. New optional `AssignProblemDeps` ports + `pickCandidate` variant-swap step. 7 new pure tests + e2e assertions. Earlier: STORY-034a done — Live-LLM A/B eval for the grader split (STORY-034 follow-up). New `packages/agent/evals/grader-ab.ts` runs each canned student transcript through BOTH the unified-tutor grade path AND the new `gradeAgent` split-grader Haiku call. ~12 new tests. Earlier: STORY-045a done — Postmark email transport (STORY-045 follow-up). New `packages/notifications/email/postmark-transport.ts` mirrors `ResendTransport`'s `EmailTransport` contract: POST to `https://api.postmarkapp.com/email` with `X-Postmark-Server-Token` auth. 4xx/5xx/network errors map to the same shape Resend uses. New `apps/api/src/email-transport-env.ts` factors the env-driven transport picker (now Resend / Postmark / Noop). New `docs/operations/EMAIL_SETUP.md` self-host guide. 23 new tests. Earlier: STORY-039a done — Piston self-validation for LLM-generated variants. `generateProblemVariant` accepts an optional `SandboxProvider`; variant's `reference_solution` must pass its own `hidden_tests` via `validateProblem` before caching. Single retry on failure with augmented prompt; persistent failure drops + returns empty. New telemetry counters (`variants_generated`, `variants_validated_pass`, `variants_dropped_fail`). `LEARNPRO_VARIANT_SELF_VALIDATE=1` env flag (default ON). ~12 new tests. Earlier: STORY-043a done — Multi-file grade-tool harness (STORY-043 P0 follow-up). `GradeInputSchema` accepts `{ code }` OR `{ files: Array<{ path, content }> }`; multi-file branch validates path-traversal + non-empty + per-language entry-file presence. `runHiddenTests` adapter passes `user_files` through `buildMultiFileHarnessForProblem` when `starter_workspace` is present; falls back to single-file otherwise. ~17 new tests. Earlier: STORY-041a done — BullMQ trigger for cheatsheet generation (deferred follow-up from STORY-041). New `apps/api/src/cheatsheet-cron.ts` mirrors STORY-033's profile-insights cron — Zod-validated queue payload, idempotent worker (`findCheatsheetForEpisodes` short-circuits when a cheatsheet already exists for the episode set), REDIS_URL-unset gracefully skips. Tutor `onEpisodeFinish` now enqueues BOTH a profile-insights job AND a cheatsheet job at session close. `defaultsFromEnv` wires the new cron alongside the existing one. Synchronous `POST /v1/cheatsheets` stays as the manual path. ~14 new tests. Earlier: STORY-038a done — Comprehension tutor route fan-out (STORY-038 follow-up). `AssignProblemOutputSchema` widened to surface `question`, `comprehension_format`, `answer_format`, `multiple_choice_options`, `correct_answer_index`, `explanation`. `GradeInputSchema` is a Zod union (`code` OR `comprehension_answer`); grade tool dispatches on `episode.problem.kind === "comprehension"` to a new `comprehensionDeps` adapter (503 when unwired). `submitComprehension(answer)` on `TutorSession`. `comprehension-policy` wired into `update-profile` so passing a comprehension problem bumps the per-concept axis. apps/api submit route accepts the new union; comprehension answers skip PII redaction. Web wrapper `submitComprehensionAnswer` shipped. ~20 new tests. Earlier: STORY-046c done — LLM-generated theme names for weekly plans (deferred from STORY-046b). New `weekly-theme-prompt.ts` + `generateWeeklyTheme` agent. `buildWeeklyPlan` accepts optional `themeGenerator`; used only on POST replan (cost gate). Falls back to STORY-046b's deterministic name on parse fail / null / <3 concepts. Forbidden-phrase guards on output. ~70 new tests. Earlier: **v1 backlog EXHAUSTED — all 19 v1 P0/P1/P2 stories merged.** STORY-037b done — Dashboard UI follow-up surfacing STORY-037a's bug-finding scores. New `` renders one row per touched archetype with humanized name + low/medium/high band + attempt count, sorted highest-attempts first. Score reframed as growth, not deficit (never a raw number, never a percentile, no "weakness" framing). New `apps/web/src/lib/bug-finding-band.ts` pure helper, new Next.js proxy `/api/bug-finding-scores`, mounted on `/dashboard`, extends STORY-027's axe-core sweep. 24 new tests (12 component + 7 band/label + 5 proxy). Earlier: STORY-046b done — Weekly themed plans built on top of STORY-032's knowledge graph. New `buildWeeklyPlan` walks the graph from the user's frontier in topological order and picks 3-5 concepts framed as a coherent week. Pace-adaptive (behind-trim / accelerated-expand). Re-plan dampening mirrors STORY-046's daily rules. New `GET /v1/weekly-plan?track_slug=...` + `POST /v1/weekly-plan/replan` Fastify routes. New `` replaces `` on /plan. LLM-generated theme names deferred — v1 uses dominant concept's name. ~68 new tests. Earlier: STORY-037a done — Debug-grader runtime wiring follow-up. New `bug_finding_scores` table (migration 0022) stores per-archetype EWMA score per user. `runDebugGrader` LLM call after tests-as-floor for `kind: "debug"` problems persists rubric reasoning + applies `bug-finding-policy` EWMA. New `GET /v1/bug-finding-scores` Fastify route. Grade-deps adapter detects debug kind and routes accordingly. _journal.json restored 0021 (cheatsheets) entry. 21 new tests. Earlier: STORY-039 done — LLM-generated problem variants on top of seed bank. New optional `variant_of: ProblemSlug` field on `ImplementProblemDefSchema` (and `DebugProblemDefSchema` for symmetry, debug variant generation deferred). New `problem_variants` cache table (migration 0023) keyed off `source_problem_id`. Pure `generateProblemVariant` agent in `@learnpro/agent` runs Haiku with the new versioned `problem-variants-v1` prompt, Zod-validates against `ProblemDefSchema`, with identity checks rejecting drift in language / difficulty / concept_tags / track / kind. Single retry on parse failure; persistent failure → empty list (best-effort, never blocks). New auth-gated `POST /v1/problem-variants` Fastify route is cache-first (returns cached variants without LLM call when cache has ≥ requested count), tops up on partial cache, persists fresh variants. Forbidden-phrase test on the system prompt. ~42 new tests. AC #3 (LLM-judge spec-clarity rubric), AC #4 (admin failed-gate surface), AC #5 (100-variant seeding), AC #6 (per-user "already seen seed" tracking), and Piston self-validation deferred to v1 follow-ups. Earlier: STORY-043 done — Multi-file workspaces in sandbox + editor (P0). `SandboxRunRequest` extended to accept `files: Array<{path, content}>` with backward-compat preprocess for legacy `code: string` shorthand. Per-language entry convention `ENTRY_FILE_BY_LANGUAGE` (python: main.py, ts: index.ts). `@learnpro/problems` schema gains `starter_workspace` + `entry_file` on the implement variant. New `` (flat list with active highlight, entry badge, inline rename) wired into PlaygroundClient + SessionClient via pure `workspaceFileTreeReducer`. 3 example multi-file problems authored. Submit ships entry file (multi-file grade-tool harness deferred). ~64 new tests. Earlier: STORY-038 done — Comprehension exercises engine: predict / trace / reason. New `kind: "comprehension"` branch added to `packages/problems/src/schema.ts` discriminated union. Migration 0020 adds comprehension columns. 68 problems (38 Python + 30 TS). Multiple-choice deterministic; free-text via Haiku rubric. New `` (read-only Monaco). New `comprehension-policy.ts` skill axis. ~80 new tests. Tutor route fan-out deferred. Earlier: STORY-041 done — Personal cheatsheet auto-generation per session. New `cheatsheets` table (migration 0021) stores user-editable markdown + entries `{ concept, definition, code_example, gotcha }`. New `cheatsheetAgent` (Haiku) with versioned prompt produces 6 entries max from session episodes. New 5 Fastify routes (list/get/put/post/export) + Next.js proxy + `` on `/session/[id]` + `/profile` history + jsPDF single-page export. ~70 new tests. BullMQ trigger off STORY-033's queue deferred — synchronous on-demand POST is the v1 path. Earlier: STORY-033 done — Async profile-update agent for cross-episode trait synthesis. New `profile_insights` table (migration 0017), `runProfileInsightsAgent` synthesizes 1-3 insights per session via Haiku, BullMQ cron (REDIS_URL gated), tutor `assign-problem` v4 surfaces `previous_insights` in context, `` on dashboard. 50 new tests. Earlier: STORY-032 done — Knowledge graph population: **206 concepts** + **428 prerequisite edges** authored as YAML under `packages/db/concepts/yaml/`. Migration `0019_knowledge_graph.sql` extends `concepts` table + creates `prerequisites` table. New `concept-graph.ts` pure helpers (DFS cycle detection, BFS walk, Kahn topological sort) + seeders. CLI `pnpm --filter @learnpro/db db:seed:concepts`. 53 new tests. Earlier: STORY-037 done — Debugging exercises engine. New `kind: "implement" | "debug"` discriminator in `packages/problems/src/schema.ts` (Zod discriminated union, backward-compat preprocess for legacy YAMLs). New `bug_archetype` enum (8 archetypes: off_by_one, mutation_in_iteration, reference_equality, async_race, late_binding, shadowing, type_coercion, default_arg_mutability). Migration `0018_debug_problems.sql` adds `kind` + `bug_archetype` columns + CHECK constraints + composite index on `episodes`. New `packages/prompts/src/debug-grade-prompt.ts` (versioned, additive — doesn't touch STORY-034's main grader). New `packages/scoring/src/policies/bug-finding-policy.ts` (per-archetype EWMA score). 47 debug problem YAMLs (25 Python + 22 TS) covering 8 archetypes. New `` + `` on `/session`. STORY-037a filed as a P2 follow-up for the runtime persistence wiring (apps/api grade-deps adapter + bug_finding_scores table). 71 new tests. Earlier: STORY-036 done — Ollama LLM adapter scaffold for privacy-conscious self-hosters. New `OllamaTransport` in `packages/llm/src/adapters/ollama.ts` conforms to `LLMProvider` (REST-only, no SDK runtime dep). New `LLMRouter` decorator routes per-request: `cloud` (Anthropic) / `local` (Ollama) / `auto-fallback` (cloud first, fall back to Ollama on cloud failure). Migration `0016_llm_mode.sql` adds `profiles.tutor_mode` column. New `GET / PUT /v1/settings/llm-mode` route + `` settings UI + Next.js proxy. New `docs/operations/SELF_HOST_OLLAMA.md` self-host guide. AC #2 (validation against 2 models) + AC #4 (eval-harness benchmarks) deferred — agent worktree can't pull 8GB+ Ollama models; manual operator reproduction steps documented. 43 new tests. Earlier: STORY-034 done — split critique/grader agent from tutor. New `gradeAgent` runs as a separate Haiku LLM call AFTER tests-as-floor, returning `{ pass; rubric: { idiomatic, efficiency, test_coverage_thinking } 1-5; reasoning }`. Versioned grader prompt with cooler tone. Migration `0013_grader_rubric.sql` adds 4 rubric columns to `episodes`. `applyGraderBonus` extends profile skill update. Tutor commentary references the rubric. Deterministic A/B test asserts split-grader range-normalized variance ≥ unified rubric variance. ~30 new tests. Live-LLM A/B deferred. Earlier: STORY-042 done — Anti-cheat v1: paste-detect modal + per-submission "I got help" toggle + got-help-aware skill skip. Migration 0015 adds `episodes.got_help boolean default false NOT NULL`. New `` (role=dialog, ESC dismisses, single-fire-per-paste) wired into PlaygroundClient + SessionClient via shared `attachPasteListener` (Monaco onDidPaste + DOM-paste fallback). Per-submission honesty toggle in the session result panel POSTs to `/api/tutor/episodes/:id/got-help`. Close-time skill skip via `wrapWithGotHelpAwareSkillSkip` decorator wrapping `buildUpdateProfileDrizzleDeps`. New `assign-problem-v3` prompt with `previous_got_help` walk-through phrasing. New `` on the dashboard with coach-voice copy. Data export/import round-trip the column. ~50 new tests. Earlier: STORY-045 done — Email digest channel (daily + weekly); STORY-059 done — sandbox SSE streaming; STORY-062 done — Redis rate limiter; STORY-061 done — importDump round-trip; STORY-040 done — GitHub portfolio; STORY-046 done — daily plan view; STORY-044 done — PWA baseline. MVP remains demoable; v1 in flight.) +> **Last updated:** 2026-05-11 (STORY-039d done — LLM-judge spec-clarity rubric for LLM-generated variants (closes AC #3 of STORY-039). Adds a second Haiku call after the structural Zod gate (and after Piston self-validation when wired) that scores the variant 1-5 on `instruction_clarity` / `example_quality` / `concept_match` and drops the variant when `min(scores) < 3`. New versioned `variant-spec-clarity-v1` prompt in `@learnpro/prompts` (forbidden-phrase tests guard the system prompt). New pure `runVariantSpecClarityJudge` agent in `@learnpro/agent` (Zod-validated response; single retry on parse failure; synthetic `{ pass: false }` on persistent failure — never throws). `generateProblemVariant` accepts an optional `judge?: SpecClarityJudge` parameter; new `variants_dropped_spec_clarity` telemetry counter; `PreviousFailure` widened to a discriminated union (`self_validation | spec_clarity`) so the retry prompt picks the right corrective phrasing (names the lowest-scoring criterion). New `buildVariantSpecClarityJudgeFromEnv` in `apps/api/src/problem-variants.ts` reads `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE` (default ON when `ANTHROPIC_API_KEY` is set; off otherwise). 54 new tests (12 prompt + 25 judge + 9 agent + 8 route). Earlier: STORY-038b done — Comprehension difficulty calibration (STORY-038 follow-up). `packages/scoring/src/difficulty.ts` gains MC + free-text branches. 27 new tests. Earlier: STORY-039c done — Per-user "already seen the seed" tracking (STORY-039 AC #6 follow-up). Migration `0024_episode_variant_of.sql`. 7 new pure tests + e2e assertions. Earlier: STORY-034a done — Live-LLM A/B eval for the grader split (STORY-034 follow-up). ~12 new tests. Earlier: STORY-045a done — Postmark email transport (STORY-045 follow-up). 23 new tests. Earlier: STORY-039a done — Piston self-validation for LLM-generated variants. `generateProblemVariant` accepts an optional `SandboxProvider`; variant's `reference_solution` must pass its own `hidden_tests` via `validateProblem` before caching. Single retry on failure with augmented prompt; persistent failure drops + returns empty. New telemetry counters (`variants_generated`, `variants_validated_pass`, `variants_dropped_fail`). `LEARNPRO_VARIANT_SELF_VALIDATE=1` env flag (default ON). ~12 new tests. Earlier: STORY-043a done — Multi-file grade-tool harness (STORY-043 P0 follow-up). `GradeInputSchema` accepts `{ code }` OR `{ files: Array<{ path, content }> }`; multi-file branch validates path-traversal + non-empty + per-language entry-file presence. `runHiddenTests` adapter passes `user_files` through `buildMultiFileHarnessForProblem` when `starter_workspace` is present; falls back to single-file otherwise. ~17 new tests. Earlier: STORY-041a done — BullMQ trigger for cheatsheet generation (deferred follow-up from STORY-041). New `apps/api/src/cheatsheet-cron.ts` mirrors STORY-033's profile-insights cron — Zod-validated queue payload, idempotent worker (`findCheatsheetForEpisodes` short-circuits when a cheatsheet already exists for the episode set), REDIS_URL-unset gracefully skips. Tutor `onEpisodeFinish` now enqueues BOTH a profile-insights job AND a cheatsheet job at session close. `defaultsFromEnv` wires the new cron alongside the existing one. Synchronous `POST /v1/cheatsheets` stays as the manual path. ~14 new tests. Earlier: STORY-038a done — Comprehension tutor route fan-out (STORY-038 follow-up). `AssignProblemOutputSchema` widened to surface `question`, `comprehension_format`, `answer_format`, `multiple_choice_options`, `correct_answer_index`, `explanation`. `GradeInputSchema` is a Zod union (`code` OR `comprehension_answer`); grade tool dispatches on `episode.problem.kind === "comprehension"` to a new `comprehensionDeps` adapter (503 when unwired). `submitComprehension(answer)` on `TutorSession`. `comprehension-policy` wired into `update-profile` so passing a comprehension problem bumps the per-concept axis. apps/api submit route accepts the new union; comprehension answers skip PII redaction. Web wrapper `submitComprehensionAnswer` shipped. ~20 new tests. Earlier: STORY-046c done — LLM-generated theme names for weekly plans (deferred from STORY-046b). New `weekly-theme-prompt.ts` + `generateWeeklyTheme` agent. `buildWeeklyPlan` accepts optional `themeGenerator`; used only on POST replan (cost gate). Falls back to STORY-046b's deterministic name on parse fail / null / <3 concepts. Forbidden-phrase guards on output. ~70 new tests. Earlier: **v1 backlog EXHAUSTED — all 19 v1 P0/P1/P2 stories merged.** STORY-037b done — Dashboard UI follow-up surfacing STORY-037a's bug-finding scores. New `` renders one row per touched archetype with humanized name + low/medium/high band + attempt count, sorted highest-attempts first. Score reframed as growth, not deficit (never a raw number, never a percentile, no "weakness" framing). New `apps/web/src/lib/bug-finding-band.ts` pure helper, new Next.js proxy `/api/bug-finding-scores`, mounted on `/dashboard`, extends STORY-027's axe-core sweep. 24 new tests (12 component + 7 band/label + 5 proxy). Earlier: STORY-046b done — Weekly themed plans built on top of STORY-032's knowledge graph. New `buildWeeklyPlan` walks the graph from the user's frontier in topological order and picks 3-5 concepts framed as a coherent week. Pace-adaptive (behind-trim / accelerated-expand). Re-plan dampening mirrors STORY-046's daily rules. New `GET /v1/weekly-plan?track_slug=...` + `POST /v1/weekly-plan/replan` Fastify routes. New `` replaces `` on /plan. LLM-generated theme names deferred — v1 uses dominant concept's name. ~68 new tests. Earlier: STORY-037a done — Debug-grader runtime wiring follow-up. New `bug_finding_scores` table (migration 0022) stores per-archetype EWMA score per user. `runDebugGrader` LLM call after tests-as-floor for `kind: "debug"` problems persists rubric reasoning + applies `bug-finding-policy` EWMA. New `GET /v1/bug-finding-scores` Fastify route. Grade-deps adapter detects debug kind and routes accordingly. _journal.json restored 0021 (cheatsheets) entry. 21 new tests. Earlier: STORY-039 done — LLM-generated problem variants on top of seed bank. New optional `variant_of: ProblemSlug` field on `ImplementProblemDefSchema` (and `DebugProblemDefSchema` for symmetry, debug variant generation deferred). New `problem_variants` cache table (migration 0023) keyed off `source_problem_id`. Pure `generateProblemVariant` agent in `@learnpro/agent` runs Haiku with the new versioned `problem-variants-v1` prompt, Zod-validates against `ProblemDefSchema`, with identity checks rejecting drift in language / difficulty / concept_tags / track / kind. Single retry on parse failure; persistent failure → empty list (best-effort, never blocks). New auth-gated `POST /v1/problem-variants` Fastify route is cache-first (returns cached variants without LLM call when cache has ≥ requested count), tops up on partial cache, persists fresh variants. Forbidden-phrase test on the system prompt. ~42 new tests. AC #3 (LLM-judge spec-clarity rubric), AC #4 (admin failed-gate surface), AC #5 (100-variant seeding), AC #6 (per-user "already seen seed" tracking), and Piston self-validation deferred to v1 follow-ups. Earlier: STORY-043 done — Multi-file workspaces in sandbox + editor (P0). `SandboxRunRequest` extended to accept `files: Array<{path, content}>` with backward-compat preprocess for legacy `code: string` shorthand. Per-language entry convention `ENTRY_FILE_BY_LANGUAGE` (python: main.py, ts: index.ts). `@learnpro/problems` schema gains `starter_workspace` + `entry_file` on the implement variant. New `` (flat list with active highlight, entry badge, inline rename) wired into PlaygroundClient + SessionClient via pure `workspaceFileTreeReducer`. 3 example multi-file problems authored. Submit ships entry file (multi-file grade-tool harness deferred). ~64 new tests. Earlier: STORY-038 done — Comprehension exercises engine: predict / trace / reason. New `kind: "comprehension"` branch added to `packages/problems/src/schema.ts` discriminated union. Migration 0020 adds comprehension columns. 68 problems (38 Python + 30 TS). Multiple-choice deterministic; free-text via Haiku rubric. New `` (read-only Monaco). New `comprehension-policy.ts` skill axis. ~80 new tests. Tutor route fan-out deferred. Earlier: STORY-041 done — Personal cheatsheet auto-generation per session. New `cheatsheets` table (migration 0021) stores user-editable markdown + entries `{ concept, definition, code_example, gotcha }`. New `cheatsheetAgent` (Haiku) with versioned prompt produces 6 entries max from session episodes. New 5 Fastify routes (list/get/put/post/export) + Next.js proxy + `` on `/session/[id]` + `/profile` history + jsPDF single-page export. ~70 new tests. BullMQ trigger off STORY-033's queue deferred — synchronous on-demand POST is the v1 path. Earlier: STORY-033 done — Async profile-update agent for cross-episode trait synthesis. New `profile_insights` table (migration 0017), `runProfileInsightsAgent` synthesizes 1-3 insights per session via Haiku, BullMQ cron (REDIS_URL gated), tutor `assign-problem` v4 surfaces `previous_insights` in context, `` on dashboard. 50 new tests. Earlier: STORY-032 done — Knowledge graph population: **206 concepts** + **428 prerequisite edges** authored as YAML under `packages/db/concepts/yaml/`. Migration `0019_knowledge_graph.sql` extends `concepts` table + creates `prerequisites` table. New `concept-graph.ts` pure helpers (DFS cycle detection, BFS walk, Kahn topological sort) + seeders. CLI `pnpm --filter @learnpro/db db:seed:concepts`. 53 new tests. Earlier: STORY-037 done — Debugging exercises engine. New `kind: "implement" | "debug"` discriminator in `packages/problems/src/schema.ts` (Zod discriminated union, backward-compat preprocess for legacy YAMLs). New `bug_archetype` enum (8 archetypes: off_by_one, mutation_in_iteration, reference_equality, async_race, late_binding, shadowing, type_coercion, default_arg_mutability). Migration `0018_debug_problems.sql` adds `kind` + `bug_archetype` columns + CHECK constraints + composite index on `episodes`. New `packages/prompts/src/debug-grade-prompt.ts` (versioned, additive — doesn't touch STORY-034's main grader). New `packages/scoring/src/policies/bug-finding-policy.ts` (per-archetype EWMA score). 47 debug problem YAMLs (25 Python + 22 TS) covering 8 archetypes. New `` + `` on `/session`. STORY-037a filed as a P2 follow-up for the runtime persistence wiring (apps/api grade-deps adapter + bug_finding_scores table). 71 new tests. Earlier: STORY-036 done — Ollama LLM adapter scaffold for privacy-conscious self-hosters. New `OllamaTransport` in `packages/llm/src/adapters/ollama.ts` conforms to `LLMProvider` (REST-only, no SDK runtime dep). New `LLMRouter` decorator routes per-request: `cloud` (Anthropic) / `local` (Ollama) / `auto-fallback` (cloud first, fall back to Ollama on cloud failure). Migration `0016_llm_mode.sql` adds `profiles.tutor_mode` column. New `GET / PUT /v1/settings/llm-mode` route + `` settings UI + Next.js proxy. New `docs/operations/SELF_HOST_OLLAMA.md` self-host guide. AC #2 (validation against 2 models) + AC #4 (eval-harness benchmarks) deferred — agent worktree can't pull 8GB+ Ollama models; manual operator reproduction steps documented. 43 new tests. Earlier: STORY-034 done — split critique/grader agent from tutor. New `gradeAgent` runs as a separate Haiku LLM call AFTER tests-as-floor, returning `{ pass; rubric: { idiomatic, efficiency, test_coverage_thinking } 1-5; reasoning }`. Versioned grader prompt with cooler tone. Migration `0013_grader_rubric.sql` adds 4 rubric columns to `episodes`. `applyGraderBonus` extends profile skill update. Tutor commentary references the rubric. Deterministic A/B test asserts split-grader range-normalized variance ≥ unified rubric variance. ~30 new tests. Live-LLM A/B deferred. Earlier: STORY-042 done — Anti-cheat v1: paste-detect modal + per-submission "I got help" toggle + got-help-aware skill skip. Migration 0015 adds `episodes.got_help boolean default false NOT NULL`. New `` (role=dialog, ESC dismisses, single-fire-per-paste) wired into PlaygroundClient + SessionClient via shared `attachPasteListener` (Monaco onDidPaste + DOM-paste fallback). Per-submission honesty toggle in the session result panel POSTs to `/api/tutor/episodes/:id/got-help`. Close-time skill skip via `wrapWithGotHelpAwareSkillSkip` decorator wrapping `buildUpdateProfileDrizzleDeps`. New `assign-problem-v3` prompt with `previous_got_help` walk-through phrasing. New `` on the dashboard with coach-voice copy. Data export/import round-trip the column. ~50 new tests. Earlier: STORY-045 done — Email digest channel (daily + weekly); STORY-059 done — sandbox SSE streaming; STORY-062 done — Redis rate limiter; STORY-061 done — importDump round-trip; STORY-040 done — GitHub portfolio; STORY-046 done — daily plan view; STORY-044 done — PWA baseline. MVP remains demoable; v1 in flight.) > **How to read this:** This is the live status of every Epic, Story, and Task in the project. Hand-maintained for now (a regenerator script lives in the v1 backlog). When you change an item's `status:` frontmatter, also update the row here in the same commit. --- @@ -59,11 +59,12 @@ STORY-053 (conversational onboarding agent) landed 2026-04-28 — `POST /v1/onbo | ID | Title | Done | |----|-------|------| -| [STORY-038b](stories/STORY-038b-comprehension-difficulty-calibration.md) | Comprehension difficulty calibration (STORY-038 follow-up) — `packages/scoring/src/difficulty.ts` gains `comprehensionEpisodeSuccessScore` + `comprehensionDifficultySignal` + `nextComprehensionDifficulty` keyed off `ComprehensionEpisodeSignalInputSchema` (Zod discriminated union on `comprehension_format`). MC success ladder 1.0/0.6/0.3/0.0 by attempts+hints; free_text uses `clamp((rubric_score - 1) / 4, 0, 1)`. Time signal uses per-problem `expected_time_sec` with format-specific defaults (60s MC, 180s free-text). Existing implement/debug branch unchanged. Grade tool's comprehension dispatch surfaces calibrated `comprehension_signal` on `GradeOutput` when ctx carries runtime metadata. 27 new tests. | 2026-05-11 | -| [STORY-039c](stories/STORY-039c-per-user-seen-seed.md) | Per-user "already seen the seed" tracking (STORY-039 AC #6 follow-up) — migration `0024_episode_variant_of.sql` adds nullable `episodes.is_variant_of_problem_id uuid`. New optional `AssignProblemDeps` ports + `pickCandidate` variant-swap step. 7 new pure tests + e2e assertions. | 2026-05-11 | -| [STORY-034a](stories/STORY-034a-grader-split-live-llm-ab.md) | Live-LLM A/B eval for the grader split (STORY-034 follow-up) — new `packages/agent/evals/grader-ab.ts` runs each canned student transcript through BOTH the unified-tutor grade path AND the new `gradeAgent` split-grader Haiku call. ~12 new tests. | 2026-05-11 | -| [STORY-045a](stories/STORY-045a-postmark-email-transport.md) | Postmark email transport adapter (STORY-045 follow-up) — new `PostmarkTransport` mirrors `ResendTransport`'s contract. POSTs to `https://api.postmarkapp.com/email` with `X-Postmark-Server-Token` auth. Same error-mapping shape. New `email-transport-env.ts` factors env-driven picker (Resend / Postmark / Noop). New self-host guide. 23 new tests. | 2026-05-11 | -| [STORY-039a](stories/STORY-039a-variant-piston-self-validation.md) | Piston self-validation for LLM-generated variants (STORY-039 follow-up) — `generateProblemVariant` accepts an optional `SandboxProvider`; variant's `reference_solution` must pass its own `hidden_tests` via `validateProblem` before caching. Single retry on failure with augmented prompt; persistent failure drops + returns empty. New telemetry counters (`variants_generated`, `variants_validated_pass`, `variants_dropped_fail`). `LEARNPRO_VARIANT_SELF_VALIDATE=1` env flag (default ON). ~12 new tests. | 2026-05-11 | +| [STORY-039d](stories/STORY-039d-variant-spec-clarity-judge.md) | LLM-judge spec-clarity rubric for LLM-generated variants (closes AC #3 of STORY-039) — new versioned `variant-spec-clarity-v1` prompt + pure `runVariantSpecClarityJudge` agent scores variants 1-5 on `instruction_clarity` / `example_quality` / `concept_match`; `min(scores) < 3` drops the variant. `generateProblemVariant` accepts an optional `judge?: SpecClarityJudge`; new `variants_dropped_spec_clarity` telemetry counter; `PreviousFailure` widened to a discriminated union so the retry prompt picks the right corrective phrasing. `buildVariantSpecClarityJudgeFromEnv` reads `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE` (default ON with API key). 54 new tests. | 2026-05-11 | +| [STORY-038b](stories/STORY-038b-comprehension-difficulty-calibration.md) | Comprehension difficulty calibration (STORY-038 follow-up) — `packages/scoring/src/difficulty.ts` MC + free-text branches. 27 new tests. | 2026-05-11 | +| [STORY-039c](stories/STORY-039c-per-user-seen-seed.md) | Per-user "already seen the seed" tracking (STORY-039 AC #6 follow-up) — migration `0024_episode_variant_of.sql`. 7 new pure tests + e2e assertions. | 2026-05-11 | +| [STORY-034a](stories/STORY-034a-grader-split-live-llm-ab.md) | Live-LLM A/B eval for the grader split (STORY-034 follow-up). ~12 new tests. | 2026-05-11 | +| [STORY-045a](stories/STORY-045a-postmark-email-transport.md) | Postmark email transport adapter (STORY-045 follow-up). 23 new tests. | 2026-05-11 | +| [STORY-039a](stories/STORY-039a-variant-piston-self-validation.md) | Piston self-validation gate for LLM-generated variants (STORY-039 AC #3 follow-up) — `generateProblemVariant` optionally runs the variant's `reference_solution` through `validateProblem` before caching. Single retry on failure; persistent failure drops + returns empty. New telemetry counters. `LEARNPRO_VARIANT_SELF_VALIDATE` env flag (default ON). ~12 new tests. | 2026-05-11 | | [STORY-043a](stories/STORY-043a-multi-file-grade-harness.md) | Multi-file grade-tool harness (STORY-043 P0 follow-up) — `GradeInputSchema` accepts `{ code }` OR `{ files: Array<{ path, content }> }` (path-traversal + entry-file validation). `runHiddenTests` adapter passes `user_files` through `buildMultiFileHarnessForProblem` when `starter_workspace` is present; falls back to single-file otherwise. ~17 new tests. | 2026-05-11 | | [STORY-041a](stories/STORY-041a-cheatsheet-bullmq-trigger.md) | BullMQ trigger for cheatsheet generation (STORY-041 follow-up) — new `apps/api/src/cheatsheet-cron.ts` mirrors STORY-033's profile-insights cron (Zod-validated payload, idempotent worker via `findCheatsheetForEpisodes`, REDIS_URL-unset graceful skip). Tutor `onEpisodeFinish` enqueues BOTH profile-insights AND cheatsheet jobs at session close. Synchronous `POST /v1/cheatsheets` stays as the manual path. ~14 new tests. | 2026-05-11 | | [STORY-038a](stories/STORY-038a-comprehension-tutor-fanout.md) | Comprehension tutor route fan-out (STORY-038 follow-up) — `AssignProblemOutputSchema` widened to surface comprehension fields. `GradeInputSchema` is a Zod union (`code` OR `comprehension_answer`); grade tool dispatches on `episode.problem.kind === "comprehension"`. `submitComprehension(answer)` on `TutorSession`. `comprehension-policy` wired into `update-profile`. apps/api submit route accepts the new union. ~20 new tests. DB-backed comprehension score table + UI swap deferred. | 2026-05-06 | diff --git a/project/stories/STORY-039-llm-problem-variants.md b/project/stories/STORY-039-llm-problem-variants.md index 99e27e5..eaec3b4 100644 --- a/project/stories/STORY-039-llm-problem-variants.md +++ b/project/stories/STORY-039-llm-problem-variants.md @@ -23,7 +23,7 @@ Variants must pass an automated quality gate before being shown to users: spec-c - [x] Variant-generation pipeline in `packages/agent/src/problem-variants.ts` (pure agent), `packages/prompts/src/problem-variants-prompt.ts` (versioned prompt), and `apps/api/src/problem-variants.ts` (Fastify route). Persistent storage in new `problem_variants` table (migration 0023). - [x] Each variant references its source via the new optional `variant_of: ProblemSlug` field on the `ImplementProblemDefSchema` and via the FK `problem_variants.source_problem_id`. - [x] Quality gate v1: every generated variant must validate against `ProblemDefSchema` AND match the source's language / difficulty / concept_tags / track / kind. Single retry on parse failure; persistent failure → 200 with empty `variants[]` (best-effort, never blocks the user). -- [ ] LLM-judge spec-clarity rubric — DEFERRED to v1 follow-up (the structural Zod gate covers correctness; the judge is a quality-of-life addition). +- [x] LLM-judge spec-clarity rubric — landed via [STORY-039d](STORY-039d-variant-spec-clarity-judge.md) on 2026-05-11. New `runVariantSpecClarityJudge` Haiku agent scores variants 1-5 on instruction_clarity / example_quality / concept_match. Variants with `min(scores) < 3` are dropped via `variants_dropped_spec_clarity` telemetry. Behind `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE=1` env flag (default ON with API key). - [ ] Embedding-based novelty score — DEFERRED to v1 follow-up (would require pgvector embedding the variant + comparing to seeds; out of v1 scope). - [ ] Self-validation through real Piston sandbox — DEFERRED. The agent's `parseProblemVariantResponse` defends against drift via the schema + identity checks; running the variant's `reference_solution` against its own `hidden_tests` requires a sandbox round-trip and is gated by `LEARNPRO_REQUIRE_PISTON=1` for the integration suite. - [ ] Admin tool to inspect failed-gate variants — DEFERRED (failed gates currently return empty; v1 follow-up adds an admin surface). @@ -49,3 +49,4 @@ Variants must pass an automated quality gate before being shown to users: spec-c - 2026-04-25 — created - 2026-05-06 — picked up - 2026-05-06 — done. Pure `generateProblemVariant` agent in `@learnpro/agent` runs Haiku with the new `problem-variants-v1` prompt; structural Zod gate via `ProblemDefSchema.parse` plus identity checks (language / difficulty / concept_tags / track / kind / slug-prefix / variant_of) reject drift. New `problem_variants` table (migration 0023) caches variants keyed off `source_problem_id`. New `POST /v1/problem-variants` Fastify route is auth-gated, cache-first, generates only on miss, persists results. New optional `variant_of` slug field on `ImplementProblemDefSchema` and `DebugProblemDefSchema` for provenance. Forbidden-phrase test on the system prompt (no FOMO / loss-aversion / fire-emoji / streak-shaming). 42 new tests across schema (4) + agent (27) + route (11). Self-validation through real Piston, embedding novelty score, LLM-judge rubric, admin failed-gate surface, and 100-variant seeding deferred to v1 follow-ups. +- 2026-05-11 — LLM-judge spec-clarity rubric AC landed via [STORY-039d](STORY-039d-variant-spec-clarity-judge.md). Adds a second Haiku call after the structural Zod gate that scores variants 1-5 on `instruction_clarity` / `example_quality` / `concept_match`; `min(scores) < 3` drops the variant. Behind `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE=1` env flag (default ON when ANTHROPIC_API_KEY is set). 54 new tests across prompt (12) + judge (25) + agent wiring (9) + route wiring (8). diff --git a/project/stories/STORY-039d-variant-spec-clarity-judge.md b/project/stories/STORY-039d-variant-spec-clarity-judge.md index 6516e71..0cf7c29 100644 --- a/project/stories/STORY-039d-variant-spec-clarity-judge.md +++ b/project/stories/STORY-039d-variant-spec-clarity-judge.md @@ -2,7 +2,7 @@ id: STORY-039d title: LLM-judge spec-clarity rubric for LLM-generated problem variants type: story -status: in-progress +status: done priority: P2 estimate: S parent: EPIC-007 @@ -41,29 +41,30 @@ that don't want the round-trip (~$0.01 per variant). ## Acceptance criteria -- [ ] New versioned prompt `packages/prompts/src/variant-spec-clarity-prompt.ts` with +- [x] New versioned prompt `packages/prompts/src/variant-spec-clarity-prompt.ts` with version tag `variant-spec-clarity-v1`. System prompt embeds the rubric (1-5 per criterion + one-sentence reasoning). Forbidden-phrase test on the system prompt. -- [ ] New judge `packages/agent/src/variant-spec-clarity-judge.ts` exposes +- [x] New judge `packages/agent/src/variant-spec-clarity-judge.ts` exposes `runVariantSpecClarityJudge({ llm, variant })` returning `{ instruction_clarity, example_quality, concept_match, reasoning, pass }` where `pass = min(scores) >= 3`. Pure function — no DB / no telemetry inside. Zod-validated response with a single retry on parse failure; persistent failure → `{ pass: false }` (best-effort, never throws). -- [ ] `generateProblemVariant` accepts an optional `judge?: SpecClarityJudge` parameter. +- [x] `generateProblemVariant` accepts an optional `judge?: SpecClarityJudge` parameter. When provided, after the structural Zod gate passes AND (when configured) Piston self-validation passes, run the judge. On `judge.pass === false`, drop the variant and increment a new `variants_dropped_spec_clarity` telemetry counter (added to `ProblemVariantsTelemetry`). Caller-controlled — existing callers don't break. -- [ ] `apps/api/src/problem-variants.ts` route honors `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE` +- [x] `apps/api/src/problem-variants.ts` route honors `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE` env flag (default ON when ANTHROPIC_API_KEY is set, otherwise OFF). When ON, passes `runVariantSpecClarityJudge` as the `judge` to `generateProblemVariant`. -- [ ] Unit tests: passing scores → `pass: true`, one failing score → `pass: false`, +- [x] Unit tests: passing scores → `pass: true`, one failing score → `pass: false`, malformed JSON → retry once then `pass: false`, forbidden-phrase test on the system - prompt. ~8-10 tests. -- [ ] Unit tests in `problem-variants.test.ts`: stub judge returning `pass: false` → variant + prompt. ~8-10 tests (12 prompt + 25 judge = 37 actual). +- [x] Unit tests in `problem-variants.test.ts`: stub judge returning `pass: false` → variant dropped + `variants_dropped_spec_clarity` counter fired. Stub judge returning - `pass: true` → variant returned as before. ~3-4 new tests. + `pass: true` → variant returned as before. ~3-4 new tests (9 new agent tests + 8 new + route tests = 17 actual). ## Deferred / explicitly-skipped @@ -118,3 +119,18 @@ that don't want the round-trip (~$0.01 per variant). - 2026-05-11 — created - 2026-05-11 — picked up +- 2026-05-11 — done. New versioned `variant-spec-clarity-v1` prompt in `@learnpro/prompts` + (system prompt embeds 1-5 rubric anchors per criterion + JSON output schema; forbidden- + phrase tests guard against tone drift). New pure `runVariantSpecClarityJudge` agent in + `@learnpro/agent` (Haiku call; Zod-validated response; single retry on parse failure; + synthetic `{ pass: false }` on persistent failure — never throws to caller; `pass = + min(scores) >= 3`). `generateProblemVariant` now accepts an optional + `judge?: SpecClarityJudge` parameter; the judge runs AFTER the structural Zod gate and + AFTER (when wired) Piston self-validation. New `variants_dropped_spec_clarity` + telemetry counter on `ProblemVariantsTelemetry`. `PreviousFailure` widened to a + discriminated union (`self_validation | spec_clarity`) so the retry prompt picks the + right corrective phrasing — the spec-clarity addendum names the lowest-scoring + criterion. New `buildVariantSpecClarityJudgeFromEnv` in `apps/api/src/problem-variants.ts` + reads `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE` (default ON when `ANTHROPIC_API_KEY` is set; + off otherwise). `defaultsFromEnv` wires the env builder. 54 new tests (12 prompt + + 25 judge + 9 agent + 8 route). 456 agent + 368 api tests pass repo-wide. From e4efb5a968419c64e5f687c4a96799abd24e175f Mon Sep 17 00:00:00 2001 From: Rahul Singh Khokhar Date: Mon, 11 May 2026 02:52:01 -0700 Subject: [PATCH 6/7] fix(agent): strict typing for STORY-039d stub judges [STORY-039d] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit CI typecheck (tsconfig.test.json) caught two issues in the stub-judge helpers: 1. `(async () => {...}) as SpecClarityJudge` was a non-overlapping cast — the arrow function ignored the `variant` parameter so its inferred type didn't match `(variant: ProblemDef) => Promise<...>`. Rewrote the helpers to return an explicit `{ judge: SpecClarityJudge; calls: () => number }` tuple via a closure over `let calls = 0`, so the function literal carries the right signature. 2. `failingJudge(scoreOverride: number = 2)` widened `instruction_clarity` to `number`, breaking the `1 | 2 | 3 | 4 | 5` literal union. Removed the override; the helper now always returns `instruction_clarity: 2`, which is what every existing call used. Co-Authored-By: Claude Opus 4.7 --- packages/agent/src/problem-variants.test.ts | 88 +++++++++++---------- 1 file changed, 48 insertions(+), 40 deletions(-) diff --git a/packages/agent/src/problem-variants.test.ts b/packages/agent/src/problem-variants.test.ts index a5b7f35..aeefd25 100644 --- a/packages/agent/src/problem-variants.test.ts +++ b/packages/agent/src/problem-variants.test.ts @@ -464,11 +464,18 @@ function recordingTelemetry(): { return { events, cb }; } -// STORY-039d — stub judges for testing. -function passingJudge(): SpecClarityJudge & { calls: number } { - const judge = (async () => { - judge.calls += 1; - return { +// STORY-039d — stub judges for testing. We expose `calls` on a stable closure so each +// test can assert how many times the judge was invoked. +interface TestJudge { + judge: SpecClarityJudge; + calls: () => number; +} + +function passingJudge(): TestJudge { + let calls = 0; + const judge: SpecClarityJudge = async () => { + calls += 1; + const result: VariantSpecClarityResult = { instruction_clarity: 5, example_quality: 4, concept_match: 5, @@ -478,17 +485,18 @@ function passingJudge(): SpecClarityJudge & { calls: number } { concept_match: "tags match", }, pass: true, - } satisfies VariantSpecClarityResult; - }) as SpecClarityJudge & { calls: number }; - judge.calls = 0; - return judge; + }; + return result; + }; + return { judge, calls: () => calls }; } -function failingJudge(scoreOverride = 2): SpecClarityJudge & { calls: number } { - const judge = (async () => { - judge.calls += 1; - return { - instruction_clarity: scoreOverride, +function failingJudge(): TestJudge { + let calls = 0; + const judge: SpecClarityJudge = async () => { + calls += 1; + const result: VariantSpecClarityResult = { + instruction_clarity: 2, example_quality: 4, concept_match: 5, reasoning: { @@ -497,19 +505,19 @@ function failingJudge(scoreOverride = 2): SpecClarityJudge & { calls: number } { concept_match: "fine", }, pass: false, - } satisfies VariantSpecClarityResult; - }) as SpecClarityJudge & { calls: number }; - judge.calls = 0; - return judge; + }; + return result; + }; + return { judge, calls: () => calls }; } -function throwingJudge(): SpecClarityJudge & { calls: number } { - const judge = (async () => { - judge.calls += 1; +function throwingJudge(): TestJudge { + let calls = 0; + const judge: SpecClarityJudge = async () => { + calls += 1; throw new Error("judge boom"); - }) as SpecClarityJudge & { calls: number }; - judge.calls = 0; - return judge; + }; + return { judge, calls: () => calls }; } describe("generateProblemVariant — STORY-039a self-validation gate", () => { @@ -707,18 +715,18 @@ describe("generateProblemVariant — STORY-039a self-validation gate", () => { describe("generateProblemVariant — STORY-039d spec-clarity judge gate", () => { it("happy path: passing judge → returns variant + emits validated_pass (no dropped_spec_clarity)", async () => { const llm = fakeLLM([JSON.stringify(validVariantPayload())]); - const judge = passingJudge(); + const stub = passingJudge(); const { events, cb } = recordingTelemetry(); const out = await generateProblemVariant({ llm, user_id: "u", source: SOURCE_PROBLEM, - judge, + judge: stub.judge, onTelemetry: cb, }); expect(out.variants).toHaveLength(1); expect(out.fallback_used).toBe(false); - expect(judge.calls).toBe(1); + expect(stub.calls()).toBe(1); expect(events).toEqual([ { kind: "generated", slug: "sum-even-numbers-variant-1", attempt: 1 }, { kind: "validated_pass", slug: "sum-even-numbers-variant-1", attempt: 1 }, @@ -730,18 +738,18 @@ describe("generateProblemVariant — STORY-039d spec-clarity judge gate", () => JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-1" })), JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-2" })), ]); - const judge = failingJudge(); + const stub = failingJudge(); const { events, cb } = recordingTelemetry(); const out = await generateProblemVariant({ llm, user_id: "u", source: SOURCE_PROBLEM, - judge, + judge: stub.judge, onTelemetry: cb, }); expect(out.variants).toEqual([]); expect(out.fallback_used).toBe(true); - expect(judge.calls).toBe(2); + expect(stub.calls()).toBe(2); expect(events.filter((e) => e.kind === "dropped_spec_clarity")).toHaveLength(2); expect(events.filter((e) => e.kind === "validated_pass")).toHaveLength(0); }); @@ -755,7 +763,7 @@ describe("generateProblemVariant — STORY-039d spec-clarity judge gate", () => llm, user_id: "u", source: SOURCE_PROBLEM, - judge: failingJudge(), + judge: failingJudge().judge, }); expect(llm.calls).toHaveLength(2); const secondMessage = llm.calls[1]?.messages[0]?.content ?? ""; @@ -821,13 +829,13 @@ describe("generateProblemVariant — STORY-039d spec-clarity judge gate", () => JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-1" })), JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-2" })), ]); - const judge = throwingJudge(); + const stub = throwingJudge(); const { events, cb } = recordingTelemetry(); const out = await generateProblemVariant({ llm, user_id: "u", source: SOURCE_PROBLEM, - judge, + judge: stub.judge, onTelemetry: cb, }); expect(out.variants).toEqual([]); @@ -841,32 +849,32 @@ describe("generateProblemVariant — STORY-039d spec-clarity judge gate", () => JSON.stringify(validVariantPayload({ slug: "sum-even-numbers-variant-2" })), ]); const sandbox = new StubFailingSandbox(); - const judge = passingJudge(); + const stub = passingJudge(); await generateProblemVariant({ llm, user_id: "u", source: SOURCE_PROBLEM, sandbox, - judge, + judge: stub.judge, }); // Sandbox failed → judge should never run. - expect(judge.calls).toBe(0); + expect(stub.calls()).toBe(0); }); it("judge AND sandbox both wired: sandbox pass + judge pass → returns variant", async () => { const llm = fakeLLM([JSON.stringify(validVariantPayload())]); const sandbox = new StubPassingSandbox(); - const judge = passingJudge(); + const stub = passingJudge(); const out = await generateProblemVariant({ llm, user_id: "u", source: SOURCE_PROBLEM, sandbox, - judge, + judge: stub.judge, }); expect(out.variants).toHaveLength(1); expect(sandbox.calls.length).toBeGreaterThan(0); - expect(judge.calls).toBe(1); + expect(stub.calls()).toBe(1); }); it("no judge wired: validated_pass still fires (behaves as STORY-039a)", async () => { @@ -889,7 +897,7 @@ describe("generateProblemVariant — STORY-039d spec-clarity judge gate", () => llm, user_id: "u", source: SOURCE_PROBLEM, - judge: failingJudge(), + judge: failingJudge().judge, onTelemetry: { variants_dropped_spec_clarity: () => { throw new Error("sink boom"); From 071b97ce52c359e778fa3fde4239bc0975571aa0 Mon Sep 17 00:00:00 2001 From: Rahul Singh Khokhar Date: Mon, 11 May 2026 02:57:38 -0700 Subject: [PATCH 7/7] chore(ci): nudge CI to retrigger after typecheck fix [STORY-039d] Empty commit to force GitHub Actions to pick up the branch. Co-Authored-By: Claude Opus 4.7