File size: 8,005 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
import { describe, it, expect, beforeEach, vi } from "vitest";
import {
  buildCacheKey,
  isRateLimited,
  recordRequest,
  getCachedFeedback,
  cacheFeedback,
  buildPrompt,
} from "../coach-feedback";
import { getRecommendedSettings } from "../difficulty";
import type { PerformanceSummary } from "../performance";

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

function makeSummary(
  overrides: Partial<PerformanceSummary> = {},
): PerformanceSummary {
  return {
    categories: [
      {
        category: "chess",
        label: "Chess",
        successRate: 65,
        attempts: 12,
        avgScore: 0.65,
        avgDurationSecs: null,
        totalXp: 300,
        level: 3,
        trend: "improving",
      },
      {
        category: "reading",
        label: "Deep Reading",
        successRate: 40,
        attempts: 5,
        avgScore: 0.4,
        avgDurationSecs: 120,
        totalXp: 100,
        level: 2,
        trend: "stable",
      },
      {
        category: "feynman",
        label: "Feynman",
        successRate: 0,
        attempts: 0,
        avgScore: 0,
        avgDurationSecs: null,
        totalXp: 0,
        level: 1,
        trend: "new",
      },
      {
        category: "logic",
        label: "Logic Puzzles",
        successRate: 80,
        attempts: 20,
        avgScore: 0.8,
        avgDurationSecs: 60,
        totalXp: 500,
        level: 5,
        trend: "stable",
      },
      {
        category: "critical-thinking",
        label: "Critical Thinking",
        successRate: 50,
        attempts: 8,
        avgScore: 0.5,
        avgDurationSecs: 90,
        totalXp: 200,
        level: 2,
        trend: "declining",
      },
      {
        category: "quests",
        label: "Skill Quests",
        successRate: 70,
        attempts: 10,
        avgScore: 0.7,
        avgDurationSecs: null,
        totalXp: 250,
        level: 3,
        trend: "improving",
      },
    ],
    overallScore: 55,
    streakDays: 3,
    longestStreak: 7,
    totalExercises: 55,
    activeDays: 10,
    lastActivityAt: "2026-03-20T01:00:00.000Z",
    ...overrides,
  };
}

// ---------------------------------------------------------------------------
// buildCacheKey
// ---------------------------------------------------------------------------

describe("buildCacheKey", () => {
  it("returns a hex string of 16 characters", () => {
    const key = buildCacheKey(1, makeSummary());
    expect(key).toMatch(/^[0-9a-f]{16}$/);
  });

  it("returns the same key for identical inputs", () => {
    const summary = makeSummary();
    const a = buildCacheKey(1, summary);
    const b = buildCacheKey(1, summary);
    expect(a).toBe(b);
  });

  it("returns different keys for different users", () => {
    const summary = makeSummary();
    const a = buildCacheKey(1, summary);
    const b = buildCacheKey(2, summary);
    expect(a).not.toBe(b);
  });

  it("returns the same key for small success rate changes within rounding", () => {
    const s1 = makeSummary();
    const s2 = makeSummary();
    // Modify chess success rate within the ±2.5% rounding window
    s1.categories[0] = { ...s1.categories[0], successRate: 63 };
    s2.categories[0] = { ...s2.categories[0], successRate: 64 };
    expect(buildCacheKey(1, s1)).toBe(buildCacheKey(1, s2));
  });

  it("returns a different key when success rate crosses rounding boundary", () => {
    const s1 = makeSummary();
    const s2 = makeSummary();
    s1.categories[0] = { ...s1.categories[0], successRate: 62 };
    s2.categories[0] = { ...s2.categories[0], successRate: 68 };
    expect(buildCacheKey(1, s1)).not.toBe(buildCacheKey(1, s2));
  });
});

// ---------------------------------------------------------------------------
// Rate limiting
// ---------------------------------------------------------------------------

