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
1 change: 1 addition & 0 deletions .claude/scheduled_tasks.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"sessionId":"c47826c7-dbff-432c-91e9-42570edef1d4","pid":35048,"acquiredAt":1778511076681}
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand Down
15 changes: 13 additions & 2 deletions apps/web/src/app/session/page.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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 (
<main
id="main-content"
Expand Down
24 changes: 20 additions & 4 deletions apps/web/src/auth/post-signin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,28 @@ describe("destinationFor — STORY-021 first-login routing", () => {
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");
});
});
21 changes: 17 additions & 4 deletions apps/web/src/auth/post-signin.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<Profile, "target_role"> | null | undefined;
if (!profile) return "/onboarding";
Expand Down
19 changes: 19 additions & 0 deletions infra/docker/docker-compose.dev.override.yaml
Original file line number Diff line number Diff line change
@@ -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"
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
7 changes: 6 additions & 1 deletion packages/db/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
18 changes: 17 additions & 1 deletion packages/db/src/tracks-query.ts
Original file line number Diff line number Diff line change
@@ -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<string | null> {
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;
Expand Down
26 changes: 26 additions & 0 deletions packages/problems/bin/seed-problems.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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);
});
4 changes: 3 additions & 1 deletion packages/problems/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand All @@ -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"
}
Expand Down
44 changes: 44 additions & 0 deletions packages/profile/src/roleLibrary.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)", () => {
Expand Down
12 changes: 8 additions & 4 deletions packages/profile/src/roleLibrary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,15 +115,19 @@ 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.
*/
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;
}
31 changes: 31 additions & 0 deletions packages/tracks/bin/seed-tracks.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
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);
});
4 changes: 3 additions & 1 deletion packages/tracks/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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:*",
Expand All @@ -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"
}
Expand Down
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading