@vue-skuilder/db 0.2.35 → 0.2.36

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 (258) hide show
  1. package/CLAUDE.md +15 -4
  2. package/build.entries.mjs +12 -0
  3. package/dist/_virtual/_rolldown/runtime.mjs +8 -0
  4. package/dist/{contentSource-BteiDpxH.d.ts → contentSource-D_E7JaxR.d.ts} +1 -1
  5. package/dist/core/UserDBDebugger.mjs +285 -0
  6. package/dist/core/UserDBDebugger.mjs.map +1 -0
  7. package/dist/core/bulkImport/cardProcessor.mjs +106 -0
  8. package/dist/core/bulkImport/cardProcessor.mjs.map +1 -0
  9. package/dist/core/{index.js → index.cjs} +6438 -7784
  10. package/dist/core/index.cjs.map +1 -0
  11. package/dist/core/index.d.ts +5 -5
  12. package/dist/core/index.mjs +20 -11368
  13. package/dist/core/interfaces/contentSource.mjs +20 -0
  14. package/dist/core/interfaces/contentSource.mjs.map +1 -0
  15. package/dist/core/navigators/Pipeline.mjs +723 -0
  16. package/dist/core/navigators/Pipeline.mjs.map +1 -0
  17. package/dist/core/navigators/PipelineAssembler.mjs +86 -0
  18. package/dist/core/navigators/PipelineAssembler.mjs.map +1 -0
  19. package/dist/core/navigators/PipelineDebugger.mjs +771 -0
  20. package/dist/core/navigators/PipelineDebugger.mjs.map +1 -0
  21. package/dist/core/navigators/SrsDebugger.mjs +34 -0
  22. package/dist/core/navigators/SrsDebugger.mjs.map +1 -0
  23. package/dist/core/navigators/StrategyPressureDebugger.mjs +19 -0
  24. package/dist/core/navigators/StrategyPressureDebugger.mjs.map +1 -0
  25. package/dist/core/navigators/defaults.mjs +96 -0
  26. package/dist/core/navigators/defaults.mjs.map +1 -0
  27. package/dist/core/navigators/diversityRerank.mjs +85 -0
  28. package/dist/core/navigators/diversityRerank.mjs.map +1 -0
  29. package/dist/core/navigators/filters/WeightedFilter.mjs +81 -0
  30. package/dist/core/navigators/filters/WeightedFilter.mjs.map +1 -0
  31. package/dist/core/navigators/filters/eloDistance.mjs +244 -0
  32. package/dist/core/navigators/filters/eloDistance.mjs.map +1 -0
  33. package/dist/core/navigators/filters/hierarchyDefinition.mjs +235 -0
  34. package/dist/core/navigators/filters/hierarchyDefinition.mjs.map +1 -0
  35. package/dist/core/navigators/filters/interferenceMitigator.mjs +201 -0
  36. package/dist/core/navigators/filters/interferenceMitigator.mjs.map +1 -0
  37. package/dist/core/navigators/filters/relativePriority.mjs +135 -0
  38. package/dist/core/navigators/filters/relativePriority.mjs.map +1 -0
  39. package/dist/core/navigators/filters/userTagPreference.mjs +101 -0
  40. package/dist/core/navigators/filters/userTagPreference.mjs.map +1 -0
  41. package/dist/core/navigators/generators/CompositeGenerator.mjs +203 -0
  42. package/dist/core/navigators/generators/CompositeGenerator.mjs.map +1 -0
  43. package/dist/core/navigators/generators/elo.mjs +77 -0
  44. package/dist/core/navigators/generators/elo.mjs.map +1 -0
  45. package/dist/core/navigators/generators/prescribed.mjs +676 -0
  46. package/dist/core/navigators/generators/prescribed.mjs.map +1 -0
  47. package/dist/core/navigators/generators/srs.mjs +158 -0
  48. package/dist/core/navigators/generators/srs.mjs.map +1 -0
  49. package/dist/core/navigators/index.mjs +345 -0
  50. package/dist/core/navigators/index.mjs.map +1 -0
  51. package/dist/core/navigators/pipelinePlan.mjs +109 -0
  52. package/dist/core/navigators/pipelinePlan.mjs.map +1 -0
  53. package/dist/core/navigators/regulators.mjs +128 -0
  54. package/dist/core/navigators/regulators.mjs.map +1 -0
  55. package/dist/core/orchestration/gradient.mjs +101 -0
  56. package/dist/core/orchestration/gradient.mjs.map +1 -0
  57. package/dist/core/orchestration/index.mjs +115 -0
  58. package/dist/core/orchestration/index.mjs.map +1 -0
  59. package/dist/core/orchestration/learning.mjs +140 -0
  60. package/dist/core/orchestration/learning.mjs.map +1 -0
  61. package/dist/core/orchestration/recording.mjs +64 -0
  62. package/dist/core/orchestration/recording.mjs.map +1 -0
  63. package/dist/core/orchestration/signal.mjs +40 -0
  64. package/dist/core/orchestration/signal.mjs.map +1 -0
  65. package/dist/core/types/contentNavigationStrategy.mjs +10 -0
  66. package/dist/core/types/contentNavigationStrategy.mjs.map +1 -0
  67. package/dist/core/types/hydration.mjs +13 -0
  68. package/dist/core/types/hydration.mjs.map +1 -0
  69. package/dist/core/types/strategyState.mjs +16 -0
  70. package/dist/core/types/strategyState.mjs.map +1 -0
  71. package/dist/core/types/studySession.mjs +14 -0
  72. package/dist/core/types/studySession.mjs.map +1 -0
  73. package/dist/core/types/types-legacy.mjs +44 -0
  74. package/dist/core/types/types-legacy.mjs.map +1 -0
  75. package/dist/core/util/index.mjs +31 -0
  76. package/dist/core/util/index.mjs.map +1 -0
  77. package/dist/core/versionStamps.mjs +46 -0
  78. package/dist/core/versionStamps.mjs.map +1 -0
  79. package/dist/courseConfigRegistration.mjs +306 -0
  80. package/dist/courseConfigRegistration.mjs.map +1 -0
  81. package/dist/{dataLayerProvider-C_QWzHf-.d.ts → dataLayerProvider-BDshhSp_.d.ts} +1 -1
  82. package/dist/diagnostics/dataset.mjs +118 -0
  83. package/dist/diagnostics/dataset.mjs.map +1 -0
  84. package/dist/diagnostics/derive.mjs +318 -0
  85. package/dist/diagnostics/derive.mjs.map +1 -0
  86. package/dist/diagnostics/{index.js → index.cjs} +1 -1
  87. package/dist/diagnostics/index.d.ts +3 -3
  88. package/dist/diagnostics/index.mjs +7 -1042
  89. package/dist/diagnostics/loader.mjs +151 -0
  90. package/dist/diagnostics/loader.mjs.map +1 -0
  91. package/dist/diagnostics/pipeline.mjs +161 -0
  92. package/dist/diagnostics/pipeline.mjs.map +1 -0
  93. package/dist/diagnostics/tagElo.mjs +177 -0
  94. package/dist/diagnostics/tagElo.mjs.map +1 -0
  95. package/dist/diagnostics/text.mjs +174 -0
  96. package/dist/diagnostics/text.mjs.map +1 -0
  97. package/dist/factory.mjs +70 -0
  98. package/dist/factory.mjs.map +1 -0
  99. package/dist/impl/common/BaseUserDB.mjs +1103 -0
  100. package/dist/impl/common/BaseUserDB.mjs.map +1 -0
  101. package/dist/impl/common/userDBHelpers.mjs +49 -0
  102. package/dist/impl/common/userDBHelpers.mjs.map +1 -0
  103. package/dist/impl/common/userDBKeys.mjs +45 -0
  104. package/dist/impl/common/userDBKeys.mjs.map +1 -0
  105. package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
  106. package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
  107. package/dist/impl/couch/CourseSyncService.mjs +242 -0
  108. package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
  109. package/dist/impl/couch/PouchDataLayerProvider.mjs +74 -0
  110. package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
  111. package/dist/impl/couch/adminDB.mjs +61 -0
  112. package/dist/impl/couch/adminDB.mjs.map +1 -0
  113. package/dist/impl/couch/auth.mjs +33 -0
  114. package/dist/impl/couch/auth.mjs.map +1 -0
  115. package/dist/impl/couch/classroomDB.mjs +227 -0
  116. package/dist/impl/couch/classroomDB.mjs.map +1 -0
  117. package/dist/impl/couch/clientCache.mjs +15 -0
  118. package/dist/impl/couch/clientCache.mjs.map +1 -0
  119. package/dist/impl/couch/courseAPI.mjs +183 -0
  120. package/dist/impl/couch/courseAPI.mjs.map +1 -0
  121. package/dist/impl/couch/courseDB.mjs +729 -0
  122. package/dist/impl/couch/courseDB.mjs.map +1 -0
  123. package/dist/impl/couch/courseLookupDB.mjs +94 -0
  124. package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
  125. package/dist/impl/couch/{index.js → index.cjs} +6911 -10367
  126. package/dist/impl/couch/index.cjs.map +1 -0
  127. package/dist/impl/couch/index.d.ts +12 -5
  128. package/dist/impl/couch/index.mjs +134 -12146
  129. package/dist/impl/couch/index.mjs.map +1 -1
  130. package/dist/impl/couch/pouchdb-setup.mjs +15 -0
  131. package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
  132. package/dist/impl/couch/updateQueue.mjs +101 -0
  133. package/dist/impl/couch/updateQueue.mjs.map +1 -0
  134. package/dist/impl/couch/user-course-relDB.mjs +55 -0
  135. package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
  136. package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
  137. package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
  138. package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
  139. package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
  140. package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
  141. package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
  142. package/dist/impl/static/courseDB.mjs +368 -0
  143. package/dist/impl/static/courseDB.mjs.map +1 -0
  144. package/dist/impl/static/coursesDB.mjs +38 -0
  145. package/dist/impl/static/coursesDB.mjs.map +1 -0
  146. package/dist/impl/static/{index.js → index.cjs} +2461 -5992
  147. package/dist/impl/static/index.cjs.map +1 -0
  148. package/dist/impl/static/index.d.ts +4 -4
  149. package/dist/impl/static/index.mjs +6 -10741
  150. package/dist/{index-C745YB_6.d.ts → index-BLDpFYG3.d.ts} +1 -1
  151. package/dist/{index.js → index.cjs} +14070 -14239
  152. package/dist/index.cjs.map +1 -0
  153. package/dist/index.d.ts +12 -23
  154. package/dist/index.mjs +38 -16937
  155. package/dist/pouch/{index.js → index.cjs} +5 -1
  156. package/dist/pouch/index.cjs.map +1 -0
  157. package/dist/pouch/index.mjs +2 -19
  158. package/dist/study/ItemQueue.mjs +95 -0
  159. package/dist/study/ItemQueue.mjs.map +1 -0
  160. package/dist/study/MixerDebugger.mjs +303 -0
  161. package/dist/study/MixerDebugger.mjs.map +1 -0
  162. package/dist/study/SessionController.mjs +1187 -0
  163. package/dist/study/SessionController.mjs.map +1 -0
  164. package/dist/study/SessionDebugger.mjs +271 -0
  165. package/dist/study/SessionDebugger.mjs.map +1 -0
  166. package/dist/study/SessionOverlay.mjs +407 -0
  167. package/dist/study/SessionOverlay.mjs.map +1 -0
  168. package/dist/study/SourceMixer.mjs +45 -0
  169. package/dist/study/SourceMixer.mjs.map +1 -0
  170. package/dist/study/SpacedRepetition.mjs +108 -0
  171. package/dist/study/SpacedRepetition.mjs.map +1 -0
  172. package/dist/study/TagFilteredContentSource.mjs +136 -0
  173. package/dist/study/TagFilteredContentSource.mjs.map +1 -0
  174. package/dist/study/services/CardHydrationService.mjs +172 -0
  175. package/dist/study/services/CardHydrationService.mjs.map +1 -0
  176. package/dist/study/services/EloService.mjs +217 -0
  177. package/dist/study/services/EloService.mjs.map +1 -0
  178. package/dist/study/services/ResponseProcessor.mjs +190 -0
  179. package/dist/study/services/ResponseProcessor.mjs.map +1 -0
  180. package/dist/study/services/SrsService.mjs +49 -0
  181. package/dist/study/services/SrsService.mjs.map +1 -0
  182. package/dist/study/services/tagRecent.mjs +65 -0
  183. package/dist/study/services/tagRecent.mjs.map +1 -0
  184. package/dist/{types-DF0JuPbs.d.ts → types-DChCz22D.d.ts} +1 -1
  185. package/dist/{types-legacy-DdVjg81H.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
  186. package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
  187. package/dist/util/Loggable.mjs +14 -0
  188. package/dist/util/Loggable.mjs.map +1 -0
  189. package/dist/util/dataDirectory.mjs +47 -0
  190. package/dist/util/dataDirectory.mjs.map +1 -0
  191. package/dist/util/logger.mjs +86 -0
  192. package/dist/util/logger.mjs.map +1 -0
  193. package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
  194. package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
  195. package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
  196. package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
  197. package/dist/util/migrator/types.mjs +11 -0
  198. package/dist/util/migrator/types.mjs.map +1 -0
  199. package/dist/util/migrator/validation.mjs +334 -0
  200. package/dist/util/migrator/validation.mjs.map +1 -0
  201. package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
  202. package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
  203. package/dist/util/packer/{index.js → index.cjs} +73 -9
  204. package/dist/util/packer/index.cjs.map +1 -0
  205. package/dist/util/packer/index.d.ts +3 -3
  206. package/dist/util/packer/index.mjs +2 -537
  207. package/eslint.config.mjs +9 -1
  208. package/package.json +25 -13
  209. package/rolldown.config.mjs +44 -0
  210. package/src/core/UserDBDebugger.ts +47 -46
  211. package/src/core/navigators/Pipeline.ts +10 -10
  212. package/src/core/navigators/PipelineDebugger.ts +55 -55
  213. package/src/core/navigators/filters/eloDistance.ts +1 -1
  214. package/src/core/navigators/generators/elo.ts +5 -1
  215. package/src/core/navigators/index.ts +9 -3
  216. package/src/factory.ts +10 -1
  217. package/src/impl/common/BaseUserDB.ts +1 -3
  218. package/src/impl/common/index.ts +2 -0
  219. package/src/impl/common/userDBHelpers.ts +4 -58
  220. package/src/impl/common/userDBKeys.ts +64 -0
  221. package/src/impl/couch/courseDB.ts +15 -3
  222. package/src/impl/couch/index.ts +2 -18
  223. package/src/impl/couch/pouchdb-setup.ts +8 -0
  224. package/src/index.ts +1 -1
  225. package/src/study/MixerDebugger.ts +46 -46
  226. package/src/study/SessionDebugger.ts +20 -20
  227. package/src/study/SessionOverlay.ts +4 -4
  228. package/src/util/logger.ts +112 -13
  229. package/tests/core/navigators/eloGenerator.test.ts +36 -0
  230. package/tsup.config.ts +24 -21
  231. package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
  232. package/dist/classroomDB-DLTtLZct.d.cts +0 -86
  233. package/dist/contentSource-FQZcZopC.d.cts +0 -2007
  234. package/dist/core/index.d.cts +0 -521
  235. package/dist/core/index.js.map +0 -1
  236. package/dist/core/index.mjs.map +0 -1
  237. package/dist/dataLayerProvider-3y21KtF-.d.cts +0 -61
  238. package/dist/diagnostics/index.d.cts +0 -561
  239. package/dist/diagnostics/index.mjs.map +0 -1
  240. package/dist/impl/couch/index.d.cts +0 -620
  241. package/dist/impl/couch/index.js.map +0 -1
  242. package/dist/impl/static/index.d.cts +0 -232
  243. package/dist/impl/static/index.js.map +0 -1
  244. package/dist/impl/static/index.mjs.map +0 -1
  245. package/dist/index-BIum9Ue2.d.cts +0 -137
  246. package/dist/index.d.cts +0 -1663
  247. package/dist/index.js.map +0 -1
  248. package/dist/index.mjs.map +0 -1
  249. package/dist/pouch/index.d.cts +0 -1
  250. package/dist/pouch/index.js.map +0 -1
  251. package/dist/pouch/index.mjs.map +0 -1
  252. package/dist/types-BcWVH4ww.d.cts +0 -58
  253. package/dist/types-legacy-DdVjg81H.d.ts +0 -168
  254. package/dist/util/packer/index.d.cts +0 -5
  255. package/dist/util/packer/index.js.map +0 -1
  256. package/dist/util/packer/index.mjs.map +0 -1
  257. package/src/study/getCardDataShape.ts +0 -34
  258. /package/dist/diagnostics/{index.js.map → index.cjs.map} +0 -0
@@ -0,0 +1,217 @@
1
+ import "../../_virtual/_rolldown/runtime.mjs";
2
+ import { logger } from "../../util/logger.mjs";
3
+ import { recordTagPresentations } from "./tagRecent.mjs";
4
+ import { adjustCourseScores, adjustCourseScoresPerTag, isCountOnlyTag, toCourseElo } from "@vue-skuilder/common";
5
+ //#region src/study/services/EloService.ts
6
+ /**
7
+ * The question's performance with bookkeeping-role tags (`expose`, `intro`;
8
+ * see common's tagRoles.ts) as count-only. A score sent for one is counted,
9
+ * not graded, and logged: it's a question-side slip against the convention.
10
+ */
11
+ function withCountOnlyRoles(perf, cardId) {
12
+ const out = { ...perf };
13
+ const counted = [];
14
+ for (const [tag, score] of Object.entries(perf)) {
15
+ if (tag === "_global" || score === null || !isCountOnlyTag(tag)) continue;
16
+ out[tag] = null;
17
+ counted.push(tag);
18
+ }
19
+ if (counted.length) logger.warn(`[EloService] ${cardId} sent scores for bookkeeping tags [${counted.join(", ")}]; counted, not graded`);
20
+ return out;
21
+ }
22
+ /**
23
+ * Service responsible for ELO rating calculations and updates.
24
+ */
25
+ var EloService = class {
26
+ dataLayer;
27
+ user;
28
+ /** Per course ID: its compiled `CourseConfig.qaUsernamePattern`, or null. */
29
+ qaPatterns = /* @__PURE__ */ new Map();
30
+ constructor(dataLayer, user) {
31
+ this.dataLayer = dataLayer;
32
+ this.user = user;
33
+ }
34
+ /**
35
+ * Whether the current user is one of the course's QA accounts
36
+ * (`CourseConfig.qaUsernamePattern`), whose responses must not move card
37
+ * ELO. The pattern is read once per course. If the config is unreadable or
38
+ * the pattern doesn't compile, nobody is a QA account.
39
+ */
40
+ async isQaUser(courseDB) {
41
+ const courseId = courseDB.getCourseID();
42
+ let pattern = this.qaPatterns.get(courseId);
43
+ if (!pattern) {
44
+ pattern = courseDB.getCourseConfig().then((cfg) => cfg.qaUsernamePattern ? new RegExp(cfg.qaUsernamePattern, "i") : null).catch((e) => {
45
+ logger.warn(`[EloService] No QA username pattern for ${courseId}: ${e}`);
46
+ return null;
47
+ });
48
+ this.qaPatterns.set(courseId, pattern);
49
+ }
50
+ return (await pattern)?.test(this.user.getUsername()) ?? false;
51
+ }
52
+ /**
53
+ * Updates both user and card ELO ratings based on user performance.
54
+ * @param userScore Score between 0-1 representing user performance
55
+ * @param course_id Course identifier
56
+ * @param card_id Card identifier
57
+ * @param userCourseRegDoc User's course registration document (will be mutated)
58
+ * @param currentCard Current card session record
59
+ * @param k Optional K-factor for ELO calculation
60
+ * @returns The captured before→after exchange for session logging, or null
61
+ * if no update was applied (missing registration / unreadable ELO).
62
+ */
63
+ async updateUserAndCardElo(userScore, course_id, card_id, userCourseRegDoc, currentCard, k) {
64
+ if (k) logger.warn(`k value interpretation not currently implemented`);
65
+ const courseDB = this.dataLayer.getCourseDB(currentCard.card.course_id);
66
+ const courseReg = userCourseRegDoc.courses.find((c) => c.courseID === course_id);
67
+ if (!courseReg) {
68
+ logger.error(`[EloService] No registration for course ${course_id} on user's registration doc — skipping ELO update for card ${card_id}. (Is the user registered for this course?)`);
69
+ return null;
70
+ }
71
+ const userElo = toCourseElo(courseReg.elo);
72
+ const cardElo = (await courseDB.getCardEloData([currentCard.card.card_id]))[0];
73
+ if (cardElo && userElo) {
74
+ const writeCard = !await this.isQaUser(courseDB);
75
+ const beforeUserGlobal = userElo.global.score;
76
+ const beforeCardGlobal = cardElo.global.score;
77
+ const cardTagKeys = Object.keys(cardElo.tags);
78
+ const beforeUserTag = {};
79
+ for (const tag of cardTagKeys) beforeUserTag[tag] = userElo.tags[tag]?.score ?? userElo.global.score;
80
+ const eloUpdate = adjustCourseScores(userElo, cardElo, userScore);
81
+ courseReg.elo = eloUpdate.userElo;
82
+ const tags = {};
83
+ for (const tag of cardTagKeys) {
84
+ const countOnly = isCountOnlyTag(tag);
85
+ tags[tag] = {
86
+ before: beforeUserTag[tag],
87
+ after: countOnly ? beforeUserTag[tag] : eloUpdate.userElo.tags[tag].score,
88
+ score: countOnly ? null : userScore
89
+ };
90
+ }
91
+ const event = {
92
+ cardId: card_id,
93
+ at: (/* @__PURE__ */ new Date()).toISOString(),
94
+ userScore,
95
+ global: {
96
+ before: beforeUserGlobal,
97
+ after: eloUpdate.userElo.global.score
98
+ },
99
+ card: {
100
+ before: beforeCardGlobal,
101
+ after: writeCard ? eloUpdate.cardElo.global.score : beforeCardGlobal
102
+ },
103
+ ...cardTagKeys.length ? { tags } : {}
104
+ };
105
+ if (!writeCard) logger.info(`[EloService] QA account: card ELO for ${card_id} not written`);
106
+ const results = await Promise.allSettled([this.user.updateUserElo(course_id, eloUpdate.userElo), writeCard ? courseDB.updateCardElo(card_id, eloUpdate.cardElo) : Promise.resolve(null)]);
107
+ const userEloStatus = results[0].status === "fulfilled";
108
+ const cardEloStatus = results[1].status === "fulfilled";
109
+ if (userEloStatus && cardEloStatus) {
110
+ const user = results[0].value;
111
+ const card = results[1].value;
112
+ if (user.ok && card && card.ok) logger.info(`[EloService] Updated ELOS:
113
+ \tUser: ${JSON.stringify(eloUpdate.userElo)})
114
+ \tCard: ${JSON.stringify(eloUpdate.cardElo)})
115
+ `);
116
+ } else {
117
+ logger.warn(`[EloService] Partial ELO update:
118
+ \tUser ELO update: ${userEloStatus ? "SUCCESS" : "FAILED"}
119
+ \tCard ELO update: ${cardEloStatus ? "SUCCESS" : "FAILED"}`);
120
+ if (!userEloStatus && results[0].status === "rejected") logger.error("[EloService] User ELO update error:", results[0].reason);
121
+ if (!cardEloStatus && results[1].status === "rejected") logger.error("[EloService] Card ELO update error:", results[1].reason);
122
+ }
123
+ return event;
124
+ }
125
+ return null;
126
+ }
127
+ /**
128
+ * Updates both user and card ELO ratings with per-tag granularity.
129
+ * Tags in taggedPerformance but not on card will be created dynamically.
130
+ *
131
+ * @param taggedPerformance Performance object with _global and per-tag scores
132
+ * @param course_id Course identifier
133
+ * @param card_id Card identifier
134
+ * @param userCourseRegDoc User's course registration document (will be mutated)
135
+ * @param currentCard Current card session record
136
+ */
137
+ async updateUserAndCardEloPerTag(taggedPerformance, course_id, card_id, userCourseRegDoc, currentCard) {
138
+ const courseDB = this.dataLayer.getCourseDB(currentCard.card.course_id);
139
+ const courseReg = userCourseRegDoc.courses.find((c) => c.courseID === course_id);
140
+ if (!courseReg) {
141
+ logger.error(`[EloService] No registration for course ${course_id} on user's registration doc — skipping per-tag ELO update for card ${card_id}. (Is the user registered for this course?)`);
142
+ return null;
143
+ }
144
+ const userElo = toCourseElo(courseReg.elo);
145
+ const [cardEloResults, cardTagsMap] = await Promise.all([courseDB.getCardEloData([currentCard.card.card_id]), courseDB.getAppliedTagsBatch([card_id])]);
146
+ const cardElo = cardEloResults[0];
147
+ const cardTags = cardTagsMap.get(card_id) ?? [];
148
+ const graded = withCountOnlyRoles(taggedPerformance, card_id);
149
+ const enriched = { ...graded };
150
+ const globalScore = taggedPerformance._global;
151
+ for (const tag of cardTags) if (!(tag in enriched)) enriched[tag] = isCountOnlyTag(tag) ? null : globalScore;
152
+ if (cardElo && userElo) {
153
+ const writeCard = !await this.isQaUser(courseDB);
154
+ const beforeUserGlobal = userElo.global.score;
155
+ const beforeCardGlobal = cardElo.global.score;
156
+ const touchedTags = Object.keys(enriched).filter((key) => key !== "_global");
157
+ const beforeUserTag = {};
158
+ for (const tag of touchedTags) beforeUserTag[tag] = userElo.tags[tag]?.score ?? userElo.global.score;
159
+ const eloUpdate = adjustCourseScoresPerTag(userElo, cardElo, enriched);
160
+ const at = (/* @__PURE__ */ new Date()).toISOString();
161
+ const recorded = recordTagPresentations(eloUpdate.userElo, graded, currentCard.records, card_id, at);
162
+ if (recorded.length) logger.info(`[EloService] recent-presentation entries for ${card_id}: [${recorded.join(", ")}]`);
163
+ courseReg.elo = eloUpdate.userElo;
164
+ const tags = {};
165
+ for (const tag of touchedTags) {
166
+ const score = enriched[tag];
167
+ const after = score === null ? beforeUserTag[tag] : eloUpdate.userElo.tags[tag]?.score ?? beforeUserTag[tag];
168
+ tags[tag] = {
169
+ before: beforeUserTag[tag],
170
+ after,
171
+ score
172
+ };
173
+ }
174
+ const event = {
175
+ cardId: card_id,
176
+ at,
177
+ userScore: globalScore,
178
+ global: {
179
+ before: beforeUserGlobal,
180
+ after: eloUpdate.userElo.global.score
181
+ },
182
+ card: {
183
+ before: beforeCardGlobal,
184
+ after: writeCard ? eloUpdate.cardElo.global.score : beforeCardGlobal
185
+ },
186
+ ...touchedTags.length ? { tags } : {}
187
+ };
188
+ if (!writeCard) logger.info(`[EloService] QA account: card ELO for ${card_id} not written`);
189
+ const results = await Promise.allSettled([this.user.updateUserElo(course_id, eloUpdate.userElo), writeCard ? courseDB.updateCardElo(card_id, eloUpdate.cardElo) : Promise.resolve(null)]);
190
+ const userEloStatus = results[0].status === "fulfilled";
191
+ const cardEloStatus = results[1].status === "fulfilled";
192
+ if (userEloStatus && cardEloStatus) {
193
+ const user = results[0].value;
194
+ const card = results[1].value;
195
+ if (user.ok && card && card.ok) {
196
+ const tagCount = Object.keys(enriched).length - 1;
197
+ logger.info(`[EloService] Updated ELOS (per-tag, ${tagCount} tags):
198
+ \tUser: ${JSON.stringify(eloUpdate.userElo)})
199
+ \tCard: ${JSON.stringify(eloUpdate.cardElo)})
200
+ `);
201
+ }
202
+ } else {
203
+ logger.warn(`[EloService] Partial ELO update (per-tag):
204
+ \tUser ELO update: ${userEloStatus ? "SUCCESS" : "FAILED"}
205
+ \tCard ELO update: ${cardEloStatus ? "SUCCESS" : "FAILED"}`);
206
+ if (!userEloStatus && results[0].status === "rejected") logger.error("[EloService] User ELO update error:", results[0].reason);
207
+ if (!cardEloStatus && results[1].status === "rejected") logger.error("[EloService] Card ELO update error:", results[1].reason);
208
+ }
209
+ return event;
210
+ }
211
+ return null;
212
+ }
213
+ };
214
+ //#endregion
215
+ export { EloService };
216
+
217
+ //# sourceMappingURL=EloService.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"EloService.mjs","names":[],"sources":["../../../src/study/services/EloService.ts"],"sourcesContent":["import {\n adjustCourseScores,\n adjustCourseScoresPerTag,\n isCountOnlyTag,\n toCourseElo,\n TaggedPerformance,\n} from '@vue-skuilder/common';\nimport {\n CourseDBInterface,\n DataLayerProvider,\n UserDBInterface,\n CourseRegistrationDoc,\n SessionEloEvent,\n} from '@db/core';\nimport { StudySessionRecord } from '../SessionController';\nimport { logger } from '@db/util/logger';\nimport { recordTagPresentations } from './tagRecent';\n\n/**\n * The question's performance with bookkeeping-role tags (`expose`, `intro`;\n * see common's tagRoles.ts) as count-only. A score sent for one is counted,\n * not graded, and logged: it's a question-side slip against the convention.\n */\nfunction withCountOnlyRoles(perf: TaggedPerformance, cardId: string): TaggedPerformance {\n const out: TaggedPerformance = { ...perf };\n const counted: string[] = [];\n for (const [tag, score] of Object.entries(perf)) {\n if (tag === '_global' || score === null || !isCountOnlyTag(tag)) continue;\n out[tag] = null;\n counted.push(tag);\n }\n if (counted.length) {\n logger.warn(\n `[EloService] ${cardId} sent scores for bookkeeping tags [${counted.join(', ')}]; ` +\n `counted, not graded`\n );\n }\n return out;\n}\n\n/**\n * Service responsible for ELO rating calculations and updates.\n */\nexport class EloService {\n private dataLayer: DataLayerProvider;\n private user: UserDBInterface;\n /** Per course ID: its compiled `CourseConfig.qaUsernamePattern`, or null. */\n private qaPatterns = new Map<string, Promise<RegExp | null>>();\n\n constructor(dataLayer: DataLayerProvider, user: UserDBInterface) {\n this.dataLayer = dataLayer;\n this.user = user;\n }\n\n /**\n * Whether the current user is one of the course's QA accounts\n * (`CourseConfig.qaUsernamePattern`), whose responses must not move card\n * ELO. The pattern is read once per course. If the config is unreadable or\n * the pattern doesn't compile, nobody is a QA account.\n */\n private async isQaUser(courseDB: CourseDBInterface): Promise<boolean> {\n const courseId = courseDB.getCourseID();\n let pattern = this.qaPatterns.get(courseId);\n if (!pattern) {\n pattern = courseDB\n .getCourseConfig()\n .then((cfg) => (cfg.qaUsernamePattern ? new RegExp(cfg.qaUsernamePattern, 'i') : null))\n .catch((e) => {\n logger.warn(`[EloService] No QA username pattern for ${courseId}: ${e}`);\n return null;\n });\n this.qaPatterns.set(courseId, pattern);\n }\n return (await pattern)?.test(this.user.getUsername()) ?? false;\n }\n\n /**\n * Updates both user and card ELO ratings based on user performance.\n * @param userScore Score between 0-1 representing user performance\n * @param course_id Course identifier\n * @param card_id Card identifier\n * @param userCourseRegDoc User's course registration document (will be mutated)\n * @param currentCard Current card session record\n * @param k Optional K-factor for ELO calculation\n * @returns The captured before→after exchange for session logging, or null\n * if no update was applied (missing registration / unreadable ELO).\n */\n public async updateUserAndCardElo(\n userScore: number,\n course_id: string,\n card_id: string,\n userCourseRegDoc: CourseRegistrationDoc,\n currentCard: StudySessionRecord,\n k?: number\n ): Promise<SessionEloEvent | null> {\n if (k) {\n logger.warn(`k value interpretation not currently implemented`);\n }\n const courseDB = this.dataLayer.getCourseDB(currentCard.card.course_id);\n const courseReg = userCourseRegDoc.courses.find((c) => c.courseID === course_id);\n if (!courseReg) {\n logger.error(\n `[EloService] No registration for course ${course_id} on user's registration doc — ` +\n `skipping ELO update for card ${card_id}. (Is the user registered for this course?)`\n );\n return null;\n }\n const userElo = toCourseElo(courseReg.elo);\n const cardElo = (await courseDB.getCardEloData([currentCard.card.card_id]))[0];\n\n if (cardElo && userElo) {\n // A QA account's update is computed in full but only the user side is\n // written; the event records the card as unmoved.\n const writeCard = !(await this.isQaUser(courseDB));\n\n // Capture before-scores as numbers up front: adjustCourseScores mutates\n // userElo/cardElo in place (and returns the same refs). This path grades\n // every tag already present on the card with the single global score.\n const beforeUserGlobal = userElo.global.score;\n const beforeCardGlobal = cardElo.global.score;\n const cardTagKeys = Object.keys(cardElo.tags);\n const beforeUserTag: Record<string, number> = {};\n for (const tag of cardTagKeys) {\n beforeUserTag[tag] = userElo.tags[tag]?.score ?? userElo.global.score;\n }\n\n const eloUpdate = adjustCourseScores(userElo, cardElo, userScore);\n courseReg.elo = eloUpdate.userElo;\n\n const tags: NonNullable<SessionEloEvent['tags']> = {};\n for (const tag of cardTagKeys) {\n // Bookkeeping roles are only counted: recorded as count-only, as below.\n const countOnly = isCountOnlyTag(tag);\n tags[tag] = {\n before: beforeUserTag[tag],\n after: countOnly ? beforeUserTag[tag] : eloUpdate.userElo.tags[tag].score,\n score: countOnly ? null : userScore,\n };\n }\n const event: SessionEloEvent = {\n cardId: card_id,\n at: new Date().toISOString(),\n userScore,\n global: { before: beforeUserGlobal, after: eloUpdate.userElo.global.score },\n card: {\n before: beforeCardGlobal,\n after: writeCard ? eloUpdate.cardElo.global.score : beforeCardGlobal,\n },\n ...(cardTagKeys.length ? { tags } : {}),\n };\n\n if (!writeCard) {\n logger.info(`[EloService] QA account: card ELO for ${card_id} not written`);\n }\n const results = await Promise.allSettled([\n this.user.updateUserElo(course_id, eloUpdate.userElo),\n writeCard ? courseDB.updateCardElo(card_id, eloUpdate.cardElo) : Promise.resolve(null),\n ]);\n\n // Check the results of each operation\n const userEloStatus = results[0].status === 'fulfilled';\n const cardEloStatus = results[1].status === 'fulfilled';\n\n if (userEloStatus && cardEloStatus) {\n const user = (results[0] as PromiseFulfilledResult<any>).value;\n const card = (results[1] as PromiseFulfilledResult<any>).value;\n\n if (user.ok && card && card.ok) {\n logger.info(\n `[EloService] Updated ELOS:\n \\tUser: ${JSON.stringify(eloUpdate.userElo)})\n \\tCard: ${JSON.stringify(eloUpdate.cardElo)})\n `\n );\n }\n } else {\n // Log which operations succeeded and which failed\n logger.warn(\n `[EloService] Partial ELO update:\n \\tUser ELO update: ${userEloStatus ? 'SUCCESS' : 'FAILED'}\n \\tCard ELO update: ${cardEloStatus ? 'SUCCESS' : 'FAILED'}`\n );\n\n if (!userEloStatus && results[0].status === 'rejected') {\n logger.error('[EloService] User ELO update error:', results[0].reason);\n }\n\n if (!cardEloStatus && results[1].status === 'rejected') {\n logger.error('[EloService] Card ELO update error:', results[1].reason);\n }\n }\n\n return event;\n }\n\n return null;\n }\n\n /**\n * Updates both user and card ELO ratings with per-tag granularity.\n * Tags in taggedPerformance but not on card will be created dynamically.\n *\n * @param taggedPerformance Performance object with _global and per-tag scores\n * @param course_id Course identifier\n * @param card_id Card identifier\n * @param userCourseRegDoc User's course registration document (will be mutated)\n * @param currentCard Current card session record\n */\n public async updateUserAndCardEloPerTag(\n taggedPerformance: TaggedPerformance,\n course_id: string,\n card_id: string,\n userCourseRegDoc: CourseRegistrationDoc,\n currentCard: StudySessionRecord\n ): Promise<SessionEloEvent | null> {\n const courseDB = this.dataLayer.getCourseDB(currentCard.card.course_id);\n const courseReg = userCourseRegDoc.courses.find((c) => c.courseID === course_id);\n if (!courseReg) {\n logger.error(\n `[EloService] No registration for course ${course_id} on user's registration doc — ` +\n `skipping per-tag ELO update for card ${card_id}. (Is the user registered for this course?)`\n );\n return null;\n }\n const userElo = toCourseElo(courseReg.elo);\n\n const [cardEloResults, cardTagsMap] = await Promise.all([\n courseDB.getCardEloData([currentCard.card.card_id]),\n courseDB.getAppliedTagsBatch([card_id]),\n ]);\n const cardElo = cardEloResults[0];\n\n // Enrich TaggedPerformance with card-level tags not explicitly graded by\n // the question's evaluate(). Category tags (concept:*, ui:*, etc.) are not\n // emitted by individual question types; applying the global score as a proxy\n // keeps hierarchy filter ELO thresholds functional without overriding any\n // fine-grained per-GPC scores the question already provided. Bookkeeping\n // roles (expose, intro) are counted instead, whoever supplies them.\n const cardTags = cardTagsMap.get(card_id) ?? [];\n const graded = withCountOnlyRoles(taggedPerformance, card_id);\n const enriched: TaggedPerformance = { ...graded };\n const globalScore = taggedPerformance._global;\n for (const tag of cardTags) {\n if (!(tag in enriched)) {\n enriched[tag] = isCountOnlyTag(tag) ? null : globalScore;\n }\n }\n\n if (cardElo && userElo) {\n // A QA account's update is computed in full but only the user side is\n // written; the event records the card as unmoved.\n const writeCard = !(await this.isQaUser(courseDB));\n\n // Capture before-scores up front — adjustCourseScoresPerTag mutates the\n // ELO objects in place. Every tag in `enriched` (except _global) is\n // touched; count-only tags (null score) increment count without moving\n // ELO and are recorded with score: null.\n const beforeUserGlobal = userElo.global.score;\n const beforeCardGlobal = cardElo.global.score;\n const touchedTags = Object.keys(enriched).filter((key) => key !== '_global');\n const beforeUserTag: Record<string, number> = {};\n for (const tag of touchedTags) {\n beforeUserTag[tag] = userElo.tags[tag]?.score ?? userElo.global.score;\n }\n\n const eloUpdate = adjustCourseScoresPerTag(userElo, cardElo, enriched);\n const at = new Date().toISOString();\n\n // Mastery signal: one ring-buffer entry per scored tag per presentation.\n // Retries (priorAttemps > 0 on the current record) add nothing — that\n // includes the dismiss-failed penalty, which lands here on a retry.\n // Only the question's own graded tags count, not the card-level tags\n // enriched with the global score above.\n const recorded = recordTagPresentations(\n eloUpdate.userElo,\n graded,\n currentCard.records,\n card_id,\n at\n );\n if (recorded.length) {\n logger.info(`[EloService] recent-presentation entries for ${card_id}: [${recorded.join(', ')}]`);\n }\n\n courseReg.elo = eloUpdate.userElo;\n\n const tags: NonNullable<SessionEloEvent['tags']> = {};\n for (const tag of touchedTags) {\n const score = enriched[tag];\n // Count-only exposure tags (null score) get a -1 sentinel score, not a\n // real ELO move — record before===after so a naive after-before reads 0.\n const after =\n score === null ? beforeUserTag[tag] : eloUpdate.userElo.tags[tag]?.score ?? beforeUserTag[tag];\n tags[tag] = { before: beforeUserTag[tag], after, score };\n }\n const event: SessionEloEvent = {\n cardId: card_id,\n at,\n userScore: globalScore,\n global: { before: beforeUserGlobal, after: eloUpdate.userElo.global.score },\n card: {\n before: beforeCardGlobal,\n after: writeCard ? eloUpdate.cardElo.global.score : beforeCardGlobal,\n },\n ...(touchedTags.length ? { tags } : {}),\n };\n\n if (!writeCard) {\n logger.info(`[EloService] QA account: card ELO for ${card_id} not written`);\n }\n const results = await Promise.allSettled([\n this.user.updateUserElo(course_id, eloUpdate.userElo),\n writeCard ? courseDB.updateCardElo(card_id, eloUpdate.cardElo) : Promise.resolve(null),\n ]);\n\n // Check the results of each operation\n const userEloStatus = results[0].status === 'fulfilled';\n const cardEloStatus = results[1].status === 'fulfilled';\n\n if (userEloStatus && cardEloStatus) {\n const user = (results[0] as PromiseFulfilledResult<any>).value;\n const card = (results[1] as PromiseFulfilledResult<any>).value;\n\n if (user.ok && card && card.ok) {\n const tagCount = Object.keys(enriched).length - 1; // exclude _global\n logger.info(\n `[EloService] Updated ELOS (per-tag, ${tagCount} tags):\n \\tUser: ${JSON.stringify(eloUpdate.userElo)})\n \\tCard: ${JSON.stringify(eloUpdate.cardElo)})\n `\n );\n }\n } else {\n // Log which operations succeeded and which failed\n logger.warn(\n `[EloService] Partial ELO update (per-tag):\n \\tUser ELO update: ${userEloStatus ? 'SUCCESS' : 'FAILED'}\n \\tCard ELO update: ${cardEloStatus ? 'SUCCESS' : 'FAILED'}`\n );\n\n if (!userEloStatus && results[0].status === 'rejected') {\n logger.error('[EloService] User ELO update error:', results[0].reason);\n }\n\n if (!cardEloStatus && results[1].status === 'rejected') {\n logger.error('[EloService] Card ELO update error:', results[1].reason);\n }\n }\n\n return event;\n }\n\n return null;\n }\n}\n"],"mappings":";;;;;;;;;;AAuBA,SAAS,mBAAmB,MAAyB,QAAmC;CACtF,MAAM,MAAyB,EAAE,GAAG,MAAM;CAC1C,MAAM,UAAoB,EAAE;AAC5B,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,EAAE;AAC/C,MAAI,QAAQ,aAAa,UAAU,QAAQ,CAAC,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,GAAmC;IACzD,MAAM,OAAQ,QAAQ,GAAmC;AAEzD,QAAI,KAAK,MAAM,QAAQ,KAAK,IAAI;KAC9B,MAAM,WAAW,OAAO,KAAK,SAAS,CAAC,SAAS;AAChD,YAAO,KACL,uCAAuC,SAAS;sBACtC,KAAK,UAAU,UAAU,QAAQ,CAAC;sBAClC,KAAK,UAAU,UAAU,QAAQ,CAAC;cAE7C;;UAEE;AAEL,WAAO,KACL;+BACqB,gBAAgB,YAAY,SAAS;+BACrC,gBAAgB,YAAY,WAClD;AAED,QAAI,CAAC,iBAAiB,QAAQ,GAAG,WAAW,WAC1C,QAAO,MAAM,uCAAuC,QAAQ,GAAG,OAAO;AAGxE,QAAI,CAAC,iBAAiB,QAAQ,GAAG,WAAW,WAC1C,QAAO,MAAM,uCAAuC,QAAQ,GAAG,OAAO;;AAI1E,UAAO;;AAGT,SAAO"}
@@ -0,0 +1,190 @@
1
+ import "../../_virtual/_rolldown/runtime.mjs";
2
+ import { logger } from "../../util/logger.mjs";
3
+ import { isQuestionRecord } from "../../core/util/index.mjs";
4
+ import { isTaggedPerformance } from "@vue-skuilder/common";
5
+ //#region src/study/services/ResponseProcessor.ts
6
+ /**
7
+ * Service responsible for orchestrating the complete response processing workflow.
8
+ * Coordinates SRS scheduling and ELO updates for user card interactions.
9
+ */
10
+ var ResponseProcessor = class {
11
+ srsService;
12
+ eloService;
13
+ /** Sink for resolved ELO exchanges, wired to the session's in-memory log. */
14
+ onEloEvent;
15
+ constructor(srsService, eloService, onEloEvent) {
16
+ this.srsService = srsService;
17
+ this.eloService = eloService;
18
+ this.onEloEvent = onEloEvent;
19
+ }
20
+ /**
21
+ * ELO updates are fired without awaiting so response handling isn't blocked
22
+ * on DB writes — but an unhandled rejection silently drops the update.
23
+ * This produces a catch handler that surfaces the failure in logs.
24
+ */
25
+ logEloFailure(context, cardId) {
26
+ return (e) => logger.error(`[ResponseProcessor] ELO update failed (${context}) for ${cardId}:`, e);
27
+ }
28
+ /**
29
+ * Fire an ELO update without blocking response handling, forwarding the
30
+ * resolved exchange to the session log (if any) and surfacing failures.
31
+ * Mirrors the previous `void update(...).catch(logEloFailure)` shape, with
32
+ * the added `.then` capturing the before→after event for diagnostics.
33
+ */
34
+ trackElo(update, context, cardId) {
35
+ update.then((event) => {
36
+ if (event) this.onEloEvent?.(event);
37
+ }).catch(this.logEloFailure(context, cardId));
38
+ }
39
+ /**
40
+ * Parses performance data into global score and optional per-tag scores.
41
+ *
42
+ * @param performance - Numeric or structured performance from QuestionRecord
43
+ * @returns Parsed performance with global score and optional tag scores
44
+ */
45
+ parsePerformance(performance) {
46
+ if (typeof performance === "number") return {
47
+ globalScore: performance,
48
+ taggedPerformance: null
49
+ };
50
+ if (isTaggedPerformance(performance)) return {
51
+ globalScore: performance._global,
52
+ taggedPerformance: performance
53
+ };
54
+ logger.warn("[ResponseProcessor] Unexpected performance structure, using neutral score", { performance });
55
+ return {
56
+ globalScore: .5,
57
+ taggedPerformance: null
58
+ };
59
+ }
60
+ /**
61
+ * Processes a user's response to a card, handling SRS scheduling and ELO updates.
62
+ * @param cardRecord User's response record
63
+ * @param cardHistory Promise resolving to the card's history
64
+ * @param studySessionItem Current study session item
65
+ * @param courseRegistrationDoc User's course registration (for ELO updates)
66
+ * @param currentCard Current study session record
67
+ * @param courseId Course identifier
68
+ * @param cardId Card identifier
69
+ * @param maxAttemptsPerView Maximum attempts allowed per view
70
+ * @param maxSessionViews Maximum session views for this card
71
+ * @param sessionViews Current number of session views
72
+ * @returns ResponseResult with navigation and UI instructions
73
+ */
74
+ async processResponse(cardRecord, cardHistory, studySessionItem, courseRegistrationDoc, currentCard, courseId, cardId, maxAttemptsPerView, maxSessionViews, sessionViews) {
75
+ if (!isQuestionRecord(cardRecord)) return {
76
+ nextCardAction: "dismiss-success",
77
+ shouldLoadNextCard: true,
78
+ isCorrect: true,
79
+ shouldClearFeedbackShadow: true
80
+ };
81
+ try {
82
+ const history = await cardHistory;
83
+ let result;
84
+ if (cardRecord.isCorrect) result = this.processCorrectResponse(cardRecord, history, studySessionItem, courseRegistrationDoc, currentCard, courseId, cardId, maxSessionViews, sessionViews);
85
+ else result = this.processIncorrectResponse(cardRecord, history, courseRegistrationDoc, currentCard, courseId, cardId, maxAttemptsPerView, maxSessionViews, sessionViews);
86
+ if (cardRecord.deferAdvance && result.shouldLoadNextCard) {
87
+ logger.info("[ResponseProcessor] deferAdvance requested — suppressing navigation, action stashed:", { nextCardAction: result.nextCardAction });
88
+ result = {
89
+ ...result,
90
+ shouldLoadNextCard: false,
91
+ deferred: true
92
+ };
93
+ }
94
+ return result;
95
+ } catch (e) {
96
+ logger.error("[ResponseProcessor] Failed to load card history", {
97
+ e,
98
+ cardId
99
+ });
100
+ throw e;
101
+ }
102
+ }
103
+ /**
104
+ * Handles processing for correct responses: SRS scheduling and ELO updates.
105
+ */
106
+ processCorrectResponse(cardRecord, history, studySessionItem, courseRegistrationDoc, currentCard, courseId, cardId, maxSessionViews, sessionViews) {
107
+ if (cardRecord.priorAttemps === 0) {
108
+ if (!currentCard.card.tags.includes("srs:skip")) this.srsService.scheduleReview(history, studySessionItem);
109
+ const { globalScore, taggedPerformance } = this.parsePerformance(cardRecord.performance);
110
+ if (taggedPerformance) {
111
+ const tagKeys = Object.keys(taggedPerformance).filter((k) => k !== "_global");
112
+ const nullTags = tagKeys.filter((k) => taggedPerformance[k] === null);
113
+ const scoredTags = tagKeys.filter((k) => taggedPerformance[k] !== null);
114
+ logger.info(`[FirstContactElo] correct first-attempt per-tag ELO update for ${cardId} (historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps}): scored=[${scoredTags.join(", ")}] count-only=[${nullTags.join(", ")}]`);
115
+ this.trackElo(this.eloService.updateUserAndCardEloPerTag(taggedPerformance, courseId, cardId, courseRegistrationDoc, currentCard), "correct per-tag", cardId);
116
+ } else {
117
+ const userScore = .5 + globalScore / 2;
118
+ if (history.records.length === 1) this.trackElo(this.eloService.updateUserAndCardElo(userScore, courseId, cardId, courseRegistrationDoc, currentCard), "correct", cardId);
119
+ else {
120
+ const k = Math.ceil(32 / history.records.length);
121
+ this.trackElo(this.eloService.updateUserAndCardElo(userScore, courseId, cardId, courseRegistrationDoc, currentCard, k), "correct repeat-view", cardId);
122
+ }
123
+ logger.info(`[FirstContactElo] correct first-attempt ELO update (score=${userScore.toFixed(3)}) for ${cardId} (historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps})`);
124
+ }
125
+ return {
126
+ nextCardAction: "dismiss-success",
127
+ shouldLoadNextCard: true,
128
+ isCorrect: true,
129
+ performanceScore: globalScore,
130
+ shouldClearFeedbackShadow: true
131
+ };
132
+ } else {
133
+ const budgetSpent = sessionViews >= maxSessionViews;
134
+ logger.info(`[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); sessionViews=${sessionViews}/${maxSessionViews} -> ${budgetSpent ? "dismiss-success" : "marked-failed"}`);
135
+ const { globalScore } = this.parsePerformance(cardRecord.performance);
136
+ return {
137
+ nextCardAction: budgetSpent ? "dismiss-success" : "marked-failed",
138
+ shouldLoadNextCard: true,
139
+ isCorrect: true,
140
+ performanceScore: globalScore,
141
+ shouldClearFeedbackShadow: true
142
+ };
143
+ }
144
+ }
145
+ /**
146
+ * Handles processing for incorrect responses: ELO updates only.
147
+ */
148
+ processIncorrectResponse(cardRecord, history, courseRegistrationDoc, currentCard, courseId, cardId, maxAttemptsPerView, maxSessionViews, sessionViews) {
149
+ const { taggedPerformance } = this.parsePerformance(cardRecord.performance);
150
+ let eloUpdated = false;
151
+ if (cardRecord.priorAttemps === 0) {
152
+ if (taggedPerformance) {
153
+ this.trackElo(this.eloService.updateUserAndCardEloPerTag(taggedPerformance, courseId, cardId, courseRegistrationDoc, currentCard), "incorrect per-tag", cardId);
154
+ logger.info(`[FirstContactElo] incorrect first-attempt per-tag ELO update for ${cardId} (historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps}, tags=${Object.keys(taggedPerformance).length - 1})`);
155
+ } else {
156
+ this.trackElo(this.eloService.updateUserAndCardElo(0, courseId, cardId, courseRegistrationDoc, currentCard), "incorrect", cardId);
157
+ logger.info(`[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${cardId} (historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps})`);
158
+ }
159
+ eloUpdated = true;
160
+ } else logger.info(`[FirstContactElo] incorrect retry — no ELO update for ${cardId} (historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps})`);
161
+ if (currentCard.records.length >= maxAttemptsPerView) if (sessionViews >= maxSessionViews) {
162
+ if (!eloUpdated) {
163
+ if (taggedPerformance) this.trackElo(this.eloService.updateUserAndCardEloPerTag(taggedPerformance, courseId, cardId, courseRegistrationDoc, currentCard), "dismiss-failed per-tag", cardId);
164
+ else this.trackElo(this.eloService.updateUserAndCardElo(0, courseId, cardId, courseRegistrationDoc, currentCard), "dismiss-failed", cardId);
165
+ logger.info(`[FirstContactElo] dismiss-failed final ELO penalty for ${cardId} (historyLen=${history.records.length}, sessionViews=${sessionViews})`);
166
+ } else logger.info(`[FirstContactElo] dismiss-failed — ELO already updated this response, skipping double penalty for ${cardId}`);
167
+ return {
168
+ nextCardAction: "dismiss-failed",
169
+ shouldLoadNextCard: true,
170
+ isCorrect: false,
171
+ shouldClearFeedbackShadow: true
172
+ };
173
+ } else return {
174
+ nextCardAction: "marked-failed",
175
+ shouldLoadNextCard: true,
176
+ isCorrect: false,
177
+ shouldClearFeedbackShadow: true
178
+ };
179
+ else return {
180
+ nextCardAction: "none",
181
+ shouldLoadNextCard: false,
182
+ isCorrect: false,
183
+ shouldClearFeedbackShadow: true
184
+ };
185
+ }
186
+ };
187
+ //#endregion
188
+ export { ResponseProcessor };
189
+
190
+ //# sourceMappingURL=ResponseProcessor.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ResponseProcessor.mjs","names":[],"sources":["../../../src/study/services/ResponseProcessor.ts"],"sourcesContent":["import {\n CardHistory,\n CardRecord,\n CourseRegistrationDoc,\n isQuestionRecord,\n QuestionRecord,\n SessionEloEvent,\n StudySessionItem,\n} from '@db/core';\nimport { logger } from '@db/util/logger';\nimport { ResponseResult, StudySessionRecord } from '../SessionController';\nimport { EloService } from './EloService';\nimport { SrsService } from './SrsService';\nimport { Performance, isTaggedPerformance, TaggedPerformance } from '@vue-skuilder/common';\n\n/**\n * Parsed performance data for ELO updates.\n */\ninterface ParsedPerformance {\n /** Global score for SRS and global ELO [0, 1] */\n globalScore: number;\n /** Per-tag scores, or null if using simple numeric performance */\n taggedPerformance: TaggedPerformance | null;\n}\n\n/**\n * Service responsible for orchestrating the complete response processing workflow.\n * Coordinates SRS scheduling and ELO updates for user card interactions.\n */\nexport class ResponseProcessor {\n private srsService: SrsService;\n private eloService: EloService;\n /** Sink for resolved ELO exchanges, wired to the session's in-memory log. */\n private onEloEvent?: (event: SessionEloEvent) => void;\n\n constructor(\n srsService: SrsService,\n eloService: EloService,\n onEloEvent?: (event: SessionEloEvent) => void\n ) {\n this.srsService = srsService;\n this.eloService = eloService;\n this.onEloEvent = onEloEvent;\n }\n\n /**\n * ELO updates are fired without awaiting so response handling isn't blocked\n * on DB writes — but an unhandled rejection silently drops the update.\n * This produces a catch handler that surfaces the failure in logs.\n */\n private logEloFailure(context: string, cardId: string): (e: unknown) => void {\n return (e) =>\n logger.error(`[ResponseProcessor] ELO update failed (${context}) for ${cardId}:`, e);\n }\n\n /**\n * Fire an ELO update without blocking response handling, forwarding the\n * resolved exchange to the session log (if any) and surfacing failures.\n * Mirrors the previous `void update(...).catch(logEloFailure)` shape, with\n * the added `.then` capturing the before→after event for diagnostics.\n */\n private trackElo(\n update: Promise<SessionEloEvent | null>,\n context: string,\n cardId: string\n ): void {\n void update\n .then((event) => {\n if (event) this.onEloEvent?.(event);\n })\n .catch(this.logEloFailure(context, cardId));\n }\n\n /**\n * Parses performance data into global score and optional per-tag scores.\n *\n * @param performance - Numeric or structured performance from QuestionRecord\n * @returns Parsed performance with global score and optional tag scores\n */\n private parsePerformance(performance: Performance): ParsedPerformance {\n if (typeof performance === 'number') {\n // Simple numeric performance - backward compatible\n return {\n globalScore: performance,\n taggedPerformance: null,\n };\n }\n\n // Structured TaggedPerformance with _global and per-tag scores\n if (isTaggedPerformance(performance)) {\n return {\n globalScore: performance._global,\n taggedPerformance: performance,\n };\n }\n\n // Fallback for unexpected structure - treat as neutral\n logger.warn('[ResponseProcessor] Unexpected performance structure, using neutral score', {\n performance,\n });\n return {\n globalScore: 0.5,\n taggedPerformance: null,\n };\n }\n\n /**\n * Processes a user's response to a card, handling SRS scheduling and ELO updates.\n * @param cardRecord User's response record\n * @param cardHistory Promise resolving to the card's history\n * @param studySessionItem Current study session item\n * @param courseRegistrationDoc User's course registration (for ELO updates)\n * @param currentCard Current study session record\n * @param courseId Course identifier\n * @param cardId Card identifier\n * @param maxAttemptsPerView Maximum attempts allowed per view\n * @param maxSessionViews Maximum session views for this card\n * @param sessionViews Current number of session views\n * @returns ResponseResult with navigation and UI instructions\n */\n public async processResponse(\n cardRecord: CardRecord,\n cardHistory: Promise<CardHistory<CardRecord>>,\n studySessionItem: StudySessionItem,\n courseRegistrationDoc: CourseRegistrationDoc,\n currentCard: StudySessionRecord,\n courseId: string,\n cardId: string,\n maxAttemptsPerView: number,\n maxSessionViews: number,\n sessionViews: number\n ): Promise<ResponseResult> {\n // Handle non-question records (simple dismiss)\n if (!isQuestionRecord(cardRecord)) {\n return {\n nextCardAction: 'dismiss-success',\n shouldLoadNextCard: true,\n isCorrect: true, // non-question records are considered \"correct\"\n shouldClearFeedbackShadow: true,\n };\n }\n\n try {\n const history = await cardHistory;\n\n let result: ResponseResult;\n\n // Handle correct responses\n if (cardRecord.isCorrect) {\n result = this.processCorrectResponse(\n cardRecord,\n history,\n studySessionItem,\n courseRegistrationDoc,\n currentCard,\n courseId,\n cardId,\n maxSessionViews,\n sessionViews\n );\n } else {\n // Handle incorrect responses\n result = this.processIncorrectResponse(\n cardRecord,\n history,\n courseRegistrationDoc,\n currentCard,\n courseId,\n cardId,\n maxAttemptsPerView,\n maxSessionViews,\n sessionViews\n );\n }\n\n // Apply deferred advancement: record is logged and ELO updated above,\n // but we suppress navigation so the view retains control of the UI\n // timeline. StudySession will stash the nextCardAction and wait for\n // a `ready-to-advance` event from the view.\n if (cardRecord.deferAdvance && result.shouldLoadNextCard) {\n logger.info(\n '[ResponseProcessor] deferAdvance requested — suppressing navigation, action stashed:',\n { nextCardAction: result.nextCardAction }\n );\n result = {\n ...result,\n shouldLoadNextCard: false,\n deferred: true,\n };\n }\n\n return result;\n } catch (e: unknown) {\n logger.error('[ResponseProcessor] Failed to load card history', { e, cardId });\n throw e;\n }\n }\n\n /**\n * Handles processing for correct responses: SRS scheduling and ELO updates.\n */\n private processCorrectResponse(\n cardRecord: QuestionRecord,\n history: CardHistory<CardRecord>,\n studySessionItem: StudySessionItem,\n courseRegistrationDoc: CourseRegistrationDoc,\n currentCard: StudySessionRecord,\n courseId: string,\n cardId: string,\n maxSessionViews: number,\n sessionViews: number\n ): ResponseResult {\n // Only schedule and update ELO for first-time attempts\n if (cardRecord.priorAttemps === 0) {\n // Schedule the card for future review based on performance (async, non-blocking)\n // Cards tagged srs:skip are one-time presentations (e.g. intro cards) — no review scheduling\n const skipSrs = currentCard.card.tags.includes('srs:skip');\n if (!skipSrs) {\n void this.srsService.scheduleReview(history, studySessionItem);\n }\n\n // Parse performance (may be numeric or structured)\n const { globalScore, taggedPerformance } = this.parsePerformance(cardRecord.performance);\n\n // Update ELO ratings\n if (taggedPerformance) {\n // Per-tag ELO update\n const tagKeys = Object.keys(taggedPerformance).filter((k) => k !== '_global');\n const nullTags = tagKeys.filter((k) => taggedPerformance[k] === null);\n const scoredTags = tagKeys.filter((k) => taggedPerformance[k] !== null);\n logger.info(\n `[FirstContactElo] correct first-attempt per-tag ELO update for ${cardId} ` +\n `(historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps}): ` +\n `scored=[${scoredTags.join(', ')}] count-only=[${nullTags.join(', ')}]`\n );\n\n this.trackElo(\n this.eloService.updateUserAndCardEloPerTag(\n taggedPerformance,\n courseId,\n cardId,\n courseRegistrationDoc,\n currentCard\n ),\n 'correct per-tag',\n cardId\n );\n } else {\n // Standard single-score ELO update (backward compatible)\n const userScore = 0.5 + globalScore / 2;\n\n if (history.records.length === 1) {\n // First interaction with this card - standard ELO update\n this.trackElo(\n this.eloService.updateUserAndCardElo(\n userScore,\n courseId,\n cardId,\n courseRegistrationDoc,\n currentCard\n ),\n 'correct',\n cardId\n );\n } else {\n // Multiple interactions - reduce K-factor to limit ELO volatility\n const k = Math.ceil(32 / history.records.length);\n this.trackElo(\n this.eloService.updateUserAndCardElo(\n userScore,\n courseId,\n cardId,\n courseRegistrationDoc,\n currentCard,\n k\n ),\n 'correct repeat-view',\n cardId\n );\n }\n logger.info(\n `[FirstContactElo] correct first-attempt ELO update (score=${userScore.toFixed(3)}) ` +\n `for ${cardId} (historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps})`\n );\n }\n\n return {\n nextCardAction: 'dismiss-success',\n shouldLoadNextCard: true,\n isCorrect: true,\n performanceScore: globalScore,\n shouldClearFeedbackShadow: true,\n };\n } else {\n // Correct, but not on the first attempt of this presentation.\n //\n // Re-present the card for consolidation — but only while there is\n // session-view budget left. This branch used to return 'marked-failed'\n // unconditionally, with no reference to sessionViews/maxSessionViews,\n // which made a *correct* answer the one outcome that could never end a\n // card's life in a session:\n //\n // present -> stumble -> get it right -> back to failedQ\n // -> re-present -> stumble -> get it right -> back to failedQ -> ...\n //\n // The incorrect path spends the budget (`sessionViews >= maxSessionViews`\n // -> 'dismiss-failed'), so the only escape was to keep answering *wrong*\n // until the card was dismissed. When supplyQ is thin the loop is also\n // tight rather than merely long: `_shouldInterleaveFailed` returns true\n // immediately with no supply available, so the same card is redrawn on\n // the very next `nextCard()` and the session reads as hung.\n const budgetSpent = sessionViews >= maxSessionViews;\n\n logger.info(\n `[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); ` +\n `sessionViews=${sessionViews}/${maxSessionViews} -> ` +\n `${budgetSpent ? 'dismiss-success' : 'marked-failed'}`\n );\n\n const { globalScore } = this.parsePerformance(cardRecord.performance);\n\n return {\n // Budget spent: the learner did get it right, so retire the card as a\n // success rather than penalising it ('dismiss-failed' would apply an\n // ELO penalty for an answer that was correct).\n nextCardAction: budgetSpent ? 'dismiss-success' : 'marked-failed',\n shouldLoadNextCard: true,\n isCorrect: true,\n performanceScore: globalScore,\n shouldClearFeedbackShadow: true,\n };\n }\n }\n\n /**\n * Handles processing for incorrect responses: ELO updates only.\n */\n private processIncorrectResponse(\n cardRecord: QuestionRecord,\n history: CardHistory<CardRecord>,\n courseRegistrationDoc: CourseRegistrationDoc,\n currentCard: StudySessionRecord,\n courseId: string,\n cardId: string,\n maxAttemptsPerView: number,\n maxSessionViews: number,\n sessionViews: number\n ): ResponseResult {\n // Parse performance (may be numeric or structured)\n const { taggedPerformance } = this.parsePerformance(cardRecord.performance);\n\n // Tracks whether this response already produced an ELO update, so the\n // dismiss-failed branch below doesn't double-penalize the same record (the\n // two coincide when maxAttemptsPerView === 1: first contact and final\n // failure land on one response).\n let eloUpdated = false;\n\n // Update ELO on the first attempt of a presentation — symmetric with the\n // correct path. Previously this was gated on `history.records.length !== 1`,\n // so first-EVER failures were skipped while first-ever successes updated,\n // biasing cold-start ELO upward. See WORKING-first-contact-elo-asymmetry.md.\n if (cardRecord.priorAttemps === 0) {\n if (taggedPerformance) {\n // Per-tag ELO update for incorrect response\n this.trackElo(\n this.eloService.updateUserAndCardEloPerTag(\n taggedPerformance,\n courseId,\n cardId,\n courseRegistrationDoc,\n currentCard\n ),\n 'incorrect per-tag',\n cardId\n );\n logger.info(\n `[FirstContactElo] incorrect first-attempt per-tag ELO update for ${cardId} ` +\n `(historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps}, ` +\n `tags=${Object.keys(taggedPerformance).length - 1})`\n );\n } else {\n // Standard single-score ELO update\n this.trackElo(\n this.eloService.updateUserAndCardElo(\n 0, // Failed response = 0 score\n courseId,\n cardId,\n courseRegistrationDoc,\n currentCard\n ),\n 'incorrect',\n cardId\n );\n logger.info(\n `[FirstContactElo] incorrect first-attempt ELO update (score=0) for ${cardId} ` +\n `(historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps})`\n );\n }\n eloUpdated = true;\n } else {\n logger.info(\n `[FirstContactElo] incorrect retry — no ELO update for ${cardId} ` +\n `(historyLen=${history.records.length}, priorAttemps=${cardRecord.priorAttemps})`\n );\n }\n\n // Determine navigation based on attempt limits\n if (currentCard.records.length >= maxAttemptsPerView) {\n if (sessionViews >= maxSessionViews) {\n // Too many session views - dismiss completely with ELO penalty.\n // Skip if this response already updated ELO above, to avoid a double\n // penalty on the same record (happens when maxAttemptsPerView === 1).\n if (!eloUpdated) {\n if (taggedPerformance) {\n // Use tagged performance for final failure\n this.trackElo(\n this.eloService.updateUserAndCardEloPerTag(\n taggedPerformance,\n courseId,\n cardId,\n courseRegistrationDoc,\n currentCard\n ),\n 'dismiss-failed per-tag',\n cardId\n );\n } else {\n this.trackElo(\n this.eloService.updateUserAndCardElo(\n 0,\n courseId,\n cardId,\n courseRegistrationDoc,\n currentCard\n ),\n 'dismiss-failed',\n cardId\n );\n }\n logger.info(\n `[FirstContactElo] dismiss-failed final ELO penalty for ${cardId} ` +\n `(historyLen=${history.records.length}, sessionViews=${sessionViews})`\n );\n } else {\n logger.info(\n `[FirstContactElo] dismiss-failed — ELO already updated this response, ` +\n `skipping double penalty for ${cardId}`\n );\n }\n return {\n nextCardAction: 'dismiss-failed',\n shouldLoadNextCard: true,\n isCorrect: false,\n shouldClearFeedbackShadow: true,\n };\n } else {\n // Mark as failed for later retry\n return {\n nextCardAction: 'marked-failed',\n shouldLoadNextCard: true,\n isCorrect: false,\n shouldClearFeedbackShadow: true,\n };\n }\n } else {\n // Allow more attempts on same card\n return {\n nextCardAction: 'none',\n shouldLoadNextCard: false,\n isCorrect: false,\n shouldClearFeedbackShadow: true,\n };\n }\n }\n}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Q,OAAO,iBAAiB,aAAa,GACvE;SAED,QAAO,KACL,qGACiC,SAClC;AAEH,UAAO;IACL,gBAAgB;IAChB,oBAAoB;IACpB,WAAW;IACX,2BAA2B;IAC5B;QAGD,QAAO;GACL,gBAAgB;GAChB,oBAAoB;GACpB,WAAW;GACX,2BAA2B;GAC5B;MAIH,QAAO;GACL,gBAAgB;GAChB,oBAAoB;GACpB,WAAW;GACX,2BAA2B;GAC5B"}
@@ -0,0 +1,49 @@
1
+ import "../../_virtual/_rolldown/runtime.mjs";
2
+ import { logger } from "../../util/logger.mjs";
3
+ import { newInterval } from "../SpacedRepetition.mjs";
4
+ import { isReview } from "../../core/interfaces/contentSource.mjs";
5
+ import moment from "moment";
6
+ //#region src/study/services/SrsService.ts
7
+ /**
8
+ * Service responsible for Spaced Repetition System (SRS) scheduling logic.
9
+ */
10
+ var SrsService = class {
11
+ user;
12
+ constructor(user) {
13
+ this.user = user;
14
+ }
15
+ /**
16
+ * Remove a scheduled review from the user's database.
17
+ * Used to clean up orphaned reviews (e.g., card deleted from course DB).
18
+ */
19
+ removeReview(reviewID) {
20
+ logger.info(`[SrsService] Removing orphaned scheduled review: ${reviewID}`);
21
+ this.user.removeScheduledCardReview(reviewID);
22
+ }
23
+ /**
24
+ * Calculates the next review time for a card based on its history and
25
+ * schedules it in the user's database.
26
+ * @param history The full history of the card.
27
+ * @param item The study session item, used to determine if a previous review needs to be cleared.
28
+ */
29
+ async scheduleReview(history, item) {
30
+ const nextInterval = newInterval(this.user, history);
31
+ const nextReviewTime = moment.utc().add(nextInterval, "seconds");
32
+ if (isReview(item)) {
33
+ logger.info(`[SrsService] Removing previously scheduled review for: ${item.cardID}`);
34
+ this.user.removeScheduledCardReview(item.reviewID);
35
+ }
36
+ this.user.scheduleCardReview({
37
+ user: this.user.getUsername(),
38
+ course_id: history.courseID,
39
+ card_id: history.cardID,
40
+ time: nextReviewTime,
41
+ scheduledFor: item.contentSourceType,
42
+ schedulingAgentId: item.contentSourceID
43
+ });
44
+ }
45
+ };
46
+ //#endregion
47
+ export { SrsService };
48
+
49
+ //# sourceMappingURL=SrsService.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SrsService.mjs","names":[],"sources":["../../../src/study/services/SrsService.ts"],"sourcesContent":["import moment from 'moment';\nimport { CardHistory, CardRecord, UserDBInterface } from '@db/core';\nimport { isReview, StudySessionItem } from '@db/impl/couch';\nimport { newInterval } from '../SpacedRepetition';\nimport { logger } from '@db/util/logger';\n\n/**\n * Service responsible for Spaced Repetition System (SRS) scheduling logic.\n */\nexport class SrsService {\n private user: UserDBInterface;\n\n constructor(user: UserDBInterface) {\n this.user = user;\n }\n\n /**\n * Remove a scheduled review from the user's database.\n * Used to clean up orphaned reviews (e.g., card deleted from course DB).\n */\n removeReview(reviewID: string): void {\n logger.info(`[SrsService] Removing orphaned scheduled review: ${reviewID}`);\n void this.user.removeScheduledCardReview(reviewID);\n }\n\n /**\n * Calculates the next review time for a card based on its history and\n * schedules it in the user's database.\n * @param history The full history of the card.\n * @param item The study session item, used to determine if a previous review needs to be cleared.\n */\n public async scheduleReview(\n history: CardHistory<CardRecord>,\n item: StudySessionItem\n ): Promise<void> {\n const nextInterval = newInterval(this.user, history);\n const nextReviewTime = moment.utc().add(nextInterval, 'seconds');\n\n if (isReview(item)) {\n logger.info(`[SrsService] Removing previously scheduled review for: ${item.cardID}`);\n void this.user.removeScheduledCardReview(item.reviewID);\n }\n\n void this.user.scheduleCardReview({\n user: this.user.getUsername(),\n course_id: history.courseID,\n card_id: history.cardID,\n time: nextReviewTime,\n scheduledFor: item.contentSourceType,\n schedulingAgentId: item.contentSourceID,\n });\n }\n}\n"],"mappings":";;;;;;;;;AASA,IAAa,aAAb,MAAwB;CACtB;CAEA,YAAY,MAAuB;AACjC,OAAK,OAAO;;;;;;CAOd,aAAa,UAAwB;AACnC,SAAO,KAAK,oDAAoD,WAAW;AACtE,OAAK,KAAK,0BAA0B,SAAS;;;;;;;;CASpD,MAAa,eACX,SACA,MACe;EACf,MAAM,eAAe,YAAY,KAAK,MAAM,QAAQ;EACpD,MAAM,iBAAiB,OAAO,KAAK,CAAC,IAAI,cAAc,UAAU;AAEhE,MAAI,SAAS,KAAK,EAAE;AAClB,UAAO,KAAK,0DAA0D,KAAK,SAAS;AAC/E,QAAK,KAAK,0BAA0B,KAAK,SAAS;;AAGpD,OAAK,KAAK,mBAAmB;GAChC,MAAM,KAAK,KAAK,aAAa;GAC7B,WAAW,QAAQ;GACnB,SAAS,QAAQ;GACjB,MAAM;GACN,cAAc,KAAK;GACnB,mBAAmB,KAAK;GACzB,CAAC"}
@@ -0,0 +1,65 @@
1
+ import "../../_virtual/_rolldown/runtime.mjs";
2
+ import { pushTagPresentation } from "@vue-skuilder/common";
3
+ //#region src/study/services/tagRecent.ts
4
+ /**
5
+ * Mastery signal: per-tag ring buffer of recent presentations.
6
+ *
7
+ * Written on the same path as the per-tag ELO update, one entry per
8
+ * *presentation* of a card. Retries within a presentation (a record with
9
+ * `priorAttemps > 0`, or any record after the first on the current card)
10
+ * are not evidence and add nothing — including the "dismiss-failed" final
11
+ * penalty, which reaches the ELO path on a retry record.
12
+ *
13
+ * Only tags the question actually graded (numeric perf) get an entry;
14
+ * count-only exposure tags (`null`) carry no correctness signal.
15
+ */
16
+ /** The record for the presentation being graded, or null if none is visible. */
17
+ function currentRecord(records) {
18
+ return records.length ? records[records.length - 1] : null;
19
+ }
20
+ /**
21
+ * Whether the record under grading is the first attempt of its presentation.
22
+ *
23
+ * `priorAttemps` is the authoritative marker (written by the question view).
24
+ * When it is absent (non-question records, or a caller that did not push the
25
+ * record onto `currentCard.records`), fall back to the presentation's record
26
+ * count. With no record visible at all we cannot tell, and say no.
27
+ */
28
+ function isFirstAttempt(records) {
29
+ const rec = currentRecord(records);
30
+ if (!rec) return false;
31
+ const prior = rec.priorAttemps;
32
+ if (typeof prior === "number") return prior === 0;
33
+ return records.length === 1;
34
+ }
35
+ /**
36
+ * Append a presentation entry to every scored tag in `perf`, mutating
37
+ * `userElo.tags[tag]` in place (each rank object is replaced, not mutated).
38
+ * No-op for retries. Returns the tags that received an entry.
39
+ */
40
+ function recordTagPresentations(userElo, perf, records, cardId, at) {
41
+ if (!isFirstAttempt(records)) return [];
42
+ const ok = currentRecord(records)?.isCorrect === true;
43
+ const written = [];
44
+ for (const [tag, score] of Object.entries(perf)) {
45
+ if (tag === "_global") continue;
46
+ if (typeof score !== "number") continue;
47
+ const rank = userElo.tags[tag] ?? {
48
+ score: userElo.global.score,
49
+ count: 0
50
+ };
51
+ const entry = {
52
+ at,
53
+ ok,
54
+ perf: score,
55
+ card: cardId
56
+ };
57
+ userElo.tags[tag] = pushTagPresentation(rank, entry);
58
+ written.push(tag);
59
+ }
60
+ return written;
61
+ }
62
+ //#endregion
63
+ export { recordTagPresentations };
64
+
65
+ //# sourceMappingURL=tagRecent.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tagRecent.mjs","names":[],"sources":["../../../src/study/services/tagRecent.ts"],"sourcesContent":["import {\n CourseElo,\n EloRank,\n TaggedPerformance,\n TagPresentation,\n pushTagPresentation,\n} from '@vue-skuilder/common';\nimport { CardRecord } from '@db/core';\n\n/**\n * Mastery signal: per-tag ring buffer of recent presentations.\n *\n * Written on the same path as the per-tag ELO update, one entry per\n * *presentation* of a card. Retries within a presentation (a record with\n * `priorAttemps > 0`, or any record after the first on the current card)\n * are not evidence and add nothing — including the \"dismiss-failed\" final\n * penalty, which reaches the ELO path on a retry record.\n *\n * Only tags the question actually graded (numeric perf) get an entry;\n * count-only exposure tags (`null`) carry no correctness signal.\n */\n\n/** The record for the presentation being graded, or null if none is visible. */\nfunction currentRecord(records: readonly CardRecord[]): CardRecord | null {\n return records.length ? records[records.length - 1] : null;\n}\n\n/**\n * Whether the record under grading is the first attempt of its presentation.\n *\n * `priorAttemps` is the authoritative marker (written by the question view).\n * When it is absent (non-question records, or a caller that did not push the\n * record onto `currentCard.records`), fall back to the presentation's record\n * count. With no record visible at all we cannot tell, and say no.\n */\nexport function isFirstAttempt(records: readonly CardRecord[]): boolean {\n const rec = currentRecord(records);\n if (!rec) return false;\n const prior = (rec as { priorAttemps?: unknown }).priorAttemps;\n if (typeof prior === 'number') return prior === 0;\n return records.length === 1;\n}\n\n/**\n * Append a presentation entry to every scored tag in `perf`, mutating\n * `userElo.tags[tag]` in place (each rank object is replaced, not mutated).\n * No-op for retries. Returns the tags that received an entry.\n */\nexport function recordTagPresentations(\n userElo: CourseElo,\n perf: TaggedPerformance,\n records: readonly CardRecord[],\n cardId: string,\n at: string\n): string[] {\n if (!isFirstAttempt(records)) return [];\n const rec = currentRecord(records) as { isCorrect?: unknown } | null;\n const ok = rec?.isCorrect === true;\n\n const written: string[] = [];\n for (const [tag, score] of Object.entries(perf)) {\n if (tag === '_global') continue;\n if (typeof score !== 'number') continue; // count-only exposure tag\n const rank: EloRank = userElo.tags[tag] ?? { score: userElo.global.score, count: 0 };\n const entry: TagPresentation = { at, ok, perf: score, card: cardId };\n userElo.tags[tag] = pushTagPresentation(rank, entry);\n written.push(tag);\n }\n return written;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAuBA,SAAS,cAAc,SAAmD;AACxE,QAAO,QAAQ,SAAS,QAAQ,QAAQ,SAAS,KAAK;;;;;;;;;;AAWxD,SAAgB,eAAe,SAAyC;CACtE,MAAM,MAAM,cAAc,QAAQ;AAClC,KAAI,CAAC,IAAK,QAAO;CACjB,MAAM,QAAS,IAAmC;AAClD,KAAI,OAAO,UAAU,SAAU,QAAO,UAAU;AAChD,QAAO,QAAQ,WAAW;;;;;;;AAQ5B,SAAgB,uBACd,SACA,MACA,SACA,QACA,IACU;AACV,KAAI,CAAC,eAAe,QAAQ,CAAE,QAAO,EAAE;CAEvC,MAAM,KADM,cAAc,QAAQ,EAClB,cAAc;CAE9B,MAAM,UAAoB,EAAE;AAC5B,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAK,EAAE;AAC/C,MAAI,QAAQ,UAAW;AACvB,MAAI,OAAO,UAAU,SAAU;EAC/B,MAAM,OAAgB,QAAQ,KAAK,QAAQ;GAAE,OAAO,QAAQ,OAAO;GAAO,OAAO;GAAG;EACpF,MAAM,QAAyB;GAAE;GAAI;GAAI,MAAM;GAAO,MAAM;GAAQ;AACpE,UAAQ,KAAK,OAAO,oBAAoB,MAAM,MAAM;AACpD,UAAQ,KAAK,IAAI;;AAEnB,QAAO"}
@@ -1,5 +1,5 @@
1
1
  import { CourseConfig } from '@vue-skuilder/common';
2
- import { D as DocType } from './types-legacy-DdVjg81H.js';
2
+ import { D as DocType } from './types-legacy-fT5Y1Wuy.js';
3
3
 
4
4
  interface StaticCourseManifest {
5
5
  version: string;
@@ -165,4 +165,4 @@ interface QuestionRecord extends CardRecord, Evaluation {
165
165
  priorAttemps: number;
166
166
  }
167
167
 
168
- export { type CardData as C, DocType as D, type Field as F, GuestUsername as G, type QualifiedCardID as Q, type SkuilderCourseData as S, type TagStub as T, type Tag as a, type DisplayableData as b, type CardRecord as c, type QuestionRecord as d, type CardHistory as e, DocTypePrefixes as f, type CourseListData as g, type DataShapeData as h, type QuestionData as i, log as l };
168
+ export { type CardData as C, DocType as D, type Field as F, GuestUsername as G, type QualifiedCardID as Q, type SkuilderCourseData as S, type TagStub as T, type Tag as a, type DisplayableData as b, type CardRecord as c, type QuestionRecord as d, type CardHistory as e, type CourseListData as f, type DataShapeData as g, type QuestionData as h, DocTypePrefixes as i, log as l };