@vue-skuilder/db 0.2.21 → 0.2.22

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 (48) hide show
  1. package/dist/{contentSource-BMxsujRu.d.cts → contentSource-B1pqryv6.d.ts} +82 -2
  2. package/dist/{contentSource-Bazgkf4C.d.ts → contentSource-CpTxVrFx.d.cts} +82 -2
  3. package/dist/core/index.d.cts +16 -6
  4. package/dist/core/index.d.ts +16 -6
  5. package/dist/core/index.js +79 -4
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +74 -4
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-Bt-D6xas.d.ts → dataLayerProvider-BZqH27f4.d.ts} +1 -1
  10. package/dist/{dataLayerProvider-DifVCcIS.d.cts → dataLayerProvider-D4c7iUc_.d.cts} +1 -1
  11. package/dist/impl/couch/index.d.cts +3 -3
  12. package/dist/impl/couch/index.d.ts +3 -3
  13. package/dist/impl/couch/index.js +63 -4
  14. package/dist/impl/couch/index.js.map +1 -1
  15. package/dist/impl/couch/index.mjs +63 -4
  16. package/dist/impl/couch/index.mjs.map +1 -1
  17. package/dist/impl/static/index.d.cts +4 -4
  18. package/dist/impl/static/index.d.ts +4 -4
  19. package/dist/impl/static/index.js +63 -4
  20. package/dist/impl/static/index.js.map +1 -1
  21. package/dist/impl/static/index.mjs +63 -4
  22. package/dist/impl/static/index.mjs.map +1 -1
  23. package/dist/{index-k9NFHpS1.d.cts → index-DGApnUZ-.d.cts} +1 -1
  24. package/dist/{index-BLLT5BYE.d.ts → index-rmNIwnkV.d.ts} +1 -1
  25. package/dist/index.d.cts +51 -14
  26. package/dist/index.d.ts +51 -14
  27. package/dist/index.js +231 -12
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +226 -12
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/{types-CHgpWQAY.d.ts → types-B-Y3aoi5.d.ts} +1 -1
  32. package/dist/{types-legacy-4tlwHnXo.d.cts → types-legacy-BytY5eAR.d.cts} +9 -1
  33. package/dist/{types-legacy-4tlwHnXo.d.ts → types-legacy-BytY5eAR.d.ts} +9 -1
  34. package/dist/{types-BFUa1pa3.d.cts → types-r6fyuWP2.d.cts} +1 -1
  35. package/dist/util/packer/index.d.cts +3 -3
  36. package/dist/util/packer/index.d.ts +3 -3
  37. package/package.json +3 -3
  38. package/src/core/index.ts +1 -0
  39. package/src/core/interfaces/userDB.ts +7 -0
  40. package/src/core/navigators/PipelineDebugger.ts +41 -1
  41. package/src/core/navigators/index.ts +3 -0
  42. package/src/core/types/studySession.ts +100 -0
  43. package/src/core/types/types-legacy.ts +8 -0
  44. package/src/impl/common/BaseUserDB.ts +36 -0
  45. package/src/study/SessionController.ts +179 -2
  46. package/src/study/SessionDebugger.ts +4 -3
  47. package/src/study/SessionOverlay.ts +1 -0
  48. package/src/study/services/ResponseProcessor.ts +32 -4
package/dist/index.mjs CHANGED
@@ -103,6 +103,7 @@ var init_types_legacy = __esm({
103
103
  DocType3["STRATEGY_STATE"] = "STRATEGY_STATE";
104
104
  DocType3["USER_OUTCOME"] = "USER_OUTCOME";
105
105
  DocType3["STRATEGY_LEARNING_STATE"] = "STRATEGY_LEARNING_STATE";
106
+ DocType3["STUDY_SESSION"] = "STUDY_SESSION";
106
107
  return DocType3;
107
108
  })(DocType || {});
