@vue-skuilder/db 0.2.35 → 0.2.37

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 (263) 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} +6413 -7738
  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 +694 -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 +1115 -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 +320 -0
  108. package/dist/impl/couch/CourseSyncService.mjs.map +1 -0
  109. package/dist/impl/couch/PouchDataLayerProvider.mjs +89 -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 +197 -0
  120. package/dist/impl/couch/courseAPI.mjs.map +1 -0
  121. package/dist/impl/couch/courseDB.mjs +735 -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} +7003 -10358
  126. package/dist/impl/couch/index.cjs.map +1 -0
  127. package/dist/impl/couch/index.d.ts +33 -5
  128. package/dist/impl/couch/index.mjs +152 -12147
  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} +2486 -5993
  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} +14190 -14249
  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/generators/prescribed.ts +42 -16
  216. package/src/core/navigators/index.ts +9 -3
  217. package/src/factory.ts +10 -1
  218. package/src/impl/common/BaseUserDB.ts +16 -5
  219. package/src/impl/common/index.ts +2 -0
  220. package/src/impl/common/userDBHelpers.ts +4 -58
  221. package/src/impl/common/userDBKeys.ts +64 -0
  222. package/src/impl/couch/CourseSyncService.ts +130 -20
  223. package/src/impl/couch/PouchDataLayerProvider.ts +14 -1
  224. package/src/impl/couch/courseAPI.ts +26 -12
  225. package/src/impl/couch/courseDB.ts +35 -15
  226. package/src/impl/couch/index.ts +18 -23
  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/tests/impl/courseSync.test.ts +139 -0
  235. package/tsup.config.ts +24 -21
  236. package/dist/SyncStrategy-BXliog1m.d.cts +0 -116
  237. package/dist/classroomDB-DLTtLZct.d.cts +0 -86
  238. package/dist/contentSource-FQZcZopC.d.cts +0 -2007
  239. package/dist/core/index.d.cts +0 -521
  240. package/dist/core/index.js.map +0 -1
  241. package/dist/core/index.mjs.map +0 -1
  242. package/dist/dataLayerProvider-3y21KtF-.d.cts +0 -61
  243. package/dist/diagnostics/index.d.cts +0 -561
  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-BIum9Ue2.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-BcWVH4ww.d.cts +0 -58
  258. package/dist/types-legacy-DdVjg81H.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
  263. /package/dist/diagnostics/{index.js.map → index.cjs.map} +0 -0
