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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
180 changes: 180 additions & 0 deletions apps/api/src/admin-variant-failures.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof import("@learnpro/db")>();
return {
...actual,
listVariantGateFailures: (...a: Parameters<typeof actual.listVariantGateFailures>) =>
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();
});
});
64 changes: 64 additions & 0 deletions apps/api/src/admin-variant-failures.ts
Original file line number Diff line number Diff line change
@@ -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,
});
});
}
2 changes: 1 addition & 1 deletion apps/api/src/autonomy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/bug-finding-scores.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/cheatsheet.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
1 change: 1 addition & 0 deletions apps/api/src/data-controls.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
7 changes: 6 additions & 1 deletion apps/api/src/e2e/harness.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/e2e/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion apps/api/src/email-digest.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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({
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/export.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
1 change: 1 addition & 0 deletions apps/api/src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const userSession =
user_id,
org_id: "self",
email: `${user_id}@learnpro.local`,
is_admin: false,
});

class FakeInteractionStore implements InteractionStore {
Expand Down
18 changes: 18 additions & 0 deletions apps/api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ import {
buildVariantSpecClarityJudgeFromEnv,
registerProblemVariantsRoutes,
} from "./problem-variants.js";
import { registerAdminVariantFailuresRoutes } from "./admin-variant-failures.js";
import {
loadExportWindowMs,
noDbExporter,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"];
Expand Down Expand Up @@ -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
Expand Down
7 changes: 6 additions & 1 deletion apps/api/src/install-eligible.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 };
Expand Down
Loading
Loading