diff --git a/apps/api/src/admin-variant-failures.test.ts b/apps/api/src/admin-variant-failures.test.ts new file mode 100644 index 0000000..ef8457f --- /dev/null +++ b/apps/api/src/admin-variant-failures.test.ts @@ -0,0 +1,180 @@ +import type { LearnProDb } from "@learnpro/db"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { buildServer } from "./index.js"; +import type { SessionResolver } from "./session.js"; + +// STORY-039e — admin failed-gate variant inspection. Read-only, gated on +// `users.is_admin = true`. The route mounts only when `adminVariantFailuresDb` is supplied. + +const listVariantGateFailures = vi.fn(); + +vi.mock("@learnpro/db", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + listVariantGateFailures: (...a: Parameters) => + listVariantGateFailures(...a), + }; +}); + +const fakeDb = {} as unknown as LearnProDb; + +const adminSession = + (user_id: string): SessionResolver => + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: true }); + +const nonAdminSession = + (user_id: string): SessionResolver => + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); + +const NULL_SESSION: SessionResolver = async () => null; +const ADMIN_USER_ID = "22222222-2222-4222-8222-222222222222"; +const NORMAL_USER_ID = "33333333-3333-4333-8333-333333333333"; +const SOURCE_PROBLEM_ID = "44444444-4444-4444-8444-444444444444"; + +function buildApp(opts: { sessionResolver?: SessionResolver; surfaceWired?: boolean }) { + const wired = opts.surfaceWired !== false; + return buildServer({ + sessionResolver: opts.sessionResolver ?? NULL_SESSION, + ...(wired ? { adminVariantFailuresDb: fakeDb } : {}), + }); +} + +beforeEach(() => { + listVariantGateFailures.mockReset(); +}); + +afterEach(() => { + vi.clearAllMocks(); +}); + +describe("GET /v1/admin/variant-failures (STORY-039e)", () => { + it("returns 401 when no session", async () => { + const app = buildApp({}); + const res = await app.inject({ method: "GET", url: "/v1/admin/variant-failures" }); + expect(res.statusCode).toBe(401); + expect(res.json().error).toBe("unauthorized"); + await app.close(); + }); + + it("returns 403 when the user is authed but not an admin", async () => { + const app = buildApp({ sessionResolver: nonAdminSession(NORMAL_USER_ID) }); + const res = await app.inject({ method: "GET", url: "/v1/admin/variant-failures" }); + expect(res.statusCode).toBe(403); + expect(res.json().error).toBe("forbidden"); + expect(listVariantGateFailures).not.toHaveBeenCalled(); + await app.close(); + }); + + it("returns 200 with failures payload when an admin requests it", async () => { + listVariantGateFailures.mockResolvedValue({ + failures: [ + { + id: "f-1", + org_id: "self", + source_problem_id: SOURCE_PROBLEM_ID, + source_problem_slug: "sum-even-numbers", + attempted_at: new Date("2026-05-10T10:00:00Z"), + failure_reason: "parse_error", + failure_detail: { reason: "invalid_json", error: "unexpected token at position 0" }, + model_id: "claude-haiku-4", + attempt_number: 1, + }, + ], + total: 1, + }); + const app = buildApp({ sessionResolver: adminSession(ADMIN_USER_ID) }); + const res = await app.inject({ method: "GET", url: "/v1/admin/variant-failures" }); + expect(res.statusCode).toBe(200); + const body = res.json(); + expect(body.failures).toHaveLength(1); + expect(body.failures[0]).toMatchObject({ + id: "f-1", + source_problem_id: SOURCE_PROBLEM_ID, + source_problem_slug: "sum-even-numbers", + failure_reason: "parse_error", + model_id: "claude-haiku-4", + attempt_number: 1, + }); + expect(body.failures[0].attempted_at).toBe("2026-05-10T10:00:00.000Z"); + expect(body.total).toBe(1); + await app.close(); + }); + + it("filters by source_problem_id and passes it through to the DB helper", async () => { + listVariantGateFailures.mockResolvedValue({ failures: [], total: 0 }); + const app = buildApp({ sessionResolver: adminSession(ADMIN_USER_ID) }); + await app.inject({ + method: "GET", + url: `/v1/admin/variant-failures?source_problem_id=${SOURCE_PROBLEM_ID}`, + }); + expect(listVariantGateFailures).toHaveBeenCalledWith( + fakeDb, + expect.objectContaining({ source_problem_id: SOURCE_PROBLEM_ID }), + ); + await app.close(); + }); + + it("paginates via limit + offset query params", async () => { + listVariantGateFailures.mockResolvedValue({ failures: [], total: 100 }); + const app = buildApp({ sessionResolver: adminSession(ADMIN_USER_ID) }); + await app.inject({ + method: "GET", + url: "/v1/admin/variant-failures?limit=25&offset=50", + }); + expect(listVariantGateFailures).toHaveBeenCalledWith( + fakeDb, + expect.objectContaining({ limit: 25, offset: 50 }), + ); + await app.close(); + }); + + it("returns 400 on invalid source_problem_id (not a uuid)", async () => { + const app = buildApp({ sessionResolver: adminSession(ADMIN_USER_ID) }); + const res = await app.inject({ + method: "GET", + url: "/v1/admin/variant-failures?source_problem_id=not-a-uuid", + }); + expect(res.statusCode).toBe(400); + expect(res.json().error).toBe("invalid_request"); + await app.close(); + }); + + it("returns 400 on out-of-range limit (>200)", async () => { + const app = buildApp({ sessionResolver: adminSession(ADMIN_USER_ID) }); + const res = await app.inject({ + method: "GET", + url: "/v1/admin/variant-failures?limit=500", + }); + expect(res.statusCode).toBe(400); + await app.close(); + }); + + it("returns 404 when adminVariantFailuresDb is NOT supplied (graceful degrade)", async () => { + const app = buildApp({ + sessionResolver: adminSession(ADMIN_USER_ID), + surfaceWired: false, + }); + const res = await app.inject({ method: "GET", url: "/v1/admin/variant-failures" }); + expect(res.statusCode).toBe(404); + await app.close(); + }); + + it("never mutates — only GET is supported on the route", async () => { + const app = buildApp({ sessionResolver: adminSession(ADMIN_USER_ID) }); + const post = await app.inject({ method: "POST", url: "/v1/admin/variant-failures" }); + expect([404, 405]).toContain(post.statusCode); + const del = await app.inject({ method: "DELETE", url: "/v1/admin/variant-failures" }); + expect([404, 405]).toContain(del.statusCode); + await app.close(); + }); + + it("empty result still returns 200 with total=0", async () => { + listVariantGateFailures.mockResolvedValue({ failures: [], total: 0 }); + const app = buildApp({ sessionResolver: adminSession(ADMIN_USER_ID) }); + const res = await app.inject({ method: "GET", url: "/v1/admin/variant-failures" }); + expect(res.statusCode).toBe(200); + expect(res.json()).toEqual({ failures: [], total: 0 }); + await app.close(); + }); +}); diff --git a/apps/api/src/admin-variant-failures.ts b/apps/api/src/admin-variant-failures.ts new file mode 100644 index 0000000..2243ce4 --- /dev/null +++ b/apps/api/src/admin-variant-failures.ts @@ -0,0 +1,64 @@ +import type { FastifyInstance } from "fastify"; +import { z } from "zod"; +import { listVariantGateFailures, type LearnProDb } from "@learnpro/db"; +import type { SessionResolver } from "./session.js"; + +// STORY-039e — Admin-only Fastify route for inspecting failed-gate LLM-generated problem +// variants. Strictly read-only — never offers retry / delete / publish actions on failed +// variants (that would be a separate Story if/when needed). Auth-gated via the standard +// session cookie + `users.is_admin = true` flag (operator promotes via psql). +// +// The route is registered only when an `adminVariantFailuresDb` is supplied to `buildServer` +// (mirrors the pattern of every other DB-bound route). On miss, the route falls through to +// Fastify's default 404. + +const QuerySchema = z.object({ + source_problem_id: z.string().uuid().optional(), + limit: z.coerce.number().int().min(1).max(200).optional(), + offset: z.coerce.number().int().min(0).optional(), +}); + +export interface AdminVariantFailuresRouteOptions { + db: LearnProDb; + sessionResolver: SessionResolver; +} + +export function registerAdminVariantFailuresRoutes( + app: FastifyInstance, + opts: AdminVariantFailuresRouteOptions, +): void { + const { db, sessionResolver } = opts; + + app.get("/v1/admin/variant-failures", async (req, reply) => { + const session = await sessionResolver(req); + if (!session) return reply.code(401).send({ error: "unauthorized" }); + if (!session.is_admin) return reply.code(403).send({ error: "forbidden" }); + + const parsed = QuerySchema.safeParse(req.query); + if (!parsed.success) { + return reply.code(400).send({ error: "invalid_request", issues: parsed.error.issues }); + } + + const result = await listVariantGateFailures(db, { + ...(parsed.data.source_problem_id !== undefined + ? { source_problem_id: parsed.data.source_problem_id } + : {}), + ...(parsed.data.limit !== undefined ? { limit: parsed.data.limit } : {}), + ...(parsed.data.offset !== undefined ? { offset: parsed.data.offset } : {}), + }); + + return reply.code(200).send({ + failures: result.failures.map((f) => ({ + id: f.id, + source_problem_id: f.source_problem_id, + source_problem_slug: f.source_problem_slug, + attempted_at: f.attempted_at.toISOString(), + failure_reason: f.failure_reason, + failure_detail: f.failure_detail, + model_id: f.model_id, + attempt_number: f.attempt_number, + })), + total: result.total, + }); + }); +} diff --git a/apps/api/src/autonomy.test.ts b/apps/api/src/autonomy.test.ts index 547f704..c3f2c9c 100644 --- a/apps/api/src/autonomy.test.ts +++ b/apps/api/src/autonomy.test.ts @@ -21,7 +21,7 @@ const fakeDb = {} as unknown as LearnProDb; const userSession = (user_id: string): SessionResolver => - async () => ({ user_id, org_id: "self", email: `${user_id}@x.y` }); + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); const NULL_SESSION: SessionResolver = async () => null; const USER_ID = "11111111-1111-1111-1111-111111111111"; diff --git a/apps/api/src/bug-finding-scores.test.ts b/apps/api/src/bug-finding-scores.test.ts index 2659660..e0f95fa 100644 --- a/apps/api/src/bug-finding-scores.test.ts +++ b/apps/api/src/bug-finding-scores.test.ts @@ -18,7 +18,7 @@ const fakeDb = {} as unknown as LearnProDb; const userSession = (user_id: string): SessionResolver => - async () => ({ user_id, org_id: "self", email: `${user_id}@x.y` }); + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); const NULL_SESSION: SessionResolver = async () => null; const USER_ID = "11111111-1111-1111-1111-111111111111"; diff --git a/apps/api/src/cheatsheet.test.ts b/apps/api/src/cheatsheet.test.ts index 45b7f77..d5b9fb8 100644 --- a/apps/api/src/cheatsheet.test.ts +++ b/apps/api/src/cheatsheet.test.ts @@ -78,7 +78,7 @@ function fakeLlm(responseText: string): LLMProvider & { calls: CompleteRequest[] const userSession = (user_id: string): SessionResolver => - async () => ({ user_id, org_id: "self", email: `${user_id}@x.y` }); + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); const NULL_SESSION: SessionResolver = async () => null; diff --git a/apps/api/src/data-controls.test.ts b/apps/api/src/data-controls.test.ts index 6bbead0..18d0dae 100644 --- a/apps/api/src/data-controls.test.ts +++ b/apps/api/src/data-controls.test.ts @@ -9,6 +9,7 @@ const userSession = user_id, org_id: "self", email: `${user_id}@learnpro.local`, + is_admin: false, }); const USER_ID = "11111111-1111-4111-8111-111111111111"; diff --git a/apps/api/src/e2e/harness.test.ts b/apps/api/src/e2e/harness.test.ts index f8545e4..e0505dd 100644 --- a/apps/api/src/e2e/harness.test.ts +++ b/apps/api/src/e2e/harness.test.ts @@ -118,7 +118,12 @@ describe("fixedUserSession", () => { email: "u1@example.com", }); const session = await resolver({} as never); - expect(session).toEqual({ user_id: "u-1", org_id: "org-1", email: "u1@example.com" }); + expect(session).toEqual({ + user_id: "u-1", + org_id: "org-1", + email: "u1@example.com", + is_admin: false, + }); }); it("defaults org_id to 'self' and supplies a stable email when omitted", async () => { diff --git a/apps/api/src/e2e/harness.ts b/apps/api/src/e2e/harness.ts index 62e1640..951e94d 100644 --- a/apps/api/src/e2e/harness.ts +++ b/apps/api/src/e2e/harness.ts @@ -161,7 +161,7 @@ export function fixedUserSession(input: { }): SessionResolver { const org_id = input.org_id ?? "self"; const email = input.email ?? "e2e-mvp-loop@learnpro.local"; - return async () => ({ user_id: input.user_id, org_id, email }); + return async () => ({ user_id: input.user_id, org_id, email, is_admin: false }); } export interface BuildE2eServerOptions { diff --git a/apps/api/src/email-digest.test.ts b/apps/api/src/email-digest.test.ts index 9365026..cefa6fb 100644 --- a/apps/api/src/email-digest.test.ts +++ b/apps/api/src/email-digest.test.ts @@ -27,7 +27,7 @@ const NULL_SESSION: SessionResolver = async () => null; const USER_ID = "11111111-1111-1111-1111-111111111111"; const userSession = (user_id: string): SessionResolver => - async () => ({ user_id, org_id: "self", email: `${user_id}@x.y` }); + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); function buildApp(opts: { sessionResolver?: SessionResolver } = {}) { return buildServer({ diff --git a/apps/api/src/export.test.ts b/apps/api/src/export.test.ts index 9708407..f8c343a 100644 --- a/apps/api/src/export.test.ts +++ b/apps/api/src/export.test.ts @@ -10,6 +10,7 @@ const userSession = user_id, org_id: "self", email: `${user_id}@learnpro.local`, + is_admin: false, }); // Always-allow / always-deny limiters for the test cases that don't care about windowing. diff --git a/apps/api/src/index.test.ts b/apps/api/src/index.test.ts index 345f145..63c2de6 100644 --- a/apps/api/src/index.test.ts +++ b/apps/api/src/index.test.ts @@ -19,6 +19,7 @@ const userSession = user_id, org_id: "self", email: `${user_id}@learnpro.local`, + is_admin: false, }); class FakeInteractionStore implements InteractionStore { diff --git a/apps/api/src/index.ts b/apps/api/src/index.ts index e8c3064..f4a5bc2 100644 --- a/apps/api/src/index.ts +++ b/apps/api/src/index.ts @@ -66,6 +66,7 @@ import { buildVariantSpecClarityJudgeFromEnv, registerProblemVariantsRoutes, } from "./problem-variants.js"; +import { registerAdminVariantFailuresRoutes } from "./admin-variant-failures.js"; import { loadExportWindowMs, noDbExporter, @@ -254,6 +255,10 @@ export interface BuildServerOptions { // `buildVariantSpecClarityJudgeFromEnv` (default ON when ANTHROPIC_API_KEY is set; // operator-disable via `LEARNPRO_VARIANT_SPEC_CLARITY_JUDGE=0`). variantSpecClarityJudge?: import("@learnpro/agent").SpecClarityJudge; + // STORY-039e — DB handle for the admin failed-gate variant inspection route. When + // supplied, registers `GET /v1/admin/variant-failures` behind the `users.is_admin = true` + // gate. Mirrors the problemVariantsDb wiring pattern; tests inject a fake DB. + adminVariantFailuresDb?: import("@learnpro/db").LearnProDb; } // Default impl when no store is provided — drops events on the floor. Useful for tests and @@ -606,6 +611,16 @@ export function buildServer(opts: BuildServerOptions = {}) { }); } + // STORY-039e — admin failed-gate variant inspection. Read-only, gated on + // `users.is_admin = true`. Same wiring pattern as the rest — present only when the DB + // handle is supplied. + if (opts.adminVariantFailuresDb) { + registerAdminVariantFailuresRoutes(app, { + db: opts.adminVariantFailuresDb, + sessionResolver, + }); + } + // STORY-060 deferred AC — friendly 429 mapping for the per-user daily token budget. Any handler // that calls into the LLM provider can throw `TokenBudgetExceededError`; this hook catches it // before Fastify's default 500 path so the playground can render the friendly message AC from @@ -667,6 +682,7 @@ function defaultsFromEnv(): { cheatsheetEpisodeFetcher?: CheatsheetEpisodeFetcher; problemVariantsDb?: import("@learnpro/db").LearnProDb; variantSpecClarityJudge?: import("@learnpro/agent").SpecClarityJudge; + adminVariantFailuresDb?: import("@learnpro/db").LearnProDb; } { const exportRateLimiter = buildExportRateLimiterFromEnv(process.env); const url = process.env["DATABASE_URL"]; @@ -778,6 +794,8 @@ function defaultsFromEnv(): { const judge = buildVariantSpecClarityJudgeFromEnv({ llm, env: process.env }); return judge ? { variantSpecClarityJudge: judge } : {}; })(), + // STORY-039e — wire the same db handle to the admin failed-gate inspection route. + adminVariantFailuresDb: db, ...(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/install-eligible.test.ts b/apps/api/src/install-eligible.test.ts index 59db757..640f522 100644 --- a/apps/api/src/install-eligible.test.ts +++ b/apps/api/src/install-eligible.test.ts @@ -80,7 +80,12 @@ async function buildServer(opts: { // eslint-disable-next-line @typescript-eslint/no-explicit-any db: fake.db as any, sessionResolver: opts.authed - ? async () => ({ user_id: "user-1", org_id: "self", email: "user-1@learnpro.local" }) + ? async () => ({ + user_id: "user-1", + org_id: "self", + email: "user-1@learnpro.local", + is_admin: false, + }) : async () => null, }); return { app }; diff --git a/apps/api/src/llm-mode.test.ts b/apps/api/src/llm-mode.test.ts index a374f9b..92c4df5 100644 --- a/apps/api/src/llm-mode.test.ts +++ b/apps/api/src/llm-mode.test.ts @@ -22,7 +22,7 @@ const NULL_SESSION: SessionResolver = async () => null; const USER_ID = "11111111-1111-1111-1111-111111111111"; const userSession = (user_id: string): SessionResolver => - async () => ({ user_id, org_id: "self", email: `${user_id}@x.y` }); + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); function buildApp(opts: { sessionResolver?: SessionResolver } = {}) { return buildServer({ diff --git a/apps/api/src/notifications.test.ts b/apps/api/src/notifications.test.ts index c9a0763..73ed174 100644 --- a/apps/api/src/notifications.test.ts +++ b/apps/api/src/notifications.test.ts @@ -60,7 +60,7 @@ function makeFakeDb(): { db: LearnProDb; captures: InsertCapture[] } { const userSession = (user_id: string): SessionResolver => - async () => ({ user_id, org_id: "self", email: `${user_id}@x.y` }); + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); const NULL_SESSION: SessionResolver = async () => null; const USER_ID = "11111111-1111-1111-1111-111111111111"; diff --git a/apps/api/src/onboarding.test.ts b/apps/api/src/onboarding.test.ts index 1dcb369..f6256ff 100644 --- a/apps/api/src/onboarding.test.ts +++ b/apps/api/src/onboarding.test.ts @@ -25,6 +25,7 @@ const userSession = user_id, org_id: "self", email: `${user_id}@learnpro.local`, + is_admin: false, }); class FakeLLMProvider implements LLMProvider { diff --git a/apps/api/src/portfolio.test.ts b/apps/api/src/portfolio.test.ts index dd5d1d3..3fe3b78 100644 --- a/apps/api/src/portfolio.test.ts +++ b/apps/api/src/portfolio.test.ts @@ -53,7 +53,7 @@ const fakeDb = { const userSession = (user_id: string): SessionResolver => - async () => ({ user_id, org_id: "self", email: `${user_id}@x.y` }); + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); const NULL_SESSION: SessionResolver = async () => null; const USER_ID = "11111111-1111-1111-1111-111111111111"; diff --git a/apps/api/src/problem-variants.test.ts b/apps/api/src/problem-variants.test.ts index 81a701d..019901e 100644 --- a/apps/api/src/problem-variants.test.ts +++ b/apps/api/src/problem-variants.test.ts @@ -135,7 +135,7 @@ function fakeLlm(responses: string[]): LLMProvider & { calls: CompleteRequest[] const userSession = (user_id: string): SessionResolver => - async () => ({ user_id, org_id: "self", email: `${user_id}@x.y` }); + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); const NULL_SESSION: SessionResolver = async () => null; diff --git a/apps/api/src/profile-insights.test.ts b/apps/api/src/profile-insights.test.ts index 3ab540d..98c3337 100644 --- a/apps/api/src/profile-insights.test.ts +++ b/apps/api/src/profile-insights.test.ts @@ -47,6 +47,7 @@ async function buildApp(opts: { authed: boolean }) { user_id: "11111111-1111-4111-8111-111111111111", org_id: "self", email: "x@y", + is_admin: false, }) : async () => null, }); diff --git a/apps/api/src/quiet-hours.test.ts b/apps/api/src/quiet-hours.test.ts index 625ff5d..f9ae933 100644 --- a/apps/api/src/quiet-hours.test.ts +++ b/apps/api/src/quiet-hours.test.ts @@ -22,7 +22,7 @@ const fakeDb = {} as unknown as LearnProDb; const userSession = (user_id: string): SessionResolver => - async () => ({ user_id, org_id: "self", email: `${user_id}@x.y` }); + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); const NULL_SESSION: SessionResolver = async () => null; const USER_ID = "11111111-1111-1111-1111-111111111111"; diff --git a/apps/api/src/recommendation.test.ts b/apps/api/src/recommendation.test.ts index d7b03a4..c41b5a4 100644 --- a/apps/api/src/recommendation.test.ts +++ b/apps/api/src/recommendation.test.ts @@ -22,7 +22,7 @@ const fakeDb = {} as unknown as LearnProDb; const userSession = (user_id: string): SessionResolver => - async () => ({ user_id, org_id: "self", email: `${user_id}@x.y` }); + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); const NULL_SESSION: SessionResolver = async () => null; const USER_ID = "11111111-1111-1111-1111-111111111111"; diff --git a/apps/api/src/session-plan.test.ts b/apps/api/src/session-plan.test.ts index 626c90f..614b3d0 100644 --- a/apps/api/src/session-plan.test.ts +++ b/apps/api/src/session-plan.test.ts @@ -14,6 +14,7 @@ const userSession = user_id, org_id: "self", email: `${user_id}@learnpro.local`, + is_admin: false, }); function plan(overrides: Partial = {}): SessionPlan { diff --git a/apps/api/src/spaced-repetition.test.ts b/apps/api/src/spaced-repetition.test.ts index c15aeae..3e57006 100644 --- a/apps/api/src/spaced-repetition.test.ts +++ b/apps/api/src/spaced-repetition.test.ts @@ -28,7 +28,7 @@ const fakeDb = { const userSession = (user_id: string): SessionResolver => - async () => ({ user_id, org_id: "self", email: `${user_id}@x.y` }); + async () => ({ user_id, org_id: "self", email: `${user_id}@x.y`, is_admin: false }); const NULL_SESSION: SessionResolver = async () => null; const USER_ID = "11111111-1111-1111-1111-111111111111"; diff --git a/apps/api/src/today-plan.test.ts b/apps/api/src/today-plan.test.ts index 83bd61c..02c795a 100644 --- a/apps/api/src/today-plan.test.ts +++ b/apps/api/src/today-plan.test.ts @@ -14,6 +14,7 @@ const userSession = user_id, org_id: "self", email: `${user_id}@learnpro.local`, + is_admin: false, }); interface FakeDepsState { diff --git a/apps/api/src/tutor.test.ts b/apps/api/src/tutor.test.ts index 13edf31..4940164 100644 --- a/apps/api/src/tutor.test.ts +++ b/apps/api/src/tutor.test.ts @@ -25,6 +25,7 @@ const userSession = user_id, org_id: "self", email: `${user_id}@learnpro.local`, + is_admin: false, }); function fakeAssignOutput(): AssignProblemOutput { diff --git a/apps/api/src/weekly-plan.test.ts b/apps/api/src/weekly-plan.test.ts index 701e004..e78c990 100644 --- a/apps/api/src/weekly-plan.test.ts +++ b/apps/api/src/weekly-plan.test.ts @@ -17,6 +17,7 @@ const userSession = user_id, org_id: "self", email: `${user_id}@learnpro.local`, + is_admin: false, }); interface FakeWeeklyDepsState { diff --git a/apps/web/src/app/(admin)/admin/variant-failures/VariantFailuresTable.test.tsx b/apps/web/src/app/(admin)/admin/variant-failures/VariantFailuresTable.test.tsx new file mode 100644 index 0000000..304e6a3 --- /dev/null +++ b/apps/web/src/app/(admin)/admin/variant-failures/VariantFailuresTable.test.tsx @@ -0,0 +1,139 @@ +import * as React from "react"; +import { renderToStaticMarkup } from "react-dom/server"; +import { describe, expect, it } from "vitest"; +import { + VariantFailuresTable, + formatDetail, + formatReason, + formatTimestamp, + type VariantFailureRow, +} from "./VariantFailuresTable"; + +void React; + +// STORY-039e — Presentational tests for the admin variant-failures table. Pure +// server-side rendering, no client state. The auth + redirect path lives in page.tsx; +// here we only assert the rendering surface. + +function sampleRow(overrides: Partial = {}): VariantFailureRow { + return { + id: "f-1", + source_problem_id: "44444444-4444-4444-8444-444444444444", + source_problem_slug: "sum-even-numbers", + attempted_at: "2026-05-10T10:00:00.000Z", + failure_reason: "parse_error", + failure_detail: { reason: "invalid_json", error: "unexpected token" }, + model_id: "claude-haiku-4", + attempt_number: 1, + ...overrides, + }; +} + +describe("VariantFailuresTable — STORY-039e", () => { + it("renders the heading + summary line with the total count", () => { + const out = renderToStaticMarkup(); + expect(out).toContain("Variant gate failures"); + expect(out).toContain("42 total"); + }); + + it("renders one row per failure with the source problem slug", () => { + const rows = [ + sampleRow({ id: "f-1", source_problem_slug: "sum-even-numbers" }), + sampleRow({ id: "f-2", source_problem_slug: "max-of-list" }), + ]; + const out = renderToStaticMarkup(); + expect(out).toContain("sum-even-numbers"); + expect(out).toContain("max-of-list"); + }); + + it("falls back to the source_problem_id when slug is null", () => { + const row = sampleRow({ source_problem_slug: null, source_problem_id: "abc-uuid" }); + const out = renderToStaticMarkup(); + expect(out).toContain("abc-uuid"); + }); + + it("formats well-known failure reasons into operator-friendly labels", () => { + const rows = [ + sampleRow({ id: "f-1", failure_reason: "parse_error" }), + sampleRow({ id: "f-2", failure_reason: "identity_mismatch" }), + sampleRow({ id: "f-3", failure_reason: "self_validation" }), + sampleRow({ id: "f-4", failure_reason: "retry_exhausted" }), + sampleRow({ id: "f-5", failure_reason: "spec_clarity_judge" }), + ]; + const out = renderToStaticMarkup(); + expect(out).toContain("Parse error"); + expect(out).toContain("Identity drift"); + expect(out).toContain("Self-validation"); + expect(out).toContain("Retry exhausted"); + expect(out).toContain("Spec clarity"); + }); + + it("renders the failure_detail JSON inside a
 block", () => {
