File size: 17,569 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
390
391
392
393
394
395
396
397
398
399
400
401
402
/**
 * Unit tests for getKnowledgeProfile (DB-backed).
 *
 * Covers:
 *   - DB query params: userId filter, feynman category filter,
 *     chronological asc ordering, select fields
 *   - Empty activity list: zero totals, empty domains/recentTopicIds,
 *     beginner recommendation
 *   - userId passthrough in returned profile
 *   - totalAttempts counts only parseable activities (skips null/malformed metadata)
 *   - recentTopicIds: last RECENCY_WINDOW (10) attempts, most-recent-first order
 *   - recommendedDifficulty derivation:
 *       < 3 β†’ beginner, moderate+low avg β†’ intermediate, β‰₯8 + avgβ‰₯0.65 β†’ expert
 *   - domains: correctly grouped and propagated from buildDomainProfiles()
 *     (domain key is the `domain` field from FEYNMAN_TOPICS, e.g. "CS", "Physics")
 *   - Error propagation: DB throws β†’ getKnowledgeProfile throws
 *
 * parseActivityMetadata matches by `meta.topic` string to a FEYNMAN_TOPICS entry,
 * so we use real topic names from the library as metadata values.
 */

import { describe, it, expect, vi, beforeEach } from "vitest";

// ── Mock Prisma ──────────────────────────────────────────────────────────────

const mockActivityFindMany = vi.fn();

vi.mock("@/lib/db", () => ({
  prisma: {
    activity: {
      findMany: (...args: unknown[]) => mockActivityFindMany(...args),
    },
  },
}));

// Import after mock hoisting
import { getKnowledgeProfile } from "../knowledge-profile";

// ── Known topic names from FEYNMAN_TOPICS (used in metadata) ─────────────────
// These must match exactly so parseActivityMetadata can look them up.
const TOPIC_CS_01     = "How a hash table works";               // cs-01, CS, beginner
const TOPIC_CS_02     = "Big O notation and time complexity";   // cs-02, CS, beginner
const TOPIC_CS_03     = "How recursion works";                  // cs-03, CS, beginner
const TOPIC_PH_01     = "Newton's three laws of motion";        // ph-01, Physics, beginner
const TOPIC_MA_01     = "What a derivative represents in calculus"; // ma-01, Mathematics, beginner
const TOPIC_BI_01     = "How DNA replication works";            // bi-01, Biology, beginner

// ── Helpers ──────────────────────────────────────────────────────────────────

/**
 * Build a raw activity row as Prisma would return it.
 * Uses actual FEYNMAN_TOPICS topic strings so parseActivityMetadata can match them.
 */
function makeActivity(
  topicString: string,
  score: number,
  createdAt: Date = new Date("2026-01-01T00:00:00Z"),
  extra: Record<string, unknown> = {},
): { metadata: string | null; score: number; createdAt: Date } {
  return {
    metadata: JSON.stringify({ topic: topicString, ...extra }),
    score,
    createdAt,
  };
}

// ── Tests ────────────────────────────────────────────────────────────────────

