diff --git a/.claude/scheduled_tasks.lock b/.claude/scheduled_tasks.lock new file mode 100644 index 0000000..221ace0 --- /dev/null +++ b/.claude/scheduled_tasks.lock @@ -0,0 +1 @@ +{"sessionId":"c47826c7-dbff-432c-91e9-42570edef1d4","pid":35048,"acquiredAt":1778511076681} \ No newline at end of file diff --git a/apps/web/package.json b/apps/web/package.json index 7719bcf..21fa43f 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -14,6 +14,7 @@ "@auth/drizzle-adapter": "^1.7.4", "@learnpro/agent": "workspace:*", "@learnpro/db": "workspace:^", + "@learnpro/profile": "workspace:*", "@learnpro/sandbox": "workspace:*", "@learnpro/scoring": "workspace:*", "@learnpro/shared": "workspace:*", diff --git a/apps/web/src/app/session/page.tsx b/apps/web/src/app/session/page.tsx index cfaed81..54ddd0c 100644 --- a/apps/web/src/app/session/page.tsx +++ b/apps/web/src/app/session/page.tsx @@ -1,5 +1,7 @@ import { redirect } from "next/navigation"; +import { getTrackIdBySlug } from "@learnpro/db"; import { auth } from "../../auth/auth.js"; +import { getAuthDb } from "../../auth/db.js"; import { SessionClient } from "./SessionClient"; export const dynamic = "force-dynamic"; @@ -14,8 +16,17 @@ export default async function SessionPage({ searchParams }: SessionPageProps) { redirect("/auth/signin"); } const sp = await searchParams; - const trackId = sp.track; - if (!trackId || !isUuid(trackId)) { + const raw = sp.track; + // Accept either a track UUID (legacy / dashboard track-picker) OR a track slug (the + // /recommended cards link via slug — STORY-069). Resolve slug → id via the DB. + let trackId: string | undefined; + if (raw && isUuid(raw)) { + trackId = raw; + } else if (raw) { + const db = getAuthDb(); + trackId = (await getTrackIdBySlug(db, raw)) ?? undefined; + } + if (!trackId) { return (
{ expect(destinationFor({ profile, episodeCount: 1 })).toBe("/dashboard"); }); - it("respects unknown target_role values too — destination is /recommended (the page falls back)", () => { - // The post-signin rule is just about *whether* a target_role exists. The /recommended page - // itself queries the API and redirects to /dashboard if the role is unknown to the library. - // This keeps the rule simple and lets the page own the recommendation lookup. + // STORY-066 — supersedes the previous "unknown role still goes to /recommended" test. The + // page would 307 back to /dashboard, which would (via this rule) 307 back to /recommended, + // looping. Sending unknown roles straight to /dashboard is what breaks the loop. + it("sends an unknown target_role to /dashboard (STORY-066) to avoid the redirect loop", () => { expect(destinationFor({ profile: { target_role: "astronaut-trainee" }, episodeCount: 0 })).toBe( + "/dashboard", + ); + }); + + // STORY-067 — label-form input (the deterministic onboarding fallback writes labels, not + // slugs) should also resolve to /recommended for known roles. + it("recognizes label-form target_role too (STORY-067)", () => { + // "Backend engineer" is the label for the "backend-engineer" slug — getRecommendation + // matches both. + expect(destinationFor({ profile: { target_role: "Backend engineer" }, episodeCount: 0 })).toBe( "/recommended", ); }); + + it("normalises whitespace + case before role-library lookup (STORY-067)", () => { + expect( + destinationFor({ profile: { target_role: " Frontend Engineer " }, episodeCount: 0 }), + ).toBe("/recommended"); + }); }); diff --git a/apps/web/src/auth/post-signin.ts b/apps/web/src/auth/post-signin.ts index 992cea8..1c01519 100644 --- a/apps/web/src/auth/post-signin.ts +++ b/apps/web/src/auth/post-signin.ts @@ -1,11 +1,19 @@ import { countUserEpisodes, getProfileTargetRole, type Profile } from "@learnpro/db"; +import { getRecommendation, ROLE_LIBRARY } from "@learnpro/profile"; import { getAuthDb } from "./db.js"; // STORY-021 — first-login routing extends the STORY-005 rule. +// STORY-066 — also guard against the `/dashboard` ↔ `/recommended` redirect loop for +// `target_role` values the library doesn't recognize. // -// no profile / target_role null → /onboarding (still pre-onboarded) -// target_role set + 0 episodes → /recommended (just-onboarded → show role-mapped tracks) -// target_role set + ≥1 episode → /dashboard (returning user — skip past /recommended) +// no profile / target_role null → /onboarding (still pre-onboarded) +// target_role NOT recognized by library → /dashboard (no recommendation exists; sending +// to /recommended would 307 right +// back to /dashboard, looping) +// target_role recognized + 0 episodes → /recommended (just-onboarded → show role-mapped +// tracks) +// target_role recognized + ≥1 episode → /dashboard (returning user — skip past +// /recommended) // // Free choice, no soft-locks (AC #3): /recommended itself just renders the suggestion + a // "Take me to the dashboard" link. Returning users never see it again because the count guard @@ -29,7 +37,12 @@ export function destinationFor(arg: unknown): string { const inputs = arg as PostSigninInputs; if (!inputs.profile) return "/onboarding"; if (!inputs.profile.target_role) return "/onboarding"; - return inputs.episodeCount === 0 ? "/recommended" : "/dashboard"; + if (inputs.episodeCount > 0) return "/dashboard"; + // STORY-066 — only route to /recommended when the role library actually has a recommendation + // for this target_role. Otherwise /recommended would 307 back to /dashboard, which would + // 307 us right back here, looping the browser until it gives up with ERR_TOO_MANY_REDIRECTS. + const role = getRecommendation(ROLE_LIBRARY, inputs.profile.target_role); + return role ? "/recommended" : "/dashboard"; } const profile = arg as Pick | null | undefined; if (!profile) return "/onboarding"; diff --git a/infra/docker/docker-compose.dev.override.yaml b/infra/docker/docker-compose.dev.override.yaml new file mode 100644 index 0000000..7feeecd --- /dev/null +++ b/infra/docker/docker-compose.dev.override.yaml @@ -0,0 +1,19 @@ +# Local override — remaps published host ports to avoid collisions with native services +# already running on this machine (native Postgres on 5432, native Redis on 6379, another +# process on 9000/9001). Container-internal ports are unchanged; only host-side ports move. +# +# Activate by passing both files to compose: +# docker compose -f infra/docker/docker-compose.dev.yaml \ +# -f infra/docker/docker-compose.dev.override.yaml up -d + +services: + postgres: + ports: + - "15432:5432" + redis: + ports: + - "16379:6379" + minio: + ports: + - "19000:9000" + - "19001:9001" diff --git a/package.json b/package.json index e6b19cd..2481fce 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,8 @@ "test": "turbo run test", "e2e": "node scripts/e2e/run.mjs", "format": "prettier --write .", - "format:check": "prettier --check ." + "format:check": "prettier --check .", + "db:bootstrap": "pnpm --filter @learnpro/db db:migrate && pnpm --filter @learnpro/db db:seed && pnpm --filter @learnpro/db db:seed:concepts && pnpm --filter @learnpro/tracks db:seed:tracks && pnpm --filter @learnpro/problems db:seed:problems" }, "devDependencies": { "@types/node": "^22.10.2", diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index a4ada69..94849b1 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -74,7 +74,12 @@ export { type StreakInputs, type TrackProgress, } from "./xp-streak.js"; -export { countUserEpisodes, getTracksBySlugs, type TrackSummary } from "./tracks-query.js"; +export { + countUserEpisodes, + getTrackIdBySlug, + getTracksBySlugs, + type TrackSummary, +} from "./tracks-query.js"; export { addWebPushSubscription, findRecentDuplicate, diff --git a/packages/db/src/tracks-query.ts b/packages/db/src/tracks-query.ts index 9e02345..8e60001 100644 --- a/packages/db/src/tracks-query.ts +++ b/packages/db/src/tracks-query.ts @@ -1,10 +1,26 @@ -import { eq, inArray } from "drizzle-orm"; +import { and, eq, inArray } from "drizzle-orm"; import type { LearnProDb } from "./client.js"; import { episodes, SELF_HOSTED_ORG_ID, tracks } from "./schema.js"; // Light-weight, read-only helpers for the recommendation flow (STORY-021). Kept here rather than // in xp-streak.ts because they're not gamification-shaped — they're pure curriculum lookups. +// STORY-069 — resolve a track slug to its UUID. Used by the /session page so that user-facing +// links like `/session?track=python-fundamentals` work alongside the legacy UUID form. Returns +// null when no row matches (handle in caller with a "Pick a track" empty state). +export async function getTrackIdBySlug( + db: LearnProDb, + slug: string, + org_id: string = SELF_HOSTED_ORG_ID, +): Promise { + const rows = await db + .select({ id: tracks.id }) + .from(tracks) + .where(and(eq(tracks.slug, slug), eq(tracks.org_id, org_id))) + .limit(1); + return rows[0]?.id ?? null; +} + export interface TrackSummary { slug: string; name: string; diff --git a/packages/problems/bin/seed-problems.ts b/packages/problems/bin/seed-problems.ts new file mode 100644 index 0000000..4e6357e --- /dev/null +++ b/packages/problems/bin/seed-problems.ts @@ -0,0 +1,26 @@ +// STORY-068 — seed the curated problem YAMLs into Postgres so fresh self-hosters have content +// for the tutor's assign-problem tool to pick from. Idempotent: re-running upserts. +// +// Prereq: `pnpm --filter @learnpro/tracks db:seed:tracks` must run first (problems FK into +// tracks via track.slug → tracks.id lookup; seedProblems throws if a referenced track is +// missing). The aggregated `db:bootstrap` script (root package.json) chains both in order. + +import { createDb, loadDatabaseUrl } from "@learnpro/db"; +import { loadProblems, seedProblems } from "../src/index.js"; + +async function main(): Promise { + const url = loadDatabaseUrl(process.env); + const { db, pool } = createDb({ connectionString: url }); + try { + const defs = loadProblems(); + const result = await seedProblems(db, defs); + console.log("[db:seed:problems] complete:", { ...result, total_loaded: defs.length }); + } finally { + await pool.end(); + } +} + +main().catch((err: unknown) => { + console.error("[db:seed:problems] failed:", err); + process.exit(1); +}); diff --git a/packages/problems/package.json b/packages/problems/package.json index 3bc6445..5109b67 100644 --- a/packages/problems/package.json +++ b/packages/problems/package.json @@ -12,7 +12,8 @@ "build": "tsc -p tsconfig.json", "lint": "eslint src", "typecheck": "tsc --noEmit", - "test": "vitest run --passWithNoTests" + "test": "vitest run --passWithNoTests", + "db:seed:problems": "tsx bin/seed-problems.ts" }, "dependencies": { "@learnpro/db": "workspace:*", @@ -24,6 +25,7 @@ "devDependencies": { "@types/js-yaml": "^4.0.9", "@types/node": "^22.10.2", + "tsx": "^4.19.2", "typescript": "^5.7.2", "vitest": "^2.1.8" } diff --git a/packages/profile/src/roleLibrary.test.ts b/packages/profile/src/roleLibrary.test.ts index 3d9d0dd..af15ffd 100644 --- a/packages/profile/src/roleLibrary.test.ts +++ b/packages/profile/src/roleLibrary.test.ts @@ -129,6 +129,50 @@ describe("getRecommendation (STORY-021)", () => { expect(getRecommendation(custom, "test-role")?.label).toBe("Test role"); expect(getRecommendation(custom, "backend-engineer")).toBeNull(); }); + + // STORY-067 — the deterministic onboarding fallback writes the user's free-text reply, which + // is usually the label form (e.g. "Backend engineer"), not the slug form. Match both so a + // self-hoster without an API key doesn't get stuck with `role: null` from /api/recommendation. + it("returns the role for an exact label match (STORY-067)", () => { + const out = getRecommendation(ROLE_LIBRARY, "Backend engineer"); + expect(out?.slug).toBe("backend-engineer"); + expect(out?.label).toBe("Backend engineer"); + }); + + it("matches the label case-insensitively (STORY-067)", () => { + expect(getRecommendation(ROLE_LIBRARY, "FRONTEND ENGINEER")?.slug).toBe("frontend-engineer"); + expect(getRecommendation(ROLE_LIBRARY, "backend engineer")?.slug).toBe("backend-engineer"); + }); + + it("trims surrounding whitespace before label matching (STORY-067)", () => { + expect(getRecommendation(ROLE_LIBRARY, " ML engineer ")?.slug).toBe("ml-engineer"); + }); + + it("slug match wins when a slug and label both could match (defensive, STORY-067)", () => { + // Pathological library where one role's slug = another role's label (lowercased). + const custom: RoleLibrary = [ + { + slug: "x", + label: "Right one", + recommended_track_slugs: ["python-fundamentals"], + recommended_daily_minutes: 10, + bias: "standard", + }, + { + slug: "should-not-win", + // Label happens to equal the first role's slug — shouldn't shadow it. + label: "x", + recommended_track_slugs: ["python-fundamentals"], + recommended_daily_minutes: 10, + bias: "standard", + }, + ]; + expect(getRecommendation(custom, "x")?.label).toBe("Right one"); + }); + + it("returns null on text that's neither a slug nor a label (STORY-067)", () => { + expect(getRecommendation(ROLE_LIBRARY, "Quantum researcher")).toBeNull(); + }); }); describe("RoleSchema (STORY-021)", () => { diff --git a/packages/profile/src/roleLibrary.ts b/packages/profile/src/roleLibrary.ts index c237e0a..2802ace 100644 --- a/packages/profile/src/roleLibrary.ts +++ b/packages/profile/src/roleLibrary.ts @@ -115,9 +115,10 @@ export const ROLE_LIBRARY: RoleLibrary = Object.freeze( ) as RoleLibrary; /** - * Case-insensitive slug lookup against the role library. Returns `null` when no role matches. - * The free-text `target_role` captured by STORY-053 may include casing or whitespace variations; - * we normalise to lowercase + trim before matching. + * Case-insensitive lookup against the role library by slug OR label. Returns `null` when no role + * matches. The free-text `target_role` captured by STORY-053 may be either form — the LLM + * onboarding agent tends to write the slug, the deterministic fallback (STORY-053 AC #6) writes + * the user's free-text reply which is usually the label. STORY-067 — both must resolve. * * Free choice, no soft-locks: a `null` return is the "we have nothing tailored for you" signal — * the /recommended page redirects to /dashboard so the user keeps moving. @@ -125,5 +126,8 @@ export const ROLE_LIBRARY: RoleLibrary = Object.freeze( export function getRecommendation(library: RoleLibrary, target_role: string): Role | null { const needle = target_role.trim().toLowerCase(); if (!needle) return null; - return library.find((r) => r.slug.toLowerCase() === needle) ?? null; + // Slug match wins (defensive — labels can theoretically shadow other slugs). + const bySlug = library.find((r) => r.slug.toLowerCase() === needle); + if (bySlug) return bySlug; + return library.find((r) => r.label.toLowerCase() === needle) ?? null; } diff --git a/packages/tracks/bin/seed-tracks.ts b/packages/tracks/bin/seed-tracks.ts new file mode 100644 index 0000000..7db7ac0 --- /dev/null +++ b/packages/tracks/bin/seed-tracks.ts @@ -0,0 +1,31 @@ +// STORY-068 — seed the curated track YAMLs into Postgres so fresh self-hosters have something +// to learn against. Idempotent: re-running upserts. Mirrors `packages/db/bin/seed-concepts.ts`'s +// pattern. + +import { createDb, loadDatabaseUrl } from "@learnpro/db"; +import { + loadTrack, + seedTrack, + PYTHON_FUNDAMENTALS_PATH, + TYPESCRIPT_FUNDAMENTALS_PATH, +} from "../src/loader.js"; + +async function main(): Promise { + const url = loadDatabaseUrl(process.env); + const { db, pool } = createDb({ connectionString: url }); + try { + const python = await seedTrack(db, loadTrack(PYTHON_FUNDAMENTALS_PATH)); + const typescript = await seedTrack(db, loadTrack(TYPESCRIPT_FUNDAMENTALS_PATH)); + console.log("[db:seed:tracks] complete:", { + python: { slug: python.slug, id: python.id }, + typescript: { slug: typescript.slug, id: typescript.id }, + }); + } finally { + await pool.end(); + } +} + +main().catch((err: unknown) => { + console.error("[db:seed:tracks] failed:", err); + process.exit(1); +}); diff --git a/packages/tracks/package.json b/packages/tracks/package.json index f2fa5d8..fa02480 100644 --- a/packages/tracks/package.json +++ b/packages/tracks/package.json @@ -12,7 +12,8 @@ "build": "tsc -p tsconfig.json", "lint": "eslint src", "typecheck": "tsc --noEmit", - "test": "vitest run --passWithNoTests" + "test": "vitest run --passWithNoTests", + "db:seed:tracks": "tsx bin/seed-tracks.ts" }, "dependencies": { "@learnpro/db": "workspace:*", @@ -24,6 +25,7 @@ "devDependencies": { "@types/js-yaml": "^4.0.9", "@types/node": "^22.10.2", + "tsx": "^4.19.2", "typescript": "^5.7.2", "vitest": "^2.1.8" } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3c1cd56..ae07b9e 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -120,6 +120,9 @@ importers: '@learnpro/db': specifier: workspace:^ version: link:../../packages/db + '@learnpro/profile': + specifier: workspace:* + version: link:../../packages/profile '@learnpro/sandbox': specifier: workspace:* version: link:../../packages/sandbox @@ -373,6 +376,9 @@ importers: '@types/node': specifier: ^22.10.2 version: 22.19.17 + tsx: + specifier: ^4.19.2 + version: 4.21.0 typescript: specifier: ^5.7.2 version: 5.9.3 @@ -505,6 +511,9 @@ importers: '@types/node': specifier: ^22.10.2 version: 22.19.17 + tsx: + specifier: ^4.19.2 + version: 4.21.0 typescript: specifier: ^5.7.2 version: 5.9.3 diff --git a/project/stories/STORY-069-session-page-slug-acceptance.md b/project/stories/STORY-069-session-page-slug-acceptance.md new file mode 100644 index 0000000..6e0f775 --- /dev/null +++ b/project/stories/STORY-069-session-page-slug-acceptance.md @@ -0,0 +1,37 @@ +--- +id: STORY-069 +title: /session page accepts track slug, not only UUID (fixes /recommended → /session navigation) +type: story +status: in-progress +priority: P0 +estimate: XS +parent: EPIC-017 +phase: v1 +tags: [bug, session, recommended, ux] +created: 2026-05-12 +updated: 2026-05-12 +--- + +## Description + +`RecommendedTracksCard` builds card hrefs as `/session?track=${encodeURIComponent(track.slug)}` (so the user sees a human-readable URL like `/session?track=python-fundamentals`). But `apps/web/src/app/session/page.tsx` only accepts UUID-form `track` query params — it has an `isUuid()` guard that bails to a "Pick a track" empty state for anything else. + +Result: every click on a `/recommended` card lands on a dead "Pick a track. Open a session with `?track=`" message — the entire post-onboarding flow stops dead at the recommendation page. + +Caught during the 2026-05-12 Chrome walkthrough (round 2). + +## Acceptance criteria + +- [x] Add `getTrackIdBySlug(db, slug, org_id?)` to `@learnpro/db`. Returns `string | null`. +- [x] `/session` page resolves UUID-form input directly; slug-form input through `getTrackIdBySlug`; missing slug → "Pick a track" empty state (unchanged). +- [x] Manual verification: `/recommended` → click Python fundamentals card → lands on `/session?track=python-fundamentals` with the SessionClient rendered for a real problem (not the empty state). +- [ ] Unit test for `getTrackIdBySlug` (integration — needs Postgres). +- [ ] Component test for `/session/page.tsx` that asserts slug input resolves before bailing to the empty state. + +## Dependencies + +- Builds on STORY-068 (tracks must actually exist in the DB for the slug lookup to find anything). + +## Activity log + +- 2026-05-12 — created + fixed. Found during Chrome walkthrough round 2 (after STORY-068 unblocked seeded content). Verified in Chrome — `/session?track=python-fundamentals` now renders a real problem panel (Python or Debug). diff --git a/project/stories/STORY-070-today-plan-deterministic-fallback.md b/project/stories/STORY-070-today-plan-deterministic-fallback.md new file mode 100644 index 0000000..25b1ca2 --- /dev/null +++ b/project/stories/STORY-070-today-plan-deterministic-fallback.md @@ -0,0 +1,44 @@ +--- +id: STORY-070 +title: Add deterministic fallback for today-plan generation when ANTHROPIC_API_KEY is unset +type: story +status: backlog +priority: P1 +estimate: S +parent: EPIC-015 +phase: v1 +tags: [bug, today-plan, self-host, fallback] +created: 2026-05-12 +updated: 2026-05-12 +--- + +## Description + +`packages/agent/src/tools/plan-session.ts` calls `LLMRouter.complete` → Anthropic without checking for the no-API-key fallback path. When `ANTHROPIC_API_KEY` is unset (the self-hosted no-LLM default), every request to `POST /v1/session-plan` and the dashboard's `GET /v1/today-plan` surfaces a 503 with `LLMRequestError: ANTHROPIC_API_KEY is not set`. The UI degrades gracefully ("Couldn't generate today's plan. [Retry]") so it's not a hard crash, but it means the entire planning surface is unreachable for self-hosters without an API key. + +Parallels: STORY-053 (onboarding) shipped a deterministic 3-question state-machine fallback for exactly this case (`LEARNPRO_DISABLE_ONBOARDING_LLM=1`). Today-plan and weekly-plan should both have analogous fallbacks. + +Caught during the 2026-05-12 Chrome walkthrough (round 2). + +## Acceptance criteria + +- [ ] `plan-session.ts`'s `run()` returns a deterministic fallback plan when the LLM throws (or when `LEARNPRO_DISABLE_PLAN_LLM=1`): + - 3-5 items pulled from the user's track's next-due concepts (via `getDueConcepts` already used by the dashboard). + - One review item if `due_reviews.length > 0`. + - `fallback: true` flag set on the response so the UI can show a "deterministic plan — wire your API key for the LLM version" coach-voice note. +- [ ] `weekly-plan.ts` gets the same treatment (matching the per-day deterministic-name behavior STORY-046b already shipped). +- [ ] Test: `pnpm --filter @learnpro/agent test plan-session` with the LLM stubbed to throw — assert deterministic items returned, `fallback: true`. +- [ ] Manual verification: with `ANTHROPIC_API_KEY` unset, the dashboard renders a plan card with real items (not "Couldn't generate today's plan"). +- [ ] No forbidden-phrase regressions on the new copy. + +## Dependencies + +None. Pure additive. + +## Notes + +The exact "fallback plan" logic is mostly already in `today-plan.ts::buildTodayPlan` — it walks `due_reviews`, `due_concepts`, and `recent_episodes` deterministically. The plan-session agent just needs to delegate to that helper when the LLM is unavailable instead of throwing. + +## Activity log + +- 2026-05-12 — created. Found during Chrome walkthrough round 2. Stack: `LLMRequestError: ANTHROPIC_API_KEY is not set` at `plan-session.ts:63` → 503 from `POST /v1/session-plan` → red "Couldn't generate today's plan" card.