@vue-skuilder/db 0.2.23 → 0.2.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
- "version": "0.2.23",
7
+ "version": "0.2.24",
8
8
  "description": "Database layer for vue-skuilder",
9
9
  "main": "dist/index.js",
10
10
  "module": "dist/index.mjs",
@@ -48,7 +48,7 @@
48
48
  },
49
49
  "dependencies": {
50
50
  "@nilock2/pouchdb-authentication": "^1.0.2",
51
- "@vue-skuilder/common": "0.2.23",
51
+ "@vue-skuilder/common": "0.2.24",
52
52
  "cross-fetch": "^4.1.0",
53
53
  "moment": "^2.29.4",
54
54
  "pouchdb": "^9.0.0",
@@ -63,5 +63,5 @@
63
63
  "vite": "^8.0.0",
64
64
  "vitest": "^4.1.0"
65
65
  },
66
- "stableVersion": "0.2.23"
66
+ "stableVersion": "0.2.24"
67
67
  }
@@ -53,6 +53,16 @@ export interface StudySessionDoc {
53
53
  /** Bootstrap run plus every replan, in execution order. */
54
54
  runs?: StudySessionRunSummary[];
55
55
 
56
+ /**
57
+ * Per-response ELO exchanges, in the order they resolved. One entry per
58
+ * ELO-updating response (first attempt of a presentation; retries don't
59
+ * move ELO). Flushed at close from an in-memory log — so `open`/`abandoned`
60
+ * sessions that never reached the close write carry none, and a same-card
61
+ * event still in flight at close may be missing. Absent on sessions
62
+ * recorded before this shipped.
63
+ */
64
+ eloEvents?: SessionEloEvent[];
65
+
56
66
  finalHints?: ReplanHints | null;
57
67
 
58
68
  stateAtStart?: SessionStateSnapshot;
@@ -96,6 +106,38 @@ export interface StudySessionRunSummary {
96
106
  };
97
107
  }
98
108
 
109
+ /**
110
+ * One learner↔card ELO exchange, captured at the moment it resolved so a
111
+ * session can be read as an ELO ledger (why did 88% accuracy net -1?). The
112
+ * exchange is otherwise write-once-and-discard: only the updated aggregates
113
+ * survive on the user/card docs, and ELO is path-dependent, so a response's
114
+ * move can't be reconstructed after the fact. Joins to a `CardRecord` by
115
+ * `cardId` + nearest `at`.
116
+ */
117
+ export interface SessionEloEvent {
118
+ /** Card this exchange was for. */
119
+ cardId: string;
120
+ /** ISO time the exchange resolved (fires just after the response record). */
121
+ at: string;
122
+ /**
123
+ * Global performance in [0,1] that drove the update. Note this is the ELO
124
+ * `userScore`, not raw correctness: the numeric path maps a correct answer
125
+ * to `0.5 + performance/2` (so a plain correct is 1.0, a graded-correct
126
+ * less) and a miss to 0; the tagged path uses `_global`.
127
+ */
128
+ userScore: number;
129
+ /** Learner global ELO before → after this response. */
130
+ global: { before: number; after: number };
131
+ /** Card global ELO before → after (absent if the card ELO was unreadable). */
132
+ card?: { before: number; after: number };
133
+ /**
134
+ * Per-tag learner ELO before → after, for every tag the exchange touched.
135
+ * `score` is the per-tag performance applied, or null for a count-only
136
+ * exposure tag (`gpc:expose:*`) that increments count without moving ELO.
137
+ */
138
+ tags?: Record<string, { before: number; after: number; score: number | null }>;
139
+ }
140
+
99
141
  /**
100
142
  * Host-defined learner state at a session boundary. Keep it thin — this is
101
143
  * written on every session, and the deltas between consecutive snapshots are
@@ -17,6 +17,7 @@ import { DocType } from '@db/core/types/types-legacy';
17
17
  import {
18
18
  makeStudySessionId,
19
19
  newSessionId,
20
+ type SessionEloEvent,
20
21
  type SessionStateSnapshot,
21
22
  type SessionStateSnapshotProvider,
22
23
  type StudySessionDoc,
@@ -381,6 +382,14 @@ export class SessionController<TView = unknown> extends Loggable {
381
382
  private _runLog: StudySessionRunSummary[] = [];
382
383
  private static readonly MAX_LOGGED_RUNS = 100;
383
384
 
385
+ /**
386
+ * Per-response ELO exchanges as they resolve (see `SessionEloEvent`). Fed by
387
+ * the ResponseProcessor's `onEloEvent` sink; flushed to the session doc at
388
+ * close. Bounded so a runaway session can't grow it without limit.
389
+ */
390
+ private _eloLog: SessionEloEvent[] = [];
391
+ private static readonly MAX_LOGGED_ELO_EVENTS = 2000;
392
+
384
393
  /** Guards `endSession()` against the several termination paths racing it. */