describe("getKnowledgeProfile", () => {
  beforeEach(() => {
    mockActivityFindMany.mockReset();
  });

  // ── DB query params ───────────────────────────────────────────────────────

  it("queries DB with userId filter", async () => {
    mockActivityFindMany.mockResolvedValue([]);
    await getKnowledgeProfile(42);
    expect(mockActivityFindMany).toHaveBeenCalledOnce();
    const [args] = mockActivityFindMany.mock.calls[0];
    expect(args.where.userId).toBe(42);
  });

  it("filters to feynman category only", async () => {
    mockActivityFindMany.mockResolvedValue([]);
    await getKnowledgeProfile(1);
    const [args] = mockActivityFindMany.mock.calls[0];
    expect(args.where.category).toBe("feynman");
  });

  it("orders activities ascending by createdAt", async () => {
    mockActivityFindMany.mockResolvedValue([]);
    await getKnowledgeProfile(1);
    const [args] = mockActivityFindMany.mock.calls[0];
    expect(args.orderBy).toEqual({ createdAt: "asc" });
  });

  it("selects only metadata, score, and createdAt", async () => {
    mockActivityFindMany.mockResolvedValue([]);
    await getKnowledgeProfile(1);
    const [args] = mockActivityFindMany.mock.calls[0];
    expect(args.select).toEqual({
      metadata: true,
      score: true,
      createdAt: true,
    });
  });

  // ── Empty activity list ───────────────────────────────────────────────────

  it("returns userId in profile", async () => {
    mockActivityFindMany.mockResolvedValue([]);
    const profile = await getKnowledgeProfile(7);
    expect(profile.userId).toBe(7);
  });

  it("returns 0 totalAttempts for empty activity list", async () => {
    mockActivityFindMany.mockResolvedValue([]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.totalAttempts).toBe(0);
  });

  it("returns empty domains map for empty activity list", async () => {
    mockActivityFindMany.mockResolvedValue([]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.domains.size).toBe(0);
  });

  it("returns empty recentTopicIds for empty activity list", async () => {
    mockActivityFindMany.mockResolvedValue([]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.recentTopicIds).toEqual([]);
  });

  it("recommends beginner for new users with no activities", async () => {
    mockActivityFindMany.mockResolvedValue([]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.recommendedDifficulty).toBe("beginner");
  });

  // ── Parseable vs unparseable activities ───────────────────────────────────

  it("counts only parseable activities in totalAttempts", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.8),
      makeActivity(TOPIC_CS_02, 0.7),
      { metadata: null, score: 0.5, createdAt: new Date() },           // null β†’ skipped
      { metadata: "not-json{{{", score: 0.5, createdAt: new Date() },  // malformed β†’ skipped
      { metadata: JSON.stringify({ noTopicField: true }), score: 0.5, createdAt: new Date() }, // missing topic β†’ skipped
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.totalAttempts).toBe(2);
  });

  it("skips null metadata without throwing", async () => {
    mockActivityFindMany.mockResolvedValue([
      { metadata: null, score: 0.8, createdAt: new Date() },
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.totalAttempts).toBe(0);
    expect(profile.recentTopicIds).toEqual([]);
  });

  it("skips malformed JSON metadata without throwing", async () => {
    mockActivityFindMany.mockResolvedValue([
      { metadata: "{{bad json", score: 0.8, createdAt: new Date() },
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.totalAttempts).toBe(0);
  });

  it("parses activities with unknown topic strings (fallback topicId)", async () => {
    // A topic not in FEYNMAN_TOPICS still parses as a TopicAttempt with a generated ID
    mockActivityFindMany.mockResolvedValue([
      { metadata: JSON.stringify({ topic: "Some obscure topic not in library" }), score: 0.7, createdAt: new Date() },
    ]);
    const profile = await getKnowledgeProfile(1);
    // Unknown topics still count as attempts
    expect(profile.totalAttempts).toBe(1);
  });

  // ── totalAttempts ─────────────────────────────────────────────────────────

  it("totalAttempts equals number of parseable activities", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.8),
      makeActivity(TOPIC_CS_02, 0.7),
      makeActivity(TOPIC_PH_01, 0.9),
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.totalAttempts).toBe(3);
  });

  // ── recentTopicIds ────────────────────────────────────────────────────────

  it("recentTopicIds reflects most-recent-first ordering", async () => {
    // Activities arrive ordered asc from DB; recentTopicIds should be newest-first
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.8, new Date("2026-01-01T00:00:00Z")),
      makeActivity(TOPIC_CS_02, 0.7, new Date("2026-01-02T00:00:00Z")),
      makeActivity(TOPIC_PH_01, 0.9, new Date("2026-01-03T00:00:00Z")),
    ]);
    const profile = await getKnowledgeProfile(1);
    // Most recent first: ph-01, cs-02, cs-01
    expect(profile.recentTopicIds[0]).toBe("ph-01");
    expect(profile.recentTopicIds[1]).toBe("cs-02");
    expect(profile.recentTopicIds[2]).toBe("cs-01");
    expect(profile.recentTopicIds.length).toBe(3);
  });

  it("caps recentTopicIds at 10 entries (RECENCY_WINDOW)", async () => {
    // 12 activities using 12 distinct known topics β€” only the last 10 should appear
    const topicStrings = [
      TOPIC_CS_01,
      TOPIC_CS_02,
      TOPIC_CS_03,
      TOPIC_PH_01,
      TOPIC_MA_01,
      TOPIC_BI_01,
      "Newton's three laws of motion",    // ph-01 reuse (same string = same ID)
      "Big O notation and time complexity", // cs-02 reuse
      "How recursion works",              // cs-03 reuse
      "Why imaginary numbers are real and useful", // ma-01 reuse
      "How a compiler turns source code into machine code", // cs-10 β€” 11th
      "How the MapReduce pattern works",  // cs-11 β€” 12th
    ];
    const activities = topicStrings.map((topic, i) => ({
      metadata: JSON.stringify({ topic }),
      score: 0.7,
      createdAt: new Date(Date.UTC(2026, 0, i + 1)),
    }));
    mockActivityFindMany.mockResolvedValue(activities);
    const profile = await getKnowledgeProfile(1);
    expect(profile.recentTopicIds.length).toBe(10);
    // The last (12th) activity topic should be first in recentTopicIds
    expect(profile.recentTopicIds[0]).toBe("cs-11");
    // The first (1st) activity topic (cs-01) should not be in the window
    expect(profile.recentTopicIds).not.toContain("cs-01");
  });

  it("recentTopicIds includes all topics when fewer than 10 activities", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.7, new Date("2026-01-01T00:00:00Z")),
      makeActivity(TOPIC_MA_01, 0.8, new Date("2026-01-02T00:00:00Z")),
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.recentTopicIds.length).toBe(2);
    // Most recent first: ma-01, cs-01
    expect(profile.recentTopicIds[0]).toBe("ma-01");
    expect(profile.recentTopicIds[1]).toBe("cs-01");
  });

  // ── recommendedDifficulty ─────────────────────────────────────────────────

  it("recommends beginner when fewer than 3 parseable activities", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.9),
      makeActivity(TOPIC_CS_02, 0.95),
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.recommendedDifficulty).toBe("beginner");
  });

  it("recommends intermediate for moderate experience with low-average scores", async () => {
    // 5 attempts with avg score 0.5 β†’ intermediate (β‰₯3 attempts, avg < 0.65)
    const activities = [
      makeActivity(TOPIC_CS_01, 0.5),
      makeActivity(TOPIC_CS_02, 0.5),
      makeActivity(TOPIC_CS_03, 0.5),
      makeActivity(TOPIC_PH_01, 0.5),
      makeActivity(TOPIC_MA_01, 0.5),
    ];
    mockActivityFindMany.mockResolvedValue(activities);
    const profile = await getKnowledgeProfile(1);
    expect(profile.recommendedDifficulty).toBe("intermediate");
  });

  it("recommends expert for experienced users with high average scores", async () => {
    // 8+ attempts with avg score >= 0.65 β†’ expert
    const activities = [
      makeActivity(TOPIC_CS_01, 0.8),
      makeActivity(TOPIC_CS_02, 0.8),
      makeActivity(TOPIC_CS_03, 0.8),
      makeActivity(TOPIC_PH_01, 0.8),
      makeActivity(TOPIC_MA_01, 0.8),
      makeActivity(TOPIC_BI_01, 0.8),
      makeActivity("Newton's three laws of motion", 0.8),
      makeActivity("Big O notation and time complexity", 0.8),
    ];
    mockActivityFindMany.mockResolvedValue(activities);
    const profile = await getKnowledgeProfile(1);
    expect(profile.recommendedDifficulty).toBe("expert");
  });

  it("stays intermediate when attempt count is high but avg score is below expert threshold", async () => {
    // 10 attempts but avg score 0.4 β€” not enough for expert
    const activities = Array.from({ length: 10 }, () =>
      makeActivity(TOPIC_CS_01, 0.4),
    );
    mockActivityFindMany.mockResolvedValue(activities);
    const profile = await getKnowledgeProfile(1);
    expect(profile.recommendedDifficulty).toBe("intermediate");
  });

  // ── domain profiles ───────────────────────────────────────────────────────

  it("populates domains from activities", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.8),
      makeActivity(TOPIC_CS_02, 0.9),
      makeActivity(TOPIC_PH_01, 0.7),
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.domains.has("CS")).toBe(true);
    expect(profile.domains.has("Physics")).toBe(true);
    expect(profile.domains.size).toBe(2);
  });

  it("domain attempt count matches parseable activities in that domain", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.8),
      makeActivity(TOPIC_CS_02, 0.9),
      makeActivity(TOPIC_PH_01, 0.7),
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.domains.get("CS")?.attempts).toBe(2);
    expect(profile.domains.get("Physics")?.attempts).toBe(1);
  });

  it("domain avgScore is the mean score for that domain", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.6),
      makeActivity(TOPIC_CS_02, 0.8),
    ]);
    const profile = await getKnowledgeProfile(1);
    // avg of 0.6 and 0.8 = 0.7
    expect(profile.domains.get("CS")?.avgScore).toBeCloseTo(0.7, 5);
  });

  it("marks topic as mastered when avg score across its attempts >= 0.7", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.8),
      makeActivity(TOPIC_CS_01, 0.9), // same topic, two high-score attempts β†’ mastered
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.domains.get("CS")?.masteredTopics).toContain("cs-01");
  });

  it("does not mark topic as mastered when avg score < 0.7", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.5),
      makeActivity(TOPIC_CS_01, 0.6), // avg 0.55 β†’ not mastered
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.domains.get("CS")?.masteredTopics).not.toContain("cs-01");
  });

  it("tracks attempted topic IDs in the domain profile", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.5),  // cs-01
      makeActivity(TOPIC_CS_03, 0.7),  // cs-03
    ]);
    const profile = await getKnowledgeProfile(1);
    const cs = profile.domains.get("CS");
    expect(cs?.attemptedTopicIds.has("cs-01")).toBe(true);
    expect(cs?.attemptedTopicIds.has("cs-03")).toBe(true);
    expect(cs?.attemptedTopicIds.has("cs-02")).toBe(false);
  });

  it("tracks taughtCount for wasTaught activities", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.7, new Date(), { wasTaught: true }),
      makeActivity(TOPIC_CS_02, 0.8, new Date(), { wasTaught: false }),
      makeActivity(TOPIC_CS_03, 0.6, new Date()), // no wasTaught field
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.domains.get("CS")?.taughtCount).toBe(1);
  });

  it("separates activities into correct domains when multiple domains present", async () => {
    mockActivityFindMany.mockResolvedValue([
      makeActivity(TOPIC_CS_01, 0.7),   // CS
      makeActivity(TOPIC_PH_01, 0.8),   // Physics
      makeActivity(TOPIC_MA_01, 0.9),   // Mathematics
      makeActivity(TOPIC_BI_01, 0.6),   // Biology
    ]);
    const profile = await getKnowledgeProfile(1);
    expect(profile.domains.size).toBe(4);
    expect(profile.domains.get("CS")?.attempts).toBe(1);
    expect(profile.domains.get("Physics")?.attempts).toBe(1);
    expect(profile.domains.get("Mathematics")?.attempts).toBe(1);
    expect(profile.domains.get("Biology")?.attempts).toBe(1);
  });

  // ── Error propagation ─────────────────────────────────────────────────────

  it("propagates DB errors", async () => {
    mockActivityFindMany.mockRejectedValue(new Error("DB connection lost"));
    await expect(getKnowledgeProfile(1)).rejects.toThrow("DB connection lost");
  });
});