@vue-skuilder/db 0.2.32 → 0.2.34

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.32",
7
+ "version": "0.2.34",
8
8
  "description": "Database layer for vue-skuilder",
9
9
  "main": "dist/index.js",
10
10
  "module": "dist/index.mjs",
@@ -60,7 +60,7 @@
60
60
  },
61
61
  "dependencies": {
62
62
  "@nilock2/pouchdb-authentication": "^1.0.2",
63
- "@vue-skuilder/common": "0.2.32",
63
+ "@vue-skuilder/common": "0.2.34",
64
64
  "cross-fetch": "^4.1.0",
65
65
  "moment": "^2.29.4",
66
66
  "pouchdb": "^9.0.0",
@@ -75,5 +75,5 @@
75
75
  "vite": "^8.0.0",
76
76
  "vitest": "^4.1.0"
77
77
  },
78
- "stableVersion": "0.2.32"
78
+ "stableVersion": "0.2.34"
79
79
  }
@@ -1,4 +1,11 @@
1
- import { CourseConfig, DataShape, NameSpacer, toZodJSON } from '@vue-skuilder/common';
1
+ import {
2
+ CourseConfig,
3
+ DataShape,
4
+ NameSpacer,
5
+ SeedMeta,
6
+ toCourseElo,
7
+ toZodJSON,
8
+ } from '@vue-skuilder/common';
2
9
  import { CourseDBInterface } from './core/interfaces/courseDB.js';
3
10
  import { logger } from './util/logger.js';
4
11
 
@@ -12,6 +19,7 @@ export interface CustomQuestionsData {
12
19
  dataShapes?: DataShape[];
13
20
  views?: { name?: string }[];
14
21
  seedData?: unknown[];
22
+ seedMeta?: (item: unknown) => SeedMeta;
15
23
  }[]; // Question class constructors
16
24
  dataShapes: DataShape[]; // DataShape definitions for studio-ui
17
25
  views: { name?: string }[]; // Vue components for rendering
@@ -36,6 +44,7 @@ export interface ProcessedQuestionData {
36
44
  dataShapes?: DataShape[];
37
45
  views?: { name?: string }[];
38
46
  seedData?: unknown[];
47
+ seedMeta?: (item: unknown) => SeedMeta;
39
48
  };
40
49
  dataShapes: DataShape[];
41
50
  views: { name?: string }[];