+    const row = sampleRow({
+      failure_detail: { field: "language", expected: "python", got: "typescript" },
+    });
+    const out = renderToStaticMarkup();
+    expect(out).toContain(" {
+    const row = sampleRow({ model_id: "claude-haiku-4", attempt_number: 2 });
+    const out = renderToStaticMarkup();
+    expect(out).toContain("claude-haiku-4");
+    expect(out).toContain(">2<");
+  });
+
+  it("shows an empty-state message when there are no failures", () => {
+    const out = renderToStaticMarkup();
+    expect(out).toContain("No variant gate failures recorded yet");
+    expect(out).not.toContain(" {
+    const rows = [sampleRow()];
+    const out = renderToStaticMarkup();
+    expect(out).not.toContain("Delete");
+    expect(out).not.toContain("Retry");
+    expect(out).not.toContain("Publish");
+    expect(out).not.toContain(" {
+  it("maps each known reason to its human label", () => {
+    expect(formatReason("parse_error")).toBe("Parse error");
+    expect(formatReason("identity_mismatch")).toBe("Identity drift");
+    expect(formatReason("self_validation")).toBe("Self-validation");
+    expect(formatReason("retry_exhausted")).toBe("Retry exhausted");
+    expect(formatReason("spec_clarity_judge")).toBe("Spec clarity");
+  });
+
+  it("returns the raw reason for unknown discriminators (defensive fallback)", () => {
+    expect(formatReason("unknown_reason")).toBe("unknown_reason");
+  });
+});
+
+describe("formatDetail — STORY-039e", () => {
+  it("pretty-prints a small JSON object", () => {
+    expect(formatDetail({ a: 1, b: "two" })).toContain('"a": 1');
+  });
+
+  it("survives circular-shaped input via the catch fallback", () => {
+    const obj: Record = {};
+    obj["self"] = obj;
+    const out = formatDetail(obj);
+    expect(typeof out).toBe("string");
+  });
+});
+
+describe("formatTimestamp — STORY-039e", () => {
+  it("returns ISO format for a valid date string", () => {
+    expect(formatTimestamp("2026-05-10T10:00:00.000Z")).toBe("2026-05-10T10:00:00.000Z");
+  });
+
+  it("falls back to the raw input for an invalid date", () => {
+    expect(formatTimestamp("not a date")).toBe("not a date");
+  });
+});
diff --git a/apps/web/src/app/(admin)/admin/variant-failures/VariantFailuresTable.tsx b/apps/web/src/app/(admin)/admin/variant-failures/VariantFailuresTable.tsx
new file mode 100644
index 0000000..dc86645
--- /dev/null
+++ b/apps/web/src/app/(admin)/admin/variant-failures/VariantFailuresTable.tsx
@@ -0,0 +1,119 @@
+import * as React from "react";
+
+void React;
+
+// STORY-039e — Presentational table for failed-gate LLM-generated problem variants.
+// Pure server-side rendering, no client state. Extracted so the page itself stays a
+// thin server-component (auth + fetch + redirect) and the rendering can be unit-tested
+// without mocking next/headers + next-auth.
+
+export interface VariantFailureRow {
+  id: string;
+  source_problem_id: string;
+  source_problem_slug: string | null;
+  attempted_at: string;
+  failure_reason: string;
+  failure_detail: Record;
+  model_id: string;
+  attempt_number: number;
+}
+
+export interface VariantFailuresTableProps {
+  failures: VariantFailureRow[];
+  total: number;
+}
+
+const reasonLabel: Record = {
+  parse_error: "Parse error",
+  identity_mismatch: "Identity drift",
+  spec_clarity_judge: "Spec clarity",
+  self_validation: "Self-validation",
+  retry_exhausted: "Retry exhausted",
+};
+
+export function formatReason(r: string): string {
+  return reasonLabel[r] ?? r;
+}
+
+export function formatDetail(detail: Record): string {
+  try {
+    return JSON.stringify(detail, null, 2);
+  } catch {
+    return String(detail);
+  }
+}
+
+export function formatTimestamp(iso: string): string {
+  try {
+    const d = new Date(iso);
+    if (Number.isNaN(d.getTime())) return iso;
+    return d.toISOString();
+  } catch {
+    return iso;
+  }
+}
+
+export function VariantFailuresTable(props: VariantFailuresTableProps): React.ReactElement {
+  return (
+    
+

+ Variant gate failures +

+

+ Read-only inspection of failed LLM-generated problem variants. Showing the most recent of{" "} + {props.total} total. +

+ {props.failures.length > 0 ? ( + + + + + + + + + + + + + {props.failures.map((row) => ( + + + + + + + + + ))} + +
Source problemReasonDetailModelAttemptWhen
+ + {row.source_problem_slug ?? row.source_problem_id} + + {formatReason(row.failure_reason)} +
+                    {formatDetail(row.failure_detail)}
+                  
+
+ {row.model_id} + {row.attempt_number} + {formatTimestamp(row.attempted_at)} +
+ ) : ( +

+ No variant gate failures recorded yet. When the LLM generator fails a structural, + identity, self-validation, or spec-clarity check, the attempts will show up here. +

+ )} +
+ ); +} diff --git a/apps/web/src/app/(admin)/admin/variant-failures/page.tsx b/apps/web/src/app/(admin)/admin/variant-failures/page.tsx new file mode 100644 index 0000000..acf29c2 --- /dev/null +++ b/apps/web/src/app/(admin)/admin/variant-failures/page.tsx @@ -0,0 +1,82 @@ +import * as React from "react"; +import { headers } from "next/headers"; +import { redirect } from "next/navigation"; +import { auth } from "../../../../auth/auth.js"; +import { VariantFailuresTable, type VariantFailureRow } from "./VariantFailuresTable.js"; + +void React; + +// STORY-039e — Operator-only admin page showing recent LLM-generated problem-variant +// failures. Strictly read-only (no retry / delete / publish actions). Non-admins are +// redirected to /dashboard. The admin check rides entirely on apps/api's 403 — apps/web +// doesn't read `users.is_admin` directly so we never duplicate the gate. +// +// Pure server-side rendering, no client state. Pagination not exposed in v1 — the default +// /v1/admin/variant-failures limit (50) is enough for an operator inspecting the recent +// failure stream. + +export const dynamic = "force-dynamic"; + +interface VariantFailuresPayload { + failures: VariantFailureRow[]; + total: number; +} + +async function loadVariantFailures(): Promise<{ + payload: VariantFailuresPayload | null; + status: number; +}> { + const incoming = await headers(); + const cookie = incoming.get("cookie") ?? ""; + const host = incoming.get("host") ?? "localhost:3000"; + const proto = incoming.get("x-forwarded-proto") ?? "http"; + const url = `${proto}://${host}/api/admin/variant-failures`; + let res: Response; + try { + res = await fetch(url, { + headers: { ...(cookie ? { cookie } : {}) }, + cache: "no-store", + }); + } catch { + return { payload: null, status: 502 }; + } + if (!res.ok) { + return { payload: null, status: res.status }; + } + const json = (await res.json().catch(() => null)) as VariantFailuresPayload | null; + return { payload: json, status: res.status }; +} + +export default async function AdminVariantFailuresPage(): Promise { + const session = await auth(); + if (!session?.user?.id) { + redirect("/auth/signin"); + } + + const { payload, status } = await loadVariantFailures(); + if (status === 403) { + // Non-admin — fall back to the regular dashboard. Apps/api owns the gate; apps/web just + // listens for the 403 and redirects. + redirect("/dashboard"); + } + if (status === 401) { + redirect("/auth/signin"); + } + + const failures = payload?.failures ?? []; + const total = payload?.total ?? 0; + + return ( +
+ +
+ ); +} diff --git a/apps/web/src/app/api/admin/variant-failures/route.ts b/apps/web/src/app/api/admin/variant-failures/route.ts new file mode 100644 index 0000000..905b242 --- /dev/null +++ b/apps/web/src/app/api/admin/variant-failures/route.ts @@ -0,0 +1,37 @@ +import { NextResponse } from "next/server"; +import { headers } from "next/headers"; + +export const runtime = "nodejs"; + +const DEFAULT_API_URL = "http://localhost:4000"; + +// STORY-039e — proxy for `GET /v1/admin/variant-failures`. Forwards the Auth.js cookie so +// apps/api can resolve the user + verify the `users.is_admin = true` flag. Forwards query +// parameters (source_problem_id / limit / offset) verbatim. Read-only: only GET is wired. +export async function GET(req: Request): Promise { + const apiUrl = process.env["LEARNPRO_API_URL"] ?? DEFAULT_API_URL; + const incoming = await headers(); + const cookie = incoming.get("cookie") ?? ""; + const incomingUrl = new URL(req.url); + const upstreamUrl = new URL(`${apiUrl}/v1/admin/variant-failures`); + for (const [k, v] of incomingUrl.searchParams.entries()) { + upstreamUrl.searchParams.append(k, v); + } + let upstream: Response; + try { + upstream = await fetch(upstreamUrl.toString(), { + method: "GET", + headers: { ...(cookie ? { cookie } : {}) }, + }); + } catch (err) { + return NextResponse.json( + { error: "api_unreachable", message: err instanceof Error ? err.message : String(err) }, + { status: 502 }, + ); + } + const body = await upstream.text(); + return new NextResponse(body, { + status: upstream.status, + headers: { "content-type": upstream.headers.get("content-type") ?? "application/json" }, + }); +} diff --git a/packages/db/migrations/0025_variant_gate_failures.sql b/packages/db/migrations/0025_variant_gate_failures.sql new file mode 100644 index 0000000..f513b9a --- /dev/null +++ b/packages/db/migrations/0025_variant_gate_failures.sql @@ -0,0 +1,66 @@ +-- STORY-039e — Persistent log of variant-generation attempts that failed any of the gates +-- (structural Zod parse, identity drift, self-validation against hidden_tests, LLM-judge +-- spec-clarity rubric, or retry exhaustion). The companion `problem_variants` table only +-- stores SUCCESSFUL variants — without this table, an operator has no surface to see WHICH +-- variants failed, WHY, or how often. +-- +-- One row per failed attempt (NOT per source — a single source problem can produce many +-- failed attempts across retries). `failure_reason` is a CHECK-constrained discriminator; +-- `failure_detail` is the per-reason payload (e.g. `{ "zod_error": "..." }` for parse_error, +-- `{ "field": "language", "expected": "python", "got": "javascript" }` for identity_mismatch). +-- +-- The route inserts fire-and-forget — telemetry sink failures are logged but never block the +-- variant-generation response. +-- +-- Strictly read-only from the admin surface — there's no retry / publish / delete action in v1. + +CREATE TABLE IF NOT EXISTS "variant_gate_failures" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "org_id" text DEFAULT 'self' NOT NULL, + "source_problem_id" uuid NOT NULL, + "attempted_at" timestamp with time zone DEFAULT now() NOT NULL, + "failure_reason" text NOT NULL, + "failure_detail" jsonb DEFAULT '{}'::jsonb NOT NULL, + "model_id" text NOT NULL, + "attempt_number" integer NOT NULL +); +--> statement-breakpoint +DO $$ BEGIN + ALTER TABLE "variant_gate_failures" ADD CONSTRAINT "variant_gate_failures_source_problem_id_problems_id_fk" FOREIGN KEY ("source_problem_id") REFERENCES "public"."problems"("id") ON DELETE cascade ON UPDATE no action; +EXCEPTION + WHEN duplicate_object THEN null; +END $$; +--> statement-breakpoint +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint WHERE conname = 'variant_gate_failures_reason_check' + ) THEN + ALTER TABLE "variant_gate_failures" + ADD CONSTRAINT "variant_gate_failures_reason_check" + CHECK ( + failure_reason IN ( + 'parse_error', + 'identity_mismatch', + 'spec_clarity_judge', + 'self_validation', + 'retry_exhausted' + ) + ); + END IF; +END +$$; +--> statement-breakpoint +DO $$ +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM pg_constraint WHERE conname = 'variant_gate_failures_attempt_check' + ) THEN + ALTER TABLE "variant_gate_failures" + ADD CONSTRAINT "variant_gate_failures_attempt_check" + CHECK (attempt_number >= 1); + END IF; +END +$$; +--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "variant_gate_failures_source_idx" ON "variant_gate_failures" USING btree ("source_problem_id","attempted_at" DESC); diff --git a/packages/db/migrations/0026_users_is_admin.sql b/packages/db/migrations/0026_users_is_admin.sql new file mode 100644 index 0000000..c18c704 --- /dev/null +++ b/packages/db/migrations/0026_users_is_admin.sql @@ -0,0 +1,10 @@ +-- STORY-039e — Add `is_admin` boolean to `users` so the admin-only Fastify routes can gate +-- access. Operator manually promotes a user via psql: +-- +-- UPDATE users SET is_admin = true WHERE email = 'operator@example.com'; +-- +-- There is no UI for admin promotion in v1 (matches the "no SaaS plumbing in MVP" rule — admin +-- access is operator-only and out-of-band). Defaults to false so existing users stay +-- non-admin. + +ALTER TABLE "users" ADD COLUMN IF NOT EXISTS "is_admin" boolean DEFAULT false NOT NULL; diff --git a/packages/db/migrations/meta/_journal.json b/packages/db/migrations/meta/_journal.json index 49d6bbd..b695384 100644 --- a/packages/db/migrations/meta/_journal.json +++ b/packages/db/migrations/meta/_journal.json @@ -176,6 +176,20 @@ "when": 1780100000000, "tag": "0024_episode_variant_of", "breakpoints": true + }, + { + "idx": 25, + "version": "7", + "when": 1780200000000, + "tag": "0025_variant_gate_failures", + "breakpoints": true + }, + { + "idx": 26, + "version": "7", + "when": 1780300000000, + "tag": "0026_users_is_admin", + "breakpoints": true } ] } diff --git a/packages/db/src/data-export.test.ts b/packages/db/src/data-export.test.ts index bdf0952..f1ae647 100644 --- a/packages/db/src/data-export.test.ts +++ b/packages/db/src/data-export.test.ts @@ -396,6 +396,7 @@ function makeUser(overrides: Partial = {}): User { xp: 0, streak_grace_days_remaining: 2, streak_grace_last_replenished_at: null, + is_admin: false, created_at: new Date(0), ...overrides, }; diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index dcda97e..a4ada69 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -229,6 +229,17 @@ export { type ListProblemVariantsOptions, type ProblemVariantRow, } from "./problem-variants.js"; +export { + VARIANT_FAILURE_REASONS, + VariantFailureReasonSchema, + insertVariantGateFailure, + listVariantGateFailures, + type InsertVariantGateFailureInput, + type ListVariantGateFailuresOptions, + type ListVariantGateFailuresResult, + type VariantFailureReason, + type VariantGateFailureRow, +} from "./variant-gate-failures.js"; export { listBugFindingScores, upsertBugFindingScore, diff --git a/packages/db/src/schema.test.ts b/packages/db/src/schema.test.ts index a5b7375..0706f82 100644 --- a/packages/db/src/schema.test.ts +++ b/packages/db/src/schema.test.ts @@ -30,6 +30,7 @@ import { submissions, tracks, users, + variant_gate_failures, verificationTokens, web_push_subscriptions, xp_awards, @@ -561,6 +562,36 @@ describe("schema: concept_reviews (STORY-031)", () => { }); }); +describe("schema: variant_gate_failures (STORY-039e)", () => { + it("has id / org_id / source_problem_id / attempted_at / failure_reason / failure_detail / model_id / attempt_number", () => { + const cols = getTableColumns(variant_gate_failures); + expect(cols.id?.primary).toBe(true); + expect(cols.org_id?.notNull).toBe(true); + expect(cols.source_problem_id?.notNull).toBe(true); + expect(cols.attempted_at?.notNull).toBe(true); + expect(cols.failure_reason?.notNull).toBe(true); + expect(cols.failure_detail?.notNull).toBe(true); + expect(cols.model_id?.notNull).toBe(true); + expect(cols.attempt_number?.notNull).toBe(true); + }); + + it("failure_detail uses jsonb", () => { + const cols = getTableColumns(variant_gate_failures); + expect(cols.failure_detail?.getSQLType()).toBe("jsonb"); + }); + + it("declares a (source_problem_id, attempted_at) index for the admin scan", () => { + const config = getTableConfig(variant_gate_failures); + const names = config.indexes.map((i) => i.config.name); + expect(names).toContain("variant_gate_failures_source_idx"); + }); + + it("is included in both ALL_TABLES and ORG_SCOPED_TABLES", () => { + expect(ALL_TABLES).toContain(variant_gate_failures); + expect(ORG_SCOPED_TABLES as readonly unknown[]).toContain(variant_gate_failures); + }); +}); + describe("schema: knowledge graph (STORY-032)", () => { it("concepts carries the four story-required nullable columns", () => { const cols = getTableColumns(concepts); diff --git a/packages/db/src/schema.ts b/packages/db/src/schema.ts index 87a83fb..8dfdb81 100644 --- a/packages/db/src/schema.ts +++ b/packages/db/src/schema.ts @@ -96,6 +96,10 @@ export const users = pgTable( streak_grace_last_replenished_at: timestamp("streak_grace_last_replenished_at", { withTimezone: true, }), + // STORY-039e — operator-only flag for admin-route access (e.g. /v1/admin/variant-failures). + // No UI to flip this — operator promotes via `UPDATE users SET is_admin = true WHERE ...`. + // Defaults to false; the admin Fastify routes return 403 when a session's user has it unset. + is_admin: boolean("is_admin").notNull().default(false), created_at: createdAt(), }, (t) => ({ @@ -740,6 +744,31 @@ export const problem_variants = pgTable( }), ); +// STORY-039e — Persistent failure log for variant-generation gate failures. Companion to +// `problem_variants` (which only stores successes). One row per failed attempt; CHECK +// constraint on `failure_reason` (mirrored in the migration) keeps the discriminator honest. +// The admin surface in apps/api + apps/web reads from here. +export const variant_gate_failures = pgTable( + "variant_gate_failures", + { + id: uuid("id").primaryKey().defaultRandom(), + org_id: orgId(), + source_problem_id: uuid("source_problem_id") + .notNull() + .references(() => problems.id, { onDelete: "cascade" }), + attempted_at: timestamp("attempted_at", { withTimezone: true }).notNull().defaultNow(), + failure_reason: text("failure_reason").notNull(), + failure_detail: jsonb("failure_detail") + .notNull() + .default(sql`'{}'::jsonb`), + model_id: text("model_id").notNull(), + attempt_number: integer("attempt_number").notNull(), + }, + (t) => ({ + source_idx: index("variant_gate_failures_source_idx").on(t.source_problem_id, t.attempted_at), + }), +); + export type User = typeof users.$inferSelect; export type NewUser = typeof users.$inferInsert; export type Account = typeof accounts.$inferSelect; @@ -788,6 +817,8 @@ export type Cheatsheet = typeof cheatsheets.$inferSelect; export type NewCheatsheet = typeof cheatsheets.$inferInsert; export type ProblemVariant = typeof problem_variants.$inferSelect; export type NewProblemVariant = typeof problem_variants.$inferInsert; +export type VariantGateFailure = typeof variant_gate_failures.$inferSelect; +export type NewVariantGateFailure = typeof variant_gate_failures.$inferInsert; export type BugFindingScoreRow = typeof bug_finding_scores.$inferSelect; export type NewBugFindingScoreRow = typeof bug_finding_scores.$inferInsert; @@ -817,6 +848,7 @@ export const ALL_TABLES = [ profile_insights, cheatsheets, problem_variants, + variant_gate_failures, bug_finding_scores, ] as const; @@ -845,6 +877,7 @@ export const ORG_SCOPED_TABLES = [ profile_insights, cheatsheets, problem_variants, + variant_gate_failures, bug_finding_scores, ] as const; diff --git a/packages/db/src/session-lookup.ts b/packages/db/src/session-lookup.ts index 8c329cd..467429e 100644 --- a/packages/db/src/session-lookup.ts +++ b/packages/db/src/session-lookup.ts @@ -6,6 +6,9 @@ export interface SessionUser { user_id: string; org_id: string; email: string; + // STORY-039e — operator-only flag, read by admin-gated Fastify routes + // (e.g. GET /v1/admin/variant-failures). Defaults to false; operator promotes via psql. + is_admin: boolean; } export interface FindSessionUserOptions { @@ -24,6 +27,7 @@ export async function findSessionUser(opts: FindSessionUserOptions): Promise { + let db: LearnProDb; + let pool: Pool; + let trackId: string; + let problemA: string; + let problemB: string; + + beforeAll(async () => { + const created = createDb({ connectionString: DATABASE_URL ?? "" }); + db = created.db; + pool = created.pool; + await runMigrations(); + await db + .insert(organizations) + .values({ id: "self", name: "Self-hosted" }) + .onConflictDoNothing(); + const insertedTrack = await db + .insert(tracks) + .values({ + slug: `variant-gate-fail-track-${Date.now()}`, + name: "Variant gate-failures test track", + language: "python", + }) + .returning({ id: tracks.id }); + trackId = insertedTrack[0]!.id; + + const insertedA = await db + .insert(problems) + .values({ + track_id: trackId, + slug: `variant-gate-fail-source-a-${Date.now()}`, + name: "Variant gate-failures source A", + language: "python", + difficulty: "2", + statement: "noop", + hidden_tests: { cases: [], concept_tags: ["arrays"] }, + }) + .returning({ id: problems.id }); + problemA = insertedA[0]!.id; + + const insertedB = await db + .insert(problems) + .values({ + track_id: trackId, + slug: `variant-gate-fail-source-b-${Date.now()}`, + name: "Variant gate-failures source B", + language: "python", + difficulty: "2", + statement: "noop", + hidden_tests: { cases: [], concept_tags: ["arrays"] }, + }) + .returning({ id: problems.id }); + problemB = insertedB[0]!.id; + }); + + afterAll(async () => { + if (db) { + await db + .delete(variant_gate_failures) + .where(eq(variant_gate_failures.source_problem_id, problemA)); + await db + .delete(variant_gate_failures) + .where(eq(variant_gate_failures.source_problem_id, problemB)); + await db.delete(problems).where(eq(problems.id, problemA)); + await db.delete(problems).where(eq(problems.id, problemB)); + await db.delete(tracks).where(eq(tracks.id, trackId)); + } + await pool?.end(); + }); + + beforeEach(async () => { + await db + .delete(variant_gate_failures) + .where(eq(variant_gate_failures.source_problem_id, problemA)); + await db + .delete(variant_gate_failures) + .where(eq(variant_gate_failures.source_problem_id, problemB)); + }); + + it("inserts + lists a parse_error failure", async () => { + await insertVariantGateFailure(db, { + source_problem_id: problemA, + failure_reason: "parse_error", + failure_detail: { zod_error: "invalid JSON: unexpected token at position 0" }, + model_id: "claude-haiku-4", + attempt_number: 1, + }); + const result = await listVariantGateFailures(db, { source_problem_id: problemA }); + expect(result.total).toBe(1); + expect(result.failures).toHaveLength(1); + expect(result.failures[0]!.failure_reason).toBe("parse_error"); + expect(result.failures[0]!.failure_detail).toEqual({ + zod_error: "invalid JSON: unexpected token at position 0", + }); + expect(result.failures[0]!.attempt_number).toBe(1); + expect(result.failures[0]!.model_id).toBe("claude-haiku-4"); + }); + + it("accepts all 5 failure_reason values from the CHECK constraint", async () => { + const reasons = [ + "parse_error", + "identity_mismatch", + "spec_clarity_judge", + "self_validation", + "retry_exhausted", + ] as const; + for (const reason of reasons) { + await insertVariantGateFailure(db, { + source_problem_id: problemA, + failure_reason: reason, + failure_detail: { reason_detail: reason }, + model_id: "claude-haiku-4", + attempt_number: 1, + }); + } + const result = await listVariantGateFailures(db, { source_problem_id: problemA }); + expect(result.total).toBe(5); + expect(new Set(result.failures.map((f) => f.failure_reason))).toEqual(new Set(reasons)); + }); + + it("filters by source_problem_id and ignores other source problems", async () => { + await insertVariantGateFailure(db, { + source_problem_id: problemA, + failure_reason: "parse_error", + failure_detail: {}, + model_id: "claude-haiku-4", + attempt_number: 1, + }); + await insertVariantGateFailure(db, { + source_problem_id: problemB, + failure_reason: "identity_mismatch", + failure_detail: { field: "language", expected: "python", got: "javascript" }, + model_id: "claude-haiku-4", + attempt_number: 1, + }); + + const onlyA = await listVariantGateFailures(db, { source_problem_id: problemA }); + expect(onlyA.failures).toHaveLength(1); + expect(onlyA.failures[0]!.source_problem_id).toBe(problemA); + expect(onlyA.failures[0]!.failure_reason).toBe("parse_error"); + + const onlyB = await listVariantGateFailures(db, { source_problem_id: problemB }); + expect(onlyB.failures).toHaveLength(1); + expect(onlyB.failures[0]!.source_problem_id).toBe(problemB); + expect(onlyB.failures[0]!.failure_reason).toBe("identity_mismatch"); + }); + + it("joins source_problem_slug from problems for the admin UI", async () => { + await insertVariantGateFailure(db, { + source_problem_id: problemA, + failure_reason: "self_validation", + failure_detail: { test_index: 0, reason: "wrong_answer" }, + model_id: "claude-haiku-4", + attempt_number: 2, + }); + const result = await listVariantGateFailures(db, { source_problem_id: problemA }); + expect(result.failures[0]!.source_problem_slug).toMatch(/^variant-gate-fail-source-a-/); + }); + + it("returns failures newest-first", async () => { + await insertVariantGateFailure(db, { + source_problem_id: problemA, + failure_reason: "parse_error", + failure_detail: { order: 1 }, + model_id: "claude-haiku-4", + attempt_number: 1, + now: new Date("2026-05-10T10:00:00Z"), + }); + await insertVariantGateFailure(db, { + source_problem_id: problemA, + failure_reason: "identity_mismatch", + failure_detail: { order: 2 }, + model_id: "claude-haiku-4", + attempt_number: 1, + now: new Date("2026-05-11T10:00:00Z"), + }); + const result = await listVariantGateFailures(db, { source_problem_id: problemA }); + expect(result.failures[0]!.failure_detail).toEqual({ order: 2 }); + expect(result.failures[1]!.failure_detail).toEqual({ order: 1 }); + }); + + it("paginates via limit + offset and reports total before pagination", async () => { + for (let i = 0; i < 5; i++) { + await insertVariantGateFailure(db, { + source_problem_id: problemA, + failure_reason: "parse_error", + failure_detail: { i }, + model_id: "claude-haiku-4", + attempt_number: 1, + now: new Date(`2026-05-1${i}T10:00:00Z`), + }); + } + const page1 = await listVariantGateFailures(db, { source_problem_id: problemA, limit: 2 }); + expect(page1.failures).toHaveLength(2); + expect(page1.total).toBe(5); + + const page2 = await listVariantGateFailures(db, { + source_problem_id: problemA, + limit: 2, + offset: 2, + }); + expect(page2.failures).toHaveLength(2); + expect(page2.total).toBe(5); + }); + + it("rejects an invalid failure_reason at the Zod boundary", async () => { + await expect( + insertVariantGateFailure(db, { + source_problem_id: problemA, + // @ts-expect-error — invalid reason for boundary check + failure_reason: "something_else", + failure_detail: {}, + model_id: "claude-haiku-4", + attempt_number: 1, + }), + ).rejects.toThrow(); + }); + + it("rejects attempt_number < 1", async () => { + await expect( + insertVariantGateFailure(db, { + source_problem_id: problemA, + failure_reason: "parse_error", + failure_detail: {}, + model_id: "claude-haiku-4", + attempt_number: 0, + }), + ).rejects.toThrow(); + }); +}); diff --git a/packages/db/src/variant-gate-failures.ts b/packages/db/src/variant-gate-failures.ts new file mode 100644 index 0000000..99accca --- /dev/null +++ b/packages/db/src/variant-gate-failures.ts @@ -0,0 +1,144 @@ +import { and, desc, eq, sql } from "drizzle-orm"; +import { z } from "zod"; +import type { LearnProDb } from "./client.js"; +import { problems, SELF_HOSTED_ORG_ID, variant_gate_failures } from "./schema.js"; + +// STORY-039e — DB helpers for the variant gate-failures log. Inserts are fire-and-forget +// from the route's POV (the agent's `failureLogger` callback wraps this); reads power the +// admin Fastify route + Next.js page. +// +// The CHECK constraint on `failure_reason` lives in migration 0024 and is mirrored here in +// `VariantFailureReasonSchema` for Zod validation at the type boundary. Anything else is a +// programmer error and surfaces as a 500 — we don't sanitize at this layer. + +export const VARIANT_FAILURE_REASONS = [ + "parse_error", + "identity_mismatch", + "spec_clarity_judge", + "self_validation", + "retry_exhausted", +] as const; + +export const VariantFailureReasonSchema = z.enum(VARIANT_FAILURE_REASONS); +export type VariantFailureReason = z.infer; + +export interface InsertVariantGateFailureInput { + source_problem_id: string; + failure_reason: VariantFailureReason; + failure_detail: Record; + model_id: string; + attempt_number: number; + org_id?: string; + now?: Date; +} + +export interface VariantGateFailureRow { + id: string; + org_id: string; + source_problem_id: string; + source_problem_slug: string | null; + attempted_at: Date; + failure_reason: VariantFailureReason; + failure_detail: Record; + model_id: string; + attempt_number: number; +} + +export async function insertVariantGateFailure( + db: LearnProDb, + input: InsertVariantGateFailureInput, +): Promise<{ id: string }> { + const reason = VariantFailureReasonSchema.parse(input.failure_reason); + if (!Number.isInteger(input.attempt_number) || input.attempt_number < 1) { + throw new Error( + `insertVariantGateFailure: attempt_number must be a positive integer, got ${input.attempt_number}`, + ); + } + const now = input.now ?? new Date(); + const inserted = await db + .insert(variant_gate_failures) + .values({ + org_id: input.org_id ?? SELF_HOSTED_ORG_ID, + source_problem_id: input.source_problem_id, + failure_reason: reason, + failure_detail: input.failure_detail, + model_id: input.model_id, + attempt_number: input.attempt_number, + attempted_at: now, + }) + .returning({ id: variant_gate_failures.id }); + const row = inserted[0]; + if (!row) throw new Error("insertVariantGateFailure: insert returned no row"); + return { id: row.id }; +} + +export interface ListVariantGateFailuresOptions { + source_problem_id?: string; + limit?: number; + offset?: number; + org_id?: string; +} + +export interface ListVariantGateFailuresResult { + failures: VariantGateFailureRow[]; + total: number; +} + +// Returns failures newest-first with the source problem's slug joined in (the admin UI +// renders the slug, not the UUID). Pagination via `limit`/`offset`; the `total` value is the +// row count BEFORE pagination, so the admin page can show "N total". Capped at 200 per page +// (matches the route's max). +export async function listVariantGateFailures( + db: LearnProDb, + opts: ListVariantGateFailuresOptions = {}, +): Promise { + const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200); + const offset = Math.max(opts.offset ?? 0, 0); + const orgIdValue = opts.org_id ?? SELF_HOSTED_ORG_ID; + + const filters = [eq(variant_gate_failures.org_id, orgIdValue)]; + if (opts.source_problem_id !== undefined) { + filters.push(eq(variant_gate_failures.source_problem_id, opts.source_problem_id)); + } + const where = filters.length === 1 ? filters[0] : and(...filters); + + const rows = await db + .select({ + id: variant_gate_failures.id, + org_id: variant_gate_failures.org_id, + source_problem_id: variant_gate_failures.source_problem_id, + source_problem_slug: problems.slug, + attempted_at: variant_gate_failures.attempted_at, + failure_reason: variant_gate_failures.failure_reason, + failure_detail: variant_gate_failures.failure_detail, + model_id: variant_gate_failures.model_id, + attempt_number: variant_gate_failures.attempt_number, + }) + .from(variant_gate_failures) + .leftJoin(problems, eq(variant_gate_failures.source_problem_id, problems.id)) + .where(where) + .orderBy(desc(variant_gate_failures.attempted_at)) + .limit(limit) + .offset(offset); + + const countRows = await db + .select({ count: sql`count(*)::int` }) + .from(variant_gate_failures) + .where(where); + const total = countRows[0]?.count ?? 0; + + return { + failures: rows.map((r) => ({ + id: r.id, + org_id: r.org_id, + source_problem_id: r.source_problem_id, + source_problem_slug: r.source_problem_slug, + attempted_at: r.attempted_at, + failure_reason: VariantFailureReasonSchema.parse(r.failure_reason), + failure_detail: (r.failure_detail ?? {}) as Record, + model_id: r.model_id, + attempt_number: r.attempt_number, + })), + total, + }; +} diff --git a/project/BOARD.md b/project/BOARD.md index 89ae621..a7b6dd8 100644 --- a/project/BOARD.md +++ b/project/BOARD.md @@ -1,6 +1,6 @@ # LearnPro Board -> **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.) +> **Last updated:** 2026-05-11 (STORY-039e done — Admin failed-gate surface for LLM-generated problem variants (STORY-039 AC #6). New `variant_gate_failures` table (migration 0025) — CHECK-constrained `failure_reason` (5 reasons: parse_error / identity_mismatch / spec_clarity_judge / self_validation / retry_exhausted) + `failure_detail jsonb` + `model_id` + `attempt_number`, indexed on `(source_problem_id, attempted_at desc)`. New `users.is_admin boolean default false` (migration 0026) gates the admin route; operator manually flips via psql. `generateProblemVariant` accepts an optional `failureLogger` callback; on every failed attempt the agent emits a discriminated `VariantFailureEntry`. The Fastify route in apps/api wires `buildDrizzleVariantFailureLogger` so failures persist (fire-and-forget). New read-only `GET /v1/admin/variant-failures` Fastify route returns paginated failures (default 50, max 200) with joined `source_problem_slug` — 401 / 403 / 200 gates. New Next.js admin page at `/admin/variant-failures` (server component) renders a minimal Source | Reason | Detail (JSON) | Model | Attempt | When table; non-admins redirect to /dashboard via apps/api's 403. ~30 new tests across DB helpers (8) + agent (12) + route (9) + UI (16). 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 `loadSeenSourceSlugs` + `loadUnattemptedVariantsBySource`. `pickCandidate` extended with a final `maybeSwapToVariant` step that swaps seen seeds for unattempted cached variants. 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, then computes range-normalized variance for each path. ~12 new tests. Earlier: STORY-045a done — Postmark email transport (STORY-045 follow-up). New `PostmarkTransport` mirrors `ResendTransport`'s contract. 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,10 @@ STORY-053 (conversational onboarding agent) landed 2026-04-28 — `POST /v1/onbo | ID | Title | Done | |----|-------|------| -| [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-039e](stories/STORY-039e-admin-failed-gate-surface.md) | Admin failed-gate surface for LLM-generated problem variants (STORY-039 AC #6 follow-up) — new `variant_gate_failures` table (migration 0025) + `users.is_admin` flag (migration 0026) + agent `failureLogger` callback (5 discriminated reasons: parse_error / identity_mismatch / spec_clarity_judge / self_validation / retry_exhausted) + read-only `GET /v1/admin/variant-failures` Fastify route (401 / 403 / 200 + filter + pagination) + minimal Next.js admin page at `/admin/variant-failures`. ~30 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 `loadSeenSourceSlugs` + `loadUnattemptedVariantsBySource`. `pickCandidate` extended with a final `maybeSwapToVariant` 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. 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 | diff --git a/project/stories/STORY-039-llm-problem-variants.md b/project/stories/STORY-039-llm-problem-variants.md index eaec3b4..52765b6 100644 --- a/project/stories/STORY-039-llm-problem-variants.md +++ b/project/stories/STORY-039-llm-problem-variants.md @@ -23,10 +23,10 @@ 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). -- [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). +- [ ] LLM-judge spec-clarity rubric — DEFERRED to v1 follow-up (the structural Zod gate covers correctness; the judge is a quality-of-life addition). - [ ] 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). +- [x] Admin tool to inspect failed-gate variants — landed via [STORY-039e](STORY-039e-admin-failed-gate-surface.md) (new `variant_gate_failures` table + read-only `GET /v1/admin/variant-failures` Fastify route gated on `users.is_admin = true` + minimal Next.js page at `/admin/variant-failures`). - [ ] 100 variants seeded for launch — DEFERRED (the agent + cache are in place; seeding 100 is an operator task once an Anthropic key is wired into CI). - [x] Per-user "already seen the seed" gating — shipped 2026-05-11 via [STORY-039c](./STORY-039c-per-user-seen-seed.md). The assigner now prefers a cached, unattempted variant when the user has closed an episode on the seed; episode lineage is stamped via the new `episodes.is_variant_of_problem_id` column (migration 0024). @@ -49,4 +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). +- 2026-05-11 — STORY-039e mopped up AC #7 (admin tool to inspect failed-gate variants). New persistent `variant_gate_failures` table (migration 0024) + `users.is_admin` flag (migration 0025) + agent `failureLogger` callback + read-only `GET /v1/admin/variant-failures` Fastify route + minimal Next.js admin page at `/admin/variant-failures`. Failed-gate attempts (parse / identity / self-validation / retry exhaustion) are now persisted with structured payloads instead of dropped silently. diff --git a/project/stories/STORY-039e-admin-failed-gate-surface.md b/project/stories/STORY-039e-admin-failed-gate-surface.md new file mode 100644 index 0000000..77ae012 --- /dev/null +++ b/project/stories/STORY-039e-admin-failed-gate-surface.md @@ -0,0 +1,70 @@ +--- +id: STORY-039e +title: Admin failed-gate surface for LLM-generated problem variants +type: story +status: done +priority: P2 +estimate: M +parent: STORY-039 +phase: v1 +tags: [problems, llm, admin, operator, v1-followup] +created: 2026-05-11 +updated: 2026-05-11 +--- + +## Description + +STORY-039 deferred AC #6 (admin tool to inspect failed-gate variants) — when a variant fails the +structural Zod gate, the identity checks, the self-validation gate (STORY-039a), or the +spec-clarity judge (STORY-039d), the agent currently drops it silently and returns empty. An +operator has no surface to see WHICH variants failed, WHY, or how often. + +This Story adds a persistent failure log + a minimal read-only admin Fastify endpoint + a minimal +admin Next.js page so the operator can see what's failing without scraping app logs. + +## Acceptance criteria + +- [x] New `variant_gate_failures` table (migration 0025) keyed by `source_problem_id` with + `failure_reason` (one of parse_error / identity_mismatch / spec_clarity_judge / self_validation + / retry_exhausted), `failure_detail jsonb`, `model_id text`, `attempt_number int`, + `attempted_at timestamptz`. Index on `(source_problem_id, attempted_at desc)`. +- [x] `users.is_admin boolean default false` column (migration 0026) — the admin route checks this. +- [x] `generateProblemVariant` extended with optional `failureLogger?: (entry) => Promise` + parameter. When provided, called on every failed attempt with the structured failure entry. + Existing callers without `failureLogger` keep working (no-op default). +- [x] Fastify route inserts failures into the new table via a `DrizzleVariantFailureLogger` + (fire-and-forget — async insert errors logged but never block the user response). +- [x] New `GET /v1/admin/variant-failures` route — paginated (default 50, max 200), filterable by + `source_problem_id`, auth-gated + admin-only (401 if no session, 403 if not admin). Returns + `{ failures: [{ source_problem_slug, failure_reason, failure_detail, model_id, + attempt_number, attempted_at }], total }`. Read-only — never mutates. +- [x] New Next.js page at `/admin/variant-failures` (server component) — renders a table with + source problem | failure reason | failure detail | model | attempt | when. Non-admins + redirect to `/dashboard`. Empty state handled. +- [x] Tests pass: DB schema test asserts insert/query; agent test asserts `failureLogger` is called + on each failure path; admin route tests cover 401/403/200/filter/pagination; web page tests + cover non-admin redirect + admin sees table + empty state. + +## Tasks under this Story + +(Inlined into the activity log — no separate TASK files needed for an M-sized follow-up.) + +## Dependencies + +- Blocked by: [STORY-039](STORY-039-llm-problem-variants.md) (provides the agent + route + cache). +- Reuses: existing `requireAuth` middleware pattern from the other admin routes. + +## Notes + +- Operator manually flips a user's `is_admin = true` via psql. No UI for that in v1 (matches the + "no SaaS plumbing in MVP" rule — this is operator-only). +- Strictly read-only surface — never offers retry / delete / publish actions on failed variants. + That would be a separate Story if/when needed. +- The route + page deliberately don't expose org_id filtering — variant failures are global + (variants are content, not user data, per the STORY-039 design note). + +## Activity log + +- 2026-05-11 — created +- 2026-05-11 — picked up +- 2026-05-11 — done. New `variant_gate_failures` table (migration 0025) — CHECK-constrained `failure_reason` (5 reasons: parse_error / identity_mismatch / spec_clarity_judge / self_validation / retry_exhausted), `failure_detail jsonb`, `model_id`, `attempt_number`, indexed on `(source_problem_id, attempted_at desc)`. New `users.is_admin boolean default false` (migration 0026). `generateProblemVariant` accepts an optional `failureLogger` callback; on every failed attempt the agent emits a discriminated `VariantFailureEntry` (parse_error vs identity_mismatch differentiated by the new `parseProblemVariantResponseDetailed` helper). The Fastify route in apps/api wires `buildDrizzleVariantFailureLogger` so failures persist; insert errors are logged + swallowed so the user response never blocks. New auth+admin-gated `GET /v1/admin/variant-failures` Fastify route returns paginated failures (default 50, max 200) with joined `source_problem_slug`. New Next.js admin page at `/admin/variant-failures` (server component) renders a minimal table — Source | Reason | Detail (JSON) | Model | Attempt | When. Non-admins redirect to /dashboard via apps/api's 403. ~30 new tests across DB helpers (8) + agent (12) + route (9) + UI (16).