108
109
  DocTypePrefixes = {
@@ -119,7 +120,8 @@ var init_types_legacy = __esm({
119
120
  ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
120
121
  ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE",
121
122
  ["USER_OUTCOME" /* USER_OUTCOME */]: "USER_OUTCOME",
122
- ["STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */]: "STRATEGY_LEARNING_STATE"
123
+ ["STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */]: "STRATEGY_LEARNING_STATE",
124
+ ["STUDY_SESSION" /* STUDY_SESSION */]: "SESSION"
123
125
  };
124
126
  }
125
127
  });
@@ -947,10 +949,13 @@ __export(PipelineDebugger_exports, {
947
949
  buildRunReport: () => buildRunReport,
948
950
  captureRun: () => captureRun,
949
951
  clearRunHistory: () => clearRunHistory,
952
+ drainCapturedRuns: () => drainCapturedRuns,
950
953
  getActivePipeline: () => getActivePipeline,
954
+ getRunsForSession: () => getRunsForSession,
951
955
  mountPipelineDebugger: () => mountPipelineDebugger,
952
956
  pipelineDebugAPI: () => pipelineDebugAPI,
953
- registerPipelineForDebug: () => registerPipelineForDebug
957
+ registerPipelineForDebug: () => registerPipelineForDebug,
958
+ setDebugSessionId: () => setDebugSessionId
954
959
  });
955
960
  function registerPipelineForDebug(pipeline) {
956
961
  _activePipeline = pipeline;
@@ -958,8 +963,20 @@ function registerPipelineForDebug(pipeline) {
958
963
  function getActivePipeline() {
959
964
  return _activePipeline;
960
965
  }
966
+ function setDebugSessionId(sessionId) {
967
+ _currentSessionId = sessionId;
968
+ }
969
+ function drainCapturedRuns() {
970
+ const drained = _pendingRuns;
971
+ _pendingRuns = [];
972
+ return drained;
973
+ }
974
+ function getRunsForSession(sessionId) {
975
+ return runHistory.filter((r) => r.sessionId === sessionId).reverse();
976
+ }
961
977
  function clearRunHistory() {
962
978
  runHistory.length = 0;
979
+ _pendingRuns = [];
963
980
  }
964
981
  function getOrigin(card) {
965
982
  const firstEntry = card.provenance[0];
@@ -974,12 +991,15 @@ function captureRun(report) {
974
991
  const fullReport = {
975
992
  ...report,
976
993
  runId: `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
994
+ sessionId: _currentSessionId,
977
995
  timestamp: /* @__PURE__ */ new Date()
978
996
  };
979
997
  runHistory.unshift(fullReport);
980
998
  if (runHistory.length > MAX_RUNS) {
981
999
  runHistory.pop();
982
1000
  }
1001
+ _pendingRuns.push(fullReport);
1002
+ return fullReport;
983
1003
  }
984
1004
  function parseCardElo(provenance) {
985
1005
  const eloEntry = provenance.find((p) => p.strategy === "elo");
@@ -1307,7 +1327,7 @@ function mountPipelineDebugger() {
1307
1327
  win.skuilder = win.skuilder || {};
1308
1328
  win.skuilder.pipeline = pipelineDebugAPI;
1309
1329
  }
1310
- var _activePipeline, MAX_RUNS, runHistory, DISCARDED_KEEP_TOP, _uiContainer, _selectedRunIndex, _cardSearchQuery, pipelineDebugAPI;
1330
+ var _activePipeline, MAX_RUNS, runHistory, _currentSessionId, _pendingRuns, DISCARDED_KEEP_TOP, _uiContainer, _selectedRunIndex, _cardSearchQuery, pipelineDebugAPI;
1311
1331
  var init_PipelineDebugger = __esm({
1312
1332
  "src/core/navigators/PipelineDebugger.ts"() {
1313
1333
  "use strict";
@@ -1316,6 +1336,7 @@ var init_PipelineDebugger = __esm({
1316
1336
  _activePipeline = null;
1317
1337
  MAX_RUNS = 10;
1318
1338
  runHistory = [];
1339
+ _pendingRuns = [];
1319
1340
  DISCARDED_KEEP_TOP = 25;
1320
1341
  _uiContainer = null;
1321
1342
  _selectedRunIndex = null;
@@ -5539,11 +5560,13 @@ __export(navigators_exports, {
5539
5560
  clearSrsBacklogDebug: () => clearSrsBacklogDebug,
5540
5561
  clearStrategyPressureDebug: () => clearStrategyPressureDebug,
5541
5562
  diversityRerank: () => diversityRerank,
5563
+ drainCapturedRuns: () => drainCapturedRuns,
5542
5564
  getActivePipeline: () => getActivePipeline,
5543
5565
  getCardOrigin: () => getCardOrigin,
5544
5566
  getRegisteredNavigator: () => getRegisteredNavigator,
5545
5567
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
5546
5568
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
5569
+ getRunsForSession: () => getRunsForSession,
5547
5570
  getSrsBacklogDebug: () => getSrsBacklogDebug,
5548
5571
  getStrategyPressureDebug: () => getStrategyPressureDebug,
5549
5572
  hasRegisteredNavigator: () => hasRegisteredNavigator,
@@ -5552,7 +5575,8 @@ __export(navigators_exports, {
5552
5575
  isGenerator: () => isGenerator,
5553
5576
  mountPipelineDebugger: () => mountPipelineDebugger,
5554
5577
  pipelineDebugAPI: () => pipelineDebugAPI,
5555
- registerNavigator: () => registerNavigator
5578
+ registerNavigator: () => registerNavigator,
5579
+ setDebugSessionId: () => setDebugSessionId
5556
5580
  });
5557
5581
  function registerNavigator(implementingClass, constructor, role) {
5558
5582
  navigatorRegistry.set(implementingClass, { constructor, role });
@@ -8895,6 +8919,32 @@ Currently logged-in as ${this._username}.`
8895
8919
  };
8896
8920
  await this.localDB.put(doc);
8897
8921
  }
8922
+ /**
8923
+ * Open and close write the same `_id`, so the 409 path is the expected
8924
+ * route for the second write, not an error case.
8925
+ */
8926
+ async putStudySession(doc) {
8927
+ try {
8928
+ await this.localDB.put(doc);
8929
+ } catch (err) {
8930
+ if (err.status === 409) {
8931
+ const existing = await this.localDB.get(doc._id);
8932
+ await this.localDB.put({ ...doc, _rev: existing._rev });
8933
+ } else {
8934
+ throw err;
8935
+ }
8936
+ }
8937
+ }
8938
+ async getStudySessions(courseId) {
8939
+ const prefix = courseId ? `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::${courseId}::` : `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::`;
8940
+ const keys = getStartAndEndKeys(prefix);
8941
+ const res = await this.localDB.allDocs({
8942
+ startkey: keys.startkey,
8943
+ endkey: keys.endkey,
8944
+ include_docs: true
8945
+ });
8946
+ return res.rows.map((r) => r.doc).filter((d) => !!d).sort((a, b) => b.startTime.localeCompare(a.startTime));
8947
+ }
8898
8948
  async putUserOutcome(record) {
8899
8949
  try {
8900
8950
  await this.localDB.put(record);
@@ -10386,6 +10436,20 @@ var init_userOutcome = __esm({
10386
10436
  }
10387
10437
  });
10388
10438
 
10439
+ // src/core/types/studySession.ts
10440
+ function makeStudySessionId(courseId, userId, sessionId) {
10441
+ return `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::${courseId}::${userId}::${sessionId}`;
10442
+ }
10443
+ function newSessionId() {
10444
+ return `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
10445
+ }
10446
+ var init_studySession = __esm({
10447
+ "src/core/types/studySession.ts"() {
10448
+ "use strict";
10449
+ init_types_legacy();
10450
+ }
10451
+ });
10452
+
10389
10453
  // src/core/types/hydration.ts
10390
10454
  var HYDRATION_MARKER_ID;
10391
10455
  var init_hydration = __esm({
@@ -10874,6 +10938,7 @@ var init_core = __esm({
10874
10938
  init_user();
10875
10939
  init_strategyState();
10876
10940
  init_userOutcome();
10941
+ init_studySession();
10877
10942
  init_hydration();
10878
10943
  init_Loggable();
10879
10944
  init_util();
@@ -11539,7 +11604,9 @@ var ResponseProcessor = class {
11539
11604
  courseRegistrationDoc,
11540
11605
  currentCard,
11541
11606
  courseId,
11542
- cardId
11607
+ cardId,
11608
+ maxSessionViews,
11609
+ sessionViews
11543
11610
  );
11544
11611
  } else {
11545
11612
  result = this.processIncorrectResponse(
@@ -11574,7 +11641,7 @@ var ResponseProcessor = class {
11574
11641
  /**
11575
11642
  * Handles processing for correct responses: SRS scheduling and ELO updates.
11576
11643
  */
11577
- processCorrectResponse(cardRecord, history, studySessionItem, courseRegistrationDoc, currentCard, courseId, cardId) {
11644
+ processCorrectResponse(cardRecord, history, studySessionItem, courseRegistrationDoc, currentCard, courseId, cardId, maxSessionViews, sessionViews) {
11578
11645
  if (cardRecord.priorAttemps === 0) {
11579
11646
  const skipSrs = currentCard.card.tags.includes("srs:skip");
11580
11647
  if (!skipSrs) {
@@ -11622,12 +11689,16 @@ var ResponseProcessor = class {
11622
11689
  shouldClearFeedbackShadow: true
11623
11690
  };
11624
11691
  } else {
11692
+ const budgetSpent = sessionViews >= maxSessionViews;
11625
11693
  logger.info(
11626
- "[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO)"
11694
+ `[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); sessionViews=${sessionViews}/${maxSessionViews} -> ${budgetSpent ? "dismiss-success" : "marked-failed"}`
11627
11695
  );
11628
11696
  const { globalScore } = this.parsePerformance(cardRecord.performance);
11629
11697
  return {
11630
- nextCardAction: "marked-failed",
11698
+ // Budget spent: the learner did get it right, so retire the card as a
11699
+ // success rather than penalising it ('dismiss-failed' would apply an
11700
+ // ELO penalty for an answer that was correct).
11701
+ nextCardAction: budgetSpent ? "dismiss-success" : "marked-failed",
11631
11702
  shouldLoadNextCard: true,
11632
11703
  isCorrect: true,
11633
11704
  performanceScore: globalScore,
@@ -12004,6 +12075,8 @@ var ItemQueue = class {
12004
12075
  // src/study/SessionController.ts
12005
12076
  init_couch();
12006
12077
  init_core();
12078
+ init_types_legacy();
12079
+ init_studySession();
12007
12080
  init_recording();
12008
12081
 
12009
12082
  // src/util/index.ts
@@ -14207,8 +14280,7 @@ function clearStaleSessionDebugState() {
14207
14280
  clearSrsBacklogDebug();
14208
14281
  clearStrategyPressureDebug();
14209
14282
  }
14210
- function startSessionTracking(supplyQLength, failedQLength) {
14211
- const sessionId = `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
14283
+ function startSessionTracking(sessionId, supplyQLength, failedQLength) {
14212
14284
  activeSession = {
14213
14285
  sessionId,
14214
14286
  startTime: /* @__PURE__ */ new Date(),
@@ -14591,6 +14663,24 @@ var SessionController = class _SessionController extends Loggable {
14591
14663
  * `this`; constructed once so observers can rely on referential identity.
14592
14664
  */
14593
14665
  _sessionControls = null;
14666
+ /**
14667
+ * Minted at construction so the bootstrap pipeline run in `prepareSession()`
14668
+ * can carry it. Stamped onto every CardRecord and pipeline run this session.
14669
+ */
14670
+ sessionId;
14671
+ /** Host-supplied. Without it, no durable session doc is written. */
14672
+ _courseId;
14673
+ _stateSnapshotProvider;
14674
+ _sessionDoc = null;
14675
+ /**
14676
+ * Awaited by the close path — the open write is slow (time-boxed snapshot)
14677
+ * and would otherwise land last, leaving a finished session marked `open`.
14678
+ */
14679
+ _openDocPromise = null;
14680
+ _runLog = [];
14681
+ static MAX_LOGGED_RUNS = 100;
14682
+ /** Guards `endSession()` against the several termination paths racing it. */
14683
+ _sessionClosed = false;
14594
14684
  startTime;
14595
14685
  endTime;
14596
14686
  _secondsRemaining;
@@ -14624,6 +14714,8 @@ var SessionController = class _SessionController extends Loggable {
14624
14714
  */
14625
14715
  constructor(sources, time, dataLayer, getViewComponent, mixer, options) {
14626
14716
  super();
14717
+ this.sessionId = newSessionId();
14718
+ setDebugSessionId(this.sessionId);
14627
14719
  this.dataLayer = dataLayer;
14628
14720
  this.mixer = mixer || new QuotaRoundRobinMixer();
14629
14721
  this.srsService = new SrsService(dataLayer.getUserDB());
@@ -14646,7 +14738,10 @@ var SessionController = class _SessionController extends Loggable {
14646
14738
  if (options?.outcomeObservers?.length) {
14647
14739
  this._outcomeObservers = [...options.outcomeObservers];
14648
14740
  }
14741
+ this._courseId = options?.courseId;
14742
+ this._stateSnapshotProvider = options?.stateSnapshotProvider;
14649
14743
  this.log(`Session constructed:
14744
+ sessionId: ${this.sessionId}
14650
14745
  startTime: ${this.startTime}
14651
14746
  endTime: ${this.endTime}
14652
14747
  defaultBatchLimit: ${this._defaultBatchLimit}`);
@@ -14691,6 +14786,7 @@ var SessionController = class _SessionController extends Loggable {
14691
14786
  }
14692
14787
  clearStaleSessionDebugState();
14693
14788
  const wellIndicated = await this.getWeightedContent();
14789
+ this._recordRuns("bootstrap");
14694
14790
  this._wellIndicatedRemaining = wellIndicated;
14695
14791
  if (wellIndicated >= 0 && wellIndicated < _SessionController.MIN_WELL_INDICATED) {
14696
14792
  this.log(
@@ -14698,11 +14794,72 @@ var SessionController = class _SessionController extends Loggable {
14698
14794
  );
14699
14795
  }
14700
14796
  await this.hydrationService.ensureHydratedCards();
14701
- startSessionTracking(this.supplyQ.length, this.failedQ.length);
14797
+ startSessionTracking(this.sessionId, this.supplyQ.length, this.failedQ.length);
14798
+ this._openDocPromise = this._openSessionDoc();
14702
14799
  this._intervalHandle = setInterval(() => {
14703
14800
  this.tick();
14704
14801
  }, 1e3);
14705
14802
  }
14803
+ /** Label the runs the last plan produced. The pipeline can't know the why. */
14804
+ _recordRuns(label, mode) {
14805
+ for (const run of drainCapturedRuns()) {
14806
+ if (this._runLog.length >= _SessionController.MAX_LOGGED_RUNS) break;
14807
+ this._runLog.push({
14808
+ runId: run.runId,
14809
+ at: run.timestamp.toISOString(),
14810
+ label,
14811
+ ...mode ? { mode } : {},
14812
+ generatedCount: run.generatedCount,
14813
+ finalCount: run.finalCount,
14814
+ reviewsSelected: run.reviewsSelected,
14815
+ newSelected: run.newSelected
14816
+ });
14817
+ }
14818
+ }
14819
+ /** Time-boxed and isolated — a bad provider degrades the record, not the session. */
14820
+ async _captureState(phase) {
14821
+ if (!this._stateSnapshotProvider) return void 0;
14822
+ const TIMEOUT_MS = 3e3;
14823
+ try {
14824
+ return await Promise.race([
14825
+ Promise.resolve(this._stateSnapshotProvider(phase)),
14826
+ new Promise((resolve) => setTimeout(() => resolve(void 0), TIMEOUT_MS))
14827
+ ]);
14828
+ } catch (e) {
14829
+ this.log(`[Session] state snapshot (${phase}) failed: ${e}`);
14830
+ return void 0;
14831
+ }
14832
+ }
14833
+ /** Writing at open is what makes an unclosed session visible at all. */
14834
+ async _openSessionDoc() {
14835
+ if (!this._courseId) return;
14836
+ try {
14837
+ const user = this.dataLayer.getUserDB();
14838
+ const doc = {
14839
+ _id: makeStudySessionId(this._courseId, user.getUsername(), this.sessionId),
14840
+ docType: "STUDY_SESSION" /* STUDY_SESSION */,
14841
+ sessionId: this.sessionId,
14842
+ courseId: this._courseId,
14843
+ userId: user.getUsername(),
14844
+ startTime: this.startTime.toISOString(),
14845
+ status: "open",
14846
+ plannedSeconds: Math.round((this.endTime.valueOf() - this.startTime.valueOf()) / 1e3),
14847
+ config: {
14848
+ defaultBatchLimit: this._defaultBatchLimit,
14849
+ sourceCount: this.sources.length,
14850
+ initHints: this._sessionHints
14851
+ },
14852
+ initialQueues: { supplyQ: this.supplyQ.length, failedQ: this.failedQ.length },
14853
+ runs: [...this._runLog],
14854
+ stateAtStart: await this._captureState("start")
14855
+ };
14856
+ this._sessionDoc = doc;
14857
+ await user.putStudySession(doc);
14858
+ this.log(`[Session] Opened session record ${doc._id}`);
14859
+ } catch (e) {
14860
+ logger.warn(`[SessionController] Failed to open session record: ${e}`);
14861
+ }
14862
+ }
14706
14863
  /**
14707
14864
  * Request a mid-session replan. Re-runs the pipeline with current user state
14708
14865
  * and atomically replaces (or merges into) the supplyQ contents. Safe to call
@@ -14883,6 +15040,7 @@ var SessionController = class _SessionController extends Loggable {
14883
15040
  };
14884
15041
  });
14885
15042
  return {
15043
+ sessionId: this.sessionId,
14886
15044
  secondsRemaining: this.secondsRemaining,
14887
15045
  hasCardGuarantee: this.hasCardGuarantee,
14888
15046
  minCardsGuarantee: this._minCardsGuarantee,
@@ -15042,6 +15200,7 @@ var SessionController = class _SessionController extends Loggable {
15042
15200
  additive: mode === "merge",
15043
15201
  limit
15044
15202
  });
15203
+ this._recordRuns(opts.label ?? "(auto)", mode);
15045
15204
  this._wellIndicatedRemaining = wellIndicated;
15046
15205
  if (limit !== void 0 && limit < this._defaultBatchLimit) {
15047
15206
  this._suppressQualityReplan = true;
@@ -15353,6 +15512,7 @@ var SessionController = class _SessionController extends Loggable {
15353
15512
  if (this._secondsRemaining <= 0 && this.failedQ.length === 0 && this._minCardsGuarantee <= 0) {
15354
15513
  this._currentCard = null;
15355
15514
  endSessionTracking();
15515
+ void this._terminate();
15356
15516
  return null;
15357
15517
  }
15358
15518
  const WEDGE_MAX_EMPTY_STREAK = 3;
@@ -15382,6 +15542,7 @@ var SessionController = class _SessionController extends Loggable {
15382
15542
  if (!nextItem) {
15383
15543
  this._currentCard = null;
15384
15544
  endSessionTracking();
15545
+ void this._terminate();
15385
15546
  return null;
15386
15547
  }
15387
15548
  let card = this.hydrationService.getHydratedCard(nextItem.cardID);
@@ -15413,8 +15574,15 @@ var SessionController = class _SessionController extends Loggable {
15413
15574
  this.log(`Exhausted ${MAX_SKIP} skip attempts finding a hydratable card`);
15414
15575
  this._currentCard = null;
15415
15576
  endSessionTracking();
15577
+ void this._terminate();
15416
15578
  return null;
15417
15579
  }
15580
+ /** Not awaited — the host renders the end screen off `nextCard()`'s null. */
15581
+ _terminate() {
15582
+ void this.endSession().catch((e) => {
15583
+ logger.warn(`[SessionController] endSession failed: ${e}`);
15584
+ });
15585
+ }
15418
15586
  /**
15419
15587
  * Public API for processing user responses to cards.
15420
15588
  * @param cardRecord User's response record
@@ -15524,7 +15692,16 @@ var SessionController = class _SessionController extends Loggable {
15524
15692
  * This method aggregates all responses from the session and records a
15525
15693
  * UserOutcomeRecord if evolutionary orchestration is enabled.
15526
15694
  */
15527
- async endSession() {
15695
+ /**
15696
+ * Idempotent. Called from every `nextCard()` path that returns null; hosts
15697
+ * should also call it with `'abandoned'` when tearing down mid-session.
15698
+ */
15699
+ async endSession(reason = "closed") {
15700
+ if (this._sessionClosed) return;
15701
+ this._sessionClosed = true;
15702
+ clearInterval(this._intervalHandle);
15703
+ setDebugSessionId(void 0);
15704
+ await this._closeSessionDoc(reason);
15528
15705
  if (!this._sessionRecord || this._sessionRecord.length === 0) {
15529
15706
  return;
15530
15707
  }
@@ -15561,6 +15738,38 @@ var SessionController = class _SessionController extends Loggable {
15561
15738
  strategies
15562
15739
  );
15563
15740
  }
15741
+ async _closeSessionDoc(reason) {
15742
+ if (this._openDocPromise) await this._openDocPromise;
15743
+ const doc = this._sessionDoc;
15744
+ if (!doc) return;
15745
+ const records = this._sessionRecord.flatMap((r) => r.records);
15746
+ const questionRecords = records.filter(isQuestionRecord);
15747
+ try {
15748
+ const closed = {
15749
+ ...doc,
15750
+ status: reason,
15751
+ endTime: (/* @__PURE__ */ new Date()).toISOString(),
15752
+ tally: {
15753
+ cardsPresented: this._sessionRecord.length,
15754
+ responses: records.length,
15755
+ correct: questionRecords.filter((r) => r.isCorrect).length,
15756
+ incorrect: questionRecords.filter((r) => !r.isCorrect).length,
15757
+ failedQRemaining: this.failedQ.length,
15758
+ secondsRemaining: Math.max(0, this._secondsRemaining)
15759
+ },
15760
+ runs: [...this._runLog],
15761
+ finalHints: this._sessionHints,
15762
+ stateAtEnd: await this._captureState("end")
15763
+ };
15764
+ this._sessionDoc = closed;
15765
+ await this.dataLayer.getUserDB().putStudySession(closed);
15766
+ this.log(
15767
+ `[Session] Session record ${closed._id} -> ${reason} (${closed.tally.cardsPresented} cards, ${closed.tally.responses} responses, ${this._runLog.length} pipeline runs)`
15768
+ );
15769
+ } catch (e) {
15770
+ logger.warn(`[SessionController] Failed to close session record: ${e}`);
15771
+ }
15772
+ }
15564
15773
  };
15565
15774
 
15566
15775
  // src/study/index.ts
@@ -15608,6 +15817,7 @@ export {
15608
15817
  createOrchestrationContext,
15609
15818
  diversityRerank,
15610
15819
  docIsDeleted,
15820
+ drainCapturedRuns,
15611
15821
  endSessionTracking,
15612
15822
  ensureAppDataDirectory,
15613
15823
  getActiveController,
@@ -15621,6 +15831,7 @@ export {
15621
15831
  getRegisteredNavigator,
15622
15832
  getRegisteredNavigatorNames,
15623
15833
  getRegisteredNavigatorRole,
15834
+ getRunsForSession,
15624
15835
  getSrsBacklogDebug,
15625
15836
  getStrategyPressureDebug,
15626
15837
  getStudySource,
@@ -15638,12 +15849,14 @@ export {
15638
15849
  isReview,
15639
15850
  log,
15640
15851
  makeScheduledCardId,
15852
+ makeStudySessionId,
15641
15853
  mixerDebugAPI,
15642
15854
  mountMixerDebugger,
15643
15855
  mountPipelineDebugger,
15644
15856
  mountSessionDebugger,
15645
15857
  mountUserDBDebugger,
15646
15858
  newInterval,
15859
+ newSessionId,
15647
15860
  parseCardHistoryID,
15648
15861
  pipelineDebugAPI,
15649
15862
  processCustomQuestionsData,
@@ -15662,6 +15875,7 @@ export {
15662
15875
  runPeriodUpdate,
15663
15876
  scoreAccuracyInZone,
15664
15877
  sessionDebugAPI,
15878
+ setDebugSessionId,
15665
15879
  snapshotQueues,
15666
15880
  startSessionTracking,
15667
15881
  toggleSessionOverlay,