package/dist/index.d.cts DELETED
@@ -1,1663 +0,0 @@
1
- export { A as AdminDBInterface, d as AssignedCard, a as AssignedContent, c as AssignedCourse, b as AssignedTag, C as ClassroomDBInterface, S as StudentClassroomDBInterface, T as TeacherClassroomDBInterface } from './classroomDB-DLTtLZct.cjs';
2
- import { U as UserDBInterface, g as CourseRegistrationDoc, m as SessionEloEvent, S as StudySessionItem, W as WeightedCard, R as ReplanHints, o as StudyContentSource, x as SessionStateSnapshotProvider, G as GeneratorResult, N as NavigatorRole, c as ContentNavigationStrategyData, F as FilterKind, y as RegulatorConfig, C as CourseDBInterface } from './contentSource-FQZcZopC.cjs';
3
- export { P as ActivityRecord, ae as CardFilter, ag as CardFilterFactory, ah as CardGenerator, aj as CardGeneratorFactory, K as ClassroomRegistration, J as ClassroomRegistrationDesignation, L as ClassroomRegistrationDoc, d as ContentNavigator, v as ContentSourceID, b as CourseInfo, Q as CourseRegistration, a as CoursesDBInterface, aB as DEFAULT_REGULATOR_CONFIG, aM as DocumentUpdater, af as FilterContext, at as FilterImpact, ai as GeneratorContext, as as GeneratorSummary, _ as HYDRATION_MARKER_ID, $ as HydrationMarker, aF as INTAKE_CLOCK_KEY, aE as IntakeClockState, av as LearnableWeight, a0 as NavigatorConstructor, ab as NavigatorRoles, aa as Navigators, aw as OrchestrationContext, au as PipelineForecaster, aq as PipelineRunReport, l as RegulatorName, j as RegulatorReading, ar as RunReportCard, f as ScheduledCard, h as SessionStateSnapshot, M as SessionTrackingData, a8 as StrategyContribution, e as StudySessionDoc, p as StudySessionFailedItem, q as StudySessionFailedNewItem, r as StudySessionFailedReviewItem, s as StudySessionNewItem, t as StudySessionReviewItem, k as StudySessionRunCard, n as StudySessionRunCardTrail, i as StudySessionRunSummary, O as UserConfig, H as UserCourseSetting, E as UserCourseSettings, B as UserDBAuthenticator, z as UserDBReader, A as UserDBWriter, Y as UserHydrationState, Z as UserHydrationStatus, T as UserOutcomeRecord, I as UsrCrsDataInterface, aL as applyReading, ax as computeDeviation, az as computeEffectiveWeight, ay as computeSpread, aA as createOrchestrationContext, ap as drainCapturedRuns, aH as frozenMsAt, am as getActivePipeline, a9 as getCardOrigin, aP as getLapses, a5 as getRegisteredFilterKind, a2 as getRegisteredNavigator, a6 as getRegisteredNavigatorNames, a4 as getRegisteredNavigatorRole, ao as getRunsForSession, aO as getStreak, w as getStudySource, a3 as hasRegisteredNavigator, a7 as initializeNavigatorRegistry, aI as intakeHours, aK as intakeReading, ad as isFilter, ac as isGenerator, u as isReview, V as makeStudySessionId, al as mountPipelineDebugger, aN as newInterval, X as newSessionId, ak as pipelineDebugAPI, a1 as registerNavigator, aG as resetIntakeClock, aD as reviewMassReading, aC as reviewWeight, an as setDebugSessionId, aJ as stepIntakeClock } from './contentSource-FQZcZopC.cjs';
4
- import { D as DataLayerProvider } from './dataLayerProvider-3y21KtF-.cjs';
5
- import { e as CardHistory, c as CardRecord, d as QuestionRecord } from './types-legacy-DdVjg81H.cjs';
6
- export { C as CardData, g as CourseListData, h as DataShapeData, b as DisplayableData, D as DocType, f as DocTypePrefixes, F as Field, G as GuestUsername, Q as QualifiedCardID, i as QuestionData, S as SkuilderCourseData, a as Tag, T as TagStub, l as log } from './types-legacy-DdVjg81H.cjs';
7
- import { SrsBacklogDebug, StrategyPressureDebug, Loggable } from './core/index.cjs';
8
- export { BulkCardProcessorConfig, DIVERSITY_FLOOR, DIVERSITY_STRENGTH, DiversityRerankOptions, GradientObservation, GradientResult, ImportResult, PeriodUpdateInput, PeriodUpdateResult, PressureGaugeDebug, SignalConfig, StrategyLearningState, StrategyStateDoc, StrategyStateId, aggregateOutcomesForGradient, areQuestionRecords, buildStrategyStateId, captureStrategyPressure, clearSrsBacklogDebug, clearStrategyPressureDebug, computeOutcomeSignal, computeStrategyGradient, diversityRerank, docIsDeleted, getCardHistoryID, getDefaultLearnableWeight, getSrsBacklogDebug, getStrategyPressureDebug, importParsedCards, isQuestionRecord, mountUserDBDebugger, parseCardHistoryID, recordUserOutcome, runPeriodUpdate, scoreAccuracyInZone, updateLearningState, updateStrategyWeight, userDBDebugAPI, validateProcessorConfig } from './core/index.cjs';
9
- import { TaggedPerformance, TagFilter, DataShape, SeedMeta, CourseConfig } from '@vue-skuilder/common';
10
- import { S as StaticCourseManifest } from './types-BcWVH4ww.cjs';
11
- export { A as AttachmentData, C as ChunkMetadata, D as DesignDocument, I as IndexMetadata, a as PackedCourseData, P as PackerConfig } from './types-BcWVH4ww.cjs';
12
- import { F as FileSystemAdapter } from './index-BIum9Ue2.cjs';
13
- export { C as CouchDBToStaticPacker, a as FileStats, b as FileSystemError } from './index-BIum9Ue2.cjs';
14
- import moment from 'moment';
15
-
16
- /**
17
- * Service responsible for ELO rating calculations and updates.
18
- */
19
- declare class EloService {
20
- private dataLayer;
21
- private user;
22
- /** Per course ID: its compiled `CourseConfig.qaUsernamePattern`, or null. */
23
- private qaPatterns;
24
- constructor(dataLayer: DataLayerProvider, user: UserDBInterface);
25
- /**
26
- * Whether the current user is one of the course's QA accounts
27
- * (`CourseConfig.qaUsernamePattern`), whose responses must not move card
28
- * ELO. The pattern is read once per course. If the config is unreadable or
29
- * the pattern doesn't compile, nobody is a QA account.
30
- */
31
- private isQaUser;
32
- /**
33
- * Updates both user and card ELO ratings based on user performance.
34
- * @param userScore Score between 0-1 representing user performance
35
- * @param course_id Course identifier
36
- * @param card_id Card identifier
37
- * @param userCourseRegDoc User's course registration document (will be mutated)
38
- * @param currentCard Current card session record
39
- * @param k Optional K-factor for ELO calculation
40
- * @returns The captured before→after exchange for session logging, or null
41
- * if no update was applied (missing registration / unreadable ELO).
42
- */
43
- updateUserAndCardElo(userScore: number, course_id: string, card_id: string, userCourseRegDoc: CourseRegistrationDoc, currentCard: StudySessionRecord, k?: number): Promise<SessionEloEvent | null>;
44
- /**
45
- * Updates both user and card ELO ratings with per-tag granularity.
46
- * Tags in taggedPerformance but not on card will be created dynamically.
47
- *
48
- * @param taggedPerformance Performance object with _global and per-tag scores
49
- * @param course_id Course identifier
50
- * @param card_id Card identifier
51
- * @param userCourseRegDoc User's course registration document (will be mutated)
52
- * @param currentCard Current card session record
53
- */
54
- updateUserAndCardEloPerTag(taggedPerformance: TaggedPerformance, course_id: string, card_id: string, userCourseRegDoc: CourseRegistrationDoc, currentCard: StudySessionRecord): Promise<SessionEloEvent | null>;
55
- }
56
-
57
- /**
58
- * Service responsible for Spaced Repetition System (SRS) scheduling logic.
59
- */
60
- declare class SrsService {
61
- private user;
62
- constructor(user: UserDBInterface);
63
- /**
64
- * Remove a scheduled review from the user's database.
65
- * Used to clean up orphaned reviews (e.g., card deleted from course DB).
66
- */
67
- removeReview(reviewID: string): void;
68
- /**
69
- * Calculates the next review time for a card based on its history and
70
- * schedules it in the user's database.
71
- * @param history The full history of the card.
72
- * @param item The study session item, used to determine if a previous review needs to be cleared.
73
- */
74
- scheduleReview(history: CardHistory<CardRecord>, item: StudySessionItem): Promise<void>;
75
- }
76
-
77
- /**
78
- * Service responsible for orchestrating the complete response processing workflow.
79
- * Coordinates SRS scheduling and ELO updates for user card interactions.
80
- */
81
- declare class ResponseProcessor {
82
- private srsService;
83
- private eloService;
84
- /** Sink for resolved ELO exchanges, wired to the session's in-memory log. */
85
- private onEloEvent?;
86
- constructor(srsService: SrsService, eloService: EloService, onEloEvent?: (event: SessionEloEvent) => void);
87
- /**
88
- * ELO updates are fired without awaiting so response handling isn't blocked
89
- * on DB writes — but an unhandled rejection silently drops the update.
90
- * This produces a catch handler that surfaces the failure in logs.
91
- */
92
- private logEloFailure;
93
- /**
94
- * Fire an ELO update without blocking response handling, forwarding the
95
- * resolved exchange to the session log (if any) and surfacing failures.
96
- * Mirrors the previous `void update(...).catch(logEloFailure)` shape, with
97
- * the added `.then` capturing the before→after event for diagnostics.
98
- */
99
- private trackElo;
100
- /**
101
- * Parses performance data into global score and optional per-tag scores.
102
- *
103
- * @param performance - Numeric or structured performance from QuestionRecord
104
- * @returns Parsed performance with global score and optional tag scores
105
- */
106
- private parsePerformance;
107
- /**
108
- * Processes a user's response to a card, handling SRS scheduling and ELO updates.
109
- * @param cardRecord User's response record
110
- * @param cardHistory Promise resolving to the card's history
111
- * @param studySessionItem Current study session item
112
- * @param courseRegistrationDoc User's course registration (for ELO updates)
113
- * @param currentCard Current study session record
114
- * @param courseId Course identifier
115
- * @param cardId Card identifier
116
- * @param maxAttemptsPerView Maximum attempts allowed per view
117
- * @param maxSessionViews Maximum session views for this card
118
- * @param sessionViews Current number of session views
119
- * @returns ResponseResult with navigation and UI instructions
120
- */
121
- processResponse(cardRecord: CardRecord, cardHistory: Promise<CardHistory<CardRecord>>, studySessionItem: StudySessionItem, courseRegistrationDoc: CourseRegistrationDoc, currentCard: StudySessionRecord, courseId: string, cardId: string, maxAttemptsPerView: number, maxSessionViews: number, sessionViews: number): Promise<ResponseResult>;
122
- /**
123
- * Handles processing for correct responses: SRS scheduling and ELO updates.
124
- */
125
- private processCorrectResponse;
126
- /**
127
- * Handles processing for incorrect responses: ELO updates only.
128
- */
129
- private processIncorrectResponse;
130
- }
131
-
132
- interface HydratedCard<TView = unknown> {
133
- item: StudySessionItem;
134
- view: TView;
135
- data: any[];
136
- tags: string[];
137
- }
138
-
139
- interface MigrationOptions {
140
- chunkBatchSize: number;
141
- validateRoundTrip: boolean;
142
- cleanupOnFailure: boolean;
143
- timeout: number;
144
- }
145
- interface MigrationResult {
146
- success: boolean;
147
- documentsRestored: number;
148
- attachmentsRestored: number;
149
- designDocsRestored: number;
150
- courseConfigRestored: number;
151
- errors: string[];
152
- warnings: string[];
153
- migrationTime: number;
154
- tempDatabaseName?: string;
155
- }
156
- interface ValidationResult {
157
- valid: boolean;
158
- documentCountMatch: boolean;
159
- attachmentIntegrity: boolean;
160
- viewFunctionality: boolean;
161
- issues: ValidationIssue[];
162
- }
163
- interface ValidationIssue {
164
- type: 'error' | 'warning';
165
- category: 'documents' | 'attachments' | 'views' | 'metadata' | 'course_config';
166
- message: string;
167
- details?: any;
168
- }
169
- interface DocumentCounts {
170
- [docType: string]: number;
171
- }
172
- interface RestoreProgress {
173
- phase: 'manifest' | 'design_docs' | 'course_config' | 'documents' | 'attachments' | 'validation';
174
- current: number;
175
- total: number;
176
- message: string;
177
- }
178
- interface StaticCourseValidation {
179
- valid: boolean;
180
- manifestExists: boolean;
181
- chunksExist: boolean;
182
- attachmentsExist: boolean;
183
- errors: string[];
184
- warnings: string[];
185
- courseId?: string;
186
- courseName?: string;
187
- }
188
- interface AggregatedDocument {
189
- _id: string;
190
- _attachments?: Record<string, any>;
191
- docType: string;
192
- [key: string]: any;
193
- }
194
- interface AttachmentUploadResult {
195
- success: boolean;
196
- attachmentName: string;
197
- docId: string;
198
- error?: string;
199
- }
200
- declare const DEFAULT_MIGRATION_OPTIONS: MigrationOptions;
201
-
202
- declare class StaticToCouchDBMigrator {
203
- private options;
204
- private progressCallback?;
205
- private fs?;
206
- constructor(options?: Partial<MigrationOptions>, fileSystemAdapter?: FileSystemAdapter);
207
- /**
208
- * Set a progress callback to receive updates during migration
209
- */
210
- setProgressCallback(callback: (progress: RestoreProgress) => void): void;
211
- /**
212
- * Migrate a static course to CouchDB
213
- */
214
- migrateCourse(staticPath: string, targetDB: PouchDB.Database): Promise<MigrationResult>;
215
- /**
216
- * Load and parse the manifest file
217
- */
218
- private loadManifest;
219
- /**
220
- * Restore design documents to CouchDB
221
- */
222
- private restoreDesignDocuments;
223
- /**
224
- * Aggregate documents from all chunks
225
- */
226
- private aggregateDocuments;
227
- /**
228
- * Load documents from a single chunk file
229
- */
230
- private loadChunk;
231
- /**
232
- * Upload documents to CouchDB in batches
233
- */
234
- private uploadDocuments;
235
- /**
236
- * Upload attachments from filesystem to CouchDB
237
- */
238
- private uploadAttachments;
239
- /**
240
- * Upload a single attachment file
241
- */
242
- private uploadSingleAttachment;
243
- /**
244
- * Restore CourseConfig document from manifest
245
- */
246
- private restoreCourseConfig;
247
- /**
248
- * Calculate expected document counts from manifest
249
- */
250
- private calculateExpectedCounts;
251
- /**
252
- * Clean up database after failed migration
253
- */
254
- private cleanupFailedMigration;
255
- /**
256
- * Report progress to callback if available
257
- */
258
- private reportProgress;
259
- /**
260
- * Check if a path is a local file path (vs URL)
261
- */
262
- private isLocalPath;
263
- }
264
-
265
- /**
266
- * Validate that a static course directory contains all required files
267
- */
268
- declare function validateStaticCourse(staticPath: string, fs?: FileSystemAdapter): Promise<StaticCourseValidation>;
269
- /**
270
- * Validate the result of a migration by checking document counts and integrity
271
- */
272
- declare function validateMigration(targetDB: PouchDB.Database, expectedCounts: DocumentCounts, manifest: StaticCourseManifest): Promise<ValidationResult>;
273
-
274
- /**
275
- * Get the application data directory for the current platform
276
- * Uses ~/.tuilder as requested by user for simplicity
277
- */
278
- declare function getAppDataDirectory(): string;
279
- /**
280
- * Ensure the application data directory exists
281
- * Creates directory recursively if it doesn't exist
282
- */
283
- declare function ensureAppDataDirectory(): Promise<string>;
284
- /**
285
- * Get the full path for a PouchDB database file
286
- * @param dbName - The database name (e.g., 'userdb-Colin')
287
- */
288
- declare function getDbPath(dbName: string): string;
289
- /**
290
- * Initialize data directory for PouchDB usage
291
- * Should be called once at application startup
292
- */
293
- declare function initializeDataDirectory(): Promise<void>;
294
-
295
- /**
296
- * Represents a batch of content fetched from a single StudyContentSource.
297
- */
298
- interface SourceBatch {
299
- sourceIndex: number;
300
- weighted: WeightedCard[];
301
- }
302
- /**
303
- * Strategy interface for mixing content from multiple sources into a unified
304
- * set of weighted candidates.
305
- *
306
- * Different implementations can provide different balancing strategies:
307
- * - QuotaRoundRobinMixer: Equal representation per source
308
- * - MinMaxNormalizingMixer: Score normalization then global sort
309
- * - PercentileBucketMixer: Bucketed round-robin
310
- * etc.
311
- */
312
- interface SourceMixer {
313
- /**
314
- * Mix weighted cards from multiple sources into a unified, ordered list.
315
- *
316
- * @param batches - Content batches from each source
317
- * @param limit - Target number of cards to return
318
- * @returns Mixed and ordered weighted cards
319
- */
320
- mix(batches: SourceBatch[], limit: number): WeightedCard[];
321
- }
322
- /**
323
- * Quota-based mixer with interleaved output.
324
- *
325
- * Allocates equal representation to each source (top-N by score), then
326
- * interleaves the results by dealing from a randomly-shuffled source order.
327
- * Within each source, cards are dealt in score-descending order.
328
- *
329
- * This ensures that cards from different courses are spread throughout the
330
- * queue rather than clustered by score bands, which matters because
331
- * SessionController consumes queues front-to-back and sessions often end
332
- * before reaching the tail.
333
- */
334
- declare class QuotaRoundRobinMixer implements SourceMixer {
335
- mix(batches: SourceBatch[], limit: number): WeightedCard[];
336
- }
337
-
338
- /** A single queued item, carrying the now-load-bearing rank score + origin. */
339
- interface SessionQueueItemDebug {
340
- cardID: string;
341
- /** Item status: 'new' | 'review' | 'failed-new' | 'failed-review'. */
342
- status: string;
343
- /** Card nature, collapsed from status: 'new' | 'review'. */
344
- origin: 'new' | 'review';
345
- /** Pipeline suitability score at queue-build time; `+INF` marks a required card. */
346
- score?: number;
347
- }
348
- /** Per-queue debug view: total length, cumulative draws, and head-first items. */
349
- interface SessionQueueDebug {
350
- length: number;
351
- dequeueCount: number;
352
- /** Items in queue order, head (next draw) first. */
353
- cards: SessionQueueItemDebug[];
354
- }
355
- /**
356
- * A card the learner has interacted with this session (one entry per card in
357
- * the session record, regardless of which queue — if any — still holds it).
358
- */
359
- interface SessionDrawnCardDebug {
360
- cardID: string;
361
- /** Queue status at draw time: 'new' | 'review' | 'failed-new' | 'failed-review'. */
362
- status: string;
363
- /** Number of CardRecords logged for this card this session (≥1). */
364
- attempts: number;
365
- /** Latest record's correctness; null for non-question (info) records. */
366
- correct: boolean | null;
367
- /** Total time spent across all of this card's records, in ms. */
368
- timeSpentMs: number;
369
- }
370
- /** Live snapshot of the controller, read fresh on each overlay tick. */
371
- interface SessionDebugSnapshot {
372
- sessionId: string;
373
- secondsRemaining: number;
374
- hasCardGuarantee: boolean;
375
- minCardsGuarantee: number;
376
- wellIndicatedRemaining: number;
377
- /** cardID of the card currently in front of the learner, if any. */
378
- currentCard: string | null;
379
- /** Session-durable hints re-merged into every pipeline run this session. */
380
- sessionHints: ReplanHints | null;
381
- /** True while a replan is executing (in-flight). */
382
- replanActive: boolean;
383
- /** Reason for the in-flight replan (caller label, or '(auto)'); may be stale when idle. */
384
- replanLabel: string | null;
385
- /** The single rank-ordered supply (new + review interleaved), head first. */
386
- supplyQ: SessionQueueDebug;
387
- failedQ: SessionQueueDebug;
388
- /** SRS backlog state per course (drives the "is review starvation permanent?" read). */
389
- reviewBacklog: SrsBacklogDebug[];
390
- /** Per-strategy backpressure gauges (prescribed pressure, practice debt, ...). */
391
- strategyPressure: StrategyPressureDebug[];
392
- /** Every card the learner has interacted with this session, draw order. */
393
- drawnCards: SessionDrawnCardDebug[];
394
- }
395
- /** The narrow surface the overlay needs from a SessionController. */
396
- interface SessionDebugTarget {
397
- getDebugSnapshot(): SessionDebugSnapshot;
398
- }
399
- /**
400
- * The live-session surface available to out-of-tree callers through the
401
- * active-controller registry: the debug snapshot, plus the small set of
402
- * user-facing session controls a view may need without holding a ref into
403
- * the `<StudySession>` component's internals (e.g. wiring a timer's
404
- * add-time button from a composable). Keep this narrow — it is not a
405
- * general escape hatch to `SessionController`.
406
- */
407
- interface ActiveSessionHandle extends SessionDebugTarget {
408
- /** Extend the session clock by `seconds`. */
409
- addTime(seconds: number): void;
410
- }
411
- /** Called by SessionController's constructor. Pass `null` to deregister. */
412
- declare function registerActiveController(controller: ActiveSessionHandle | null): void;
413
- declare function getActiveController(): ActiveSessionHandle | null;
414
- /**
415
- * Toggle the pinned overlay on/off. No-ops (with a console hint) when there is
416
- * no DOM, so it is safe to call from any host environment.
417
- */
418
- declare function toggleSessionOverlay(): void;
419
-
420
- /**
421
- * Options for requesting a mid-session replan.
422
- *
423
- * All fields are optional — callers can pass just the fields they need.
424
- * When omitted, defaults match the existing behaviour (full 20-card
425
- * replace with no hints).
426
- */
427
- interface ReplanOptions {
428
- /** Scoring hints forwarded to the pipeline (boost/exclude/require). */
429
- hints?: ReplanHints;
430
- /**
431
- * Session-durable scoring hints. Unlike `hints` (one-shot, applied to
432
- * exactly the run this replan triggers), `sessionHints` are stashed on
433
- * the controller and re-merged into *every* subsequent pipeline run for
434
- * the remainder of the session — including the bare auto-replans
435
- * (depletion/quality) that carry no caller hints, and the wedge-breaker.
436
- *
437
- * Use for "emphasis that should outlive a single queue rebuild" — e.g.
438
- * boosting a just-failed concept tag, or a post-lesson concept boost set
439
- * at session start. Without this, a one-shot `hints` boost evaporates on
440
- * the next replan and the freshly-rebuilt (replace-mode) queue clobbers
441
- * whatever it surfaced.
442
- *
443
- * Semantics (KISS): setting `sessionHints` *replaces* the prior session
444
- * hints wholesale (caller beware — no accumulation, no decay). They live
445
- * until session end or until explicitly overwritten. Normal usage applies
446
- * a fixed boost, so repeated identical requests are no-ops.
447
- *
448
- * Merged with per-run `hints` via the pipeline's `mergeHints` (boosts
449
- * multiply, require/exclude lists concatenate).
450
- */
451
- sessionHints?: ReplanHints;
452
- /**
453
- * Like `sessionHints`, but *merged* into the existing session-durable hints
454
- * (via `mergeHints`) instead of replacing them. Use when emphasis should
455
- * *accumulate* across replans rather than clobber — e.g. introducing a second
456
- * concept mid-session must not wipe the first concept's boost, nor any
457
- * `difficultyBooster`/`conceptBackoff` state on other concepts.
458
- *
459
- * Merge semantics (see `mergeHints`): boosts MULTIPLY, require/exclude lists
460
- * concat-dedup. Re-emphasising the *same* tag therefore compounds — callers
461
- * boosting a tag they may have already boosted should clamp at the call site.
462
- *
463
- * If both `sessionHints` and `mergeSessionHints` are supplied, the replace is
464
- * applied first, then the merge — but they are normally mutually exclusive.
465
- */
466
- mergeSessionHints?: ReplanHints;
467
- /**
468
- * Maximum number of new cards to return from the pipeline.
469
- * Default: 20 (the standard session batch size).
470
- */
471
- limit?: number;
472
- /**
473
- * How to integrate the new cards into the existing supplyQ.
474
- * - `'replace'` (default): atomically swap the entire supplyQ.
475
- * - `'merge'`: insert new cards at the front, keeping existing cards.
476
- */
477
- mode?: 'replace' | 'merge';
478
- /**
479
- * Guarantee that at least this many cards will be served after the
480
- * replan, even if the session timer has expired. Prevents intro cards
481
- * from surfacing at the end of a session with zero follow-up exercise.
482
- * Decremented on each card draw while active.
483
- */
484
- minFollowUpCards?: number;
485
- /**
486
- * Human-readable label for debugging / provenance.
487
- * Appears in console logs and in card provenance entries created
488
- * by ephemeral hint application.
489
- */
490
- label?: string;
491
- }
492
- interface StudySessionRecord {
493
- card: {
494
- course_id: string;
495
- card_id: string;
496
- card_elo: number;
497
- tags: string[];
498
- };
499
- item: StudySessionItem;
500
- records: CardRecord[];
501
- }
502
-
503
- type SessionAction = 'dismiss-success' | 'dismiss-failed' | 'marked-failed' | 'dismiss-error';
504
- interface ResponseResult {
505
- nextCardAction: Exclude<SessionAction, 'dismiss-error'> | 'none';
506
- shouldLoadNextCard: boolean;
507
- /**
508
- * When true, the card requested deferred advancement via `deferAdvance`.
509
- * The record was logged and ELO updated, but navigation was suppressed.
510
- * StudySession should stash `nextCardAction` and wait for a
511
- * `ready-to-advance` event from the card before calling `nextCard()`.
512
- */
513
- deferred?: boolean;
514
- isCorrect: boolean;
515
- performanceScore?: number;
516
- shouldClearFeedbackShadow: boolean;
517
- }
518
- /**
519
- * Read-only snapshot of a single processed response, handed to every
520
- * registered {@link OutcomeObserver} after ELO/SRS have been recorded.
521
- *
522
- * Only emitted for question records (non-question dismisses are skipped).
523
- */
524
- interface SessionOutcome {
525
- /** The user's response. Includes `isCorrect`, `performance`, `priorAttemps`. */
526
- readonly record: QuestionRecord;
527
- /**
528
- * The card that was answered, including its `tags` — the primary key an
529
- * observer matches against (e.g. `gpc:exercise:*`). `card_elo` reflects
530
- * pre-update state; the ELO write for this response is already in flight.
531
- */
532
- readonly card: StudySessionRecord['card'];
533
- /** The navigation decision produced for this response (read-only). */
534
- readonly result: Readonly<ResponseResult>;
535
- }
536
- /**
537
- * The narrow capability surface handed to an {@link OutcomeObserver}. This is
538
- * the *only* way an observer can affect the session — it cannot touch ELO,
539
- * the queues, the timer, or mutate the `ResponseResult`. A misbehaving
540
- * observer degrades to "wrong boost", never "corrupted session".
541
- */
542
- interface SessionControls {
543
- /** Current session-durable hints, or null. For read-modify-write. */
544
- getSessionHints(): ReplanHints | null;
545
- /** Replace the session-durable hints wholesale (no decay). */
546
- setSessionHints(hints: ReplanHints | null): void;
547
- /**
548
- * Merge `hints` into the existing session-durable hints via the pipeline's
549
- * `mergeHints` (boosts multiply, require/exclude lists concat-dedup).
550
- * Convenience for the common "add a boost on top of what's there" case.
551
- * Note: multiplicative + no decay — clamp boost factors yourself if a
552
- * repeatedly-failed tag could compound unboundedly.
553
- */
554
- mergeSessionHints(hints: ReplanHints): void;
555
- /** Request a replan (e.g. `{ mode: 'merge' }` for immediate visibility). */
556
- requestReplan(opts?: ReplanOptions): Promise<void>;
557
- }
558
- /**
559
- * A consumer-supplied hook invoked after each question response is processed.
560
- *
561
- * Fires on *every* question response (gate inside on `record.isCorrect` /
562
- * `result.nextCardAction` as needed). Awaited but isolated: a throwing
563
- * observer is caught and logged, never wedging the session. Keep the
564
- * synchronous body cheap and `void` any long work (e.g. a triggered replan)
565
- * so you don't stall navigation.
566
- *
567
- * Registered via `StudySessionConfig.outcomeObservers` → constructor options.
568
- */
569
- type OutcomeObserver = (outcome: SessionOutcome, controls: SessionControls) => void | Promise<void>;
570
- interface SessionServices {
571
- response: ResponseProcessor;
572
- }
573
- declare class SessionController<TView = unknown> extends Loggable {
574
- _className: string;
575
- services: SessionServices;
576
- private srsService;
577
- private eloService;
578
- private hydrationService;
579
- private mixer;
580
- private dataLayer;
581
- private courseNameCache;
582
- /**
583
- * Default pipeline batch size for new-card planning.
584
- * Set via constructor options; falls back to 20 when not specified.
585
- * Individual replans can override via `ReplanOptions.limit`.
586
- */
587
- private _defaultBatchLimit;
588
- private sources;
589
- private _sessionRecord;
590
- set sessionRecord(r: StudySessionRecord[]);
591
- private _currentCard;
592
- /**
593
- * The single supply queue: `new` + `review` items interleaved in pipeline
594
- * rank order (the mixer's score-ordered, source-interleaved output, with
595
- * `+INF` required cards floated to the front). Drawn front-to-back; reviews
596
- * and new compete on one cross-comparable scale rather than being re-mixed
597
- * by a probability gate. Replaced/re-ranked wholesale on replan. See
598
- * `docs/decision-single-supply-queue.md`.
599
- */
600
- private supplyQ;
601
- private failedQ;
602
- /**
603
- * Supply draws since the last failed-queue *event* (a failed draw, or a card
604
- * entering failedQ on failure). Drives the light steady failed-interleave
605
- * (§7): after this many consecutive supply draws, a pending failed card is
606
- * drawn so remediation doesn't starve mid-session. Incremented on each supply
607
- * draw; reset to 0 both when a failed card is drawn AND when one is added to
608
- * failedQ — the latter gives a just-failed card spacing instead of an instant
609
- * retry (the counter would otherwise already be ≥ threshold from the preceding
610
- * supply run).
611
- */
612
- private _supplyDrawsSinceFailed;
613
- /**
614
- * Promise tracking a currently in-progress replan, or null if idle.
615
- * Used by nextCard() to await completion before drawing from queues.
616
- */
617
- private _replanPromise;
618
- /**
619
- * Reason for the replan currently executing in `_runReplan`, surfaced by the
620
- * debug overlay's spinner. The caller's `opts.label` when present, else
621
- * `'(auto)'`. Only meaningful while `_replanPromise` is non-null; cleared
622
- * when the in-flight chain settles.
623
- */
624
- private _activeReplanLabel;
625
- /**
626
- * Number of well-indicated supply cards remaining before the queue
627
- * degrades to poorly-indicated content. Decremented on each supplyQ
628
- * draw; when it hits 0, a replan is triggered automatically
629
- * (user state has changed from completing good cards).
630
- */
631
- private _wellIndicatedRemaining;
632
- /**
633
- * When true, suppresses the quality-based auto-replan trigger in
634
- * nextCard(). Set after a burst replan (small limit) to prevent the
635
- * auto-replan from clobbering the burst cards before they're consumed.
636
- * Cleared when the depletion-triggered replan fires (supplyQ exhausted).
637
- */
638
- private _suppressQualityReplan;
639
- /**
640
- * When > 0, the session timer cannot end the session. Decremented on
641
- * each nextCard() draw. Set by replans that include `minFollowUpCards`.
642
- */
643
- private _minCardsGuarantee;
644
- /**
645
- * Session-durable scoring hints. Re-merged into every pipeline run for
646
- * the rest of the session (initial plan + every replan, including bare
647
- * auto-replans and the wedge-breaker), via `_applyHintsToSources`.
648
- *
649
- * Set by `setSessionHints()` (e.g. session-start post-lesson boost) or by
650
- * any replan carrying `ReplanOptions.sessionHints` (e.g. a just-failed
651
- * concept boost). Replace semantics, no decay — lives until overwritten
652
- * or session end. See `ReplanOptions.sessionHints` for rationale.
653
- *
654
- * Note: the controller-managed auto-excludes (current card, session
655
- * record, imminent draw) are intentionally NOT folded in here — those are
656
- * recomputed per-run in `_runReplan` and would otherwise go stale.
657
- */
658
- private _sessionHints;
659
- /**
660
- * Card IDs that have been *served* (drawn/consumed) this session. Populated
661
- * at the single consumption choke-point (removeItemFromQueue), so it reflects
662
- * a draw the instant it happens — earlier than `_sessionRecord`, which only
663
- * lands once the card is *responded to*.
664
- *
665
- * Used to keep already-served cards out of supplyQ on every (re)plan, across
666
- * ALL origins: a `new` card shown once must never re-enter, and once replans
667
- * re-pull reviews, an answered/in-flight review must not re-enter the supply
668
- * before its SRS reschedule clears the due-window (the review-loop guard,
669
- * decision doc §4). This is the general guard against re-presentation —
670
- * including the case where a replan in flight captured a now-drawn card (e.g.
671
- * a +INF require-injected follow-up the depletion prefetch grabbed just before
672
- * it was drawn). failedQ is separate and controller-owned, so failed cards
673
- * legitimately recur there without being gated here.
674
- */
675
- private _servedCardIds;
676
- /**
677
- * Consumer-supplied hooks invoked after each question response is processed.
678
- * Seeded from constructor options (threaded from
679
- * `StudySessionConfig.outcomeObservers`). See {@link OutcomeObserver}.
680
- */
681
- private _outcomeObservers;
682
- /**
683
- * Lazily-built, stable capability object handed to observers. Bound to
684
- * `this`; constructed once so observers can rely on referential identity.
685
- */
686
- private _sessionControls;
687
- /**
688
- * Minted at construction so the bootstrap pipeline run in `prepareSession()`
689
- * can carry it. Stamped onto every CardRecord and pipeline run this session.
690
- */
691
- readonly sessionId: string;
692
- /** Host-supplied. Without it, no durable session doc is written. */
693
- private _courseId?;
694
- private _stateSnapshotProvider?;
695
- private _sessionDoc;
696
- /**
697
- * Awaited by the close path — the open write is slow (time-boxed snapshot)
698
- * and would otherwise land last, leaving a finished session marked `open`.
699
- */
700
- private _openDocPromise;
701
- private _runLog;
702
- private static readonly MAX_LOGGED_RUNS;
703
- /**
704
- * Per-response ELO exchanges as they resolve (see `SessionEloEvent`). Fed by
705
- * the ResponseProcessor's `onEloEvent` sink; flushed to the session doc at
706
- * close. Bounded so a runaway session can't grow it without limit.
707
- */
708
- private _eloLog;
709
- private static readonly MAX_LOGGED_ELO_EVENTS;
710
- /** Guards `endSession()` against the several termination paths racing it. */
711
- private _sessionClosed;
712
- private startTime;
713
- private endTime;
714
- private _secondsRemaining;
715
- get secondsRemaining(): number;
716
- /** True when a card guarantee is active, preventing timer-based session end. */
717
- get hasCardGuarantee(): boolean;
718
- get report(): string;
719
- get detailedReport(): string;
720
- private _intervalHandle;
721
- /**
722
- * @param sources - Array of content sources to mix for the session
723
- * @param time - Session duration in seconds
724
- * @param dataLayer - Data layer provider
725
- * @param getViewComponent - Function to resolve view components
726
- * @param mixer - Optional source mixer strategy (defaults to QuotaRoundRobinMixer)
727
- * @param options - Optional session-level configuration
728
- * @param options.defaultBatchLimit - Default supply working-set size (default: 20).
729
- * Smaller values for newer users cause more frequent replans, keeping plans
730
- * aligned with rapidly-changing user state.
731
- */
732
- constructor(sources: StudyContentSource[], time: number, dataLayer: DataLayerProvider, getViewComponent: (viewId: string) => TView, mixer?: SourceMixer, options?: {
733
- defaultBatchLimit?: number;
734
- outcomeObservers?: OutcomeObserver[];
735
- /** Omit to run without durable session recording. */
736
- courseId?: string;
737
- stateSnapshotProvider?: SessionStateSnapshotProvider;
738
- });
739
- private tick;
740
- /**
741
- * Returns a rough, erring toward conservative, guess at
742
- * the amount of time the failed cards queue will require
743
- * to clean up.
744
- *
745
- * (seconds)
746
- */
747
- private estimateCleanupTime;
748
- prepareSession(): Promise<void>;
749
- /** Label the runs the last plan produced. The pipeline can't know the why. */
750
- private _recordRuns;
751
- /** Time-boxed and isolated — a bad provider degrades the record, not the session. */
752
- private _captureState;
753
- /** Writing at open is what makes an unclosed session visible at all. */
754
- private _openSessionDoc;
755
- /**
756
- * Request a mid-session replan. Re-runs the pipeline with current user state
757
- * and atomically replaces (or merges into) the supplyQ contents. Safe to call
758
- * at any time during a session.
759
- *
760
- * Concurrency policy:
761
- * - Two unhinted auto-replans never run in parallel; the second coalesces
762
- * into the first (returns the same promise).
763
- * - A hint-bearing replan that arrives while another replan is in flight
764
- * is queued to run **after** the in-flight one rather than dropped.
765
- * This preserves caller intent (label, requireCards, excludeTags,
766
- * limit, minFollowUpCards) instead of silently discarding it. Without
767
- * queueing, a background auto-replan that started just before a
768
- * completion-triggered replan would clobber the queue with unhinted
769
- * results (e.g. surfacing another gpc-intro card right after one
770
- * completed, skipping the prescribed `c-wst-*` follow-up).
771
- *
772
- * Re-pulls and re-ranks the whole supply (including reviews); does NOT affect
773
- * failedQ (controller-owned remediation).
774
- *
775
- * If nextCard() is called while a replan is in flight, it will automatically
776
- * await the replan before drawing from queues, ensuring the user always sees
777
- * cards scored against their latest state.
778
- *
779
- * Typical trigger: application-level code (e.g. after a GPC intro completion)
780
- * calls this to ensure newly-unlocked content appears in the session.
781
- */
782
- requestReplan(options?: ReplanOptions | ReplanHints): Promise<void>;
783
- /**
784
- * True when a requestReplan call carries caller intent that must not be
785
- * silently dropped. Bare unhinted auto-replans (depletion / quality
786
- * triggers in nextCard) return false and may coalesce.
787
- */
788
- private _replanHasIntent;
789
- /**
790
- * Body of a single replan: populate auto-excludes, stash hints on
791
- * sources, log, then run the pipeline. Extracted so it can be invoked
792
- * either immediately (no in-flight replan) or queued (chained after
793
- * the in-flight one resolves).
794
- *
795
- * IMPORTANT: hint stash and the queue-state snapshot used to build
796
- * excludeCards happen at *invocation* time, not at *queue* time. For a
797
- * queued replan that means excludes reflect the state after the prior
798
- * replan landed — which is what we want, since the prior replan's
799
- * supplyQ.peek(0) is the imminent draw we need to exclude.
800
- */
801
- private _runReplan;
802
- /**
803
- * Set the session-durable scoring hints (replace semantics, no decay).
804
- *
805
- * Unlike a one-shot replan hint, these are re-merged into every pipeline
806
- * run for the rest of the session — including the initial plan when set
807
- * before `prepareSession()`, every replan, the bare auto-replans, and the
808
- * wedge-breaker. Pass `null` to clear.
809
- *
810
- * Typical callers:
811
- * - `StudySession` at session start, threading `StudySessionConfig.initHints`
812
- * (e.g. a post-lesson concept boost) — so the boost outlives the first
813
- * queue rebuild instead of being clobbered by the first auto-replan.
814
- * - A consumer view on a failure, boosting the just-failed concept tag.
815
- *
816
- * Does not itself trigger a replan; the next plan/replan picks it up.
817
- */
818
- setSessionHints(hints: ReplanHints | null): void;
819
- /**
820
- * Read the current session-durable hints (for read-modify-write callers,
821
- * e.g. an outcome observer that clamps a compounding boost).
822
- */
823
- getSessionHints(): ReplanHints | null;
824
- /**
825
- * Live state snapshot for the debug overlay (window.skuilder.session
826
- * .dbgOverlay()). Reads directly from the private queues and hints, so it
827
- * always reflects the current moment — unlike the passive SessionDebugger
828
- * snapshots, which only capture what was explicitly pushed to them.
829
- */
830
- getDebugSnapshot(): SessionDebugSnapshot;
831
- /**
832
- * Merge `hints` into the durable session hints via the pipeline's
833
- * `mergeHints` (boosts multiply, require/exclude lists concat-dedup).
834
- * Convenience over get-then-set for the common additive case. Note the
835
- * multiplicative, no-decay semantics — clamp boost factors at the call
836
- * site if a repeatedly-emphasised tag could compound unboundedly.
837
- */
838
- mergeSessionHints(hints: ReplanHints): void;
839
- /**
840
- * Merge the durable `_sessionHints` with this run's one-shot hints and
841
- * push the result to every source for consumption on the next pipeline
842
- * run. Centralised so the initial plan and all replan paths apply session
843
- * emphasis identically. No-op when there are no hints of either kind.
844
- */
845
- private _applyHintsToSources;
846
- /**
847
- * Build (once) the stable capability object handed to outcome observers.
848
- * Methods are bound to `this`; the object identity is stable across calls
849
- * so observers may key off it.
850
- */
851
- private _getSessionControls;
852
- /**
853
- * Notify registered outcome observers about a processed response.
854
- *
855
- * Only question records are surfaced (non-question dismisses are skipped).
856
- * Observers run after ELO/SRS are recorded and before navigation. Each is
857
- * awaited but isolated in try/catch — a throwing observer is logged and
858
- * skipped, never wedging the session. Keep observers cheap and `void` any
859
- * long work (e.g. a triggered replan) to avoid stalling the draw.
860
- */
861
- /**
862
- * Append a resolved ELO exchange to the in-memory log. Fires async (the ELO
863
- * update is non-blocking), so an event can land after the response that
864
- * produced it has returned — but well before close, which is when the log is
865
- * persisted. Bounded to avoid unbounded growth.
866
- */
867
- private _recordEloEvent;
868
- private _notifyOutcomeObservers;
869
- /**
870
- * Run a replan, bypassing requestReplan()'s coalesce logic.
871
- *
872
- * Use this when correctness depends on a *fresh* pipeline run, not on
873
- * the existence of *some* in-flight replan. Specifically: the
874
- * wedge-breaker path in nextCard(), where coalescing into a previous
875
- * run that we now know produced insufficient content would re-create
876
- * the bug we're trying to prevent.
877
- *
878
- * Still tracks _replanPromise like requestReplan() does so concurrent
879
- * observers (auto-trigger guards in nextCard()) see consistent state.
880
- */
881
- private _replanUncoalesced;
882
- /**
883
- * Normalise the requestReplan argument. Accepts either a ReplanOptions
884
- * object (new API) or a plain Record<string, unknown> (legacy callers
885
- * that passed hints directly). Distinguishes the two by checking for
886
- * the presence of ReplanOptions-specific keys.
887
- */
888
- private normalizeReplanOptions;
889
- /** Minimum well-indicated cards before an additive retry is attempted */
890
- private static readonly MIN_WELL_INDICATED;
891
- /**
892
- * Score threshold for considering a card "well-indicated."
893
- * Cards below this score are treated as fallback filler — present only
894
- * because no strategy hard-removed them, but likely penalized by one
895
- * or more filters. Strategy-agnostic: the SessionController doesn't
896
- * know or care which strategy assigned the score.
897
- */
898
- private static readonly WELL_INDICATED_SCORE;
899
- /**
900
- * supplyQ length at or below which the opportunistic depletion-prefetch
901
- * fires. Sets the lead time available for the background replan to land
902
- * before the user actually empties the queue and falls into the
903
- * (synchronous) wedge-breaker path.
904
- *
905
- * Set to a small absolute value (not a fraction of batch limit) because
906
- * pipeline latency is roughly fixed regardless of batch size — what
907
- * matters is "how many cards of user-pace do we have left." 3 cards
908
- * × ~3-5s/card = ~10-15s of lead time, comfortably exceeding typical
909
- * pipeline latency.
910
- */
911
- private static readonly DEPLETION_PREFETCH_THRESHOLD;
912
- /**
913
- * Internal replan execution. Runs the pipeline, rebuilds the supplyQ,
914
- * atomically swaps it in, and triggers hydration for the new contents.
915
- *
916
- * If the initial replan produces fewer than MIN_WELL_INDICATED cards that
917
- * pass all hierarchy filters, one additive retry is attempted — merging
918
- * any new high-quality candidates into the front of the queue.
919
- */
920
- private _executeReplan;
921
- addTime(seconds: number): void;
922
- get failedCount(): number;
923
- toString(): string;
924
- reportString(): string;
925
- /**
926
- * Returns debug information about the current session state.
927
- * Used by SessionControllerDebug component for runtime inspection.
928
- */
929
- getDebugInfo(): {
930
- api: {
931
- mode: string;
932
- description: string;
933
- };
934
- supplyQueue: {
935
- length: number;
936
- dequeueCount: number;
937
- items: {
938
- courseID: any;
939
- cardID: any;
940
- status: any;
941
- score: any;
942
- }[];
943
- };
944
- failedQueue: {
945
- length: number;
946
- dequeueCount: number;
947
- items: {
948
- courseID: any;
949
- cardID: any;
950
- status: any;
951
- score: any;
952
- }[];
953
- };
954
- hydratedCache: {
955
- count: number;
956
- cardIds: string[];
957
- };
958
- replan: {
959
- inProgress: boolean;
960
- suppressQualityReplan: boolean;
961
- defaultBatchLimit: number;
962
- minCardsGuarantee: number;
963
- };
964
- };
965
- /**
966
- * Fetch weighted content from all sources, mix across sources, and populate
967
- * the single supply queue in pipeline rank order.
968
- *
969
- * Reviews and new cards compete on one cross-comparable scale (SRS 0.5–1.0
970
- * w/ backlog pressure vs ELO 0.0–1.0) — there is no origin split and no
971
- * second mixer. The working set is `supplyLimit` cards (the top of the mixed
972
- * ranking, plus any `+INF` required cards floated to the front); replans
973
- * re-pull and re-rank the whole supply, so a heavy review backlog surfaces as
974
- * a refreshed top-ranked working set rather than a frozen 200-card snapshot.
975
- *
976
- * @param options.replan - If true, this is a mid-session replan rather than
977
- * initial session setup. Atomically replaces supplyQ contents and treats
978
- * empty results as non-fatal.
979
- * @param options.additive - If true (replan only), merge high-quality
980
- * candidates into the front of the existing supplyQ instead of replacing it.
981
- * @returns Number of "well-indicated" cards (passed all hierarchy filters)
982
- * in the new content. Returns -1 if no content was loaded.
983
- */
984
- private getWeightedContent;
985
- /**
986
- * Build a supply item from a weighted candidate. Review-origin cards carry
987
- * their `reviewID` so SRS outcome tracking and re-presentation work; new
988
- * cards do not. `score` is carried on both for the debug overlay.
989
- */
990
- private _buildSupplyItem;
991
- /**
992
- * Returns items that should be pre-hydrated.
993
- * Deterministic: top N items from each queue to ensure coverage.
994
- * Failed queue items will typically already be hydrated (from initial render).
995
- */
996
- private _getItemsToHydrate;
997
- /**
998
- * Selects the next item to present to the user.
999
- *
1000
- * The supplyQ is already rank-ordered (the pipeline + mixer did the mixing,
1001
- * with `+INF` required cards floated to the front), so the primary path is a
1002
- * deterministic front-to-back draw — no second new-vs-review mixer. The only
1003
- * remaining decisions are (a) when the session ends and (b) when to interleave
1004
- * a remediation card from failedQ. See decision doc §2/§3/§7.
1005
- */
1006
- private _selectNextItemToHydrate;
1007
- /** Supply draws between forced failed-queue interleaves (light steady cadence). */
1008
- private static readonly FAILED_INTERLEAVE_EVERY;
1009
- /**
1010
- * Slack (seconds) below which the endgame failed-pressure kicks in: when the
1011
- * time left after clearing remediation drops under this, bias hard to failed
1012
- * so the session doesn't end with un-cleared remediation. Mirrors the old
1013
- * `availableTime > 20` ladder thresholds.
1014
- */
1015
- private static readonly FAILED_ENDGAME_SLACK_SECONDS;
1016
- /**
1017
- * Whether to interleave a failed (remediation) card now instead of drawing
1018
- * the supply head. Replaces the old `newBound`/`reviewBound` probability
1019
- * ladder's failed path (decision doc §7).
1020
- *
1021
- * @param supplyAvailable - whether supplyQ has a card to draw instead.
1022
- */
1023
- private _shouldInterleaveFailed;
1024
- nextCard(action?: SessionAction): Promise<HydratedCard<TView> | null>;
1025
- /** Not awaited — the host renders the end screen off `nextCard()`'s null. */
1026
- private _terminate;
1027
- /**
1028
- * Public API for processing user responses to cards.
1029
- * @param cardRecord User's response record
1030
- * @param cardHistory Promise resolving to the card's history
1031
- * @param courseRegistrationDoc User's course registration document
1032
- * @param currentCard Current study session record
1033
- * @param courseId Course identifier
1034
- * @param cardId Card identifier
1035
- * @param maxAttemptsPerView Maximum attempts allowed per view
1036
- * @param maxSessionViews Maximum session views for this card
1037
- * @param sessionViews Current number of session views
1038
- * @returns ResponseResult with navigation and UI instructions
1039
- */
1040
- submitResponse(cardRecord: CardRecord, cardHistory: Promise<CardHistory<CardRecord>>, courseRegistrationDoc: CourseRegistrationDoc, currentCard: StudySessionRecord, courseId: string, cardId: string, maxAttemptsPerView: number, maxSessionViews: number, sessionViews: number): Promise<ResponseResult>;
1041
- private dismissCurrentCard;
1042
- /**
1043
- * Remove an item from its source queue after consumption by nextCard().
1044
- */
1045
- private removeItemFromQueue;
1046
- /**
1047
- * Remove a satisfied card ID from the durable session-hint `requireCards`
1048
- * list. Called when a card is consumed (see removeItemFromQueue). No-op if
1049
- * the card was not a durable requirement.
1050
- *
1051
- * Matches literal IDs only: a glob/pattern requirement (which may stand for
1052
- * several cards) is NOT considered satisfied by a single draw and is left in
1053
- * place — durable patterns are the caller's responsibility, one-shot `hints`
1054
- * remain the right tool for them.
1055
- */
1056
- private _clearDurableRequirement;
1057
- /**
1058
- * End the session and record learning outcomes.
1059
- *
1060
- * This method aggregates all responses from the session and records a
1061
- * UserOutcomeRecord if evolutionary orchestration is enabled.
1062
- */
1063
- /**
1064
- * Idempotent. Called from every `nextCard()` path that returns null; hosts
1065
- * should also call it with `'abandoned'` when tearing down mid-session.
1066
- */
1067
- endSession(reason?: 'closed' | 'abandoned'): Promise<void>;
1068
- private _closeSessionDoc;
1069
- }
1070
-
1071
- /**
1072
- * A StudyContentSource that filters cards based on tag inclusion/exclusion.
1073
- *
1074
- * This enables ephemeral, tag-scoped study sessions where users can focus
1075
- * on specific topics within a course without permanent configuration.
1076
- *
1077
- * Filter logic:
1078
- * - If `include` is non-empty: card must have at least one of the included tags
1079
- * - If `exclude` is non-empty: card must not have any of the excluded tags
1080
- * - Both filters are applied (include first, then exclude)
1081
- */
1082
- declare class TagFilteredContentSource implements StudyContentSource {
1083
- private courseId;
1084
- private filter;
1085
- private user;
1086
- private resolvedCardIds;
1087
- constructor(courseId: string, filter: TagFilter, user: UserDBInterface);
1088
- /**
1089
- * Resolves the TagFilter to a set of eligible card IDs.
1090
- *
1091
- * - Cards in `include` tags are OR'd together (card needs at least one)
1092
- * - Cards in `exclude` tags are removed from the result
1093
- */
1094
- private resolveFilteredCardIds;
1095
- /**
1096
- * Get cards with suitability scores for presentation.
1097
- *
1098
- * Filters cards by tag inclusion/exclusion and assigns score=1.0 to all.
1099
- * TagFilteredContentSource does not currently support pluggable navigation
1100
- * strategies - it returns flat-scored candidates.
1101
- *
1102
- * @param limit - Maximum number of cards to return
1103
- * @returns Cards sorted by score descending (all scores = 1.0)
1104
- */
1105
- getWeightedCards(limit: number): Promise<GeneratorResult>;
1106
- /**
1107
- * Clears the cached resolved card IDs.
1108
- * Call this if the underlying tag data may have changed during a session.
1109
- */
1110
- clearCache(): void;
1111
- /**
1112
- * Returns the course ID this source is filtering.
1113
- */
1114
- getCourseId(): string;
1115
- /**
1116
- * Returns the active tag filter.
1117
- */
1118
- getFilter(): TagFilter;
1119
- }
1120
-
1121
- /**
1122
- * Summary of a single source's contribution to the mix.
1123
- */
1124
- interface SourceSummary {
1125
- sourceIndex: number;
1126
- sourceId: string;
1127
- sourceName?: string;
1128
- totalCards: number;
1129
- reviewCount: number;
1130
- newCount: number;
1131
- topScore: number;
1132
- bottomScore: number;
1133
- scoreRange: [number, number];
1134
- avgScore: number;
1135
- }
1136
- /**
1137
- * Per-source selection breakdown.
1138
- */
1139
- interface SourceSelectionBreakdown {
1140
- sourceId: string;
1141
- sourceName?: string;
1142
- reviewsProvided: number;
1143
- newProvided: number;
1144
- reviewsSelected: number;
1145
- newSelected: number;
1146
- totalSelected: number;
1147
- selectionRate: number;
1148
- }
1149
- /**
1150
- * Detailed card information in the mixer context.
1151
- */
1152
- interface MixerCardInfo {
1153
- cardId: string;
1154
- courseId: string;
1155
- origin: 'review' | 'new' | 'failed' | 'unknown';
1156
- score: number;
1157
- sourceIndex: number;
1158
- selected: boolean;
1159
- rankInSource?: number;
1160
- rankInMix?: number;
1161
- }
1162
- /**
1163
- * Complete record of a single mixer execution.
1164
- */
1165
- interface MixerRunReport {
1166
- runId: string;
1167
- timestamp: Date;
1168
- mixerType: string;
1169
- requestedLimit: number;
1170
- quotaPerSource?: number;
1171
- sourceSummaries: SourceSummary[];
1172
- cards: MixerCardInfo[];
1173
- finalCount: number;
1174
- reviewsSelected: number;
1175
- newSelected: number;
1176
- sourceBreakdowns: SourceSelectionBreakdown[];
1177
- }
1178
- /**
1179
- * Capture a mixer run for later inspection.
1180
- */
1181
- declare function captureMixerRun(mixerType: string, batches: SourceBatch[], sourceIds: string[], sourceNames: (string | undefined)[], requestedLimit: number, quotaPerSource: number | undefined, mixedResult: WeightedCard[]): void;
1182
- /**
1183
- * Console API object exposed on window.skuilder.mixer
1184
- */
1185
- declare const mixerDebugAPI: {
1186
- /**
1187
- * Get raw run history for programmatic access.
1188
- */
1189
- readonly runs: MixerRunReport[];
1190
- /**
1191
- * Show summary of a specific mixer run.
1192
- */
1193
- showRun(idOrIndex?: string | number): void;
1194
- /**
1195
- * Show summary of the last mixer run.
1196
- */
1197
- showLastMix(): void;
1198
- /**
1199
- * Explain source balance in the last run.
1200
- */
1201
- explainSourceBalance(): void;
1202
- /**
1203
- * Compare score distributions across sources.
1204
- */
1205
- compareScores(): void;
1206
- /**
1207
- * Show detailed information for a specific card.
1208
- */
1209
- showCard(cardId: string): void;
1210
- /**
1211
- * Show all runs in compact format.
1212
- */
1213
- listRuns(): void;
1214
- /**
1215
- * Export run history as JSON for bug reports.
1216
- */
1217
- export(): string;
1218
- /**
1219
- * Clear run history.
1220
- */
1221
- clear(): void;
1222
- /**
1223
- * Show help.
1224
- */
1225
- help(): void;
1226
- };
1227
- /**
1228
- * Mount the debug API on window.skuilder.mixer
1229
- */
1230
- declare function mountMixerDebugger(): void;
1231
-
1232
- /**
1233
- * Snapshot of queue state at a given moment.
1234
- */
1235
- interface QueueSnapshot {
1236
- timestamp: Date;
1237
- supplyQLength: number;
1238
- failedQLength: number;
1239
- supplyQNext3?: string[];
1240
- }
1241
- /**
1242
- * Record of a single card presentation.
1243
- */
1244
- interface CardPresentation {
1245
- timestamp: Date;
1246
- sequenceNumber: number;
1247
- cardId: string;
1248
- courseId: string;
1249
- courseName?: string;
1250
- origin: 'review' | 'new' | 'failed';
1251
- queueSource: 'supplyQ' | 'failedQ';
1252
- score?: number;
1253
- }
1254
- /**
1255
- * Complete session execution record.
1256
- */
1257
- interface SessionRunReport {
1258
- sessionId: string;
1259
- startTime: Date;
1260
- endTime?: Date;
1261
- initialQueues: QueueSnapshot;
1262
- presentations: CardPresentation[];
1263
- queueSnapshots: QueueSnapshot[];
1264
- }
1265
- /**
1266
- * Release pipeline run-history / SRS backlog debug memory from the previous
1267
- * session before this session begins piling new runs on top of it. Must be
1268
- * called before the first pipeline run of the new session (including the
1269
- * bootstrap run in prepareSession) — clearing on session START rather than
1270
- * END keeps post-session inspection, the dominant debugging workflow, fully
1271
- * functional: a finished session's run history sits intact until the user
1272
- * actually begins another one. It's a separate call from startSessionTracking
1273
- * because that function can't run until supplyQ/failedQ are populated by the
1274
- * bootstrap pipeline run, which would otherwise be cleared out from under it.
1275
- */
1276
- declare function clearStaleSessionDebugState(): void;
1277
- /**
1278
- * Start tracking a new session. The id is owned by `SessionController` — it is
1279
- * minted at construction so pipeline runs from `prepareSession()` onward can
1280
- * carry it.
1281
- */
1282
- declare function startSessionTracking(sessionId: string, supplyQLength: number, failedQLength: number): void;
1283
- /**
1284
- * Record a card presentation.
1285
- */
1286
- declare function recordCardPresentation(cardId: string, courseId: string, courseName: string | undefined, origin: 'review' | 'new' | 'failed', queueSource: 'supplyQ' | 'failedQ', score?: number): void;
1287
- /**
1288
- * Take a snapshot of current queue state.
1289
- */
1290
- declare function snapshotQueues(supplyQLength: number, failedQLength: number, supplyQNext3?: string[]): void;
1291
- /**
1292
- * End the current session tracking.
1293
- */
1294
- declare function endSessionTracking(): void;
1295
- /**
1296
- * Console API object exposed on window.skuilder.session
1297
- */
1298
- declare const sessionDebugAPI: {
1299
- /**
1300
- * Get raw session history for programmatic access.
1301
- */
1302
- readonly sessions: SessionRunReport[];
1303
- /**
1304
- * Get active session if any.
1305
- */
1306
- readonly active: SessionRunReport | null;
1307
- /**
1308
- * Show current queue state.
1309
- */
1310
- showQueue(): void;
1311
- /**
1312
- * Toggle the pinned, live-updating DOM overlay for the active controller
1313
- * (queues, session hints, timer). No-ops in non-browser hosts.
1314
- */
1315
- dbgOverlay(): void;
1316
- /**
1317
- * Show presentation history for current or past session.
1318
- */
1319
- showHistory(sessionIndex?: number): void;
1320
- /**
1321
- * Analyze course interleaving pattern.
1322
- */
1323
- showInterleaving(sessionIndex?: number): void;
1324
- /**
1325
- * List all tracked sessions.
1326
- */
1327
- listSessions(): void;
1328
- /**
1329
- * Export session history as JSON for bug reports.
1330
- */
1331
- export(): string;
1332
- /**
1333
- * Clear session history.
1334
- */
1335
- clear(): void;
1336
- /**
1337
- * Show help.
1338
- */
1339
- help(): void;
1340
- };
1341
- /**
1342
- * Mount the debug API on window.skuilder.session
1343
- */
1344
- declare function mountSessionDebugger(): void;
1345
-
1346
- type PlannedNavigatorOrigin =
1347
- /** From the course's strategy documents. */
1348
- 'strategy-doc'
1349
- /** Added by the assembler because the course declared none of its kind. */
1350
- | 'assembler-default'
1351
- /** Part of the fallback pipeline for a course with no strategy documents. */
1352
- | 'default-pipeline';
1353
- interface PlannedNavigator {
1354
- role: NavigatorRole;
1355
- origin: PlannedNavigatorOrigin;
1356
- /** The name runs report this navigator under (generator summaries, filter impacts). */
1357
- name: string;
1358
- implementingClass: string;
1359
- /** The strategy document: the course's own, or the default the assembler supplies. */
1360
- strategy: ContentNavigationStrategyData;
1361
- /**
1362
- * Filters only: the kind its class declares (`static kind`), read from the
1363
- * navigator registry. Undefined if undeclared, which runs as a gate.
1364
- */
1365
- kind?: FilterKind;
1366
- }
1367
- interface SkippedStrategy {
1368
- strategy: ContentNavigationStrategyData;
1369
- reason: string;
1370
- }
1371
- interface PipelinePlan {
1372
- /** Assembled from strategy documents, or the fallback for a course with none. */
1373
- kind: 'assembled' | 'default';
1374
- generators: PlannedNavigator[];
1375
- /** In run order. */
1376
- filters: PlannedNavigator[];
1377
- skipped: SkippedStrategy[];
1378
- warnings: string[];
1379
- /** Consequences of the plan worth knowing that aren't errors. */
1380
- notes: string[];
1381
- /** The regulator stage's settings (see regulators.ts). */
1382
- regulators: RegulatorConfig;
1383
- }
1384
- type PipelineStageKey = 'generate' | 'filter' | 'drop-zero' | 'regulate' | 'hints' | 'diversity' | 'select';
1385
- /** One step of a pipeline run, in order. Shared by views and text exports. */
1386
- interface PipelineStageInfo {
1387
- key: PipelineStageKey;
1388
- title: string;
1389
- summary: string;
1390
- }
1391
- /**
1392
- * The steps every pipeline run takes, in order (`Pipeline.getWeightedCards`).
1393
- * `generate` and `filter` are where a plan's navigators run; the rest are
1394
- * fixed framework behaviour.
1395
- */
1396
- declare const PIPELINE_STAGES: readonly PipelineStageInfo[];
1397
- /**
1398
- * Plan the pipeline a course's strategy documents assemble into.
1399
- *
1400
- * Mirrors the assembly rules: generators keep document order, with ELO and SRS
1401
- * added when absent; an ELO distance filter is added when absent; filters run
1402
- * sorted by name; unknown implementing classes are skipped with a warning. With no documents at all, describes the default
1403
- * pipeline that `createDefaultPipeline` builds instead.
1404
- */
1405
- declare function planPipeline(strategies: ContentNavigationStrategyData[], courseId: string): PipelinePlan;
1406
-
1407
- interface CourseLookupDoc {
1408
- _id: string;
1409
- _rev: string;
1410
- name: string;
1411
- disambiguator?: string;
1412
- }
1413
- /**
1414
- * A Lookup table of existant courses. Each docID in this DB correspondes to a
1415
- * course database whose name is `coursedb-{docID}`
1416
- */
1417
- declare class CourseLookup {
1418
- private static _dbInstance;
1419
- /**
1420
- * Static getter for the PouchDB database instance.
1421
- * Connects using ENV variables and caches the instance.
1422
- * Throws an error if required ENV variables are not set.
1423
- */
1424
- private static get _db();
1425
- /**
1426
- * Adds a new course to the lookup database, and returns the courseID
1427
- * @param courseName
1428
- * @returns
1429
- */
1430
- static add(courseName: string): Promise<string>;
1431
- /**
1432
- * Adds a new course to the lookup database with a specific courseID
1433
- * @param courseId The specific course ID to use
1434
- * @param courseName The course name
1435
- * @param disambiguator Optional disambiguator
1436
- * @returns Promise<void>
1437
- */
1438
- static addWithId(courseId: string, courseName: string, disambiguator?: string): Promise<void>;
1439
- /**
1440
- * Removes a course from the index
1441
- * @param courseID
1442
- */
1443
- static delete(courseID: string): Promise<PouchDB.Core.Response>;
1444
- static allCourseWare(): Promise<CourseLookupDoc[]>;
1445
- static updateDisambiguator(courseID: string, disambiguator?: string): Promise<PouchDB.Core.Response>;
1446
- static isCourse(courseID: string): Promise<boolean>;
1447
- }
1448
-
1449
- /**
1450
- * Interface for custom questions data structure returned by allCustomQuestions()
1451
- */
1452
- interface CustomQuestionsData {
1453
- courses: {
1454
- name: string;
1455
- }[];
1456
- questionClasses: {
1457
- name: string;
1458
- dataShapes?: DataShape[];
1459
- views?: {
1460
- name?: string;
1461
- }[];
1462
- seedData?: unknown[];
1463
- seedMeta?: (item: unknown) => SeedMeta;
1464
- }[];
1465
- dataShapes: DataShape[];
1466
- views: {
1467
- name?: string;
1468
- }[];
1469
- meta: {
1470
- questionCount: number;
1471
- dataShapeCount: number;
1472
- viewCount: number;
1473
- courseCount: number;
1474
- packageName: string;
1475
- sourceDirectory: string;
1476
- };
1477
- }
1478
- /**
1479
- * Interface for processed question data for registration
1480
- */
1481
- interface ProcessedQuestionData {
1482
- name: string;
1483
- course: string;
1484
- questionClass: {
1485
- name: string;
1486
- dataShapes?: DataShape[];
1487
- views?: {
1488
- name?: string;
1489
- }[];
1490
- seedData?: unknown[];
1491
- seedMeta?: (item: unknown) => SeedMeta;
1492
- };
1493
- dataShapes: DataShape[];
1494
- views: {
1495
- name?: string;
1496
- }[];
1497
- }
1498
- /**
1499
- * Interface for processed data shape for registration
1500
- */
1501
- interface ProcessedDataShape {
1502
- name: string;
1503
- course: string;
1504
- dataShape: DataShape;
1505
- }
1506
- /**
1507
- * Check if a data shape is already registered in the course config with valid schema
1508
- */
1509
- declare function isDataShapeRegistered(dataShape: ProcessedDataShape, courseConfig: CourseConfig): boolean;
1510
- declare function isDataShapeSchemaAvailable(dataShape: ProcessedDataShape, courseConfig: CourseConfig): boolean;
1511
- /**
1512
- * Check if a question type is already registered in the course config
1513
- */
1514
- declare function isQuestionTypeRegistered(question: ProcessedQuestionData, courseConfig: CourseConfig): boolean;
1515
- /**
1516
- * Process custom questions data into registration-ready format
1517
- */
1518
- declare function processCustomQuestionsData(customQuestions: CustomQuestionsData): {
1519
- dataShapes: ProcessedDataShape[];
1520
- questions: ProcessedQuestionData[];
1521
- };
1522
- /**
1523
- * Register a data shape in the course config
1524
- */
1525
- declare function registerDataShape(dataShape: ProcessedDataShape, courseConfig: CourseConfig): boolean;
1526
- /**
1527
- * Register a question type in the course config
1528
- */
1529
- declare function registerQuestionType(question: ProcessedQuestionData, courseConfig: CourseConfig): boolean;
1530
- /**
1531
- * Remove a data shape from the course config
1532
- * @returns true if the data shape was removed, false if it wasn't found
1533
- */
1534
- declare function removeDataShape(dataShapeName: string, courseConfig: CourseConfig): boolean;
1535
- /**
1536
- * Remove a question type from the course config
1537
- * @returns true if the question type was removed, false if it wasn't found
1538
- */
1539
- declare function removeQuestionType(questionTypeName: string, courseConfig: CourseConfig): boolean;
1540
- /**
1541
- * Remove data shapes and question types from course config and persist to database
1542
- */
1543
- declare function removeCustomQuestionTypes(dataShapeNames: string[], questionTypeNames: string[], courseConfig: CourseConfig, courseDB: CourseDBInterface): Promise<{
1544
- success: boolean;
1545
- removedCount: number;
1546
- errorMessage?: string;
1547
- }>;
1548
- /**
1549
- * Register seed data for a question type
1550
- *
1551
- * @param question - The processed question data
1552
- * @param courseDB - The course database interface
1553
- * @param username - The username to attribute seed data to
1554
- */
1555
- declare function registerSeedData(question: ProcessedQuestionData, courseDB: CourseDBInterface, username: string): Promise<void>;
1556
- /**
1557
- * Register BlanksCard (markdown fillIn) question type specifically
1558
- */
1559
- declare function registerBlanksCard(BlanksCard: {
1560
- name: string;
1561
- views?: {
1562
- name?: string;
1563
- }[];
1564
- }, BlanksCardDataShapes: DataShape[], courseConfig: CourseConfig, courseDB: CourseDBInterface, username?: string): Promise<{
1565
- success: boolean;
1566
- errorMessage?: string;
1567
- }>;
1568
- /**
1569
- * Main function to register all custom question types and data shapes
1570
- *
1571
- * @param customQuestions - The custom questions data from allCustomQuestions()
1572
- * @param courseConfig - The course configuration object
1573
- * @param courseDB - The course database interface
1574
- * @param username - The username to attribute seed data to
1575
- */
1576
- declare function registerCustomQuestionTypes(customQuestions: CustomQuestionsData, courseConfig: CourseConfig, courseDB: CourseDBInterface, username?: string): Promise<{
1577
- success: boolean;
1578
- registeredCount: number;
1579
- errorMessage?: string;
1580
- }>;
1581
-
1582
- declare const NOT_SET: "NOT_SET";
1583
- interface DBEnv {
1584
- COUCHDB_SERVER_URL: string;
1585
- COUCHDB_SERVER_PROTOCOL: string;
1586
- COUCHDB_USERNAME?: string;
1587
- COUCHDB_PASSWORD?: string;
1588
- LOCAL_STORAGE_PREFIX: string;
1589
- }
1590
- declare const ENV: DBEnv;
1591
-
1592
- interface DataLayerConfig {
1593
- type: 'couch' | 'static';
1594
- options: {
1595
- staticContentPath?: string;
1596
- localStoragePrefix?: string;
1597
- /** The host app's version (e.g. a git SHA), stamped on every study session it records. */
1598
- appVersion?: string;
1599
- manifests?: Record<string, StaticCourseManifest>;
1600
- COUCHDB_SERVER_URL?: string;
1601
- COUCHDB_SERVER_PROTOCOL?: string;
1602
- COUCHDB_USERNAME?: string;
1603
- COUCHDB_PASSWORD?: string;
1604
- COURSE_IDS?: string[];
1605
- /**
1606
- * Per-app tuning for the CouchDB→PouchDB course sync. Only applies when
1607
- * `type === 'couch'` and the course has `localSync.enabled === true`.
1608
- * See CourseSyncService.ReplicationOptions for defaults.
1609
- */
1610
- courseSync?: {
1611
- replication?: {
1612
- batchSize?: number;
1613
- batchesLimit?: number;
1614
- };
1615
- };
1616
- };
1617
- }
1618
- /**
1619
- * Initialize the data layer with the specified configuration
1620
- */
1621
- declare function initializeDataLayer(config: DataLayerConfig): Promise<DataLayerProvider>;
1622
- /**
1623
- * Get the initialized data layer instance
1624
- * @throws Error if not initialized
1625
- */
1626
- declare function getDataLayer(): DataLayerProvider;
1627
- /**
1628
- * Reset the data layer (primarily for testing)
1629
- */
1630
- declare function _resetDataLayer(): Promise<void>;
1631
-
1632
- declare const REVIEW_TIME_FORMAT: string;
1633
- /**
1634
- * Build a ScheduledCard `_id` for the given review time.
1635
- *
1636
- * The id suffix is not a mere uniquifier: `getReviewstoDate` PARSES the id
1637
- * (with {@link REVIEW_TIME_FORMAT}) to decide due-ness, so the id is the
1638
- * datum. Anything that writes or rewrites scheduled-card docs (scheduling,
1639
- * user-state snapshot rebasing) must construct ids through this helper —
1640
- * a hand-rolled formatter will get moment's `kk` token (01-24 hours) wrong.
1641
- */
1642
- declare function makeScheduledCardId(reviewTime: string | Date | moment.Moment): string;
1643
-
1644
- type UserAccountStatus = 'pending_verification' | 'verified' | 'suspended';
1645
- interface Entitlement {
1646
- status: 'trial' | 'paid';
1647
- registrationDate: string;
1648
- purchaseDate: string;
1649
- expires?: string;
1650
- }
1651
- type UserEntitlements = Record<string, Entitlement>;
1652
- interface CouchDbUserDoc extends PouchDB.Authentication.User {
1653
- name: string;
1654
- email: string;
1655
- status: UserAccountStatus;
1656
- verificationToken?: string | null;
1657
- verificationTokenExpiresAt?: string | null;
1658
- passwordResetToken?: string | null;
1659
- passwordResetTokenExpiresAt?: string | null;
1660
- entitlements: UserEntitlements;
1661
- }
1662
-
1663
- export { type ActiveSessionHandle, type AggregatedDocument, type AttachmentUploadResult, CardHistory, type CardPresentation, CardRecord, ContentNavigationStrategyData, type CouchDbUserDoc, CourseDBInterface, CourseLookup, CourseRegistrationDoc, type CustomQuestionsData, DEFAULT_MIGRATION_OPTIONS, type DataLayerConfig, DataLayerProvider, type DocumentCounts, ENV, type Entitlement, FileSystemAdapter, FilterKind, GeneratorResult, Loggable, type MigrationOptions, type MigrationResult, type MixerCardInfo, type MixerRunReport, NOT_SET, NavigatorRole, type OutcomeObserver, PIPELINE_STAGES, type PipelinePlan, type PipelineStageInfo, type PipelineStageKey, type PlannedNavigator, type PlannedNavigatorOrigin, type ProcessedDataShape, type ProcessedQuestionData, QuestionRecord, type QueueSnapshot, QuotaRoundRobinMixer, REVIEW_TIME_FORMAT, RegulatorConfig, ReplanHints, type ReplanOptions, type ResponseResult, type RestoreProgress, type SessionAction, SessionController, type SessionControls, type SessionDebugSnapshot, type SessionDebugTarget, type SessionDrawnCardDebug, SessionEloEvent, type SessionOutcome, type SessionQueueDebug, type SessionQueueItemDebug, type SessionRunReport, SessionStateSnapshotProvider, type SkippedStrategy, type SourceBatch, type SourceMixer, type SourceSelectionBreakdown, type SourceSummary, SrsBacklogDebug, StaticCourseManifest, type StaticCourseValidation, StaticToCouchDBMigrator, StrategyPressureDebug, StudyContentSource, StudySessionItem, type StudySessionRecord, TagFilteredContentSource, type UserAccountStatus, UserDBInterface, type UserEntitlements, type ValidationIssue, type ValidationResult, WeightedCard, _resetDataLayer, captureMixerRun, clearStaleSessionDebugState, endSessionTracking, ensureAppDataDirectory, getActiveController, getAppDataDirectory, getDataLayer, getDbPath, initializeDataDirectory, initializeDataLayer, isDataShapeRegistered, isDataShapeSchemaAvailable, isQuestionTypeRegistered, makeScheduledCardId, mixerDebugAPI, mountMixerDebugger, mountSessionDebugger, planPipeline, processCustomQuestionsData, recordCardPresentation, registerActiveController, registerBlanksCard, registerCustomQuestionTypes, registerDataShape, registerQuestionType, registerSeedData, removeCustomQuestionTypes, removeDataShape, removeQuestionType, sessionDebugAPI, snapshotQueues, startSessionTracking, toggleSessionOverlay, validateMigration, validateStaticCourse };