385
394
  private _sessionClosed: boolean = false;
386
395
 
@@ -447,7 +456,9 @@ export class SessionController<TView = unknown> extends Loggable {
447
456
  );
448
457
 
449
458
  this.services = {
450
- response: new ResponseProcessor(this.srsService, this.eloService),
459
+ response: new ResponseProcessor(this.srsService, this.eloService, (event) =>
460
+ this._recordEloEvent(event)
461
+ ),
451
462
  };
452
463
 
453
464
  this.sources = sources;
@@ -954,6 +965,17 @@ export class SessionController<TView = unknown> extends Loggable {
954
965
  * skipped, never wedging the session. Keep observers cheap and `void` any
955
966
  * long work (e.g. a triggered replan) to avoid stalling the draw.
956
967
  */
968
+ /**
969
+ * Append a resolved ELO exchange to the in-memory log. Fires async (the ELO
970
+ * update is non-blocking), so an event can land after the response that
971
+ * produced it has returned — but well before close, which is when the log is
972
+ * persisted. Bounded to avoid unbounded growth.
973
+ */
974
+ private _recordEloEvent(event: SessionEloEvent): void {
975
+ if (this._eloLog.length >= SessionController.MAX_LOGGED_ELO_EVENTS) return;
976
+ this._eloLog.push(event);
977
+ }
978
+
957
979
  private async _notifyOutcomeObservers(
958
980
  record: CardRecord,
959
981
  currentCard: StudySessionRecord,
@@ -1969,6 +1991,7 @@ export class SessionController<TView = unknown> extends Loggable {
1969
1991
  secondsRemaining: Math.max(0, this._secondsRemaining),
1970
1992
  },
1971
1993
  runs: [...this._runLog],
1994
+ eloEvents: [...this._eloLog],
1972
1995
  finalHints: this._sessionHints,
1973
1996
  stateAtEnd: await this._captureState('end'),
1974
1997
  };
@@ -4,7 +4,12 @@ import {
4
4
  toCourseElo,
5
5
  TaggedPerformance,
6
6
  } from '@vue-skuilder/common';
7
- import { DataLayerProvider, UserDBInterface, CourseRegistrationDoc } from '@db/core';
7
+ import {
8
+ DataLayerProvider,
9
+ UserDBInterface,
10
+ CourseRegistrationDoc,
11
+ SessionEloEvent,
12
+ } from '@db/core';
8
13
  import { StudySessionRecord } from '../SessionController';
9
14
  import { logger } from '@db/util/logger';
10
15
 
@@ -28,6 +33,8 @@ export class EloService {
28
33
  * @param userCourseRegDoc User's course registration document (will be mutated)
29
34
  * @param currentCard Current card session record
30
35
  * @param k Optional K-factor for ELO calculation
36
+ * @returns The captured before→after exchange for session logging, or null
37
+ * if no update was applied (missing registration / unreadable ELO).
31
38
  */
32
39
  public async updateUserAndCardElo(
33
40
  userScore: number,
@@ -36,7 +43,7 @@ export class EloService {
36
43
  userCourseRegDoc: CourseRegistrationDoc,
37
44
  currentCard: StudySessionRecord,
38
45
  k?: number
39
- ): Promise<void> {
46
+ ): Promise<SessionEloEvent | null> {
40
47
  if (k) {
41
48
  logger.warn(`k value interpretation not currently implemented`);
42
49
  }
@@ -47,15 +54,43 @@ export class EloService {
47
54
  `[EloService] No registration for course ${course_id} on user's registration doc — ` +
48
55
  `skipping ELO update for card ${card_id}. (Is the user registered for this course?)`
49
56
  );
50
- return;
57
+ return null;
51
58
  }
52
59
  const userElo = toCourseElo(courseReg.elo);
53
60
  const cardElo = (await courseDB.getCardEloData([currentCard.card.card_id]))[0];
54
61
 
55
62
  if (cardElo && userElo) {
63
+ // Capture before-scores as numbers up front: adjustCourseScores mutates
64
+ // userElo/cardElo in place (and returns the same refs). This path grades
65
+ // every tag already present on the card with the single global score.
66
+ const beforeUserGlobal = userElo.global.score;
67
+ const beforeCardGlobal = cardElo.global.score;
68
+ const cardTagKeys = Object.keys(cardElo.tags);
69
+ const beforeUserTag: Record<string, number> = {};
70
+ for (const tag of cardTagKeys) {
71
+ beforeUserTag[tag] = userElo.tags[tag]?.score ?? userElo.global.score;
72
+ }
73
+
56
74
  const eloUpdate = adjustCourseScores(userElo, cardElo, userScore);
57
75
  courseReg.elo = eloUpdate.userElo;
58
76
 
77
+ const tags: NonNullable<SessionEloEvent['tags']> = {};
78
+ for (const tag of cardTagKeys) {
79
+ tags[tag] = {
80
+ before: beforeUserTag[tag],
81
+ after: eloUpdate.userElo.tags[tag].score,
82
+ score: userScore,
83
+ };
84
+ }
85
+ const event: SessionEloEvent = {
86
+ cardId: card_id,
87
+ at: new Date().toISOString(),
88
+ userScore,
89
+ global: { before: beforeUserGlobal, after: eloUpdate.userElo.global.score },
90
+ card: { before: beforeCardGlobal, after: eloUpdate.cardElo.global.score },
91
+ ...(cardTagKeys.length ? { tags } : {}),
92
+ };
93
+
59
94
  const results = await Promise.allSettled([
60
95
  this.user.updateUserElo(course_id, eloUpdate.userElo),
61
96
  courseDB.updateCardElo(card_id, eloUpdate.cardElo),
@@ -93,7 +128,11 @@ export class EloService {
93
128
  logger.error('[EloService] Card ELO update error:', results[1].reason);
94
129
  }
95
130
  }
131
+
132
+ return event;
96
133
  }
134
+
135
+ return null;
97
136
  }
98
137
 
99
138
  /**
@@ -112,7 +151,7 @@ export class EloService {
112
151
  card_id: string,
113
152
  userCourseRegDoc: CourseRegistrationDoc,
114
153
  currentCard: StudySessionRecord
115
- ): Promise<void> {
154
+ ): Promise<SessionEloEvent | null> {
116
155
  const courseDB = this.dataLayer.getCourseDB(currentCard.card.course_id);
117
156
  const courseReg = userCourseRegDoc.courses.find((c) => c.courseID === course_id);
118
157
  if (!courseReg) {
@@ -120,7 +159,7 @@ export class EloService {
120
159
  `[EloService] No registration for course ${course_id} on user's registration doc — ` +
121
160
  `skipping per-tag ELO update for card ${card_id}. (Is the user registered for this course?)`
122
161
  );
123
- return;
162
+ return null;
124
163
  }
125
164
  const userElo = toCourseElo(courseReg.elo);
126
165
 
@@ -145,9 +184,39 @@ export class EloService {
145
184
  }
146
185
 
147
186
  if (cardElo && userElo) {
187
+ // Capture before-scores up front — adjustCourseScoresPerTag mutates the
188
+ // ELO objects in place. Every tag in `enriched` (except _global) is
189
+ // touched; count-only tags (null score) increment count without moving
190
+ // ELO and are recorded with score: null.
191
+ const beforeUserGlobal = userElo.global.score;
192
+ const beforeCardGlobal = cardElo.global.score;
193
+ const touchedTags = Object.keys(enriched).filter((key) => key !== '_global');
194
+ const beforeUserTag: Record<string, number> = {};
195
+ for (const tag of touchedTags) {
196
+ beforeUserTag[tag] = userElo.tags[tag]?.score ?? userElo.global.score;
197
+ }
198
+
148
199
  const eloUpdate = adjustCourseScoresPerTag(userElo, cardElo, enriched);
149
200
  courseReg.elo = eloUpdate.userElo;
150
201
 
202
+ const tags: NonNullable<SessionEloEvent['tags']> = {};
203
+ for (const tag of touchedTags) {
204
+ const score = enriched[tag];
205
+ // Count-only exposure tags (null score) get a -1 sentinel score, not a
206
+ // real ELO move — record before===after so a naive after-before reads 0.
207
+ const after =
208
+ score === null ? beforeUserTag[tag] : eloUpdate.userElo.tags[tag]?.score ?? beforeUserTag[tag];
209
+ tags[tag] = { before: beforeUserTag[tag], after, score };
210
+ }
211
+ const event: SessionEloEvent = {
212
+ cardId: card_id,
213
+ at: new Date().toISOString(),
214
+ userScore: globalScore,
215
+ global: { before: beforeUserGlobal, after: eloUpdate.userElo.global.score },
216
+ card: { before: beforeCardGlobal, after: eloUpdate.cardElo.global.score },
217
+ ...(touchedTags.length ? { tags } : {}),
218
+ };
219
+
151
220
  const results = await Promise.allSettled([
152
221
  this.user.updateUserElo(course_id, eloUpdate.userElo),
153
222
  courseDB.updateCardElo(card_id, eloUpdate.cardElo),
@@ -186,6 +255,10 @@ export class EloService {
186
255
  logger.error('[EloService] Card ELO update error:', results[1].reason);
187
256
  }
188
257
  }
258
+
259
+ return event;
189
260
  }
261
+
262
+ return null;
190
263
  }
191
264
  }
@@ -4,6 +4,7 @@ import {
4
4
  CourseRegistrationDoc,
5
5
  isQuestionRecord,
6
6
  QuestionRecord,
7
+ SessionEloEvent,
7
8
  StudySessionItem,
8
9
  } from '@db/core';
9
10
  import { logger } from '@db/util/logger';
@@ -29,10 +30,17 @@ interface ParsedPerformance {
29
30
  export class ResponseProcessor {
30
31
  private srsService: SrsService;
31
32
  private eloService: EloService;
33
+ /** Sink for resolved ELO exchanges, wired to the session's in-memory log. */
34
+ private onEloEvent?: (event: SessionEloEvent) => void;
32
35
 
33
- constructor(srsService: SrsService, eloService: EloService) {
36
+ constructor(
37
+ srsService: SrsService,
38
+ eloService: EloService,
39
+ onEloEvent?: (event: SessionEloEvent) => void
40
+ ) {
34
41
  this.srsService = srsService;
35
42
  this.eloService = eloService;
43
+ this.onEloEvent = onEloEvent;
36
44
  }
37
45
 
38
46
  /**
@@ -45,6 +53,24 @@ export class ResponseProcessor {
45
53
  logger.error(`[ResponseProcessor] ELO update failed (${context}) for ${cardId}:`, e);
46
54
  }
47
55
 
56
+ /**
57
+ * Fire an ELO update without blocking response handling, forwarding the
58
+ * resolved exchange to the session log (if any) and surfacing failures.
59
+ * Mirrors the previous `void update(...).catch(logEloFailure)` shape, with
60
+ * the added `.then` capturing the before→after event for diagnostics.
61
+ */
62
+ private trackElo(
63
+ update: Promise<SessionEloEvent | null>,
64
+ context: string,
65
+ cardId: string
66
+ ): void {
67
+ void update
68
+ .then((event) => {
69
+ if (event) this.onEloEvent?.(event);
70
+ })
71
+ .catch(this.logEloFailure(context, cardId));
72
+ }
73
+
48
74
  /**
49
75
  * Parses performance data into global score and optional per-tag scores.
50
76
  *
@@ -208,37 +234,49 @@ export class ResponseProcessor {
208
234
  `scored=[${scoredTags.join(', ')}] count-only=[${nullTags.join(', ')}]`
209
235
  );
210
236
 
211
- void this.eloService
212
- .updateUserAndCardEloPerTag(
237
+ this.trackElo(
238
+ this.eloService.updateUserAndCardEloPerTag(
213
239
  taggedPerformance,
214
240
  courseId,
215
241
  cardId,
216
242
  courseRegistrationDoc,
217
243
  currentCard
218
- )
219
- .catch(this.logEloFailure('correct per-tag', cardId));
244
+ ),
245
+ 'correct per-tag',
246
+ cardId
247
+ );
220
248
  } else {
221
249
  // Standard single-score ELO update (backward compatible)
222
250
  const userScore = 0.5 + globalScore / 2;
223
251
 
224
252
  if (history.records.length === 1) {
225
253
  // First interaction with this card - standard ELO update
226
- void this.eloService
227
- .updateUserAndCardElo(userScore, courseId, cardId, courseRegistrationDoc, currentCard)
228
- .catch(this.logEloFailure('correct', cardId));
254
+ this.trackElo(
255
+ this.eloService.updateUserAndCardElo(
256
+ userScore,
257
+ courseId,
258
+ cardId,
259
+ courseRegistrationDoc,
260
+ currentCard
261
+ ),
262
+ 'correct',
263
+ cardId
264
+ );
229
265
  } else {
230
266
  // Multiple interactions - reduce K-factor to limit ELO volatility
231
267
  const k = Math.ceil(32 / history.records.length);
232
- void this.eloService
233
- .updateUserAndCardElo(
268
+ this.trackElo(
269
+ this.eloService.updateUserAndCardElo(
234
270
  userScore,
235
271
  courseId,
236
272
  cardId,
237
273
  courseRegistrationDoc,
238
274
  currentCard,
239
275
  k
240
- )
241
- .catch(this.logEloFailure('correct repeat-view', cardId));
276
+ ),
277
+ 'correct repeat-view',
278
+ cardId
279
+ );
242
280
  }
243
281
  logger.info(
244
282
  `[FirstContactElo] correct first-attempt ELO update (score=${userScore.toFixed(3)}) ` +
@@ -324,15 +362,17 @@ export class ResponseProcessor {
324
362
  if (cardRecord.priorAttemps === 0) {
325
363
  if (taggedPerformance) {
326
364
  // Per-tag ELO update for incorrect response
327
- void this.eloService
328
- .updateUserAndCardEloPerTag(
365
+ this.trackElo(
366
+ this.eloService.updateUserAndCardEloPerTag(
329
367
  taggedPerformance,
330
368
  courseId,
331
369
  cardId,
332
370
  courseRegistrationDoc,
333
371
  currentCard
334
- )
335
- .catch(this.logEloFailure('incorrect per-tag', cardId));
372
+ ),
373
+ 'incorrect per-tag',
374
+ cardId
375
+ );
336
376
  logger.info(
337
377
  `[FirstContactElo] incorrect first-attempt per-tag ELO update for ${cardId} ` +
338
378
  `(historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps}, ` +
@@ -340,15 +380,17 @@ export class ResponseProcessor {
340
380
  );
341
381
  } else {
342
382
  // Standard single-score ELO update
343
- void this.eloService
344
- .updateUserAndCardElo(
383
+ this.trackElo(
384
+ this.eloService.updateUserAndCardElo(
345
385
  0, // Failed response = 0 score
346
386
  courseId,
347
387
  cardId,
348
388
  courseRegistrationDoc,
349
389
  currentCard
350
- )
351
- .catch(this.logEloFailure('incorrect', cardId));
390
+ ),
391
+ 'incorrect',
392
+ cardId
393
+ );
352
394
  logger.info(
353
395
  `[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${cardId} ` +
354
396
  `(historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps})`
@@ -371,19 +413,29 @@ export class ResponseProcessor {
371
413
  if (!eloUpdated) {
372
414
  if (taggedPerformance) {
373
415
  // Use tagged performance for final failure
374
- void this.eloService
375
- .updateUserAndCardEloPerTag(
416
+ this.trackElo(
417
+ this.eloService.updateUserAndCardEloPerTag(
376
418
  taggedPerformance,
377
419
  courseId,
378
420
  cardId,
379
421
  courseRegistrationDoc,
380
422
  currentCard
381
- )
382
- .catch(this.logEloFailure('dismiss-failed per-tag', cardId));
423
+ ),
424
+ 'dismiss-failed per-tag',
425
+ cardId
426
+ );
383
427
  } else {
384
- void this.eloService
385
- .updateUserAndCardElo(0, courseId, cardId, courseRegistrationDoc, currentCard)
386
- .catch(this.logEloFailure('dismiss-failed', cardId));
428
+ this.trackElo(
429
+ this.eloService.updateUserAndCardElo(
430
+ 0,
431
+ courseId,
432
+ cardId,
433
+ courseRegistrationDoc,
434
+ currentCard
435
+ ),
436
+ 'dismiss-failed',
437
+ cardId
438
+ );
387
439
  }
388
440
  logger.info(
389
441
  `[FirstContactElo] dismiss-failed final ELO penalty for ${cardId} ` +