@vue-skuilder/db 0.2.24 → 0.2.26
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/{SyncStrategy-CCU1H81I.d.cts → SyncStrategy-BXliog1m.d.cts} +14 -1
- package/dist/{SyncStrategy-CCU1H81I.d.ts → SyncStrategy-BXliog1m.d.ts} +14 -1
- package/dist/{contentSource-jBskhS2Y.d.cts → contentSource-D3c1fMAk.d.cts} +24 -2
- package/dist/{contentSource-Z9lQOuu5.d.ts → contentSource-LPf044hY.d.ts} +24 -2
- package/dist/core/index.d.cts +3 -3
- package/dist/core/index.d.ts +3 -3
- package/dist/core/index.js +2508 -481
- package/dist/core/index.js.map +1 -1
- package/dist/core/index.mjs +2498 -466
- package/dist/core/index.mjs.map +1 -1
- package/dist/{dataLayerProvider-DbA3d_Pd.d.cts → dataLayerProvider-CeLiFbHv.d.cts} +1 -1
- package/dist/{dataLayerProvider-CvSh3KW-.d.ts → dataLayerProvider-DaAootVV.d.ts} +1 -1
- package/dist/impl/couch/index.d.cts +4 -3
- package/dist/impl/couch/index.d.ts +4 -3
- package/dist/impl/couch/index.js +2266 -217
- package/dist/impl/couch/index.js.map +1 -1
- package/dist/impl/couch/index.mjs +2260 -206
- package/dist/impl/couch/index.mjs.map +1 -1
- package/dist/impl/static/index.d.cts +3 -3
- package/dist/impl/static/index.d.ts +3 -3
- package/dist/impl/static/index.js +2353 -320
- package/dist/impl/static/index.js.map +1 -1
- package/dist/impl/static/index.mjs +2343 -305
- package/dist/impl/static/index.mjs.map +1 -1
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +8211 -7961
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +8095 -7846
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
- package/src/core/interfaces/userDB.ts +10 -0
- package/src/impl/common/BaseUserDB.ts +53 -4
- package/src/impl/common/SyncStrategy.ts +11 -1
- package/src/impl/common/index.ts +1 -0
- package/src/impl/common/types.ts +5 -0
- package/src/impl/couch/CouchDBSyncStrategy.ts +25 -1
- package/src/study/SessionController.ts +6 -2
- package/src/study/SpacedRepetition.ts +11 -2
- package/src/study/services/EloService.ts +20 -1
- 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.26",
|
|
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.26",
|
|
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.26"
|
|
67
67
|
}
|
|
@@ -257,6 +257,16 @@ export interface UserDBAuthenticator {
|
|
|
257
257
|
logout(): Promise<{
|
|
258
258
|
ok: boolean;
|
|
259
259
|
}>;
|
|
260
|
+
|
|
261
|
+
/**
|
|
262
|
+
* Adopt a session established outside this client (e.g. third-party
|
|
263
|
+
* sign-in completed server-side), optionally migrating guest data.
|
|
264
|
+
*/
|
|
265
|
+
adoptSession(opts: { migrateGuestData: boolean }): Promise<{
|
|
266
|
+
ok: boolean;
|
|
267
|
+
error?: string;
|
|
268
|
+
username?: string;
|
|
269
|
+
}>;
|
|
260
270
|
}
|
|
261
271
|
|
|
262
272
|
/**
|
|
@@ -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';
|
|
@@ -40,6 +40,7 @@ import {
|
|
|
40
40
|
removeScheduledCardReviewLocal,
|
|
41
41
|
} from './userDBHelpers';
|
|
42
42
|
import { PouchError } from '../couch/types';
|
|
43
|
+
import type { AdoptSessionResult } from './types';
|
|
43
44
|
import UpdateQueue, { Update } from '../couch/updateQueue';
|
|
44
45
|
import { UsrCrsData } from '../couch/user-course-relDB';
|
|
45
46
|
import { getCredentialledCourseConfig } from '../couch/index';
|
|
@@ -250,6 +251,45 @@ Currently logged-in as ${this._username}.`
|
|
|
250
251
|
return loginResult;
|
|
251
252
|
}
|
|
252
253
|
|
|
254
|
+
/**
|
|
255
|
+
* Adopt a remote session that was established outside this client — e.g. a
|
|
256
|
+
* backend verified a third-party sign-in (Google) and set the session cookie
|
|
257
|
+
* on its response. Afterwards the user is logged in exactly as after
|
|
258
|
+
* login(): username switched, guest pointer cleared, init() re-run.
|
|
259
|
+
*
|
|
260
|
+
* @param opts.migrateGuestData Carry the current guest account's local data
|
|
261
|
+
* into the adopted account. Pass true for a freshly created account (as
|
|
262
|
+
* createAccount() does), false for an existing one (as login() does).
|
|
263
|
+
*/
|
|
264
|
+
public async adoptSession(opts: { migrateGuestData: boolean }): Promise<AdoptSessionResult> {
|
|
265
|
+
if (!this.syncStrategy.canAuthenticate() || !this.syncStrategy.adoptSession) {
|
|
266
|
+
throw new Error('Session adoption not supported by current sync strategy');
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// Captured from memory, not the remote: the remote session already
|
|
270
|
+
// belongs to the adopted user.
|
|
271
|
+
const guestUsername = this._username.startsWith(GuestUsername) ? this._username : undefined;
|
|
272
|
+
if (!guestUsername) {
|
|
273
|
+
throw new Error(`Cannot adopt a session while logged in.
|
|
274
|
+
Log out of account ${this.getUsername()} first.`);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
const result = await this.syncStrategy.adoptSession(
|
|
278
|
+
opts.migrateGuestData ? guestUsername : undefined
|
|
279
|
+
);
|
|
280
|
+
if (result.ok && result.username) {
|
|
281
|
+
log(`Adopted session for ${result.username}`);
|
|
282
|
+
this._username = result.username;
|
|
283
|
+
try {
|
|
284
|
+
localStorage.removeItem('sk-guest-uuid');
|
|
285
|
+
} catch (e) {
|
|
286
|
+
logger.warn('localStorage not available (Node.js environment):', e);
|
|
287
|
+
}
|
|
288
|
+
await this.init();
|
|
289
|
+
}
|
|
290
|
+
return result;
|
|
291
|
+
}
|
|
292
|
+
|
|
253
293
|
public async resetUserData(): Promise<{ status: Status; error?: string }> {
|
|
254
294
|
// Only allow reset for local-only sync strategies
|
|
255
295
|
if (this.syncStrategy.canAuthenticate()) {
|
|
@@ -1018,8 +1058,17 @@ Currently logged-in as ${this._username}.`
|
|
|
1018
1058
|
function (h: CardHistory<T>) {
|
|
1019
1059
|
h.records.push(record);
|
|
1020
1060
|
h.bestInterval = h.bestInterval || 0;
|
|
1021
|
-
|
|
1022
|
-
|
|
1061
|
+
// Scheduling (SpacedRepetition.newQuestionInterval) re-derives
|
|
1062
|
+
// lapses/streak from `records` on every call, so these persisted
|
|
1063
|
+
// fields are informational — kept current so the stored doc reads
|
|
1064
|
+
// truthfully when inspected outside a session.
|
|
1065
|
+
if (areQuestionRecords(h)) {
|
|
1066
|
+
h.lapses = getLapses(h.records);
|
|
1067
|
+
h.streak = getStreak(h.records);
|
|
1068
|
+
} else {
|
|
1069
|
+
h.lapses = h.lapses || 0;
|
|
1070
|
+
h.streak = h.streak || 0;
|
|
1071
|
+
}
|
|
1023
1072
|
return h;
|
|
1024
1073
|
}
|
|
1025
1074
|
);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// packages/db/src/impl/common/SyncStrategy.ts
|
|
2
2
|
|
|
3
|
-
import type { AccountCreationResult, AuthenticationResult } from './types';
|
|
3
|
+
import type { AccountCreationResult, AdoptSessionResult, AuthenticationResult } from './types';
|
|
4
4
|
|
|
5
5
|
/**
|
|
6
6
|
* Strategy interface for handling user data synchronization
|
|
@@ -90,6 +90,16 @@ export interface SyncStrategy {
|
|
|
90
90
|
*/
|
|
91
91
|
logout?(): Promise<AuthenticationResult>;
|
|
92
92
|
|
|
93
|
+
/**
|
|
94
|
+
* Adopt a remote session established outside this client (e.g. a server that
|
|
95
|
+
* verified a third-party sign-in and set the session cookie), optionally
|
|
96
|
+
* migrating a guest account's local data into it (if supported).
|
|
97
|
+
* @param migrateFromGuest Guest username whose local data should be carried
|
|
98
|
+
* over. The caller must capture it BEFORE the session switched, since the
|
|
99
|
+
* remote now reports the adopted user.
|
|
100
|
+
*/
|
|
101
|
+
adoptSession?(migrateFromGuest?: string): Promise<AdoptSessionResult>;
|
|
102
|
+
|
|
93
103
|
/**
|
|
94
104
|
* Get the current logged-in username
|
|
95
105
|
* Returns the username if logged in, or a default guest username
|
package/src/impl/common/index.ts
CHANGED
package/src/impl/common/types.ts
CHANGED
|
@@ -22,6 +22,11 @@ export interface AuthenticationResult {
|
|
|
22
22
|
error?: string;
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
export interface AdoptSessionResult extends AuthenticationResult {
|
|
26
|
+
/** The adopted session's user, when ok. */
|
|
27
|
+
username?: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
25
30
|
/**
|
|
26
31
|
* User session information
|
|
27
32
|
*/
|
|
@@ -5,7 +5,11 @@ import { GuestUsername } from '../../core/types/types-legacy';
|
|
|
5
5
|
import { logger } from '../../util/logger';
|
|
6
6
|
import { Status } from '@vue-skuilder/common';
|
|
7
7
|
import type { SyncStrategy } from '../common/SyncStrategy';
|
|
8
|
-
import type {
|
|
8
|
+
import type {
|
|
9
|
+
AccountCreationResult,
|
|
10
|
+
AdoptSessionResult,
|
|
11
|
+
AuthenticationResult,
|
|
12
|
+
} from '../common/types';
|
|
9
13
|
import { getLocalUserDB, hexEncode, updateGuestAccountExpirationDate, accomodateGuest } from '../common';
|
|
10
14
|
import pouch from './pouchdb-setup';
|
|
11
15
|
import { createPouchDBConfig } from './index';
|
|
@@ -261,6 +265,26 @@ export class CouchDBSyncStrategy implements SyncStrategy {
|
|
|
261
265
|
}
|
|
262
266
|
}
|
|
263
267
|
|
|
268
|
+
async adoptSession(migrateFromGuest?: string): Promise<AdoptSessionResult> {
|
|
269
|
+
let username: string;
|
|
270
|
+
try {
|
|
271
|
+
username = await getLoggedInUsername();
|
|
272
|
+
} catch {
|
|
273
|
+
return { ok: false, error: 'No session to adopt' };
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (migrateFromGuest?.startsWith(GuestUsername)) {
|
|
277
|
+
logger.info(`Migrating data from funnel account ${migrateFromGuest} to ${username}`);
|
|
278
|
+
const migrationResult = await this.migrateFunnelData(migrateFromGuest, username);
|
|
279
|
+
if (!migrationResult.success) {
|
|
280
|
+
logger.warn(`Migration failed: ${migrationResult.error}`);
|
|
281
|
+
// Continue anyway - don't block the login
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return { ok: true, username };
|
|
286
|
+
}
|
|
287
|
+
|
|
264
288
|
async logout(): Promise<AuthenticationResult> {
|
|
265
289
|
try {
|
|
266
290
|
const result = await this.getRemoteCouchRootDB().logOut();
|
|
@@ -1244,8 +1244,12 @@ export class SessionController<TView = unknown> extends Loggable {
|
|
|
1244
1244
|
});
|
|
1245
1245
|
} catch (error) {
|
|
1246
1246
|
this.error(`Failed to get content from source ${i}:`, error);
|
|
1247
|
-
// Re-throw if this is the only source - we can't proceed without any content
|
|
1248
|
-
|
|
1247
|
+
// Re-throw if this is the only source - we can't proceed without any content.
|
|
1248
|
+
// Initial load only: a replan falls through to the non-fatal
|
|
1249
|
+
// `batches.length === 0` path below and keeps the existing queue.
|
|
1250
|
+
// Throwing there would escape nextCard() (via the wedge-breaker) and
|
|
1251
|
+
// strand the host mid-session with neither a card nor a null.
|
|
1252
|
+
if (this.sources.length === 1 && !replan) {
|
|
1249
1253
|
throw new Error(`Cannot start session: failed to load content from source ${i}`);
|
|
1250
1254
|
}
|
|
1251
1255
|
}
|
|
@@ -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
|
|
|
@@ -12,6 +12,7 @@ import {
|
|
|
12
12
|
} from '@db/core';
|
|
13
13
|
import { StudySessionRecord } from '../SessionController';
|
|
14
14
|
import { logger } from '@db/util/logger';
|
|
15
|
+
import { recordTagPresentations } from './tagRecent';
|
|
15
16
|
|
|
16
17
|
/**
|
|
17
18
|
* Service responsible for ELO rating calculations and updates.
|
|
@@ -197,6 +198,24 @@ export class EloService {
|
|
|
197
198
|
}
|
|
198
199
|
|
|
199
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
|
+
|
|
200
219
|
courseReg.elo = eloUpdate.userElo;
|
|
201
220
|
|
|
202
221
|
const tags: NonNullable<SessionEloEvent['tags']> = {};
|
|
@@ -210,7 +229,7 @@ export class EloService {
|
|
|
210
229
|
}
|
|
211
230
|
const event: SessionEloEvent = {
|
|
212
231
|
cardId: card_id,
|
|
213
|
-
at
|
|
232
|
+
at,
|
|
214
233
|
userScore: globalScore,
|
|
215
234
|
global: { before: beforeUserGlobal, after: eloUpdate.userElo.global.score },
|
|
216
235
|
card: { before: beforeCardGlobal, after: eloUpdate.cardElo.global.score },
|
|
@@ -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
|
+
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CourseElo,
|
|
3
|
+
EloRank,
|
|
4
|
+
TaggedPerformance,
|
|
5
|
+
TagPresentation,
|
|
6
|
+
pushTagPresentation,
|
|
7
|
+
} from '@vue-skuilder/common';
|
|
8
|
+
import { CardRecord } from '@db/core';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Mastery signal: per-tag ring buffer of recent presentations.
|
|
12
|
+
*
|
|
13
|
+
* Written on the same path as the per-tag ELO update, one entry per
|
|
14
|
+
* *presentation* of a card. Retries within a presentation (a record with
|
|
15
|
+
* `priorAttemps > 0`, or any record after the first on the current card)
|
|
16
|
+
* are not evidence and add nothing — including the "dismiss-failed" final
|
|
17
|
+
* penalty, which reaches the ELO path on a retry record.
|
|
18
|
+
*
|
|
19
|
+
* Only tags the question actually graded (numeric perf) get an entry;
|
|
20
|
+
* count-only exposure tags (`null`) carry no correctness signal.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** The record for the presentation being graded, or null if none is visible. */
|
|
24
|
+
function currentRecord(records: readonly CardRecord[]): CardRecord | null {
|
|
25
|
+
return records.length ? records[records.length - 1] : null;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Whether the record under grading is the first attempt of its presentation.
|
|
30
|
+
*
|
|
31
|
+
* `priorAttemps` is the authoritative marker (written by the question view).
|
|
32
|
+
* When it is absent (non-question records, or a caller that did not push the
|
|
33
|
+
* record onto `currentCard.records`), fall back to the presentation's record
|
|
34
|
+
* count. With no record visible at all we cannot tell, and say no.
|
|
35
|
+
*/
|
|
36
|
+
export function isFirstAttempt(records: readonly CardRecord[]): boolean {
|
|
37
|
+
const rec = currentRecord(records);
|
|
38
|
+
if (!rec) return false;
|
|
39
|
+
const prior = (rec as { priorAttemps?: unknown }).priorAttemps;
|
|
40
|
+
if (typeof prior === 'number') return prior === 0;
|
|
41
|
+
return records.length === 1;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Append a presentation entry to every scored tag in `perf`, mutating
|
|
46
|
+
* `userElo.tags[tag]` in place (each rank object is replaced, not mutated).
|
|
47
|
+
* No-op for retries. Returns the tags that received an entry.
|
|
48
|
+
*/
|
|
49
|
+
export function recordTagPresentations(
|
|
50
|
+
userElo: CourseElo,
|
|
51
|
+
perf: TaggedPerformance,
|
|
52
|
+
records: readonly CardRecord[],
|
|
53
|
+
cardId: string,
|
|
54
|
+
at: string
|
|
55
|
+
): string[] {
|
|
56
|
+
if (!isFirstAttempt(records)) return [];
|
|
57
|
+
const rec = currentRecord(records) as { isCorrect?: unknown } | null;
|
|
58
|
+
const ok = rec?.isCorrect === true;
|
|
59
|
+
|
|
60
|
+
const written: string[] = [];
|
|
61
|
+
for (const [tag, score] of Object.entries(perf)) {
|
|
62
|
+
if (tag === '_global') continue;
|
|
63
|
+
if (typeof score !== 'number') continue; // count-only exposure tag
|
|
64
|
+
const rank: EloRank = userElo.tags[tag] ?? { score: userElo.global.score, count: 0 };
|
|
65
|
+
const entry: TagPresentation = { at, ok, perf: score, card: cardId };
|
|
66
|
+
userElo.tags[tag] = pushTagPresentation(rank, entry);
|
|
67
|
+
written.push(tag);
|
|
68
|
+
}
|
|
69
|
+
return written;
|
|
70
|
+
}
|