File size: 11,989 Bytes
9580dce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
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<string>;
}

export interface KnowledgeProfile {
  userId: number;
  totalAttempts: number;
  domains: Map<string, DomainProfile>;
  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<string, DomainProfile> {
  const domains = new Map<string, DomainProfile>();

  // Group attempts by domain
  const byDomain = new Map<string, TopicAttempt[]>();
  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<string, number[]>();
    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<KnowledgeProfile> {
  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<string>();
  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<string>();

  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<T>(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;
}