@vue-skuilder/db 0.2.23 → 0.2.25
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/dist/{contentSource-DT9NaX69.d.cts → contentSource-CrRnbjBx.d.cts} +63 -2
- package/dist/{contentSource-BvOpKUeU.d.ts → contentSource-kD35o65m.d.ts} +63 -2
- package/dist/core/index.d.cts +3 -3
- package/dist/core/index.d.ts +3 -3
- package/dist/core/index.js +2474 -481
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.mjs +2464 -466
- package/dist/core/index.mjs.map +1 -1
- package/dist/{dataLayerProvider-CY2B2lyW.d.ts → dataLayerProvider-CtzddVdy.d.ts} +1 -1
- package/dist/{dataLayerProvider-wY6s_4x9.d.cts → dataLayerProvider-IecbidDO.d.cts} +1 -1
- package/dist/impl/couch/index.d.cts +2 -2
- package/dist/impl/couch/index.d.ts +2 -2
- package/dist/impl/couch/index.js +2237 -238
- package/dist/impl/couch/index.js.map +1 -1
- package/dist/impl/couch/index.mjs +2231 -227
- package/dist/impl/couch/index.mjs.map +1 -1
- package/dist/impl/static/index.d.cts +2 -2
- package/dist/impl/static/index.d.ts +2 -2
- package/dist/impl/static/index.js +2319 -320
- package/dist/impl/static/index.js.map +1 -1
- package/dist/impl/static/index.mjs +2309 -305
- package/dist/impl/static/index.mjs.map +1 -1
- package/dist/index.d.cts +32 -7
- package/dist/index.d.ts +32 -7
- package/dist/index.js +8194 -7868
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +8059 -7734
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
- package/src/core/types/studySession.ts +42 -0
- package/src/impl/common/BaseUserDB.ts +13 -4
- package/src/study/SessionController.ts +24 -1
- package/src/study/SpacedRepetition.ts +11 -2
- package/src/study/services/EloService.ts +97 -5
- package/src/study/services/ResponseProcessor.ts +79 -27
- package/src/study/services/tagRecent.test.ts +101 -0
- package/src/study/services/tagRecent.ts +70 -0
package/package.json
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public"
|
|
6
6
|
},
|
|
7
|
-
"version": "0.2.
|
|
7
|
+
"version": "0.2.25",
|
|
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.
|
|
51
|
+
"@vue-skuilder/common": "0.2.25",
|
|
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.
|
|
66
|
+
"stableVersion": "0.2.25"
|
|
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
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
type HydrationMarker,
|
|
8
8
|
type UserHydrationStatus,
|
|
9
9
|
} from '@db/core';
|
|
10
|
-
import { getCardHistoryID } from '@db/core/util';
|
|
10
|
+
import { areQuestionRecords, getCardHistoryID } from '@db/core/util';
|
|
11
11
|
import { CourseElo, Status } from '@vue-skuilder/common';
|
|
12
12
|
import moment, { Moment } from 'moment';
|
|
13
13
|
import { GuestUsername } from '../../core/types/types-legacy';
|
|
@@ -26,7 +26,7 @@ import {
|
|
|
26
26
|
ScheduledCard,
|
|
27
27
|
UserConfig,
|
|
28
28
|
} from '@db/core/types/user';
|
|
29
|
-
import { DocumentUpdater } from '@db/study';
|
|
29
|
+
import { DocumentUpdater, getLapses, getStreak } from '@db/study';
|
|
30
30
|
import { CardHistory, CardRecord } from '../../core/types/types-legacy';
|
|
31
31
|
import { UserOutcomeRecord } from '../../core/types/userOutcome';
|
|
32
32
|
import { StudySessionDoc } from '../../core/types/studySession';
|
|
@@ -1018,8 +1018,17 @@ Currently logged-in as ${this._username}.`
|
|
|
1018
1018
|
function (h: CardHistory<T>) {
|
|
1019
1019
|
h.records.push(record);
|
|
1020
1020
|
h.bestInterval = h.bestInterval || 0;
|
|
1021
|
-
|
|
1022
|
-
|
|
1021
|
+
// Scheduling (SpacedRepetition.newQuestionInterval) re-derives
|
|
1022
|
+
// lapses/streak from `records` on every call, so these persisted
|
|
1023
|
+
// fields are informational — kept current so the stored doc reads
|
|
1024
|
+
// truthfully when inspected outside a session.
|
|
1025
|
+
if (areQuestionRecords(h)) {
|
|
1026
|
+
h.lapses = getLapses(h.records);
|
|
1027
|
+
h.streak = getStreak(h.records);
|
|
1028
|
+
} else {
|
|
1029
|
+
h.lapses = h.lapses || 0;
|
|
1030
|
+
h.streak = h.streak || 0;
|
|
1031
|
+
}
|
|
1023
1032
|
return h;
|
|
1024
1033
|
}
|
|
1025
1034
|
);
|
|
@@ -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
|
};
|
|
@@ -92,7 +92,12 @@ function lastSuccessfulInterval(cardHistory: QuestionRecord[]): number {
|
|
|
92
92
|
return getInitialInterval(cardHistory); // used as a magic number here - indicates no prior intervals
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
-
|
|
95
|
+
/**
|
|
96
|
+
* Number of trailing consecutive correct records (retries within a single
|
|
97
|
+
* presentation count as separate records). Exported so the persisted
|
|
98
|
+
* `CardHistory.streak` can be kept in step with this derivation.
|
|
99
|
+
*/
|
|
100
|
+
export function getStreak(records: QuestionRecord[]): number {
|
|
96
101
|
let streak = 0;
|
|
97
102
|
let index = records.length - 1;
|
|
98
103
|
|
|
@@ -103,7 +108,11 @@ function getStreak(records: QuestionRecord[]): number {
|
|
|
103
108
|
|
|
104
109
|
return streak;
|
|
105
110
|
}
|
|
106
|
-
|
|
111
|
+
/**
|
|
112
|
+
* Total number of incorrect records on the card. Exported so the persisted
|
|
113
|
+
* `CardHistory.lapses` can be kept in step with this derivation.
|
|
114
|
+
*/
|
|
115
|
+
export function getLapses(records: QuestionRecord[]): number {
|
|
107
116
|
return records.filter((r) => r.isCorrect === false).length;
|
|
108
117
|
}
|
|
109
118
|
|
|
@@ -4,9 +4,15 @@ import {
|
|
|
4
4
|
toCourseElo,
|
|
5
5
|
TaggedPerformance,
|
|
6
6
|
} from '@vue-skuilder/common';
|
|
7
|
-
import {
|
|
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';
|
|
15
|
+
import { recordTagPresentations } from './tagRecent';
|
|
10
16
|
|
|
11
17
|
/**
|
|
12
18
|
* Service responsible for ELO rating calculations and updates.
|
|
@@ -28,6 +34,8 @@ export class EloService {
|
|
|
28
34
|
* @param userCourseRegDoc User's course registration document (will be mutated)
|
|
29
35
|
* @param currentCard Current card session record
|
|
30
36
|
* @param k Optional K-factor for ELO calculation
|
|
37
|
+
* @returns The captured before→after exchange for session logging, or null
|
|
38
|
+
* if no update was applied (missing registration / unreadable ELO).
|
|
31
39
|
*/
|
|
32
40
|
public async updateUserAndCardElo(
|
|
33
41
|
userScore: number,
|
|
@@ -36,7 +44,7 @@ export class EloService {
|
|
|
36
44
|
userCourseRegDoc: CourseRegistrationDoc,
|
|
37
45
|
currentCard: StudySessionRecord,
|
|
38
46
|
k?: number
|
|
39
|
-
): Promise<
|
|
47
|
+
): Promise<SessionEloEvent | null> {
|
|
40
48
|
if (k) {
|
|
41
49
|
logger.warn(`k value interpretation not currently implemented`);
|
|
42
50
|
}
|
|
@@ -47,15 +55,43 @@ export class EloService {
|
|
|
47
55
|
`[EloService] No registration for course ${course_id} on user's registration doc — ` +
|
|
48
56
|
`skipping ELO update for card ${card_id}. (Is the user registered for this course?)`
|
|
49
57
|
);
|
|
50
|
-
return;
|
|
58
|
+
return null;
|
|
51
59
|
}
|
|
52
60
|
const userElo = toCourseElo(courseReg.elo);
|
|
53
61
|
const cardElo = (await courseDB.getCardEloData([currentCard.card.card_id]))[0];
|
|
54
62
|
|
|
55
63
|
if (cardElo && userElo) {
|
|
64
|
+
// Capture before-scores as numbers up front: adjustCourseScores mutates
|
|
65
|
+
// userElo/cardElo in place (and returns the same refs). This path grades
|
|
66
|
+
// every tag already present on the card with the single global score.
|
|
67
|
+
const beforeUserGlobal = userElo.global.score;
|
|
68
|
+
const beforeCardGlobal = cardElo.global.score;
|
|
69
|
+
const cardTagKeys = Object.keys(cardElo.tags);
|
|
70
|
+
const beforeUserTag: Record<string, number> = {};
|
|
71
|
+
for (const tag of cardTagKeys) {
|
|
72
|
+
beforeUserTag[tag] = userElo.tags[tag]?.score ?? userElo.global.score;
|
|
73
|
+
}
|
|
74
|
+
|
|
56
75
|
const eloUpdate = adjustCourseScores(userElo, cardElo, userScore);
|
|
57
76
|
courseReg.elo = eloUpdate.userElo;
|
|
58
77
|
|
|
78
|
+
const tags: NonNullable<SessionEloEvent['tags']> = {};
|
|
79
|
+
for (const tag of cardTagKeys) {
|
|
80
|
+
tags[tag] = {
|
|
81
|
+
before: beforeUserTag[tag],
|
|
82
|
+
after: eloUpdate.userElo.tags[tag].score,
|
|
83
|
+
score: userScore,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
const event: SessionEloEvent = {
|
|
87
|
+
cardId: card_id,
|
|
88
|
+
at: new Date().toISOString(),
|
|
89
|
+
userScore,
|
|
90
|
+
global: { before: beforeUserGlobal, after: eloUpdate.userElo.global.score },
|
|
91
|
+
card: { before: beforeCardGlobal, after: eloUpdate.cardElo.global.score },
|
|
92
|
+
...(cardTagKeys.length ? { tags } : {}),
|
|
93
|
+
};
|
|
94
|
+
|
|
59
95
|
const results = await Promise.allSettled([
|
|
60
96
|
this.user.updateUserElo(course_id, eloUpdate.userElo),
|
|
61
97
|
courseDB.updateCardElo(card_id, eloUpdate.cardElo),
|
|
@@ -93,7 +129,11 @@ export class EloService {
|
|
|
93
129
|
logger.error('[EloService] Card ELO update error:', results[1].reason);
|
|
94
130
|
}
|
|
95
131
|
}
|
|
132
|
+
|
|
133
|
+
return event;
|
|
96
134
|
}
|
|
135
|
+
|
|
136
|
+
return null;
|
|
97
137
|
}
|
|
98
138
|
|
|
99
139
|
/**
|
|
@@ -112,7 +152,7 @@ export class EloService {
|
|
|
112
152
|
card_id: string,
|
|
113
153
|
userCourseRegDoc: CourseRegistrationDoc,
|
|
114
154
|
currentCard: StudySessionRecord
|
|
115
|
-
): Promise<
|
|
155
|
+
): Promise<SessionEloEvent | null> {
|
|
116
156
|
const courseDB = this.dataLayer.getCourseDB(currentCard.card.course_id);
|
|
117
157
|
const courseReg = userCourseRegDoc.courses.find((c) => c.courseID === course_id);
|
|
118
158
|
if (!courseReg) {
|
|
@@ -120,7 +160,7 @@ export class EloService {
|
|
|
120
160
|
`[EloService] No registration for course ${course_id} on user's registration doc — ` +
|
|
121
161
|
`skipping per-tag ELO update for card ${card_id}. (Is the user registered for this course?)`
|
|
122
162
|
);
|
|
123
|
-
return;
|
|
163
|
+
return null;
|
|
124
164
|
}
|
|
125
165
|
const userElo = toCourseElo(courseReg.elo);
|
|
126
166
|
|
|
@@ -145,9 +185,57 @@ export class EloService {
|
|
|
145
185
|
}
|
|
146
186
|
|
|
147
187
|
if (cardElo && userElo) {
|
|
188
|
+
// Capture before-scores up front — adjustCourseScoresPerTag mutates the
|
|
189
|
+
// ELO objects in place. Every tag in `enriched` (except _global) is
|
|
190
|
+
// touched; count-only tags (null score) increment count without moving
|
|
191
|
+
// ELO and are recorded with score: null.
|
|
192
|
+
const beforeUserGlobal = userElo.global.score;
|
|
193
|
+
const beforeCardGlobal = cardElo.global.score;
|
|
194
|
+
const touchedTags = Object.keys(enriched).filter((key) => key !== '_global');
|
|
195
|
+
const beforeUserTag: Record<string, number> = {};
|
|
196
|
+
for (const tag of touchedTags) {
|
|
197
|
+
beforeUserTag[tag] = userElo.tags[tag]?.score ?? userElo.global.score;
|
|
198
|
+
}
|
|
199
|
+
|
|
148
200
|
const eloUpdate = adjustCourseScoresPerTag(userElo, cardElo, enriched);
|
|
201
|
+
const at = new Date().toISOString();
|
|
202
|
+
|
|
203
|
+
// Mastery signal: one ring-buffer entry per scored tag per presentation.
|
|
204
|
+
// Retries (priorAttemps > 0 on the current record) add nothing — that
|
|
205
|
+
// includes the dismiss-failed penalty, which lands here on a retry.
|
|
206
|
+
// Only the question's own graded tags count, not the card-level tags
|
|
207
|
+
// enriched with the global score above.
|
|
208
|
+
const recorded = recordTagPresentations(
|
|
209
|
+
eloUpdate.userElo,
|
|
210
|
+
taggedPerformance,
|
|
211
|
+
currentCard.records,
|
|
212
|
+
card_id,
|
|
213
|
+
at
|
|
214
|
+
);
|
|
215
|
+
if (recorded.length) {
|
|
216
|
+
logger.info(`[EloService] recent-presentation entries for ${card_id}: [${recorded.join(', ')}]`);
|
|
217
|
+
}
|
|
218
|
+
|
|
149
219
|
courseReg.elo = eloUpdate.userElo;
|
|
150
220
|
|
|
221
|
+
const tags: NonNullable<SessionEloEvent['tags']> = {};
|
|
222
|
+
for (const tag of touchedTags) {
|
|
223
|
+
const score = enriched[tag];
|
|
224
|
+
// Count-only exposure tags (null score) get a -1 sentinel score, not a
|
|
225
|
+
// real ELO move — record before===after so a naive after-before reads 0.
|
|
226
|
+
const after =
|
|
227
|
+
score === null ? beforeUserTag[tag] : eloUpdate.userElo.tags[tag]?.score ?? beforeUserTag[tag];
|
|
228
|
+
tags[tag] = { before: beforeUserTag[tag], after, score };
|
|
229
|
+
}
|
|
230
|
+
const event: SessionEloEvent = {
|
|
231
|
+
cardId: card_id,
|
|
232
|
+
at,
|
|
233
|
+
userScore: globalScore,
|
|
234
|
+
global: { before: beforeUserGlobal, after: eloUpdate.userElo.global.score },
|
|
235
|
+
card: { before: beforeCardGlobal, after: eloUpdate.cardElo.global.score },
|
|
236
|
+
...(touchedTags.length ? { tags } : {}),
|
|
237
|
+
};
|
|
238
|
+
|
|
151
239
|
const results = await Promise.allSettled([
|
|
152
240
|
this.user.updateUserElo(course_id, eloUpdate.userElo),
|
|
153
241
|
courseDB.updateCardElo(card_id, eloUpdate.cardElo),
|
|
@@ -186,6 +274,10 @@ export class EloService {
|
|
|
186
274
|
logger.error('[EloService] Card ELO update error:', results[1].reason);
|
|
187
275
|
}
|
|
188
276
|
}
|
|
277
|
+
|
|
278
|
+
return event;
|
|
189
279
|
}
|
|
280
|
+
|
|
281
|
+
return null;
|
|
190
282
|
}
|
|
191
283
|
}
|
|
@@ -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(
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
227
|
-
.updateUserAndCardElo(
|
|
228
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
423
|
+
),
|
|
424
|
+
'dismiss-failed per-tag',
|
|
425
|
+
cardId
|
|
426
|
+
);
|
|
383
427
|
} else {
|
|
384
|
-
|
|
385
|
-
.updateUserAndCardElo(
|
|
386
|
-
|
|
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} ` +
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { describe, it, expect } from 'vitest';
|
|
2
|
+
import { TAG_RECENT_MAX, pushTagPresentation, type CourseElo, type EloRank } from '@vue-skuilder/common';
|
|
3
|
+
import { isFirstAttempt, recordTagPresentations } from './tagRecent';
|
|
4
|
+
import type { CardRecord } from '@db/core';
|
|
5
|
+
|
|
6
|
+
const rec = (priorAttemps: number, isCorrect: boolean): CardRecord =>
|
|
7
|
+
({
|
|
8
|
+
isCorrect,
|
|
9
|
+
priorAttemps,
|
|
10
|
+
performance: 1,
|
|
11
|
+
courseID: 'c',
|
|
12
|
+
cardID: 'x',
|
|
13
|
+
timeSpent: 1,
|
|
14
|
+
timeStamp: '' as unknown as CardRecord['timeStamp'],
|
|
15
|
+
userAnswer: '',
|
|
16
|
+
}) as unknown as CardRecord;
|
|
17
|
+
|
|
18
|
+
const blank = (): CourseElo => ({ global: { score: 1000, count: 0 }, tags: {}, misc: {} });
|
|
19
|
+
|
|
20
|
+
describe('pushTagPresentation', () => {
|
|
21
|
+
it('appends, caps at TAG_RECENT_MAX, drops the oldest, and does not mutate', () => {
|
|
22
|
+
let rank: EloRank = { score: 1000, count: 0 };
|
|
23
|
+
const first = { at: 't0', ok: true, perf: 1, card: 'c0' };
|
|
24
|
+
rank = pushTagPresentation(rank, first);
|
|
25
|
+
expect(rank.recent).toEqual([first]);
|
|
26
|
+
|
|
27
|
+
const before = rank;
|
|
28
|
+
for (let i = 1; i <= TAG_RECENT_MAX; i++) {
|
|
29
|
+
rank = pushTagPresentation(rank, { at: `t${i}`, ok: i % 2 === 0, perf: 0.5, card: `c${i}` });
|
|
30
|
+
}
|
|
31
|
+
expect(before.recent).toHaveLength(1); // input untouched
|
|
32
|
+
expect(rank.recent).toHaveLength(TAG_RECENT_MAX);
|
|
33
|
+
expect(rank.recent![0].at).toBe('t1'); // t0 dropped
|
|
34
|
+
expect(rank.recent![TAG_RECENT_MAX - 1].at).toBe(`t${TAG_RECENT_MAX}`);
|
|
35
|
+
expect(rank.score).toBe(1000);
|
|
36
|
+
});
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
describe('isFirstAttempt', () => {
|
|
40
|
+
it('reads priorAttemps from the current (last) record', () => {
|
|
41
|
+
expect(isFirstAttempt([rec(0, false)])).toBe(true);
|
|
42
|
+
expect(isFirstAttempt([rec(0, false), rec(1, true)])).toBe(false);
|
|
43
|
+
});
|
|
44
|
+
it('falls back to record count when the marker is absent', () => {
|
|
45
|
+
const bare = { isCorrect: true } as unknown as CardRecord;
|
|
46
|
+
expect(isFirstAttempt([bare])).toBe(true);
|
|
47
|
+
expect(isFirstAttempt([bare, bare])).toBe(false);
|
|
48
|
+
expect(isFirstAttempt([])).toBe(false);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe('recordTagPresentations', () => {
|
|
53
|
+
it('writes one entry per scored tag on a first attempt, skipping count-only tags', () => {
|
|
54
|
+
const elo = blank();
|
|
55
|
+
const written = recordTagPresentations(
|
|
56
|
+
elo,
|
|
57
|
+
{ _global: 0.6, 'gpc:exercise:th-TH': 0.6, 'gpc:expose:w-W': null },
|
|
58
|
+
[rec(0, true)],
|
|
59
|
+
'c-ml-worth-3',
|
|
60
|
+
'2026-09-18T00:00:00.000Z'
|
|
61
|
+
);
|
|
62
|
+
expect(written).toEqual(['gpc:exercise:th-TH']);
|
|
63
|
+
expect(elo.tags['gpc:exercise:th-TH'].recent).toEqual([
|
|
64
|
+
{ at: '2026-09-18T00:00:00.000Z', ok: true, perf: 0.6, card: 'c-ml-worth-3' },
|
|
65
|
+
]);
|
|
66
|
+
expect(elo.tags['gpc:expose:w-W']).toBeUndefined();
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('records a first-attempt miss as ok:false', () => {
|
|
70
|
+
const elo = blank();
|
|
71
|
+
recordTagPresentations(elo, { _global: 0, 'gpc:exercise:sh-SH': 0 }, [rec(0, false)], 'c-ml-hush-2', 't');
|
|
72
|
+
expect(elo.tags['gpc:exercise:sh-SH'].recent).toEqual([{ at: 't', ok: false, perf: 0, card: 'c-ml-hush-2' }]);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('adds nothing for a retry (priorAttemps > 0), even a correct one', () => {
|
|
76
|
+
const elo = blank();
|
|
77
|
+
recordTagPresentations(elo, { _global: 0, 'gpc:exercise:sh-SH': 0 }, [rec(0, false)], 'k', 't0');
|
|
78
|
+
const written = recordTagPresentations(
|
|
79
|
+
elo,
|
|
80
|
+
{ _global: 1, 'gpc:exercise:sh-SH': 1 },
|
|
81
|
+
[rec(0, false), rec(1, true)],
|
|
82
|
+
'k',
|
|
83
|
+
't1'
|
|
84
|
+
);
|
|
85
|
+
expect(written).toEqual([]);
|
|
86
|
+
expect(elo.tags['gpc:exercise:sh-SH'].recent).toHaveLength(1);
|
|
87
|
+
expect(elo.tags['gpc:exercise:sh-SH'].recent![0].ok).toBe(false);
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
it('preserves score/count on an existing rank and caps the buffer', () => {
|
|
91
|
+
const elo = blank();
|
|
92
|
+
elo.tags['t'] = { score: 1234, count: 7 };
|
|
93
|
+
for (let i = 0; i < TAG_RECENT_MAX + 3; i++) {
|
|
94
|
+
recordTagPresentations(elo, { _global: 1, t: 1 }, [rec(0, true)], `card-${i}`, `t${i}`);
|
|
95
|
+
}
|
|
96
|
+
expect(elo.tags['t'].score).toBe(1234);
|
|
97
|
+
expect(elo.tags['t'].count).toBe(7);
|
|
98
|
+
expect(elo.tags['t'].recent).toHaveLength(TAG_RECENT_MAX);
|
|
99
|
+
expect(elo.tags['t'].recent![0].card).toBe('card-3');
|
|
100
|
+
});
|
|
101
|
+
});
|