Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 }
: {}),
});
}

Expand Down Expand Up @@ -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"];
Expand Down Expand Up @@ -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
Expand Down
188 changes: 188 additions & 0 deletions apps/api/src/problem-variants.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -412,3 +412,191 @@ 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<CompleteResponse> {
return {
text: "",
model: "claude-haiku-4-5-20251001",
finish_reason: "end_turn",
usage: { input_tokens: 0, output_tokens: 0 },
};
},
async *stream(_req: CompleteRequest): AsyncIterable<StreamChunk> {
yield { delta: "", done: true };
},
async embed(_req: EmbedRequest): Promise<EmbedResponse> {
return { vector: [], model: "voyage-3", usage: {} };
},
async toolCall(_req: ToolCallRequest): Promise<ToolCallResponse> {
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();
});
});
43 changes: 42 additions & 1 deletion apps/api/src/problem-variants.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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 });
}
13 changes: 13 additions & 0 deletions packages/agent/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Loading
Loading