describe("isRateLimited / recordRequest", () => {
  // Reset rate limit state between tests by recording to a unique user ID
  let testUserId: number;

  beforeEach(() => {
    // Use a unique user ID per test to avoid cross-test interference
    testUserId = Math.floor(Math.random() * 1_000_000) + 1000;
  });

  it("allows requests below the limit", () => {
    expect(isRateLimited(testUserId)).toBe(false);
  });

  it("blocks after 10 requests in an hour", () => {
    for (let i = 0; i < 10; i++) {
      recordRequest(testUserId);
    }
    expect(isRateLimited(testUserId)).toBe(true);
  });

  it("allows 9 requests without blocking", () => {
    for (let i = 0; i < 9; i++) {
      recordRequest(testUserId);
    }
    expect(isRateLimited(testUserId)).toBe(false);
  });
});

// ---------------------------------------------------------------------------
// Cache operations
// ---------------------------------------------------------------------------

describe("getCachedFeedback / cacheFeedback", () => {
  const testFeedback = {
    feedback: "You're doing great at chess but need more reading practice.",
    recommendedExercise: {
      category: "reading" as const,
      difficulty: "medium",
    },
    encouragement: "Your 3-day streak shows real commitment!",
  };

  it("returns null for non-existent key", () => {
    expect(getCachedFeedback("nonexistent-key-xyz")).toBeNull();
  });

  it("returns cached feedback when it exists", () => {
    const key = "test-cache-key-" + Date.now();
    cacheFeedback(key, testFeedback);
    const result = getCachedFeedback(key);
    expect(result).toEqual(testFeedback);
  });

  it("returns null for expired cache entries", () => {
    const key = "test-expired-key-" + Date.now();
    cacheFeedback(key, testFeedback);

    // Manually expire by advancing time
    vi.useFakeTimers();
    vi.advanceTimersByTime(3 * 60 * 60 * 1000 + 1); // 3h + 1ms
    const result = getCachedFeedback(key);
    expect(result).toBeNull();
    vi.useRealTimers();
  });
});

// ---------------------------------------------------------------------------
// buildPrompt
// ---------------------------------------------------------------------------

describe("buildPrompt", () => {
  it("includes category data in the prompt", () => {
    const summary = makeSummary();
    const recommendations = getRecommendedSettings(summary);
    const prompt = buildPrompt(summary, recommendations);

    expect(prompt).toContain("Chess");
    expect(prompt).toContain("65%");
    expect(prompt).toContain("improving");
    expect(prompt).toContain("Active Coach");
  });

  it("includes streak and overall data", () => {
    const summary = makeSummary();
    const recommendations = getRecommendedSettings(summary);
    const prompt = buildPrompt(summary, recommendations);

    expect(prompt).toContain("Streak: 3 days");
    expect(prompt).toContain("longest: 7");
    expect(prompt).toContain("Total exercises completed: 55");
  });

  it("mentions unexplored categories", () => {
    const summary = makeSummary();
    const recommendations = getRecommendedSettings(summary);
    const prompt = buildPrompt(summary, recommendations);

    expect(prompt).toContain("Unexplored categories");
    expect(prompt).toContain("Feynman");
  });

  it("handles a user with no exercises", () => {
    const summary = makeSummary({
      categories: makeSummary().categories.map((c) => ({
        ...c,
        attempts: 0,
        successRate: 0,
      })),
      totalExercises: 0,
      overallScore: 0,
    });
    const recommendations = getRecommendedSettings(summary);
    const prompt = buildPrompt(summary, recommendations);

    expect(prompt).toContain("No exercises completed yet.");
  });

  it("requests JSON-only output", () => {
    const summary = makeSummary();
    const recommendations = getRecommendedSettings(summary);
    const prompt = buildPrompt(summary, recommendations);

    expect(prompt).toContain("ONLY in valid JSON");
    expect(prompt).toContain("no markdown");
  });
});