@vue-skuilder/db 0.2.34 → 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 (262) 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-CTQ4kWhR.d.cts → contentSource-D_E7JaxR.d.ts} +2 -2
  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-rlLE2Mf-.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} +130 -1
  87. package/dist/diagnostics/index.cjs.map +1 -0
  88. package/dist/diagnostics/index.d.ts +108 -5
  89. package/dist/diagnostics/index.mjs +7 -914
  90. package/dist/diagnostics/loader.mjs +151 -0
  91. package/dist/diagnostics/loader.mjs.map +1 -0
  92. package/dist/diagnostics/pipeline.mjs +161 -0
  93. package/dist/diagnostics/pipeline.mjs.map +1 -0
  94. package/dist/diagnostics/tagElo.mjs +177 -0
  95. package/dist/diagnostics/tagElo.mjs.map +1 -0
  96. package/dist/diagnostics/text.mjs +174 -0
  97. package/dist/diagnostics/text.mjs.map +1 -0
  98. package/dist/factory.mjs +70 -0
  99. package/dist/factory.mjs.map +1 -0
  100. package/dist/impl/common/BaseUserDB.mjs +1103 -0
  101. package/dist/impl/common/BaseUserDB.mjs.map +1 -0
  102. package/dist/impl/common/userDBHelpers.mjs +49 -0
  103. package/dist/impl/common/userDBHelpers.mjs.map +1 -0
  104. package/dist/impl/common/userDBKeys.mjs +45 -0
  105. package/dist/impl/common/userDBKeys.mjs.map +1 -0
  106. package/dist/impl/couch/CouchDBSyncStrategy.mjs +272 -0
  107. package/dist/impl/couch/CouchDBSyncStrategy.mjs.map +1 -0
  108. package/dist/impl/couch/CourseSyncService.mjs +242 -0
  109. package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
  110. package/dist/impl/couch/PouchDataLayerProvider.mjs +74 -0
  111. package/dist/impl/couch/PouchDataLayerProvider.mjs.map +1 -0
  112. package/dist/impl/couch/adminDB.mjs +61 -0
  113. package/dist/impl/couch/adminDB.mjs.map +1 -0
  114. package/dist/impl/couch/auth.mjs +33 -0
  115. package/dist/impl/couch/auth.mjs.map +1 -0
  116. package/dist/impl/couch/classroomDB.mjs +227 -0
  117. package/dist/impl/couch/classroomDB.mjs.map +1 -0
  118. package/dist/impl/couch/clientCache.mjs +15 -0
  119. package/dist/impl/couch/clientCache.mjs.map +1 -0
  120. package/dist/impl/couch/courseAPI.mjs +183 -0
  121. package/dist/impl/couch/courseAPI.mjs.map +1 -0
  122. package/dist/impl/couch/courseDB.mjs +729 -0
  123. package/dist/impl/couch/courseDB.mjs.map +1 -0
  124. package/dist/impl/couch/courseLookupDB.mjs +94 -0
  125. package/dist/impl/couch/courseLookupDB.mjs.map +1 -0
  126. package/dist/impl/couch/{index.js → index.cjs} +6911 -10367
  127. package/dist/impl/couch/index.cjs.map +1 -0
  128. package/dist/impl/couch/index.d.ts +12 -5
  129. package/dist/impl/couch/index.mjs +134 -12146
  130. package/dist/impl/couch/index.mjs.map +1 -1
  131. package/dist/impl/couch/pouchdb-setup.mjs +15 -0
  132. package/dist/impl/couch/pouchdb-setup.mjs.map +1 -0
  133. package/dist/impl/couch/updateQueue.mjs +101 -0
  134. package/dist/impl/couch/updateQueue.mjs.map +1 -0
  135. package/dist/impl/couch/user-course-relDB.mjs +55 -0
  136. package/dist/impl/couch/user-course-relDB.mjs.map +1 -0
  137. package/dist/impl/static/NoOpSyncStrategy.mjs +49 -0
  138. package/dist/impl/static/NoOpSyncStrategy.mjs.map +1 -0
  139. package/dist/impl/static/StaticDataLayerProvider.mjs +94 -0
  140. package/dist/impl/static/StaticDataLayerProvider.mjs.map +1 -0
  141. package/dist/impl/static/StaticDataUnpacker.mjs +311 -0
  142. package/dist/impl/static/StaticDataUnpacker.mjs.map +1 -0
  143. package/dist/impl/static/courseDB.mjs +368 -0
  144. package/dist/impl/static/courseDB.mjs.map +1 -0
  145. package/dist/impl/static/coursesDB.mjs +38 -0
  146. package/dist/impl/static/coursesDB.mjs.map +1 -0
  147. package/dist/impl/static/{index.js → index.cjs} +2461 -5992
  148. package/dist/impl/static/index.cjs.map +1 -0
  149. package/dist/impl/static/index.d.ts +4 -4
  150. package/dist/impl/static/index.mjs +6 -10741
  151. package/dist/{index-CVGehe_t.d.ts → index-BLDpFYG3.d.ts} +1 -1
  152. package/dist/{index.js → index.cjs} +14070 -14239
  153. package/dist/index.cjs.map +1 -0
  154. package/dist/index.d.ts +12 -23
  155. package/dist/index.mjs +38 -16937
  156. package/dist/pouch/{index.js → index.cjs} +5 -1
  157. package/dist/pouch/index.cjs.map +1 -0
  158. package/dist/pouch/index.mjs +2 -19
  159. package/dist/study/ItemQueue.mjs +95 -0
  160. package/dist/study/ItemQueue.mjs.map +1 -0
  161. package/dist/study/MixerDebugger.mjs +303 -0
  162. package/dist/study/MixerDebugger.mjs.map +1 -0
  163. package/dist/study/SessionController.mjs +1187 -0
  164. package/dist/study/SessionController.mjs.map +1 -0
  165. package/dist/study/SessionDebugger.mjs +271 -0
  166. package/dist/study/SessionDebugger.mjs.map +1 -0
  167. package/dist/study/SessionOverlay.mjs +407 -0
  168. package/dist/study/SessionOverlay.mjs.map +1 -0
  169. package/dist/study/SourceMixer.mjs +45 -0
  170. package/dist/study/SourceMixer.mjs.map +1 -0
  171. package/dist/study/SpacedRepetition.mjs +108 -0
  172. package/dist/study/SpacedRepetition.mjs.map +1 -0
  173. package/dist/study/TagFilteredContentSource.mjs +136 -0
  174. package/dist/study/TagFilteredContentSource.mjs.map +1 -0
  175. package/dist/study/services/CardHydrationService.mjs +172 -0
  176. package/dist/study/services/CardHydrationService.mjs.map +1 -0
  177. package/dist/study/services/EloService.mjs +217 -0
  178. package/dist/study/services/EloService.mjs.map +1 -0
  179. package/dist/study/services/ResponseProcessor.mjs +190 -0
  180. package/dist/study/services/ResponseProcessor.mjs.map +1 -0
  181. package/dist/study/services/SrsService.mjs +49 -0
  182. package/dist/study/services/SrsService.mjs.map +1 -0
  183. package/dist/study/services/tagRecent.mjs +65 -0
  184. package/dist/study/services/tagRecent.mjs.map +1 -0
  185. package/dist/{types-dXWfyz9B.d.ts → types-DChCz22D.d.ts} +1 -1
  186. package/dist/{types-legacy-BkOYOR6U.d.cts → types-legacy-fT5Y1Wuy.d.ts} +1 -1
  187. package/dist/userDBKeys-ne1g4Xuq.d.ts +16 -0
  188. package/dist/util/Loggable.mjs +14 -0
  189. package/dist/util/Loggable.mjs.map +1 -0
  190. package/dist/util/dataDirectory.mjs +47 -0
  191. package/dist/util/dataDirectory.mjs.map +1 -0
  192. package/dist/util/logger.mjs +86 -0
  193. package/dist/util/logger.mjs.map +1 -0
  194. package/dist/util/migrator/FileSystemAdapter.mjs +18 -0
  195. package/dist/util/migrator/FileSystemAdapter.mjs.map +1 -0
  196. package/dist/util/migrator/StaticToCouchDBMigrator.mjs +428 -0
  197. package/dist/util/migrator/StaticToCouchDBMigrator.mjs.map +1 -0
  198. package/dist/util/migrator/types.mjs +11 -0
  199. package/dist/util/migrator/types.mjs.map +1 -0
  200. package/dist/util/migrator/validation.mjs +334 -0
  201. package/dist/util/migrator/validation.mjs.map +1 -0
  202. package/dist/util/packer/CouchDBToStaticPacker.mjs +438 -0
  203. package/dist/util/packer/CouchDBToStaticPacker.mjs.map +1 -0
  204. package/dist/util/packer/{index.js → index.cjs} +73 -9
  205. package/dist/util/packer/index.cjs.map +1 -0
  206. package/dist/util/packer/index.d.ts +3 -3
  207. package/dist/util/packer/index.mjs +2 -537
  208. package/eslint.config.mjs +9 -1
  209. package/package.json +25 -13
  210. package/rolldown.config.mjs +44 -0
  211. package/src/core/UserDBDebugger.ts +47 -46
  212. package/src/core/navigators/Pipeline.ts +10 -10
  213. package/src/core/navigators/PipelineDebugger.ts +55 -55
  214. package/src/core/navigators/filters/eloDistance.ts +11 -1
  215. package/src/core/navigators/generators/elo.ts +5 -1
  216. package/src/core/navigators/index.ts +9 -3
  217. package/src/diagnostics/derive.ts +6 -0
  218. package/src/diagnostics/index.ts +1 -0
  219. package/src/diagnostics/tagElo.ts +257 -0
  220. package/src/factory.ts +10 -1
  221. package/src/impl/common/BaseUserDB.ts +1 -3
  222. package/src/impl/common/index.ts +2 -0
  223. package/src/impl/common/userDBHelpers.ts +4 -58
  224. package/src/impl/common/userDBKeys.ts +64 -0
  225. package/src/impl/couch/courseDB.ts +15 -3
  226. package/src/impl/couch/index.ts +2 -18
  227. package/src/impl/couch/pouchdb-setup.ts +8 -0
  228. package/src/index.ts +1 -1
  229. package/src/study/MixerDebugger.ts +46 -46
  230. package/src/study/SessionDebugger.ts +20 -20
  231. package/src/study/SessionOverlay.ts +4 -4
  232. package/src/util/logger.ts +112 -13
  233. package/tests/core/navigators/eloGenerator.test.ts +36 -0
  234. package/tsup.config.ts +24 -21
  235. package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
  236. package/dist/classroomDB-DLTtLZct.d.cts +0 -86
  237. package/dist/contentSource-JmWYu8IK.d.ts +0 -2007
  238. package/dist/core/index.d.cts +0 -521
  239. package/dist/core/index.js.map +0 -1
  240. package/dist/core/index.mjs.map +0 -1
  241. package/dist/dataLayerProvider-DfI_KYAe.d.cts +0 -61
  242. package/dist/diagnostics/index.d.cts +0 -458
  243. package/dist/diagnostics/index.js.map +0 -1
  244. package/dist/diagnostics/index.mjs.map +0 -1
  245. package/dist/impl/couch/index.d.cts +0 -620
  246. package/dist/impl/couch/index.js.map +0 -1
  247. package/dist/impl/static/index.d.cts +0 -232
  248. package/dist/impl/static/index.js.map +0 -1
  249. package/dist/impl/static/index.mjs.map +0 -1
  250. package/dist/index-Ktg72jKb.d.cts +0 -137
  251. package/dist/index.d.cts +0 -1663
  252. package/dist/index.js.map +0 -1
  253. package/dist/index.mjs.map +0 -1
  254. package/dist/pouch/index.d.cts +0 -1
  255. package/dist/pouch/index.js.map +0 -1
  256. package/dist/pouch/index.mjs.map +0 -1
  257. package/dist/types-D0oQeJAi.d.cts +0 -58
  258. package/dist/types-legacy-BkOYOR6U.d.ts +0 -168
  259. package/dist/util/packer/index.d.cts +0 -5
  260. package/dist/util/packer/index.js.map +0 -1
  261. package/dist/util/packer/index.mjs.map +0 -1
  262. package/src/study/getCardDataShape.ts +0 -34
