@vue-skuilder/db 0.2.24 → 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.
Files changed (34) hide show
  1. package/dist/{contentSource-jBskhS2Y.d.cts → contentSource-CrRnbjBx.d.cts} +13 -2
  2. package/dist/{contentSource-Z9lQOuu5.d.ts → contentSource-kD35o65m.d.ts} +13 -2
  3. package/dist/core/index.d.cts +3 -3
  4. package/dist/core/index.d.ts +3 -3
  5. package/dist/core/index.js +2474 -481
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +2464 -466
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-CvSh3KW-.d.ts → dataLayerProvider-CtzddVdy.d.ts} +1 -1
  10. package/dist/{dataLayerProvider-DbA3d_Pd.d.cts → dataLayerProvider-IecbidDO.d.cts} +1 -1
  11. package/dist/impl/couch/index.d.cts +2 -2
  12. package/dist/impl/couch/index.d.ts +2 -2
  13. package/dist/impl/couch/index.js +2237 -238
  14. package/dist/impl/couch/index.js.map +1 -1
  15. package/dist/impl/couch/index.mjs +2231 -227
  16. package/dist/impl/couch/index.mjs.map +1 -1
  17. package/dist/impl/static/index.d.cts +2 -2
  18. package/dist/impl/static/index.d.ts +2 -2
  19. package/dist/impl/static/index.js +2319 -320
  20. package/dist/impl/static/index.js.map +1 -1
  21. package/dist/impl/static/index.mjs +2309 -305
  22. package/dist/impl/static/index.mjs.map +1 -1
  23. package/dist/index.d.cts +3 -3
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +8155 -7955
  26. package/dist/index.js.map +1 -1
  27. package/dist/index.mjs +8050 -7851
  28. package/dist/index.mjs.map +1 -1
  29. package/package.json +3 -3
  30. package/src/impl/common/BaseUserDB.ts +13 -4
  31. package/src/study/SpacedRepetition.ts +11 -2
  32. package/src/study/services/EloService.ts +20 -1
  33. package/src/study/services/tagRecent.test.ts +101 -0
  34. 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.24",
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.24",
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.24"
66
+ "stableVersion": "0.2.25"
67
67
  }
@@ -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
- h.lapses = h.lapses || 0;
1022
- h.streak = h.streak || 0;
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
  );
@@ -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
- function getStreak(records: QuestionRecord[]): number {
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
- function getLapses(records: QuestionRecord[]): number {
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: new Date().toISOString(),
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
+ }