import { prisma } from "@/lib/db"; import { FEYNMAN_TOPICS, type Topic } from "./topics"; import { filterReadyTopics } from "./prerequisites"; // --------------------------------------------------------------------------- // Types // --------------------------------------------------------------------------- export interface TopicAttempt { topicId: string; topic: string; domain: string; difficulty: "beginner" | "intermediate" | "expert"; score: number; // 0-1 wasTaught: boolean; attemptedAt: Date; } export interface DomainProfile { domain: string; attempts: number; avgScore: number; // 0-1 taughtCount: number; masteredTopics: string[]; // topic IDs with avg score >= 0.7 across attempts attemptedTopicIds: Set; } export interface KnowledgeProfile { userId: number; totalAttempts: number; domains: Map; recentTopicIds: string[]; // last N topic IDs attempted (for freshness filter) recommendedDifficulty: "beginner" | "intermediate" | "expert"; } // --------------------------------------------------------------------------- // Constants // --------------------------------------------------------------------------- /** Score threshold (0-1) to consider a topic "mastered" */ const MASTERY_THRESHOLD = 0.7; /** Number of recent topics to avoid repeating */ const RECENCY_WINDOW = 10; /** Minimum attempts before recommending intermediate topics */ const INTERMEDIATE_THRESHOLD = 3; /** Minimum attempts + avg score for expert topics */ const EXPERT_MIN_ATTEMPTS = 8; const EXPERT_MIN_AVG_SCORE = 0.65; // --------------------------------------------------------------------------- // Core functions // --------------------------------------------------------------------------- /** * Parse Feynman activity metadata to extract topic attempt data. * Returns null if metadata is missing or malformed. */ export function parseActivityMetadata( activity: { metadata: string | null; score: number | null; createdAt: Date }, ): TopicAttempt | null { if (!activity.metadata) return null; try { const meta = JSON.parse(activity.metadata); if (!meta.topic || typeof meta.topic !== "string") return null; // Match topic string to a known topic in the pool const matched = FEYNMAN_TOPICS.find( (t) => t.topic === meta.topic, ); return { topicId: matched?.id ?? `unknown-${meta.topic.slice(0, 20)}`, topic: meta.topic, domain: matched?.domain ?? "Unknown", difficulty: matched?.difficulty ?? "beginner", score: activity.score ?? 0, wasTaught: !!meta.wasTaught, attemptedAt: activity.createdAt, }; } catch { return null; } } /** * Build per-domain profiles from a list of topic attempts. */ export function buildDomainProfiles( attempts: TopicAttempt[], ): Map { const domains = new Map(); // Group attempts by domain const byDomain = new Map(); for (const a of attempts) { const arr = byDomain.get(a.domain) ?? []; arr.push(a); byDomain.set(a.domain, arr); } for (const [domain, domainAttempts] of byDomain) { const scores = domainAttempts.map((a) => a.score); const avgScore = scores.length > 0 ? scores.reduce((s, v) => s + v, 0) / scores.length : 0; const taughtCount = domainAttempts.filter((a) => a.wasTaught).length; // Compute mastered topics: group by topicId, average scores, check threshold const topicScores = new Map(); for (const a of domainAttempts) { const arr = topicScores.get(a.topicId) ?? []; arr.push(a.score); topicScores.set(a.topicId, arr); } const masteredTopics: string[] = []; for (const [topicId, tScores] of topicScores) { const avg = tScores.reduce((s, v) => s + v, 0) / tScores.length; if (avg >= MASTERY_THRESHOLD) { masteredTopics.push(topicId); } } const attemptedTopicIds = new Set(domainAttempts.map((a) => a.topicId)); domains.set(domain, { domain, attempts: domainAttempts.length, avgScore: Math.round(avgScore * 1000) / 1000, taughtCount, masteredTopics, attemptedTopicIds, }); } return domains; } /** * Determine the recommended difficulty level based on overall performance. * * - New users (< INTERMEDIATE_THRESHOLD attempts): beginner * - Users with moderate experience but lower scores: intermediate * - Experienced users with strong scores: expert */ export function recommendDifficulty( totalAttempts: number, overallAvgScore: number, ): "beginner" | "intermediate" | "expert" { if (totalAttempts < INTERMEDIATE_THRESHOLD) return "beginner"; if ( totalAttempts >= EXPERT_MIN_ATTEMPTS && overallAvgScore >= EXPERT_MIN_AVG_SCORE ) { return "expert"; } return "intermediate"; } /** * Build a complete knowledge profile for a user from their Feynman activities. */ export async function getKnowledgeProfile( userId: number, ): Promise { const activities = await prisma.activity.findMany({ where: { userId, category: "feynman" }, orderBy: { createdAt: "asc" }, select: { metadata: true, score: true, createdAt: true }, }); const attempts: TopicAttempt[] = []; for (const a of activities) { const parsed = parseActivityMetadata(a); if (parsed) attempts.push(parsed); } const domains = buildDomainProfiles(attempts); // Recent topic IDs (most recent first, limited to RECENCY_WINDOW) const recentTopicIds = attempts .slice(-RECENCY_WINDOW) .reverse() .map((a) => a.topicId); // Overall average score const allScores = attempts.map((a) => a.score); const overallAvg = allScores.length > 0 ? allScores.reduce((s, v) => s + v, 0) / allScores.length : 0; return { userId, totalAttempts: attempts.length, domains, recentTopicIds, recommendedDifficulty: recommendDifficulty(attempts.length, overallAvg), }; } // --------------------------------------------------------------------------- // Calibrated topic selection // --------------------------------------------------------------------------- /** * Select calibrated topics for a user based on their knowledge profile. * * Strategy: * 1. Filter out recently attempted topics (recency window) * 2. Prefer topics whose prerequisites are met (ready topics) * 3. Prefer unexplored domains (domains the user hasn't tried yet) * 4. Weight difficulty toward the user's recommended level * 5. Include a mix: one at-level, one stretch, one from a weak/unexplored area * 6. May include one locked topic (unmet prereqs) so users see the path ahead * 7. Fallback to standard random selection if pool is depleted */ export function getCalibratedTopics( profile: KnowledgeProfile, domain?: string, count: number = 3, ): Topic[] { // Start with the full pool or domain-filtered pool let pool = domain ? FEYNMAN_TOPICS.filter((t) => t.domain === domain) : [...FEYNMAN_TOPICS]; if (pool.length === 0) return []; // Step 1: Filter out recently attempted topics const recentSet = new Set(profile.recentTopicIds); const freshPool = pool.filter((t) => !recentSet.has(t.id)); // Use fresh pool if it has enough topics, otherwise use full pool pool = freshPool.length >= count ? freshPool : pool; if (pool.length <= count) return shuffle(pool); // Collect mastered topic IDs for prerequisite checking const masteredIds = new Set(); for (const [, dp] of profile.domains) { for (const id of dp.masteredTopics) { masteredIds.add(id); } } // Separate pool into ready (prereqs met) and locked (prereqs unmet) const readyPool = filterReadyTopics(pool, masteredIds); const lockedPool = pool.filter((t) => !readyPool.includes(t)); const picks: Topic[] = []; const usedIds = new Set(); const pick = (t: Topic) => { if (!usedIds.has(t.id)) { picks.push(t); usedIds.add(t.id); } }; const rec = profile.recommendedDifficulty; const difficultyOrder = getDifficultyOrder(rec); // Step 2: Pick one ready topic at the recommended difficulty (at-level) const atLevel = readyPool.filter( (t) => t.difficulty === difficultyOrder[0] && !usedIds.has(t.id), ); if (atLevel.length > 0) { // Prefer unexplored domains or weak domains const prioritized = prioritizeByProfile(atLevel, profile); pick(prioritized[0]); } // Step 3: Pick one ready stretch topic (one difficulty above) if (picks.length < count) { const stretch = readyPool.filter( (t) => t.difficulty === difficultyOrder[1] && !usedIds.has(t.id), ); if (stretch.length > 0) { const prioritized = prioritizeByProfile(stretch, profile); pick(prioritized[0]); } } // Step 4: Pick one from a weak or unexplored area (ready topics preferred) if (picks.length < count) { const remaining = readyPool.filter((t) => !usedIds.has(t.id)); const weakOrNew = prioritizeByProfile(remaining, profile); if (weakOrNew.length > 0) { pick(weakOrNew[0]); } } // Step 5: If we still need topics, include one locked topic to show the path ahead if (picks.length < count && lockedPool.length > 0) { const prioritized = prioritizeByProfile(lockedPool, profile); pick(prioritized[0]); } // Step 6: Fill remaining slots from any untouched ready topics if (picks.length < count) { const remaining = readyPool.filter((t) => !usedIds.has(t.id)); const shuffled = shuffle(remaining); for (const t of shuffled) { if (picks.length >= count) break; pick(t); } } // Step 7: Fill from full pool as last resort if (picks.length < count) { const remaining = pool.filter((t) => !usedIds.has(t.id)); const shuffled = shuffle(remaining); for (const t of shuffled) { if (picks.length >= count) break; pick(t); } } return shuffle(picks); } // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- /** * Get the preferred difficulty order based on recommended level. * Returns [primary, stretch, fallback]. */ function getDifficultyOrder( rec: "beginner" | "intermediate" | "expert", ): Array<"beginner" | "intermediate" | "expert"> { switch (rec) { case "beginner": return ["beginner", "intermediate", "expert"]; case "intermediate": return ["intermediate", "expert", "beginner"]; case "expert": return ["expert", "intermediate", "beginner"]; } } /** * Sort topics to prioritize unexplored domains and domains with lower scores. * Returns a new sorted array (does not mutate input). */ function prioritizeByProfile( topics: Topic[], profile: KnowledgeProfile, ): Topic[] { return [...topics].sort((a, b) => { const aDomain = profile.domains.get(a.domain); const bDomain = profile.domains.get(b.domain); // Unexplored domains first const aExplored = aDomain ? 1 : 0; const bExplored = bDomain ? 1 : 0; if (aExplored !== bExplored) return aExplored - bExplored; // Then: unattempted topics within a domain first const aAttempted = aDomain?.attemptedTopicIds.has(a.id) ? 1 : 0; const bAttempted = bDomain?.attemptedTopicIds.has(b.id) ? 1 : 0; if (aAttempted !== bAttempted) return aAttempted - bAttempted; // Then: lower avg score domains first (weaker areas) const aScore = aDomain?.avgScore ?? 0; const bScore = bDomain?.avgScore ?? 0; if (aScore !== bScore) return aScore - bScore; // Random tiebreak return Math.random() - 0.5; }); } function shuffle(arr: T[]): T[] { const result = [...arr]; for (let i = result.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [result[i], result[j]] = [result[j], result[i]]; } return result; }