Download src/lib/feynman/__tests__/knowledge-profile.test.ts from NAP1320/RotNot: direct link, hf CLI and curl.
- Browser
- Download file 15.1 kB
-
https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/feynman/__tests__/knowledge-profile.test.ts
- Command line
-
hf download hf://spaces/NAP1320/RotNot/src/lib/feynman/__tests__/knowledge-profile.test.ts
-
curl -L -o knowledge-profile.test.ts https://huggingface.co/spaces/NAP1320/RotNot/resolve/main/src/lib/feynman/__tests__/knowledge-profile.test.ts
15.1 kB
| import { describe, it, expect } from "vitest"; | |
| import { | |
| parseActivityMetadata, | |
| buildDomainProfiles, | |
| recommendDifficulty, | |
| getCalibratedTopics, | |
| type TopicAttempt, | |
| type KnowledgeProfile, | |
| } from "@/lib/feynman/knowledge-profile"; | |
| import { FEYNMAN_TOPICS } from "@/lib/feynman/topics"; | |
| // --------------------------------------------------------------------------- | |
| // parseActivityMetadata | |
| // --------------------------------------------------------------------------- | |
| describe("parseActivityMetadata", () => { | |
| it("parses valid metadata with a known topic", () => { | |
| const result = parseActivityMetadata({ | |
| metadata: JSON.stringify({ | |
| topic: "How a hash table works", | |
| wasTaught: false, | |
| accuracy: 8, | |
| completeness: 7, | |
| clarity: 9, | |
| }), | |
| score: 0.8, | |
| createdAt: new Date("2026-03-20T10:00:00Z"), | |
| }); | |
| expect(result).not.toBeNull(); | |
| expect(result!.topicId).toBe("cs-01"); | |
| expect(result!.domain).toBe("CS"); | |
| expect(result!.difficulty).toBe("beginner"); | |
| expect(result!.score).toBe(0.8); | |
| expect(result!.wasTaught).toBe(false); | |
| }); | |
| it("returns null for null metadata", () => { | |
| expect( | |
| parseActivityMetadata({ | |
| metadata: null, | |
| score: 0.5, | |
| createdAt: new Date(), | |
| }), | |
| ).toBeNull(); | |
| }); | |
| it("returns null for malformed JSON", () => { | |
| expect( | |
| parseActivityMetadata({ | |
| metadata: "not-json", | |
| score: 0.5, | |
| createdAt: new Date(), | |
| }), | |
| ).toBeNull(); | |
| }); | |
| it("returns null for metadata missing topic field", () => { | |
| expect( | |
| parseActivityMetadata({ | |
| metadata: JSON.stringify({ accuracy: 8 }), | |
| score: 0.5, | |
| createdAt: new Date(), | |
| }), | |
| ).toBeNull(); | |
| }); | |
| it("handles wasTaught flag correctly", () => { | |
| const result = parseActivityMetadata({ | |
| metadata: JSON.stringify({ | |
| topic: "Newton's three laws of motion", | |
| wasTaught: true, | |
| }), | |
| score: 0.6, | |
| createdAt: new Date(), | |
| }); | |
| expect(result).not.toBeNull(); | |
| expect(result!.wasTaught).toBe(true); | |
| expect(result!.domain).toBe("Physics"); | |
| }); | |
| it("handles unknown topics with fallback IDs", () => { | |
| const result = parseActivityMetadata({ | |
| metadata: JSON.stringify({ topic: "Quantum entanglement deep dive" }), | |
| score: 0.4, | |
| createdAt: new Date(), | |
| }); | |
| expect(result).not.toBeNull(); | |
| expect(result!.topicId).toContain("unknown-"); | |
| expect(result!.domain).toBe("Unknown"); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // buildDomainProfiles | |
| // --------------------------------------------------------------------------- | |
| describe("buildDomainProfiles", () => { | |
| const mockAttempts: TopicAttempt[] = [ | |
| { | |
| topicId: "cs-01", | |
| topic: "How a hash table works", | |
| domain: "CS", | |
| difficulty: "beginner", | |
| score: 0.8, | |
| wasTaught: false, | |
| attemptedAt: new Date("2026-03-18"), | |
| }, | |
| { | |
| topicId: "cs-02", | |
| topic: "Big O notation and time complexity", | |
| domain: "CS", | |
| difficulty: "beginner", | |
| score: 0.6, | |
| wasTaught: true, | |
| attemptedAt: new Date("2026-03-19"), | |
| }, | |
| { | |
| topicId: "ph-01", | |
| topic: "Newton's three laws of motion", | |
| domain: "Physics", | |
| difficulty: "beginner", | |
| score: 0.9, | |
| wasTaught: false, | |
| attemptedAt: new Date("2026-03-20"), | |
| }, | |
| ]; | |
| it("groups attempts by domain", () => { | |
| const profiles = buildDomainProfiles(mockAttempts); | |
| expect(profiles.size).toBe(2); | |
| expect(profiles.has("CS")).toBe(true); | |
| expect(profiles.has("Physics")).toBe(true); | |
| }); | |
| it("calculates correct attempt counts", () => { | |
| const profiles = buildDomainProfiles(mockAttempts); | |
| expect(profiles.get("CS")!.attempts).toBe(2); | |
| expect(profiles.get("Physics")!.attempts).toBe(1); | |
| }); | |
| it("calculates average scores", () => { | |
| const profiles = buildDomainProfiles(mockAttempts); | |
| expect(profiles.get("CS")!.avgScore).toBe(0.7); // (0.8 + 0.6) / 2 | |
| expect(profiles.get("Physics")!.avgScore).toBe(0.9); | |
| }); | |
| it("tracks taught count", () => { | |
| const profiles = buildDomainProfiles(mockAttempts); | |
| expect(profiles.get("CS")!.taughtCount).toBe(1); | |
| expect(profiles.get("Physics")!.taughtCount).toBe(0); | |
| }); | |
| it("identifies mastered topics (avg score >= 0.7)", () => { | |
| const profiles = buildDomainProfiles(mockAttempts); | |
| expect(profiles.get("CS")!.masteredTopics).toContain("cs-01"); | |
| expect(profiles.get("Physics")!.masteredTopics).toContain("ph-01"); | |
| }); | |
| it("tracks attempted topic IDs", () => { | |
| const profiles = buildDomainProfiles(mockAttempts); | |
| const cs = profiles.get("CS")!; | |
| expect(cs.attemptedTopicIds.has("cs-01")).toBe(true); | |
| expect(cs.attemptedTopicIds.has("cs-02")).toBe(true); | |
| expect(cs.attemptedTopicIds.has("cs-03")).toBe(false); | |
| }); | |
| it("returns empty map for no attempts", () => { | |
| const profiles = buildDomainProfiles([]); | |
| expect(profiles.size).toBe(0); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // recommendDifficulty | |
| // --------------------------------------------------------------------------- | |
| describe("recommendDifficulty", () => { | |
| it("recommends beginner for new users (< 3 attempts)", () => { | |
| expect(recommendDifficulty(0, 0)).toBe("beginner"); | |
| expect(recommendDifficulty(1, 0.9)).toBe("beginner"); | |
| expect(recommendDifficulty(2, 0.8)).toBe("beginner"); | |
| }); | |
| it("recommends intermediate for moderate experience", () => { | |
| expect(recommendDifficulty(5, 0.5)).toBe("intermediate"); | |
| expect(recommendDifficulty(7, 0.6)).toBe("intermediate"); | |
| }); | |
| it("recommends expert for experienced users with strong scores", () => { | |
| expect(recommendDifficulty(10, 0.75)).toBe("expert"); | |
| expect(recommendDifficulty(8, 0.65)).toBe("expert"); | |
| }); | |
| it("stays intermediate for experienced users with low scores", () => { | |
| expect(recommendDifficulty(15, 0.4)).toBe("intermediate"); | |
| }); | |
| }); | |
| // --------------------------------------------------------------------------- | |
| // getCalibratedTopics | |
| // --------------------------------------------------------------------------- | |
| describe("getCalibratedTopics", () => { | |
| function makeProfile(overrides: Partial<KnowledgeProfile> = {}): KnowledgeProfile { | |
| return { | |
| userId: 1, | |
| totalAttempts: 0, | |
| domains: new Map(), | |
| recentTopicIds: [], | |
| recommendedDifficulty: "beginner", | |
| ...overrides, | |
| }; | |
| } | |
| it("returns 3 topics by default", () => { | |
| const topics = getCalibratedTopics(makeProfile()); | |
| expect(topics).toHaveLength(3); | |
| }); | |
| it("returns topics from the topic pool", () => { | |
| const topics = getCalibratedTopics(makeProfile()); | |
| const allIds = new Set(FEYNMAN_TOPICS.map((t) => t.id)); | |
| for (const t of topics) { | |
| expect(allIds.has(t.id)).toBe(true); | |
| } | |
| }); | |
| it("returns unique topics", () => { | |
| const topics = getCalibratedTopics(makeProfile()); | |
| const ids = topics.map((t) => t.id); | |
| expect(new Set(ids).size).toBe(ids.length); | |
| }); | |
| it("avoids recently attempted topics when possible", () => { | |
| // Mark most beginner topics as recent | |
| const recentIds = FEYNMAN_TOPICS.filter((t) => t.difficulty === "beginner") | |
| .slice(0, 8) | |
| .map((t) => t.id); | |
| const profile = makeProfile({ recentTopicIds: recentIds }); | |
| const topics = getCalibratedTopics(profile); | |
| // At least some topics should not be in the recent list | |
| const freshCount = topics.filter((t) => !recentIds.includes(t.id)).length; | |
| expect(freshCount).toBeGreaterThan(0); | |
| }); | |
| it("filters by domain when specified", () => { | |
| const topics = getCalibratedTopics(makeProfile(), "CS"); | |
| for (const t of topics) { | |
| expect(t.domain).toBe("CS"); | |
| } | |
| }); | |
| it("returns empty array for nonexistent domain", () => { | |
| const topics = getCalibratedTopics(makeProfile(), "Nonexistent"); | |
| expect(topics).toHaveLength(0); | |
| }); | |
| it("respects custom count", () => { | |
| const topics = getCalibratedTopics(makeProfile(), undefined, 2); | |
| expect(topics).toHaveLength(2); | |
| }); | |
| it("prefers recommended difficulty level", () => { | |
| // Run 20 times to account for shuffle randomness | |
| let matchCount = 0; | |
| const profile = makeProfile({ recommendedDifficulty: "beginner", totalAttempts: 0 }); | |
| for (let i = 0; i < 20; i++) { | |
| const topics = getCalibratedTopics(profile); | |
| const beginnerCount = topics.filter((t) => t.difficulty === "beginner").length; | |
| if (beginnerCount >= 1) matchCount++; | |
| } | |
| // Should include at least one beginner topic most of the time | |
| expect(matchCount).toBeGreaterThanOrEqual(15); | |
| }); | |
| it("returns all available topics when pool is small", () => { | |
| // Philosophy has 6 topics; asking for 100 | |
| const topics = getCalibratedTopics(makeProfile(), "Philosophy", 100); | |
| const philTopics = FEYNMAN_TOPICS.filter((t) => t.domain === "Philosophy"); | |
| expect(topics).toHaveLength(philTopics.length); | |
| }); | |
| // ------------------------------------------------------------------------- | |
| // Prerequisite-aware selection (readyPool vs lockedPool logic) | |
| // ------------------------------------------------------------------------- | |
| it("always includes topics with no prerequisites (beginners are always ready)", () => { | |
| // With an empty mastered set, topics with no prereqs should be available | |
| const profile = makeProfile({ recommendedDifficulty: "beginner" }); | |
| // Run 20 times to account for shuffling | |
| let hasBeginnerCount = 0; | |
| for (let i = 0; i < 20; i++) { | |
| const topics = getCalibratedTopics(profile); | |
| const hasNoPrerequireds = topics.some((t) => !t.prerequisites?.length); | |
| if (hasNoPrerequireds) hasBeginnerCount++; | |
| } | |
| expect(hasBeginnerCount).toBeGreaterThanOrEqual(18); | |
| }); | |
| it("preferentially returns ready topics when mastered set satisfies prerequisites", () => { | |
| // cs-05 requires cs-02. If we have mastered cs-02, cs-05 should become available. | |
| // cs-09 requires cs-01 AND cs-02 — both mastered here. | |
| const profile = makeProfile({ | |
| recommendedDifficulty: "intermediate", | |
| totalAttempts: 5, | |
| domains: new Map([ | |
| [ | |
| "CS", | |
| { | |
| domain: "CS", | |
| attempts: 5, | |
| avgScore: 0.8, | |
| taughtCount: 0, | |
| masteredTopics: ["cs-01", "cs-02"], | |
| attemptedTopicIds: new Set(["cs-01", "cs-02"]), | |
| }, | |
| ], | |
| ]), | |
| }); | |
| // Run multiple times and assert that cs-05 (or another ready topic) can appear | |
| let readyTopicFound = false; | |
| for (let i = 0; i < 30; i++) { | |
| const topics = getCalibratedTopics(profile, "CS"); | |
| // cs-05 requires cs-02 (mastered) — should be ready | |
| if (topics.some((t) => t.id === "cs-05")) { | |
| readyTopicFound = true; | |
| break; | |
| } | |
| } | |
| expect(readyTopicFound).toBe(true); | |
| }); | |
| it("does not include locked topics when enough ready topics exist", () => { | |
| // For CS domain filtered to beginner, there are several topics with no prereqs. | |
| // With mastered = {} (nothing mastered), only topics with no prereqs are ready. | |
| // cs-03, cs-01, cs-02, cs-04, cs-06, cs-10 are beginner CS topics with no prereqs. | |
| // Asking for 3 should fill entirely from the ready pool. | |
| const profile = makeProfile({ recommendedDifficulty: "beginner" }); | |
| const csTopicsNoPrereqs = FEYNMAN_TOPICS.filter( | |
| (t) => t.domain === "CS" && !t.prerequisites?.length, | |
| ); | |
| // Sanity: should have at least 3 beginner no-prereq CS topics | |
| expect(csTopicsNoPrereqs.length).toBeGreaterThanOrEqual(3); | |
| // Run 20 times; verify returned topics are all from the no-prereq set | |
| let allReadyCount = 0; | |
| for (let i = 0; i < 20; i++) { | |
| const topics = getCalibratedTopics(profile, "CS", 3); | |
| const allReady = topics.every( | |
| (t) => !t.prerequisites?.length || t.prerequisites.length === 0, | |
| ); | |
| if (allReady) allReadyCount++; | |
| } | |
| // Should almost always return ready-only topics when enough exist | |
| expect(allReadyCount).toBeGreaterThanOrEqual(15); | |
| }); | |
| it("may include a locked topic when the ready pool is small (step 5 fallback)", () => { | |
| // cs-08 requires cs-06 (no prereqs itself), so mastering cs-06 is not satisfied here. | |
| // We ask for enough topics that the locked pool must be used. | |
| // In CS domain: mark almost all no-prereq topics as recent to shrink the fresh pool, | |
| // but keep mastered empty so topics with prereqs are locked. | |
| const noPrereqCsIds = FEYNMAN_TOPICS.filter( | |
| (t) => t.domain === "CS" && !t.prerequisites?.length, | |
| ).map((t) => t.id); | |
| const profile = makeProfile({ | |
| recentTopicIds: noPrereqCsIds, // all no-prereq CS topics are recent | |
| recommendedDifficulty: "intermediate", | |
| totalAttempts: 6, | |
| }); | |
| // Requesting 5 topics from CS with no prereqs marked as recent. | |
| // Since fresh pool is small, the fallback paths must draw from locked pool. | |
| let lockedTopicSeen = false; | |
| for (let i = 0; i < 30; i++) { | |
| const topics = getCalibratedTopics(profile, "CS", 5); | |
| if (topics.some((t) => t.prerequisites && t.prerequisites.length > 0)) { | |
| lockedTopicSeen = true; | |
| break; | |
| } | |
| } | |
| expect(lockedTopicSeen).toBe(true); | |
| }); | |
| it("returned topics are always unique even when mixing ready and locked pools", () => { | |
| // Stress test: run 50 iterations, assert no duplicates regardless of path taken | |
| const profile = makeProfile({ recommendedDifficulty: "intermediate", totalAttempts: 4 }); | |
| for (let i = 0; i < 50; i++) { | |
| const topics = getCalibratedTopics(profile, "CS", 4); | |
| const ids = topics.map((t) => t.id); | |
| expect(new Set(ids).size).toBe(ids.length); | |
| } | |
| }); | |
| it("topics with all prerequisites mastered appear before topics with unmet prerequisites", () => { | |
| // ph-04 requires ph-01 + ph-02. We master ph-01 and ph-02, making ph-04 ready. | |
| // ph-07 requires ph-04 (not yet mastered here) — ph-07 remains locked. | |
| const profile = makeProfile({ | |
| recommendedDifficulty: "expert", | |
| totalAttempts: 10, | |
| domains: new Map([ | |
| [ | |
| "Physics", | |
| { | |
| domain: "Physics", | |
| attempts: 10, | |
| avgScore: 0.75, | |
| taughtCount: 0, | |
| masteredTopics: ["ph-01", "ph-02"], | |
| attemptedTopicIds: new Set(["ph-01", "ph-02"]), | |
| }, | |
| ], | |
| ]), | |
| }); | |
| // ph-04 (prereqs: ph-01, ph-02 — both mastered) should be reachable | |
| let ph04Found = false; | |
| // ph-07 (prereq: ph-04 — not mastered) should also be reachable (Step 5 locked path) | |
| // but ph-04 should appear before ph-07 across multiple runs | |
| for (let i = 0; i < 30; i++) { | |
| const topics = getCalibratedTopics(profile, "Physics", 3); | |
| if (topics.some((t) => t.id === "ph-04")) { | |
| ph04Found = true; | |
| break; | |
| } | |
| } | |
| expect(ph04Found).toBe(true); | |
| }); | |
| }); | |