@@ -0,0 +1,1187 @@
1
+ import "../_virtual/_rolldown/runtime.mjs";
2
+ import { logger } from "../util/logger.mjs";
3
+ import { drainCapturedRuns, setDebugSessionId } from "../core/navigators/PipelineDebugger.mjs";
4
+ import { getSrsBacklogDebug } from "../core/navigators/SrsDebugger.mjs";
5
+ import { getStrategyPressureDebug } from "../core/navigators/StrategyPressureDebugger.mjs";
6
+ import { getCardOrigin } from "../core/navigators/index.mjs";
7
+ import { sessionVersions } from "../core/versionStamps.mjs";
8
+ import { DocType } from "../core/types/types-legacy.mjs";
9
+ import { Loggable } from "../util/Loggable.mjs";
10
+ import { recordUserOutcome } from "../core/orchestration/recording.mjs";
11
+ import { mergeHints } from "../core/navigators/Pipeline.mjs";
12
+ import { isQuestionRecord } from "../core/util/index.mjs";
13
+ import { SrsService } from "./services/SrsService.mjs";
14
+ import { EloService } from "./services/EloService.mjs";
15
+ import { ResponseProcessor } from "./services/ResponseProcessor.mjs";
16
+ import { CardHydrationService } from "./services/CardHydrationService.mjs";
17
+ import { ItemQueue } from "./ItemQueue.mjs";
18
+ import { makeStudySessionId, newSessionId } from "../core/types/studySession.mjs";
19
+ import { QuotaRoundRobinMixer } from "./SourceMixer.mjs";
20
+ import { captureMixerRun } from "./MixerDebugger.mjs";
21
+ import { registerActiveController } from "./SessionOverlay.mjs";
22
+ import { clearStaleSessionDebugState, endSessionTracking, recordCardPresentation, snapshotQueues, startSessionTracking } from "./SessionDebugger.mjs";
23
+ import { isReview } from "../core/interfaces/contentSource.mjs";
24
+ //#region src/study/SessionController.ts
25
+ /** Unselected cards persisted per run, after the selected ones. */
26
+ const PERSISTED_RUNNERS_UP = 5;
27
+ /** 4 significant figures: keeps 6.4e-7 distinguishable from 0 without 17-digit floats. */
28
+ function sig4(x) {
29
+ return Number(x.toPrecision(4));
30
+ }
31
+ function toRunCard(c) {
32
+ return {
33
+ cardId: c.cardId,
34
+ origin: c.origin,
35
+ ...c.generator ? { generator: c.generator } : {},
36
+ ...c.required ? { required: c.required } : {},
37
+ score: Number.isFinite(c.finalScore) ? sig4(c.finalScore) : null,
38
+ selected: c.selected
39
+ };
40
+ }
41
+ function toRunCardTrail(c) {
42
+ return {
43
+ ...toRunCard(c),
44
+ trail: c.provenance.filter((p) => p.action !== "passed").map((p) => ({
45
+ strategyName: p.strategyName,
46
+ action: p.action,
47
+ score: sig4(p.score),
48
+ reason: p.reason
49
+ }))
50
+ };
51
+ }
52
+ function persistedReading(r) {
53
+ return {
54
+ ...r,
55
+ urgency: sig4(r.urgency),
56
+ multiplier: sig4(r.multiplier),
57
+ inputs: Object.fromEntries(Object.entries(r.inputs).map(([k, v]) => [k, sig4(v)]))
58
+ };
59
+ }
60
+ /** `run.cards` is selected-then-near-misses, each in score order. */
61
+ function persistedRunCards(run) {
62
+ const selected = run.cards.filter((c) => c.selected);
63
+ const runnersUp = run.cards.filter((c) => !c.selected).slice(0, PERSISTED_RUNNERS_UP);
64
+ return [...selected, ...runnersUp].map(toRunCard);
65
+ }
66
+ function persistedUnselectedNew(u) {
67
+ return {
68
+ ...u.nextInLine ? { nextInLine: toRunCardTrail(u.nextInLine) } : {},
69
+ ...u.topGenerated ? { topGenerated: toRunCardTrail(u.topGenerated) } : {}
70
+ };
71
+ }
72
+ var SessionController = class SessionController extends Loggable {
73
+ _className = "SessionController";
74
+ services;
75
+ srsService;
76
+ eloService;
77
+ hydrationService;
78
+ mixer;
79
+ dataLayer;
80
+ courseNameCache = /* @__PURE__ */ new Map();
81
+ /**
82
+ * Default pipeline batch size for new-card planning.
83
+ * Set via constructor options; falls back to 20 when not specified.
84
+ * Individual replans can override via `ReplanOptions.limit`.
85
+ */
86
+ _defaultBatchLimit = 20;
87
+ sources;
88
+ _sessionRecord = [];
89
+ set sessionRecord(r) {
90
+ this._sessionRecord = r;
91
+ }
92
+ _currentCard = null;
93
+ /**
94
+ * The single supply queue: `new` + `review` items interleaved in pipeline
95
+ * rank order (the mixer's score-ordered, source-interleaved output, with
96
+ * `+INF` required cards floated to the front). Drawn front-to-back; reviews
97
+ * and new compete on one cross-comparable scale rather than being re-mixed
98
+ * by a probability gate. Replaced/re-ranked wholesale on replan. See
99
+ * `docs/decision-single-supply-queue.md`.
100
+ */
101
+ supplyQ = new ItemQueue();
102
+ failedQ = new ItemQueue();
103
+ /**
104
+ * Supply draws since the last failed-queue *event* (a failed draw, or a card
105
+ * entering failedQ on failure). Drives the light steady failed-interleave
106
+ * (§7): after this many consecutive supply draws, a pending failed card is
107
+ * drawn so remediation doesn't starve mid-session. Incremented on each supply
108
+ * draw; reset to 0 both when a failed card is drawn AND when one is added to
109
+ * failedQ — the latter gives a just-failed card spacing instead of an instant
110
+ * retry (the counter would otherwise already be ≥ threshold from the preceding
111
+ * supply run).
112
+ */
113
+ _supplyDrawsSinceFailed = 0;
114
+ /**
115
+ * Promise tracking a currently in-progress replan, or null if idle.
116
+ * Used by nextCard() to await completion before drawing from queues.
117
+ */
118
+ _replanPromise = null;
119
+ /**
120
+ * Reason for the replan currently executing in `_runReplan`, surfaced by the
121
+ * debug overlay's spinner. The caller's `opts.label` when present, else
122
+ * `'(auto)'`. Only meaningful while `_replanPromise` is non-null; cleared
123
+ * when the in-flight chain settles.
124
+ */
125
+ _activeReplanLabel = null;
126
+ /**
127
+ * Number of well-indicated supply cards remaining before the queue
128
+ * degrades to poorly-indicated content. Decremented on each supplyQ
129
+ * draw; when it hits 0, a replan is triggered automatically
130
+ * (user state has changed from completing good cards).
131
+ */
132
+ _wellIndicatedRemaining = 0;
133
+ /**
134
+ * When true, suppresses the quality-based auto-replan trigger in
135
+ * nextCard(). Set after a burst replan (small limit) to prevent the
136
+ * auto-replan from clobbering the burst cards before they're consumed.
137
+ * Cleared when the depletion-triggered replan fires (supplyQ exhausted).
138
+ */
139
+ _suppressQualityReplan = false;
140
+ /**
141
+ * When > 0, the session timer cannot end the session. Decremented on
142
+ * each nextCard() draw. Set by replans that include `minFollowUpCards`.
143
+ */
144
+ _minCardsGuarantee = 0;
145
+ /**
146
+ * Session-durable scoring hints. Re-merged into every pipeline run for
147
+ * the rest of the session (initial plan + every replan, including bare
148
+ * auto-replans and the wedge-breaker), via `_applyHintsToSources`.
149
+ *
150
+ * Set by `setSessionHints()` (e.g. session-start post-lesson boost) or by
151
+ * any replan carrying `ReplanOptions.sessionHints` (e.g. a just-failed
152
+ * concept boost). Replace semantics, no decay — lives until overwritten
153
+ * or session end. See `ReplanOptions.sessionHints` for rationale.
154
+ *
155
+ * Note: the controller-managed auto-excludes (current card, session
156
+ * record, imminent draw) are intentionally NOT folded in here — those are
157
+ * recomputed per-run in `_runReplan` and would otherwise go stale.
158
+ */
159
+ _sessionHints = null;
160
+ /**
161
+ * Card IDs that have been *served* (drawn/consumed) this session. Populated
162
+ * at the single consumption choke-point (removeItemFromQueue), so it reflects
163
+ * a draw the instant it happens — earlier than `_sessionRecord`, which only
164
+ * lands once the card is *responded to*.
165
+ *
166
+ * Used to keep already-served cards out of supplyQ on every (re)plan, across
167
+ * ALL origins: a `new` card shown once must never re-enter, and once replans
168
+ * re-pull reviews, an answered/in-flight review must not re-enter the supply
169
+ * before its SRS reschedule clears the due-window (the review-loop guard,
170
+ * decision doc §4). This is the general guard against re-presentation —
171
+ * including the case where a replan in flight captured a now-drawn card (e.g.
172
+ * a +INF require-injected follow-up the depletion prefetch grabbed just before
173
+ * it was drawn). failedQ is separate and controller-owned, so failed cards
174
+ * legitimately recur there without being gated here.
175
+ */
176
+ _servedCardIds = /* @__PURE__ */ new Set();
177
+ /**
178
+ * Consumer-supplied hooks invoked after each question response is processed.
179
+ * Seeded from constructor options (threaded from
180
+ * `StudySessionConfig.outcomeObservers`). See {@link OutcomeObserver}.
181
+ */
182
+ _outcomeObservers = [];
183
+ /**
184
+ * Lazily-built, stable capability object handed to observers. Bound to
185
+ * `this`; constructed once so observers can rely on referential identity.
186
+ */
187
+ _sessionControls = null;
188
+ /**
189
+ * Minted at construction so the bootstrap pipeline run in `prepareSession()`
190
+ * can carry it. Stamped onto every CardRecord and pipeline run this session.
191
+ */
192
+ sessionId;
193
+ /** Host-supplied. Without it, no durable session doc is written. */
194
+ _courseId;
195
+ _stateSnapshotProvider;
196
+ _sessionDoc = null;
197
+ /**
198
+ * Awaited by the close path — the open write is slow (time-boxed snapshot)
199
+ * and would otherwise land last, leaving a finished session marked `open`.
200
+ */
201
+ _openDocPromise = null;
202
+ _runLog = [];
203
+ static MAX_LOGGED_RUNS = 100;
204
+ /**
205
+ * Per-response ELO exchanges as they resolve (see `SessionEloEvent`). Fed by
206
+ * the ResponseProcessor's `onEloEvent` sink; flushed to the session doc at
207
+ * close. Bounded so a runaway session can't grow it without limit.
208
+ */
209
+ _eloLog = [];
210
+ static MAX_LOGGED_ELO_EVENTS = 2e3;
211
+ /** Guards `endSession()` against the several termination paths racing it. */
212
+ _sessionClosed = false;
213
+ startTime;
214
+ endTime;
215
+ _secondsRemaining;
216
+ get secondsRemaining() {
217
+ return this._secondsRemaining;
218
+ }
219
+ /** True when a card guarantee is active, preventing timer-based session end. */
220
+ get hasCardGuarantee() {
221
+ return this._minCardsGuarantee > 0;
222
+ }
223
+ get report() {
224
+ const supplyCount = this.supplyQ.dequeueCount;
225
+ return `${supplyCount} supply ${supplyCount === 1 ? "card" : "cards"} drawn`;
226
+ }
227
+ get detailedReport() {
228
+ return this.supplyQ.toString + "\n" + this.failedQ.toString;
229
+ }
230
+ _intervalHandle;
231
+ /**
232
+ * @param sources - Array of content sources to mix for the session
233
+ * @param time - Session duration in seconds
234
+ * @param dataLayer - Data layer provider
235
+ * @param getViewComponent - Function to resolve view components
236
+ * @param mixer - Optional source mixer strategy (defaults to QuotaRoundRobinMixer)
237
+ * @param options - Optional session-level configuration
238
+ * @param options.defaultBatchLimit - Default supply working-set size (default: 20).
239
+ * Smaller values for newer users cause more frequent replans, keeping plans
240
+ * aligned with rapidly-changing user state.
241
+ */
242
+ constructor(sources, time, dataLayer, getViewComponent, mixer, options) {
243
+ super();
244
+ this.sessionId = newSessionId();
245
+ setDebugSessionId(this.sessionId);
246
+ this.dataLayer = dataLayer;
247
+ this.mixer = mixer || new QuotaRoundRobinMixer();
248
+ this.srsService = new SrsService(dataLayer.getUserDB());
249
+ this.eloService = new EloService(dataLayer, dataLayer.getUserDB());
250
+ this.hydrationService = new CardHydrationService(getViewComponent, (courseId) => dataLayer.getCourseDB(courseId), () => this._getItemsToHydrate());
251
+ this.services = { response: new ResponseProcessor(this.srsService, this.eloService, (event) => this._recordEloEvent(event)) };
252
+ this.sources = sources;
253
+ this.startTime = /* @__PURE__ */ new Date();
254
+ this._secondsRemaining = time;
255
+ this.endTime = new Date(this.startTime.valueOf() + 1e3 * this._secondsRemaining);
256
+ if (options?.defaultBatchLimit !== void 0) this._defaultBatchLimit = options.defaultBatchLimit;
257
+ if (options?.outcomeObservers?.length) this._outcomeObservers = [...options.outcomeObservers];
258
+ this._courseId = options?.courseId;
259
+ this._stateSnapshotProvider = options?.stateSnapshotProvider;
260
+ this.log(`Session constructed:
261
+ sessionId: ${this.sessionId}
262
+ startTime: ${this.startTime}
263
+ endTime: ${this.endTime}
264
+ defaultBatchLimit: ${this._defaultBatchLimit}`);
265
+ registerActiveController(this);
266
+ }
267
+ tick() {
268
+ this._secondsRemaining = Math.floor((this.endTime.valueOf() - Date.now()) / 1e3);
269
+ if (this._secondsRemaining <= 0) clearInterval(this._intervalHandle);
270
+ }
271
+ /**
272
+ * Returns a rough, erring toward conservative, guess at
273
+ * the amount of time the failed cards queue will require
274
+ * to clean up.
275
+ *
276
+ * (seconds)
277
+ */
278
+ estimateCleanupTime() {
279
+ let time = 0;
280
+ for (let i = 0; i < this.failedQ.length; i++) {
281
+ const c = this.failedQ.peek(i);
282
+ const record = this._sessionRecord.find((r) => r.item.cardID === c.cardID);
283
+ let cardTime = 0;
284
+ if (record) {
285
+ for (let j = 0; j < record.records.length; j++) cardTime += record.records[j].timeSpent;
286
+ cardTime = cardTime / record.records.length;
287
+ time += cardTime;
288
+ }
289
+ }
290
+ const ret = time / 1e3;
291
+ this.log(`Failed card cleanup estimate: ${Math.round(ret)}`);
292
+ return ret;
293
+ }
294
+ async prepareSession() {
295
+ if (this.sources.some((s) => typeof s.getWeightedCards !== "function")) throw new Error("[SessionController] All content sources must implement getWeightedCards().");
296
+ clearStaleSessionDebugState();
297
+ const wellIndicated = await this.getWeightedContent();
298
+ this._recordRuns("bootstrap");
299
+ this._wellIndicatedRemaining = wellIndicated;
300
+ if (wellIndicated >= 0 && wellIndicated < SessionController.MIN_WELL_INDICATED) this.log(`[Init] Only ${wellIndicated}/${SessionController.MIN_WELL_INDICATED} well-indicated cards in initial load`);
301
+ await this.hydrationService.ensureHydratedCards();
302
+ startSessionTracking(this.sessionId, this.supplyQ.length, this.failedQ.length);
303
+ this._openDocPromise = this._openSessionDoc();
304
+ this._intervalHandle = setInterval(() => {
305
+ this.tick();
306
+ }, 1e3);
307
+ }
308
+ /** Label the runs the last plan produced. The pipeline can't know the why. */
309
+ _recordRuns(label, mode) {
310
+ for (const run of drainCapturedRuns()) {
311
+ if (this._runLog.length >= SessionController.MAX_LOGGED_RUNS) break;
312
+ this._runLog.push({
313
+ runId: run.runId,
314
+ at: run.timestamp.toISOString(),
315
+ label,
316
+ ...mode ? { mode } : {},
317
+ generatedCount: run.generatedCount,
318
+ finalCount: run.finalCount,
319
+ reviewsSelected: run.reviewsSelected,
320
+ newSelected: run.newSelected,
321
+ ...typeof run.userElo === "number" ? { userElo: run.userElo } : {},
322
+ ...run.generators ? { generators: run.generators } : {},
323
+ ...run.filters ? { filters: run.filters } : {},
324
+ ...run.hints ? { hints: run.hints } : {},
325
+ ...run.discardedTail ? { discardedTail: run.discardedTail } : {},
326
+ cards: persistedRunCards(run),
327
+ ...run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {},
328
+ ...run.regulators ? { regulators: run.regulators.map(persistedReading) } : {},
329
+ ...run.versions ? { versions: run.versions } : {}
330
+ });
331
+ }
332
+ }
333
+ /** Time-boxed and isolated — a bad provider degrades the record, not the session. */
334
+ async _captureState(phase) {
335
+ if (!this._stateSnapshotProvider) return void 0;
336
+ const TIMEOUT_MS = 3e3;
337
+ try {
338
+ return await Promise.race([Promise.resolve(this._stateSnapshotProvider(phase)), new Promise((resolve) => setTimeout(() => resolve(void 0), TIMEOUT_MS))]);
339
+ } catch (e) {
340
+ this.log(`[Session] state snapshot (${phase}) failed: ${e}`);
341
+ return;
342
+ }
343
+ }
344
+ /** Writing at open is what makes an unclosed session visible at all. */
345
+ async _openSessionDoc() {
346
+ if (!this._courseId) return;
347
+ try {
348
+ const user = this.dataLayer.getUserDB();
349
+ const doc = {
350
+ _id: makeStudySessionId(this._courseId, user.getUsername(), this.sessionId),
351
+ docType: DocType.STUDY_SESSION,
352
+ sessionId: this.sessionId,
353
+ courseId: this._courseId,
354
+ userId: user.getUsername(),
355
+ startTime: this.startTime.toISOString(),
356
+ status: "open",
357
+ plannedSeconds: Math.round((this.endTime.valueOf() - this.startTime.valueOf()) / 1e3),
358
+ config: {
359
+ defaultBatchLimit: this._defaultBatchLimit,
360
+ sourceCount: this.sources.length,
361
+ initHints: this._sessionHints
362
+ },
363
+ versions: sessionVersions(),
364
+ initialQueues: {
365
+ supplyQ: this.supplyQ.length,
366
+ failedQ: this.failedQ.length
367
+ },
368
+ runs: [...this._runLog],
369
+ stateAtStart: await this._captureState("start")
370
+ };
371
+ this._sessionDoc = doc;
372
+ await user.putStudySession(doc);
373
+ this.log(`[Session] Opened session record ${doc._id}`);
374
+ } catch (e) {
375
+ logger.warn(`[SessionController] Failed to open session record: ${e}`);
376
+ }
377
+ }
378
+ /**
379
+ * Request a mid-session replan. Re-runs the pipeline with current user state
380
+ * and atomically replaces (or merges into) the supplyQ contents. Safe to call
381
+ * at any time during a session.
382
+ *
383
+ * Concurrency policy:
384
+ * - Two unhinted auto-replans never run in parallel; the second coalesces
385
+ * into the first (returns the same promise).
386
+ * - A hint-bearing replan that arrives while another replan is in flight
387
+ * is queued to run **after** the in-flight one rather than dropped.
388
+ * This preserves caller intent (label, requireCards, excludeTags,
389
+ * limit, minFollowUpCards) instead of silently discarding it. Without
390
+ * queueing, a background auto-replan that started just before a
391
+ * completion-triggered replan would clobber the queue with unhinted
392
+ * results (e.g. surfacing another gpc-intro card right after one
393
+ * completed, skipping the prescribed `c-wst-*` follow-up).
394
+ *
395
+ * Re-pulls and re-ranks the whole supply (including reviews); does NOT affect
396
+ * failedQ (controller-owned remediation).
397
+ *
398
+ * If nextCard() is called while a replan is in flight, it will automatically
399
+ * await the replan before drawing from queues, ensuring the user always sees
400
+ * cards scored against their latest state.
401
+ *
402
+ * Typical trigger: application-level code (e.g. after a GPC intro completion)
403
+ * calls this to ensure newly-unlocked content appears in the session.
404
+ */
405
+ async requestReplan(options) {
406
+ const opts = this.normalizeReplanOptions(options);
407
+ const hasIntent = this._replanHasIntent(opts);
408
+ if (this._replanPromise) {
409
+ if (!hasIntent) {
410
+ this.log("Replan already in progress, coalescing unhinted auto-replan");
411
+ return this._replanPromise;
412
+ }
413
+ const labelTag = opts.label ? ` [${opts.label}]` : "";
414
+ this.log(`Replan in progress; queueing hint-bearing replan${labelTag} behind in-flight run`);
415
+ const queued = this._replanPromise.catch(() => void 0).then(() => this._runReplan(opts));
416
+ const tracked = queued.finally(() => {
417
+ if (this._replanPromise === tracked) {
418
+ this._replanPromise = null;
419
+ this._activeReplanLabel = null;
420
+ }
421
+ });
422
+ this._replanPromise = tracked;
423
+ return queued;
424
+ }
425
+ const run = this._runReplan(opts);
426
+ const tracked = run.finally(() => {
427
+ if (this._replanPromise === tracked) {
428
+ this._replanPromise = null;
429
+ this._activeReplanLabel = null;
430
+ }
431
+ });
432
+ this._replanPromise = tracked;
433
+ await run;
434
+ }
435
+ /**
436
+ * True when a requestReplan call carries caller intent that must not be
437
+ * silently dropped. Bare unhinted auto-replans (depletion / quality
438
+ * triggers in nextCard) return false and may coalesce.
439
+ */
440
+ _replanHasIntent(opts) {
441
+ if (opts.limit !== void 0) return true;
442
+ if (opts.minFollowUpCards !== void 0) return true;
443
+ if (opts.mode && opts.mode !== "replace") return true;
444
+ if (opts.hints && Object.keys(opts.hints).length > 0) return true;
445
+ if (opts.sessionHints !== void 0) return true;
446
+ if (opts.mergeSessionHints !== void 0) return true;
447
+ return false;
448
+ }
449
+ /**
450
+ * Body of a single replan: populate auto-excludes, stash hints on
451
+ * sources, log, then run the pipeline. Extracted so it can be invoked
452
+ * either immediately (no in-flight replan) or queued (chained after
453
+ * the in-flight one resolves).
454
+ *
455
+ * IMPORTANT: hint stash and the queue-state snapshot used to build
456
+ * excludeCards happen at *invocation* time, not at *queue* time. For a
457
+ * queued replan that means excludes reflect the state after the prior
458
+ * replan landed — which is what we want, since the prior replan's
459
+ * supplyQ.peek(0) is the imminent draw we need to exclude.
460
+ */
461
+ async _runReplan(opts) {
462
+ this._activeReplanLabel = opts.label ?? "(auto)";
463
+ if (!opts.hints) opts.hints = {};
464
+ const hints = opts.hints;
465
+ const excludeSet = new Set(hints.excludeCards ?? []);
466
+ if (this._currentCard?.item.cardID) excludeSet.add(this._currentCard.item.cardID);
467
+ for (const rec of this._sessionRecord) excludeSet.add(rec.card.card_id);
468
+ if (this.supplyQ.length > 0) excludeSet.add(this.supplyQ.peek(0).cardID);
469
+ hints.excludeCards = [...excludeSet];
470
+ if (opts.sessionHints !== void 0) {
471
+ this._sessionHints = opts.sessionHints;
472
+ this.log(`[Replan] Session hints ${opts.sessionHints ? "set" : "cleared"}: ${JSON.stringify(opts.sessionHints)}`);
473
+ }
474
+ if (opts.mergeSessionHints !== void 0) {
475
+ this._sessionHints = mergeHints([this._sessionHints, opts.mergeSessionHints]) ?? null;
476
+ this.log(`[Replan] Session hints merged: ${JSON.stringify(this._sessionHints)}`);
477
+ }
478
+ this._applyHintsToSources(opts.hints, opts.label);
479
+ const labelTag = opts.label ? ` [${opts.label}]` : "";
480
+ this.log(`Mid-session replan requested${labelTag} (limit: ${opts.limit ?? "default"}, mode: ${opts.mode ?? "replace"}${opts.hints ? ", with hints" : ""})`);
481
+ if (opts.minFollowUpCards !== void 0 && opts.minFollowUpCards > 0) {
482
+ this._minCardsGuarantee = Math.max(this._minCardsGuarantee, opts.minFollowUpCards);
483
+ this.log(`[Replan] Card guarantee set to ${this._minCardsGuarantee}`);
484
+ }
485
+ await this._executeReplan(opts);
486
+ }
487
+ /**
488
+ * Set the session-durable scoring hints (replace semantics, no decay).
489
+ *
490
+ * Unlike a one-shot replan hint, these are re-merged into every pipeline
491
+ * run for the rest of the session — including the initial plan when set
492
+ * before `prepareSession()`, every replan, the bare auto-replans, and the
493
+ * wedge-breaker. Pass `null` to clear.
494
+ *
495
+ * Typical callers:
496
+ * - `StudySession` at session start, threading `StudySessionConfig.initHints`
497
+ * (e.g. a post-lesson concept boost) — so the boost outlives the first
498
+ * queue rebuild instead of being clobbered by the first auto-replan.
499
+ * - A consumer view on a failure, boosting the just-failed concept tag.
500
+ *
501
+ * Does not itself trigger a replan; the next plan/replan picks it up.
502
+ */
503
+ setSessionHints(hints) {
504
+ this._sessionHints = hints;
505
+ this.log(`Session hints ${hints ? "set" : "cleared"}: ${JSON.stringify(hints)}`);
506
+ }
507
+ /**
508
+ * Read the current session-durable hints (for read-modify-write callers,
509
+ * e.g. an outcome observer that clamps a compounding boost).
510
+ */
511
+ getSessionHints() {
512
+ return this._sessionHints;
513
+ }
514
+ /**
515
+ * Live state snapshot for the debug overlay (window.skuilder.session
516
+ * .dbgOverlay()). Reads directly from the private queues and hints, so it
517
+ * always reflects the current moment — unlike the passive SessionDebugger
518
+ * snapshots, which only capture what was explicitly pushed to them.
519
+ */
520
+ getDebugSnapshot() {
521
+ const describe = (q) => {
522
+ const cards = [];
523
+ for (let i = 0; i < q.length; i++) {
524
+ const item = q.peek(i);
525
+ cards.push({
526
+ cardID: item.cardID,
527
+ status: item.status,
528
+ origin: isReview(item) ? "review" : "new",
529
+ score: item.score
530
+ });
531
+ }
532
+ return {
533
+ length: q.length,
534
+ dequeueCount: q.dequeueCount,
535
+ cards
536
+ };
537
+ };
538
+ const drawnCards = this._sessionRecord.map((r) => {
539
+ const last = r.records[r.records.length - 1];
540
+ return {
541
+ cardID: r.item.cardID,
542
+ status: r.item.status,
543
+ attempts: r.records.length,
544
+ correct: last && isQuestionRecord(last) ? last.isCorrect : null,
545
+ timeSpentMs: r.records.reduce((sum, rec) => sum + rec.timeSpent, 0)
546
+ };
547
+ });
548
+ return {
549
+ sessionId: this.sessionId,
550
+ secondsRemaining: this.secondsRemaining,
551
+ hasCardGuarantee: this.hasCardGuarantee,
552
+ minCardsGuarantee: this._minCardsGuarantee,
553
+ wellIndicatedRemaining: this._wellIndicatedRemaining,
554
+ currentCard: this._currentCard?.item.cardID ?? null,
555
+ sessionHints: this._sessionHints,
556
+ replanActive: this._replanPromise !== null,
557
+ replanLabel: this._activeReplanLabel,
558
+ supplyQ: describe(this.supplyQ),
559
+ failedQ: describe(this.failedQ),
560
+ reviewBacklog: getSrsBacklogDebug(),
561
+ strategyPressure: getStrategyPressureDebug(),
562
+ drawnCards
563
+ };
564
+ }
565
+ /**
566
+ * Merge `hints` into the durable session hints via the pipeline's
567
+ * `mergeHints` (boosts multiply, require/exclude lists concat-dedup).
568
+ * Convenience over get-then-set for the common additive case. Note the
569
+ * multiplicative, no-decay semantics — clamp boost factors at the call
570
+ * site if a repeatedly-emphasised tag could compound unboundedly.
571
+ */
572
+ mergeSessionHints(hints) {
573
+ this._sessionHints = mergeHints([this._sessionHints, hints]) ?? null;
574
+ this.log(`Session hints merged: ${JSON.stringify(this._sessionHints)}`);
575
+ }
576
+ /**
577
+ * Merge the durable `_sessionHints` with this run's one-shot hints and
578
+ * push the result to every source for consumption on the next pipeline
579
+ * run. Centralised so the initial plan and all replan paths apply session
580
+ * emphasis identically. No-op when there are no hints of either kind.
581
+ */
582
+ _applyHintsToSources(oneShot, label) {
583
+ const oneShotWithLabel = oneShot && label ? {
584
+ ...oneShot,
585
+ _label: label
586
+ } : oneShot;
587
+ const merged = mergeHints([this._sessionHints, oneShotWithLabel]);
588
+ if (!merged) return;
589
+ for (const source of this.sources) source.setEphemeralHints?.(merged);
590
+ }
591
+ /**
592
+ * Build (once) the stable capability object handed to outcome observers.
593
+ * Methods are bound to `this`; the object identity is stable across calls
594
+ * so observers may key off it.
595
+ */
596
+ _getSessionControls() {
597
+ if (!this._sessionControls) this._sessionControls = {
598
+ getSessionHints: () => this.getSessionHints(),
599
+ setSessionHints: (h) => this.setSessionHints(h),
600
+ mergeSessionHints: (h) => this.mergeSessionHints(h),
601
+ requestReplan: (opts) => this.requestReplan(opts)
602
+ };
603
+ return this._sessionControls;
604
+ }
605
+ /**
606
+ * Notify registered outcome observers about a processed response.
607
+ *
608
+ * Only question records are surfaced (non-question dismisses are skipped).
609
+ * Observers run after ELO/SRS are recorded and before navigation. Each is
610
+ * awaited but isolated in try/catch — a throwing observer is logged and
611
+ * skipped, never wedging the session. Keep observers cheap and `void` any
612
+ * long work (e.g. a triggered replan) to avoid stalling the draw.
613
+ */
614
+ /**
615
+ * Append a resolved ELO exchange to the in-memory log. Fires async (the ELO
616
+ * update is non-blocking), so an event can land after the response that
617
+ * produced it has returned — but well before close, which is when the log is
618
+ * persisted. Bounded to avoid unbounded growth.
619
+ */
620
+ _recordEloEvent(event) {
621
+ if (this._eloLog.length >= SessionController.MAX_LOGGED_ELO_EVENTS) return;
622
+ this._eloLog.push(event);
623
+ }
624
+ async _notifyOutcomeObservers(record, currentCard, result) {
625
+ if (this._outcomeObservers.length === 0) return;
626
+ if (!isQuestionRecord(record)) return;
627
+ const outcome = {
628
+ record,
629
+ card: currentCard.card,
630
+ result
631
+ };
632
+ const controls = this._getSessionControls();
633
+ for (const observer of this._outcomeObservers) try {
634
+ await observer(outcome, controls);
635
+ } catch (e) {
636
+ this.error("[OutcomeObserver] observer threw; ignoring", e);
637
+ }
638
+ }
639
+ /**
640
+ * Run a replan, bypassing requestReplan()'s coalesce logic.
641
+ *
642
+ * Use this when correctness depends on a *fresh* pipeline run, not on
643
+ * the existence of *some* in-flight replan. Specifically: the
644
+ * wedge-breaker path in nextCard(), where coalescing into a previous
645
+ * run that we now know produced insufficient content would re-create
646
+ * the bug we're trying to prevent.
647
+ *
648
+ * Still tracks _replanPromise like requestReplan() does so concurrent
649
+ * observers (auto-trigger guards in nextCard()) see consistent state.
650
+ */
651
+ async _replanUncoalesced(opts) {
652
+ const run = this._runReplan(opts);
653
+ const tracked = run.finally(() => {
654
+ if (this._replanPromise === tracked) {
655
+ this._replanPromise = null;
656
+ this._activeReplanLabel = null;
657
+ }
658
+ });
659
+ this._replanPromise = tracked;
660
+ await run;
661
+ }
662
+ /**
663
+ * Normalise the requestReplan argument. Accepts either a ReplanOptions
664
+ * object (new API) or a plain Record<string, unknown> (legacy callers
665
+ * that passed hints directly). Distinguishes the two by checking for
666
+ * the presence of ReplanOptions-specific keys.
667
+ */
668
+ normalizeReplanOptions(input) {
669
+ if (!input) return {};
670
+ const replanKeys = [
671
+ "hints",
672
+ "sessionHints",
673
+ "limit",
674
+ "mode",
675
+ "label",
676
+ "minFollowUpCards"
677
+ ];
678
+ if (Object.keys(input).some((k) => replanKeys.includes(k))) return input;
679
+ return { hints: input };
680
+ }
681
+ /** Minimum well-indicated cards before an additive retry is attempted */
682
+ static MIN_WELL_INDICATED = 5;
683
+ /**
684
+ * Score threshold for considering a card "well-indicated."
685
+ * Cards below this score are treated as fallback filler — present only
686
+ * because no strategy hard-removed them, but likely penalized by one
687
+ * or more filters. Strategy-agnostic: the SessionController doesn't
688
+ * know or care which strategy assigned the score.
689
+ */
690
+ static WELL_INDICATED_SCORE = .1;
691
+ /**
692
+ * supplyQ length at or below which the opportunistic depletion-prefetch
693
+ * fires. Sets the lead time available for the background replan to land
694
+ * before the user actually empties the queue and falls into the
695
+ * (synchronous) wedge-breaker path.
696
+ *
697
+ * Set to a small absolute value (not a fraction of batch limit) because
698
+ * pipeline latency is roughly fixed regardless of batch size — what
699
+ * matters is "how many cards of user-pace do we have left." 3 cards
700
+ * × ~3-5s/card = ~10-15s of lead time, comfortably exceeding typical
701
+ * pipeline latency.
702
+ */
703
+ static DEPLETION_PREFETCH_THRESHOLD = 3;
704
+ /**
705
+ * Internal replan execution. Runs the pipeline, rebuilds the supplyQ,
706
+ * atomically swaps it in, and triggers hydration for the new contents.
707
+ *
708
+ * If the initial replan produces fewer than MIN_WELL_INDICATED cards that
709
+ * pass all hierarchy filters, one additive retry is attempted — merging
710
+ * any new high-quality candidates into the front of the queue.
711
+ */
712
+ async _executeReplan(opts = {}) {
713
+ const limit = opts.limit;
714
+ const mode = opts.mode ?? "replace";
715
+ const wellIndicated = await this.getWeightedContent({
716
+ replan: true,
717
+ additive: mode === "merge",
718
+ limit
719
+ });
720
+ this._recordRuns(opts.label ?? "(auto)", mode);
721
+ this._wellIndicatedRemaining = wellIndicated;
722
+ if (limit !== void 0 && limit < this._defaultBatchLimit) {
723
+ this._suppressQualityReplan = true;
724
+ this.log(`[Replan] Burst mode (limit=${limit}): suppressing quality-based auto-replan`);
725
+ } else this._suppressQualityReplan = false;
726
+ if (wellIndicated >= 0 && wellIndicated < SessionController.MIN_WELL_INDICATED) this.log(`[Replan] Only ${wellIndicated}/${SessionController.MIN_WELL_INDICATED} well-indicated cards after replan`);
727
+ await this.hydrationService.ensureHydratedCards();
728
+ const labelTag = opts.label ? ` [${opts.label}]` : "";
729
+ this.log(`Replan complete${labelTag}: supplyQ now has ${this.supplyQ.length} cards (mode=${mode})`);
730
+ snapshotQueues(this.supplyQ.length, this.failedQ.length);
731
+ }
732
+ addTime(seconds) {
733
+ this.endTime = new Date(this.endTime.valueOf() + 1e3 * seconds);
734
+ }
735
+ get failedCount() {
736
+ return this.failedQ.length;
737
+ }
738
+ toString() {
739
+ return `Session: ${this.supplyQ.length} supply, ${this.failedQ.length} failed`;
740
+ }
741
+ reportString() {
742
+ return `${this.supplyQ.dequeueCount} supply, ${this.failedQ.dequeueCount} failed`;
743
+ }
744
+ /**
745
+ * Returns debug information about the current session state.
746
+ * Used by SessionControllerDebug component for runtime inspection.
747
+ */
748
+ getDebugInfo() {
749
+ const supportsWeightedCards = this.sources.some((s) => typeof s.getWeightedCards === "function");
750
+ const extractQueueItems = (queue, limit = 10) => {
751
+ const items = [];
752
+ for (let i = 0; i < Math.min(queue.length, limit); i++) {
753
+ const item = queue.peek(i);
754
+ items.push({
755
+ courseID: item.courseID || "unknown",
756
+ cardID: item.cardID || "unknown",
757
+ status: item.status || "unknown",
758
+ score: item.score
759
+ });
760
+ }
761
+ return items;
762
+ };
763
+ return {
764
+ api: {
765
+ mode: supportsWeightedCards ? "weighted" : "legacy",
766
+ description: supportsWeightedCards ? "Using getWeightedCards() API with scored candidates" : "ERROR: getWeightedCards() not a function."
767
+ },
768
+ supplyQueue: {
769
+ length: this.supplyQ.length,
770
+ dequeueCount: this.supplyQ.dequeueCount,
771
+ items: extractQueueItems(this.supplyQ)
772
+ },
773
+ failedQueue: {
774
+ length: this.failedQ.length,
775
+ dequeueCount: this.failedQ.dequeueCount,
776
+ items: extractQueueItems(this.failedQ)
777
+ },
778
+ hydratedCache: {
779
+ count: this.hydrationService.hydratedCount,
780
+ cardIds: this.hydrationService.getHydratedCardIds()
781
+ },
782
+ replan: {
783
+ inProgress: this._replanPromise !== null,
784
+ suppressQualityReplan: this._suppressQualityReplan,
785
+ defaultBatchLimit: this._defaultBatchLimit,
786
+ minCardsGuarantee: this._minCardsGuarantee
787
+ }
788
+ };
789
+ }
790
+ /**
791
+ * Fetch weighted content from all sources, mix across sources, and populate
792
+ * the single supply queue in pipeline rank order.
793
+ *
794
+ * Reviews and new cards compete on one cross-comparable scale (SRS 0.5–1.0
795
+ * w/ backlog pressure vs ELO 0.0–1.0) — there is no origin split and no
796
+ * second mixer. The working set is `supplyLimit` cards (the top of the mixed
797
+ * ranking, plus any `+INF` required cards floated to the front); replans
798
+ * re-pull and re-rank the whole supply, so a heavy review backlog surfaces as
799
+ * a refreshed top-ranked working set rather than a frozen 200-card snapshot.
800
+ *
801
+ * @param options.replan - If true, this is a mid-session replan rather than
802
+ * initial session setup. Atomically replaces supplyQ contents and treats
803
+ * empty results as non-fatal.
804
+ * @param options.additive - If true (replan only), merge high-quality
805
+ * candidates into the front of the existing supplyQ instead of replacing it.
806
+ * @returns Number of "well-indicated" cards (passed all hierarchy filters)
807
+ * in the new content. Returns -1 if no content was loaded.
808
+ */
809
+ async getWeightedContent(options) {
810
+ const replan = options?.replan ?? false;
811
+ const additive = options?.additive ?? false;
812
+ const supplyLimit = options?.limit ?? this._defaultBatchLimit;
813
+ const fetchLimit = supplyLimit;
814
+ if (!replan) this._applyHintsToSources();
815
+ const batches = [];
816
+ for (let i = 0; i < this.sources.length; i++) {
817
+ const source = this.sources[i];
818
+ try {
819
+ const weighted = (await source.getWeightedCards(fetchLimit)).cards;
820
+ batches.push({
821
+ sourceIndex: i,
822
+ weighted
823
+ });
824
+ } catch (error) {
825
+ this.error(`Failed to get content from source ${i}:`, error);
826
+ if (this.sources.length === 1 && !replan) throw new Error(`Cannot start session: failed to load content from source ${i}`);
827
+ }
828
+ }
829
+ if (batches.length === 0) {
830
+ if (replan) {
831
+ this.log("Replan: no content from any source, keeping existing supplyQ");
832
+ return -1;
833
+ }
834
+ throw new Error(`Cannot start session: failed to load content from all ${this.sources.length} source(s). Check logs for details.`);
835
+ }
836
+ const mixedWeighted = this.mixer.mix(batches, fetchLimit * this.sources.length);
837
+ const sourceIds = batches.map((b) => {
838
+ return b.weighted[0]?.courseId || `source-${b.sourceIndex}`;
839
+ });
840
+ await Promise.all(sourceIds.map(async (id) => {
841
+ if (!this.courseNameCache.has(id)) try {
842
+ const config = await this.dataLayer.getCoursesDB().getCourseConfig(id);
843
+ this.courseNameCache.set(id, config.name);
844
+ } catch {}
845
+ }));
846
+ const sourceNames = sourceIds.map((id) => this.courseNameCache.get(id));
847
+ const quotaPerSource = this.mixer instanceof QuotaRoundRobinMixer ? Math.ceil(fetchLimit * this.sources.length / batches.length) : void 0;
848
+ captureMixerRun(this.mixer.constructor.name, batches, sourceIds, sourceNames, fetchLimit * this.sources.length, quotaPerSource, mixedWeighted);
849
+ const candidates = mixedWeighted.filter((w) => !this._servedCardIds.has(w.cardId));
850
+ const mandatoryWeighted = candidates.filter((w) => w.score === Number.POSITIVE_INFINITY);
851
+ const optionalWeighted = candidates.filter((w) => w.score !== Number.POSITIVE_INFINITY);
852
+ const supplyWeighted = [...mandatoryWeighted, ...optionalWeighted.slice(0, Math.max(0, supplyLimit - mandatoryWeighted.length))];
853
+ const mandatoryIds = new Set(mandatoryWeighted.map((w) => w.cardId));
854
+ const wellIndicated = supplyWeighted.filter((w) => w.score >= SessionController.WELL_INDICATED_SCORE).length;
855
+ let report = replan ? "Replan content:\n" : "Mixed content session created with:\n";
856
+ const supplyItems = supplyWeighted.map((w) => {
857
+ const origin = getCardOrigin(w);
858
+ const scoreStr = Number.isFinite(w.score) ? w.score.toFixed(2) : "+INF";
859
+ report += `${origin === "review" ? "Review" : "New"}: ${w.courseId}::${w.cardId} (score: ${scoreStr})\n`;
860
+ return this._buildSupplyItem(w, origin);
861
+ });
862
+ if (additive) {
863
+ const added = this.supplyQ.mergeToFront(supplyItems, (item) => item.cardID, mandatoryIds);
864
+ report += `Additive merge: ${added} cards added to front of supplyQ\n`;
865
+ } else if (replan) this.supplyQ.replaceAll(supplyItems, (item) => item.cardID);
866
+ else for (const item of supplyItems) this.supplyQ.add(item, item.cardID);
867
+ this.log(report);
868
+ return wellIndicated;
869
+ }
870
+ /**
871
+ * Build a supply item from a weighted candidate. Review-origin cards carry
872
+ * their `reviewID` so SRS outcome tracking and re-presentation work; new
873
+ * cards do not. `score` is carried on both for the debug overlay.
874
+ */
875
+ _buildSupplyItem(w, origin = getCardOrigin(w)) {
876
+ const base = {
877
+ cardID: w.cardId,
878
+ courseID: w.courseId,
879
+ contentSourceType: "course",
880
+ contentSourceID: w.courseId,
881
+ score: w.score
882
+ };
883
+ if (origin === "review") return {
884
+ ...base,
885
+ status: "review",
886
+ reviewID: w.reviewID
887
+ };
888
+ return {
889
+ ...base,
890
+ status: "new"
891
+ };
892
+ }
893
+ /**
894
+ * Returns items that should be pre-hydrated.
895
+ * Deterministic: top N items from each queue to ensure coverage.
896
+ * Failed queue items will typically already be hydrated (from initial render).
897
+ */
898
+ _getItemsToHydrate() {
899
+ const items = [];
900
+ const SUPPLY_PREFETCH = 3;
901
+ const FAILED_PREFETCH = 2;
902
+ for (let i = 0; i < Math.min(SUPPLY_PREFETCH, this.supplyQ.length); i++) items.push(this.supplyQ.peek(i));
903
+ for (let i = 0; i < Math.min(FAILED_PREFETCH, this.failedQ.length); i++) items.push(this.failedQ.peek(i));
904
+ return items;
905
+ }
906
+ /**
907
+ * Selects the next item to present to the user.
908
+ *
909
+ * The supplyQ is already rank-ordered (the pipeline + mixer did the mixing,
910
+ * with `+INF` required cards floated to the front), so the primary path is a
911
+ * deterministic front-to-back draw — no second new-vs-review mixer. The only
912
+ * remaining decisions are (a) when the session ends and (b) when to interleave
913
+ * a remediation card from failedQ. See decision doc §2/§3/§7.
914
+ */
915
+ _selectNextItemToHydrate() {
916
+ if (this.supplyQ.length === 0 && this.failedQ.length === 0) return null;
917
+ if (this._secondsRemaining < 2 && this.failedQ.length === 0 && this._minCardsGuarantee <= 0) return null;
918
+ if (this._secondsRemaining <= 0 && this._minCardsGuarantee <= 0) return this.failedQ.length > 0 ? this.failedQ.peek(0) : null;
919
+ const supplyTop = this.supplyQ.length > 0 ? this.supplyQ.peek(0) : null;
920
+ if (this._minCardsGuarantee > 0 && supplyTop) return supplyTop;
921
+ if (this.failedQ.length > 0 && this._shouldInterleaveFailed(supplyTop !== null)) return this.failedQ.peek(0);
922
+ if (supplyTop) return supplyTop;
923
+ if (this.failedQ.length > 0) return this.failedQ.peek(0);
924
+ this.log(`No more cards available for the session!`);
925
+ return null;
926
+ }
927
+ /** Supply draws between forced failed-queue interleaves (light steady cadence). */
928
+ static FAILED_INTERLEAVE_EVERY = 4;
929
+ /**
930
+ * Slack (seconds) below which the endgame failed-pressure kicks in: when the
931
+ * time left after clearing remediation drops under this, bias hard to failed
932
+ * so the session doesn't end with un-cleared remediation. Mirrors the old
933
+ * `availableTime > 20` ladder thresholds.
934
+ */
935
+ static FAILED_ENDGAME_SLACK_SECONDS = 20;
936
+ /**
937
+ * Whether to interleave a failed (remediation) card now instead of drawing
938
+ * the supply head. Replaces the old `newBound`/`reviewBound` probability
939
+ * ladder's failed path (decision doc §7).
940
+ *
941
+ * @param supplyAvailable - whether supplyQ has a card to draw instead.
942
+ */
943
+ _shouldInterleaveFailed(supplyAvailable) {
944
+ if (this.failedQ.length === 0) return false;
945
+ if (!supplyAvailable) return true;
946
+ if (this._secondsRemaining - this.estimateCleanupTime() <= SessionController.FAILED_ENDGAME_SLACK_SECONDS) return true;
947
+ return this._supplyDrawsSinceFailed >= SessionController.FAILED_INTERLEAVE_EVERY;
948
+ }
949
+ async nextCard(action = "dismiss-success") {
950
+ this.dismissCurrentCard(action);
951
+ if (this._minCardsGuarantee > 0) {
952
+ this._minCardsGuarantee--;
953
+ this.log(`[CardGuarantee] ${this._minCardsGuarantee} guaranteed cards remaining`);
954
+ }
955
+ if (this._replanPromise && this.supplyQ.length === 0 && this.failedQ.length === 0) {
956
+ this.log("nextCard: queues empty, awaiting in-flight replan before drawing");
957
+ await this._replanPromise;
958
+ }
959
+ if (this.supplyQ.length <= SessionController.DEPLETION_PREFETCH_THRESHOLD && this._secondsRemaining > 0 && !this._replanPromise) {
960
+ this._suppressQualityReplan = false;
961
+ this.log(`[AutoReplan:depletion] supplyQ has ${this.supplyQ.length} card(s) (${this.failedQ.length} failed pending) with ${this._secondsRemaining}s remaining. Triggering background replan.`);
962
+ this.requestReplan({
963
+ label: "auto:depletion",
964
+ mode: "merge"
965
+ });
966
+ }
967
+ if (!this._suppressQualityReplan && this._wellIndicatedRemaining <= 3 && this.supplyQ.length > 0 && !this._replanPromise) {
968
+ this.log(`[AutoReplan:quality] ${this._wellIndicatedRemaining} well-indicated cards remaining (supplyQ: ${this.supplyQ.length}). Triggering background replan.`);
969
+ this.requestReplan({ label: "auto:quality" });
970
+ }
971
+ if (this._secondsRemaining <= 0 && this.failedQ.length === 0 && this._minCardsGuarantee <= 0) {
972
+ this._currentCard = null;
973
+ endSessionTracking();
974
+ this._terminate();
975
+ return null;
976
+ }
977
+ const WEDGE_MAX_EMPTY_STREAK = 3;
978
+ const WEDGE_BACKOFF_MS = 250;
979
+ let wedgeEmptyStreak = 0;
980
+ while (this._secondsRemaining > 0 && this.supplyQ.length === 0 && this.failedQ.length === 0) {
981
+ this.log(`[WedgeBreaker] All queues empty with ${this._secondsRemaining}s remaining. Running pipeline (attempt ${wedgeEmptyStreak + 1}/${WEDGE_MAX_EMPTY_STREAK}).`);
982
+ await this._replanUncoalesced({ label: "wedge-breaker" });
983
+ if (this.supplyQ.length === 0 && this.failedQ.length === 0) {
984
+ wedgeEmptyStreak++;
985
+ if (wedgeEmptyStreak >= WEDGE_MAX_EMPTY_STREAK) {
986
+ this.log(`[WedgeBreaker] Pipeline returned no content ${WEDGE_MAX_EMPTY_STREAK} consecutive times. Giving up; session will end.`);
987
+ break;
988
+ }
989
+ await new Promise((resolve) => setTimeout(resolve, WEDGE_BACKOFF_MS));
990
+ } else wedgeEmptyStreak = 0;
991
+ }
992
+ const MAX_SKIP = 20;
993
+ for (let attempt = 0; attempt < MAX_SKIP; attempt++) {
994
+ const nextItem = this._selectNextItemToHydrate();
995
+ if (!nextItem) {
996
+ this._currentCard = null;
997
+ endSessionTracking();
998
+ this._terminate();
999
+ return null;
1000
+ }
1001
+ let card = this.hydrationService.getHydratedCard(nextItem.cardID);
1002
+ if (!card) card = await this.hydrationService.waitForCard(nextItem.cardID);
1003
+ this.removeItemFromQueue(nextItem);
1004
+ if (card) {
1005
+ await this.hydrationService.ensureHydratedCards();
1006
+ this._currentCard = card;
1007
+ const origin = nextItem.status === "review" || nextItem.status === "failed-review" ? "review" : nextItem.status === "new" || nextItem.status === "failed-new" ? "new" : "failed";
1008
+ const queueSource = nextItem.status.startsWith("failed") ? "failedQ" : "supplyQ";
1009
+ recordCardPresentation(nextItem.cardID, nextItem.courseID, this.courseNameCache.get(nextItem.courseID), origin, queueSource, nextItem.score);
1010
+ for (const source of this.sources) source.notePresented?.({
1011
+ cardId: nextItem.cardID,
1012
+ courseId: nextItem.courseID,
1013
+ status: nextItem.status
1014
+ });
1015
+ snapshotQueues(this.supplyQ.length, this.failedQ.length);
1016
+ return card;
1017
+ }
1018
+ this.log(`Skipping card ${nextItem.cardID}: hydration failed, trying next`);
1019
+ if (isReview(nextItem)) this.srsService.removeReview(nextItem.reviewID);
1020
+ }
1021
+ this.log(`Exhausted ${MAX_SKIP} skip attempts finding a hydratable card`);
1022
+ this._currentCard = null;
1023
+ endSessionTracking();
1024
+ this._terminate();
1025
+ return null;
1026
+ }
1027
+ /** Not awaited — the host renders the end screen off `nextCard()`'s null. */
1028
+ _terminate() {
1029
+ this.endSession().catch((e) => {
1030
+ logger.warn(`[SessionController] endSession failed: ${e}`);
1031
+ });
1032
+ }
1033
+ /**
1034
+ * Public API for processing user responses to cards.
1035
+ * @param cardRecord User's response record
1036
+ * @param cardHistory Promise resolving to the card's history
1037
+ * @param courseRegistrationDoc User's course registration document
1038
+ * @param currentCard Current study session record
1039
+ * @param courseId Course identifier
1040
+ * @param cardId Card identifier
1041
+ * @param maxAttemptsPerView Maximum attempts allowed per view
1042
+ * @param maxSessionViews Maximum session views for this card
1043
+ * @param sessionViews Current number of session views
1044
+ * @returns ResponseResult with navigation and UI instructions
1045
+ */
1046
+ async submitResponse(cardRecord, cardHistory, courseRegistrationDoc, currentCard, courseId, cardId, maxAttemptsPerView, maxSessionViews, sessionViews) {
1047
+ const studySessionItem = { ...currentCard.item };
1048
+ const result = await this.services.response.processResponse(cardRecord, cardHistory, studySessionItem, courseRegistrationDoc, currentCard, courseId, cardId, maxAttemptsPerView, maxSessionViews, sessionViews);
1049
+ await this._notifyOutcomeObservers(cardRecord, currentCard, result);
1050
+ return result;
1051
+ }
1052
+ dismissCurrentCard(action = "dismiss-success") {
1053
+ if (this._currentCard) {
1054
+ if (action === "dismiss-success") this.hydrationService.removeCard(this._currentCard.item.cardID);
1055
+ else if (action === "marked-failed") {
1056
+ let failedItem;
1057
+ if (isReview(this._currentCard.item)) failedItem = {
1058
+ cardID: this._currentCard.item.cardID,
1059
+ courseID: this._currentCard.item.courseID,
1060
+ contentSourceID: this._currentCard.item.contentSourceID,
1061
+ contentSourceType: this._currentCard.item.contentSourceType,
1062
+ status: "failed-review",
1063
+ reviewID: this._currentCard.item.reviewID
1064
+ };
1065
+ else failedItem = {
1066
+ cardID: this._currentCard.item.cardID,
1067
+ courseID: this._currentCard.item.courseID,
1068
+ contentSourceID: this._currentCard.item.contentSourceID,
1069
+ contentSourceType: this._currentCard.item.contentSourceType,
1070
+ status: "failed-new"
1071
+ };
1072
+ this.failedQ.add(failedItem, failedItem.cardID);
1073
+ this._supplyDrawsSinceFailed = 0;
1074
+ } else if (action === "dismiss-error") this.hydrationService.removeCard(this._currentCard.item.cardID);
1075
+ else if (action === "dismiss-failed") this.hydrationService.removeCard(this._currentCard.item.cardID);
1076
+ }
1077
+ }
1078
+ /**
1079
+ * Remove an item from its source queue after consumption by nextCard().
1080
+ */
1081
+ removeItemFromQueue(item) {
1082
+ this._clearDurableRequirement(item.cardID);
1083
+ this._servedCardIds.add(item.cardID);
1084
+ if (this.failedQ.peek(0)?.cardID === item.cardID) {
1085
+ this.failedQ.dequeue((queueItem) => queueItem.cardID);
1086
+ this._supplyDrawsSinceFailed = 0;
1087
+ } else if (this.supplyQ.peek(0)?.cardID === item.cardID) {
1088
+ this.supplyQ.dequeue((queueItem) => queueItem.cardID);
1089
+ this._supplyDrawsSinceFailed++;
1090
+ if (this._wellIndicatedRemaining > 0) this._wellIndicatedRemaining--;
1091
+ }
1092
+ }
1093
+ /**
1094
+ * Remove a satisfied card ID from the durable session-hint `requireCards`
1095
+ * list. Called when a card is consumed (see removeItemFromQueue). No-op if
1096
+ * the card was not a durable requirement.
1097
+ *
1098
+ * Matches literal IDs only: a glob/pattern requirement (which may stand for
1099
+ * several cards) is NOT considered satisfied by a single draw and is left in
1100
+ * place — durable patterns are the caller's responsibility, one-shot `hints`
1101
+ * remain the right tool for them.
1102
+ */
1103
+ _clearDurableRequirement(cardID) {
1104
+ const req = this._sessionHints?.requireCards;
1105
+ if (!req || req.length === 0) return;
1106
+ const next = req.filter((id) => id !== cardID);
1107
+ if (next.length === req.length) return;
1108
+ this._sessionHints = {
1109
+ ...this._sessionHints,
1110
+ requireCards: next.length > 0 ? next : void 0
1111
+ };
1112
+ this.log(`[Replan] Durable requirement satisfied & cleared on draw: ${cardID}`);
1113
+ }
1114
+ /**
1115
+ * End the session and record learning outcomes.
1116
+ *
1117
+ * This method aggregates all responses from the session and records a
1118
+ * UserOutcomeRecord if evolutionary orchestration is enabled.
1119
+ */
1120
+ /**
1121
+ * Idempotent. Called from every `nextCard()` path that returns null; hosts
1122
+ * should also call it with `'abandoned'` when tearing down mid-session.
1123
+ */
1124
+ async endSession(reason = "closed") {
1125
+ if (this._sessionClosed) return;
1126
+ this._sessionClosed = true;
1127
+ clearInterval(this._intervalHandle);
1128
+ setDebugSessionId(void 0);
1129
+ await this._closeSessionDoc(reason);
1130
+ if (!this._sessionRecord || this._sessionRecord.length === 0) return;
1131
+ const questionRecords = this._sessionRecord.flatMap((r) => r.records).filter((r) => r.userAnswer !== void 0);
1132
+ if (questionRecords.length === 0) return;
1133
+ let orchestrationContext = null;
1134
+ const strategies = [];
1135
+ for (const source of this.sources) if (source.getOrchestrationContext) {
1136
+ try {
1137
+ orchestrationContext = await source.getOrchestrationContext();
1138
+ if (source.getStrategyIds) strategies.push(...source.getStrategyIds());
1139
+ } catch (e) {
1140
+ logger.warn(`[SessionController] Failed to get orchestration context: ${e}`);
1141
+ }
1142
+ if (orchestrationContext) break;
1143
+ }
1144
+ if (!orchestrationContext) {
1145
+ logger.debug("[SessionController] No orchestration context available, skipping outcome recording");
1146
+ return;
1147
+ }
1148
+ const periodEnd = (/* @__PURE__ */ new Date()).toISOString();
1149
+ const periodStart = new Date(this.startTime).toISOString();
1150
+ await recordUserOutcome(orchestrationContext, periodStart, periodEnd, questionRecords, strategies);
1151
+ }
1152
+ async _closeSessionDoc(reason) {
1153
+ if (this._openDocPromise) await this._openDocPromise;
1154
+ const doc = this._sessionDoc;
1155
+ if (!doc) return;
1156
+ const records = this._sessionRecord.flatMap((r) => r.records);
1157
+ const questionRecords = records.filter(isQuestionRecord);
1158
+ try {
1159
+ const closed = {
1160
+ ...doc,
1161
+ status: reason,
1162
+ endTime: (/* @__PURE__ */ new Date()).toISOString(),
1163
+ tally: {
1164
+ cardsPresented: this._sessionRecord.length,
1165
+ responses: records.length,
1166
+ correct: questionRecords.filter((r) => r.isCorrect).length,
1167
+ incorrect: questionRecords.filter((r) => !r.isCorrect).length,
1168
+ failedQRemaining: this.failedQ.length,
1169
+ secondsRemaining: Math.max(0, this._secondsRemaining)
1170
+ },
1171
+ runs: [...this._runLog],
1172
+ eloEvents: [...this._eloLog],
1173
+ finalHints: this._sessionHints,
1174
+ stateAtEnd: await this._captureState("end")
1175
+ };
1176
+ this._sessionDoc = closed;
1177
+ await this.dataLayer.getUserDB().putStudySession(closed);
1178
+ this.log(`[Session] Session record ${closed._id} -> ${reason} (${closed.tally.cardsPresented} cards, ${closed.tally.responses} responses, ${this._runLog.length} pipeline runs)`);
1179
+ } catch (e) {
1180
+ logger.warn(`[SessionController] Failed to close session record: ${e}`);
1181
+ }
1182
+ }
1183
+ };
1184
+ //#endregion
1185
+ export { SessionController };
1186
+
1187
+ //# sourceMappingURL=SessionController.mjs.map