@@ -388,19 +397,22 @@ export async function registerSeedData(
388
397
  logger.info(`Registering seed data for question: ${question.name}`);
389
398
 
390
399
  try {
391
- const seedDataPromises = question.questionClass.seedData
392
- .filter(() => question.dataShapes.length > 0)
393
- .map((seedDataItem: unknown) =>
394
- courseDB.addNote(
400
+ if (question.dataShapes.length > 0) {
401
+ // One note at a time: notes sharing a tag would race on the tag doc, and a lost
402
+ // tag write aborts the note's remaining cards.
403
+ for (const seedDataItem of question.questionClass.seedData) {
404
+ const meta = question.questionClass.seedMeta?.(seedDataItem) ?? {};
405
+ await courseDB.addNote(
395
406
  question.course,
396
407
  question.dataShapes[0],
397
408
  seedDataItem,
398
409
  username,
399
- []
400
- )
401
- );
402
-
403
- await Promise.all(seedDataPromises);
410
+ meta.tags ?? [],
411
+ undefined,
412
+ meta.elo !== undefined ? toCourseElo(meta.elo) : undefined
413
+ );
414
+ }
415
+ }
404
416
  logger.info(`Seed data registered for question: ${question.name}`);
405
417
  } catch (error) {
406
418
  logger.warn(
@@ -8,6 +8,12 @@ import { logger } from '../util/logger';
8
8
  type Moment = moment.Moment;
9
9
  const duration = moment.duration;
10
10
 
11
+ /**
12
+ * Longest interval (seconds) after a correct answer flagged `fluent: false`.
13
+ * Matches the 20h floor in `lastSuccessfulInterval`: due again next day.
14
+ */
15
+ const SLOW_CORRECT_MAX_INTERVAL = 20 * 60 * 60;
16
+
11
17
  export interface DocumentUpdater {
12
18
  update<T extends PouchDB.Core.Document<object>>(id: string, update: Update<T>): Promise<T>;
13
19
  }
@@ -50,6 +56,7 @@ function newQuestionInterval(user: DocumentUpdater, cardHistory: CardHistory<Que
50
56
  cardHistory.lapses = getLapses(cardHistory.records);
51
57
  cardHistory.streak = getStreak(cardHistory.records);
52
58
 
59
+ let ret = interval;
53
60
  if (
54
61
  cardHistory.lapses &&
55
62
  cardHistory.streak &&
@@ -58,15 +65,21 @@ function newQuestionInterval(user: DocumentUpdater, cardHistory: CardHistory<Que
58
65
  ) {
59
66
  // weighted average of best-ever performance vs current performance, based
60
67
  // on how often the card has been failed, and the current streak of success
61
- const ret =
68
+ ret =
62
69
  (cardHistory.lapses * interval + cardHistory.streak * cardHistory.bestInterval) /
63
70
  (cardHistory.lapses + cardHistory.streak);
64
71
  logger.debug(`Weighted average interval calculation:
65
72
  \t(${cardHistory.lapses} * ${interval} + ${cardHistory.streak} * ${cardHistory.bestInterval}) / (${cardHistory.lapses} + ${cardHistory.streak}) = ${ret}`);
66
- return ret;
67
- } else {
68
- return interval;
69
73
  }
74
+
75
+ if (currentAttempt.fluent === false) {
76
+ // Correct but too slow: keep it coming back until it's fast on a first presentation.
77
+ logger.debug(
78
+ `Correct but not fluent: capping interval ${ret}s at ${SLOW_CORRECT_MAX_INTERVAL}s`
79
+ );
80
+ return Math.min(ret, SLOW_CORRECT_MAX_INTERVAL);
81
+ }
82
+ return ret;
70
83
  } else {
71
84
  return 0;
72
85
  }
@@ -75,13 +88,17 @@ function newQuestionInterval(user: DocumentUpdater, cardHistory: CardHistory<Que
75
88
  /**
76
89
  * Returns the amount of time, in seconds, of the most recent successful
77
90
  * interval for this card. An interval is successful if the user answers
78
- * a question correctly on the first attempt.
91
+ * a question correctly on the first attempt, and not flagged as too slow.
79
92
  *
80
93
  * @param cardHistory The record of user attempts with the question
81
94
  */
82
95
  function lastSuccessfulInterval(cardHistory: QuestionRecord[]): number {
83
96
  for (let i = cardHistory.length - 1; i >= 1; i--) {
84
- if (cardHistory[i].priorAttemps === 0 && cardHistory[i].isCorrect) {
97
+ if (
98
+ cardHistory[i].priorAttemps === 0 &&
99
+ cardHistory[i].isCorrect &&
100
+ cardHistory[i].fluent !== false
101
+ ) {
85
102
  const lastInterval = secondsBetween(cardHistory[i - 1].timeStamp, cardHistory[i].timeStamp);
86
103
  const ret = Math.max(lastInterval, 20 * 60 * 60);
87
104
  logger.debug(`Last interval w/ this card was: ${lastInterval}s, returning ${ret}s`);
@@ -6,6 +6,7 @@ import {
6
6
  TaggedPerformance,
7
7
  } from '@vue-skuilder/common';
8
8
  import {
9
+ CourseDBInterface,
9
10
  DataLayerProvider,
10
11
  UserDBInterface,
11
12
  CourseRegistrationDoc,
@@ -43,12 +44,36 @@ function withCountOnlyRoles(perf: TaggedPerformance, cardId: string): TaggedPerf
43
44
  export class EloService {
44
45
  private dataLayer: DataLayerProvider;
45
46
  private user: UserDBInterface;
47
+ /** Per course ID: its compiled `CourseConfig.qaUsernamePattern`, or null. */
48
+ private qaPatterns = new Map<string, Promise<RegExp | null>>();
46
49
 
47
50
  constructor(dataLayer: DataLayerProvider, user: UserDBInterface) {
48
51
  this.dataLayer = dataLayer;
49
52
  this.user = user;
50
53
  }
51
54
 
55
+ /**
56
+ * Whether the current user is one of the course's QA accounts
57
+ * (`CourseConfig.qaUsernamePattern`), whose responses must not move card
58
+ * ELO. The pattern is read once per course. If the config is unreadable or
59
+ * the pattern doesn't compile, nobody is a QA account.
60
+ */
61
+ private async isQaUser(courseDB: CourseDBInterface): Promise<boolean> {
62
+ const courseId = courseDB.getCourseID();
63
+ let pattern = this.qaPatterns.get(courseId);
64
+ if (!pattern) {
65
+ pattern = courseDB
66
+ .getCourseConfig()
67
+ .then((cfg) => (cfg.qaUsernamePattern ? new RegExp(cfg.qaUsernamePattern, 'i') : null))
68
+ .catch((e) => {
69
+ logger.warn(`[EloService] No QA username pattern for ${courseId}: ${e}`);
70
+ return null;
71
+ });
72
+ this.qaPatterns.set(courseId, pattern);
73
+ }
74
+ return (await pattern)?.test(this.user.getUsername()) ?? false;
75
+ }
76
+
52
77
  /**
53
78
  * Updates both user and card ELO ratings based on user performance.
54
79
  * @param userScore Score between 0-1 representing user performance
@@ -84,6 +109,10 @@ export class EloService {
84
109
  const cardElo = (await courseDB.getCardEloData([currentCard.card.card_id]))[0];
85
110
 
86
111
  if (cardElo && userElo) {
112
+ // A QA account's update is computed in full but only the user side is
113
+ // written; the event records the card as unmoved.
114
+ const writeCard = !(await this.isQaUser(courseDB));
115
+
87
116
  // Capture before-scores as numbers up front: adjustCourseScores mutates
88
117
  // userElo/cardElo in place (and returns the same refs). This path grades
89
118
  // every tag already present on the card with the single global score.
@@ -113,13 +142,19 @@ export class EloService {
113
142
  at: new Date().toISOString(),
114
143
  userScore,
115
144
  global: { before: beforeUserGlobal, after: eloUpdate.userElo.global.score },
116
- card: { before: beforeCardGlobal, after: eloUpdate.cardElo.global.score },
145
+ card: {
146
+ before: beforeCardGlobal,
147
+ after: writeCard ? eloUpdate.cardElo.global.score : beforeCardGlobal,
148
+ },
117
149
  ...(cardTagKeys.length ? { tags } : {}),
118
150
  };
119
151
 
152
+ if (!writeCard) {
153
+ logger.info(`[EloService] QA account: card ELO for ${card_id} not written`);
154
+ }
120
155
  const results = await Promise.allSettled([
121
156
  this.user.updateUserElo(course_id, eloUpdate.userElo),
122
- courseDB.updateCardElo(card_id, eloUpdate.cardElo),
157
+ writeCard ? courseDB.updateCardElo(card_id, eloUpdate.cardElo) : Promise.resolve(null),
123
158
  ]);
124
159
 
125
160
  // Check the results of each operation
@@ -212,6 +247,10 @@ export class EloService {
212
247
  }
213
248
 
214
249
  if (cardElo && userElo) {
250
+ // A QA account's update is computed in full but only the user side is
251
+ // written; the event records the card as unmoved.
252
+ const writeCard = !(await this.isQaUser(courseDB));
253
+
215
254
  // Capture before-scores up front — adjustCourseScoresPerTag mutates the
216
255
  // ELO objects in place. Every tag in `enriched` (except _global) is
217
256
  // touched; count-only tags (null score) increment count without moving
@@ -259,13 +298,19 @@ export class EloService {
259
298
  at,
260
299
  userScore: globalScore,
261
300
  global: { before: beforeUserGlobal, after: eloUpdate.userElo.global.score },
262
- card: { before: beforeCardGlobal, after: eloUpdate.cardElo.global.score },
301
+ card: {
302
+ before: beforeCardGlobal,
303
+ after: writeCard ? eloUpdate.cardElo.global.score : beforeCardGlobal,
304
+ },
263
305
  ...(touchedTags.length ? { tags } : {}),
264
306
  };
265
307
 
308
+ if (!writeCard) {
309
+ logger.info(`[EloService] QA account: card ELO for ${card_id} not written`);
310
+ }
266
311
  const results = await Promise.allSettled([
267
312
  this.user.updateUserElo(course_id, eloUpdate.userElo),
268
- courseDB.updateCardElo(card_id, eloUpdate.cardElo),
313
+ writeCard ? courseDB.updateCardElo(card_id, eloUpdate.cardElo) : Promise.resolve(null),
269
314
  ]);
270
315
 
271
316
  // Check the results of each operation