@vue-skuilder/db 0.2.20 → 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 (49) hide show
  1. package/dist/{contentSource-BDRX_YYJ.d.ts → contentSource-B1pqryv6.d.ts} +87 -2
  2. package/dist/{contentSource-D-LQYFyx.d.cts → contentSource-CpTxVrFx.d.cts} +87 -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-Dpshuql4.d.ts → dataLayerProvider-BZqH27f4.d.ts} +1 -1
  10. package/dist/{dataLayerProvider-Dd2UcCif.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/core/types/user.ts +6 -1
  45. package/src/impl/common/BaseUserDB.ts +36 -0
  46. package/src/study/SessionController.ts +179 -2
  47. package/src/study/SessionDebugger.ts +4 -3
  48. package/src/study/SessionOverlay.ts +1 -0
  49. package/src/study/services/ResponseProcessor.ts +32 -4
package/dist/index.js CHANGED
@@ -125,6 +125,7 @@ var init_types_legacy = __esm({
125
125
  DocType3["STRATEGY_STATE"] = "STRATEGY_STATE";
126
126
  DocType3["USER_OUTCOME"] = "USER_OUTCOME";
127
127
  DocType3["STRATEGY_LEARNING_STATE"] = "STRATEGY_LEARNING_STATE";
128
+ DocType3["STUDY_SESSION"] = "STUDY_SESSION";
128
129
  return DocType3;
129
130
  })(DocType || {});
130
131
  DocTypePrefixes = {
@@ -141,7 +142,8 @@ var init_types_legacy = __esm({
141
142
  ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
142
143
  ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE",
143
144
  ["USER_OUTCOME" /* USER_OUTCOME */]: "USER_OUTCOME",
144
- ["STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */]: "STRATEGY_LEARNING_STATE"
145
+ ["STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */]: "STRATEGY_LEARNING_STATE",
146
+ ["STUDY_SESSION" /* STUDY_SESSION */]: "SESSION"
145
147
  };
146
148
  }
147
149
  });
@@ -970,10 +972,13 @@ __export(PipelineDebugger_exports, {
970
972
  buildRunReport: () => buildRunReport,
971
973
  captureRun: () => captureRun,
972
974
  clearRunHistory: () => clearRunHistory,
975
+ drainCapturedRuns: () => drainCapturedRuns,
973
976
  getActivePipeline: () => getActivePipeline,
977
+ getRunsForSession: () => getRunsForSession,
974
978
  mountPipelineDebugger: () => mountPipelineDebugger,
975
979
  pipelineDebugAPI: () => pipelineDebugAPI,
976
- registerPipelineForDebug: () => registerPipelineForDebug
980
+ registerPipelineForDebug: () => registerPipelineForDebug,
981
+ setDebugSessionId: () => setDebugSessionId
977
982
  });
978
983
  function registerPipelineForDebug(pipeline) {
979
984
  _activePipeline = pipeline;
@@ -981,8 +986,20 @@ function registerPipelineForDebug(pipeline) {
981
986
  function getActivePipeline() {
982
987
  return _activePipeline;
983
988
  }
989
+ function setDebugSessionId(sessionId) {
990
+ _currentSessionId = sessionId;
991
+ }
992
+ function drainCapturedRuns() {
993
+ const drained = _pendingRuns;
994
+ _pendingRuns = [];
995
+ return drained;
996
+ }
997
+ function getRunsForSession(sessionId) {
998
+ return runHistory.filter((r) => r.sessionId === sessionId).reverse();
999
+ }
984
1000
  function clearRunHistory() {
985
1001
  runHistory.length = 0;
1002
+ _pendingRuns = [];
986
1003
  }
987
1004
  function getOrigin(card) {
988
1005
  const firstEntry = card.provenance[0];
@@ -997,12 +1014,15 @@ function captureRun(report) {
997
1014
  const fullReport = {
998
1015
  ...report,
999
1016
  runId: `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
1017
+ sessionId: _currentSessionId,
1000
1018
  timestamp: /* @__PURE__ */ new Date()
1001
1019
  };
1002
1020
  runHistory.unshift(fullReport);
1003
1021
  if (runHistory.length > MAX_RUNS) {
1004
1022
  runHistory.pop();
1005
1023
  }
1024
+ _pendingRuns.push(fullReport);
1025
+ return fullReport;
1006
1026
  }
1007
1027
  function parseCardElo(provenance) {
1008
1028
  const eloEntry = provenance.find((p) => p.strategy === "elo");
@@ -1330,7 +1350,7 @@ function mountPipelineDebugger() {
1330
1350
  win.skuilder = win.skuilder || {};
1331
1351
  win.skuilder.pipeline = pipelineDebugAPI;
1332
1352
  }
1333
- var _activePipeline, MAX_RUNS, runHistory, DISCARDED_KEEP_TOP, _uiContainer, _selectedRunIndex, _cardSearchQuery, pipelineDebugAPI;
1353
+ var _activePipeline, MAX_RUNS, runHistory, _currentSessionId, _pendingRuns, DISCARDED_KEEP_TOP, _uiContainer, _selectedRunIndex, _cardSearchQuery, pipelineDebugAPI;
1334
1354
  var init_PipelineDebugger = __esm({
1335
1355
  "src/core/navigators/PipelineDebugger.ts"() {
1336
1356
  "use strict";
@@ -1339,6 +1359,7 @@ var init_PipelineDebugger = __esm({
1339
1359
  _activePipeline = null;
1340
1360
  MAX_RUNS = 10;
1341
1361
  runHistory = [];
1362
+ _pendingRuns = [];
1342
1363
  DISCARDED_KEEP_TOP = 25;
1343
1364
  _uiContainer = null;
1344
1365
  _selectedRunIndex = null;
@@ -5562,11 +5583,13 @@ __export(navigators_exports, {
5562
5583
  clearSrsBacklogDebug: () => clearSrsBacklogDebug,
5563
5584
  clearStrategyPressureDebug: () => clearStrategyPressureDebug,
5564
5585
  diversityRerank: () => diversityRerank,
5586
+ drainCapturedRuns: () => drainCapturedRuns,
5565
5587
  getActivePipeline: () => getActivePipeline,
5566
5588
  getCardOrigin: () => getCardOrigin,
5567
5589
  getRegisteredNavigator: () => getRegisteredNavigator,
5568
5590
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
5569
5591
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
5592
+ getRunsForSession: () => getRunsForSession,
5570
5593
  getSrsBacklogDebug: () => getSrsBacklogDebug,
5571
5594
  getStrategyPressureDebug: () => getStrategyPressureDebug,
5572
5595
  hasRegisteredNavigator: () => hasRegisteredNavigator,
@@ -5575,7 +5598,8 @@ __export(navigators_exports, {
5575
5598
  isGenerator: () => isGenerator,
5576
5599
  mountPipelineDebugger: () => mountPipelineDebugger,
5577
5600
  pipelineDebugAPI: () => pipelineDebugAPI,
5578
- registerNavigator: () => registerNavigator
5601
+ registerNavigator: () => registerNavigator,
5602
+ setDebugSessionId: () => setDebugSessionId
5579
5603
  });
5580
5604
  function registerNavigator(implementingClass, constructor, role) {
5581
5605
  navigatorRegistry.set(implementingClass, { constructor, role });
@@ -8914,6 +8938,32 @@ Currently logged-in as ${this._username}.`
8914
8938
  };
8915
8939
  await this.localDB.put(doc);
8916
8940
  }
8941
+ /**
8942
+ * Open and close write the same `_id`, so the 409 path is the expected
8943
+ * route for the second write, not an error case.
8944
+ */
8945
+ async putStudySession(doc) {
8946
+ try {
8947
+ await this.localDB.put(doc);
8948
+ } catch (err) {
8949
+ if (err.status === 409) {
8950
+ const existing = await this.localDB.get(doc._id);
8951
+ await this.localDB.put({ ...doc, _rev: existing._rev });
8952
+ } else {
8953
+ throw err;
8954
+ }
8955
+ }
8956
+ }
8957
+ async getStudySessions(courseId) {
8958
+ const prefix = courseId ? `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::${courseId}::` : `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::`;
8959
+ const keys = getStartAndEndKeys(prefix);
8960
+ const res = await this.localDB.allDocs({
8961
+ startkey: keys.startkey,
8962
+ endkey: keys.endkey,
8963
+ include_docs: true
8964
+ });
8965
+ return res.rows.map((r) => r.doc).filter((d) => !!d).sort((a, b) => b.startTime.localeCompare(a.startTime));
8966
+ }
8917
8967
  async putUserOutcome(record) {
8918
8968
  try {
8919
8969
  await this.localDB.put(record);
@@ -10406,6 +10456,20 @@ var init_userOutcome = __esm({
10406
10456
  }
10407
10457
  });
10408
10458
 
10459
+ // src/core/types/studySession.ts
10460
+ function makeStudySessionId(courseId, userId, sessionId) {
10461
+ return `${DocTypePrefixes["STUDY_SESSION" /* STUDY_SESSION */]}::${courseId}::${userId}::${sessionId}`;
10462
+ }
10463
+ function newSessionId() {
10464
+ return `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
10465
+ }
10466
+ var init_studySession = __esm({
10467
+ "src/core/types/studySession.ts"() {
10468
+ "use strict";
10469
+ init_types_legacy();
10470
+ }
10471
+ });
10472
+
10409
10473
  // src/core/types/hydration.ts
10410
10474
  var HYDRATION_MARKER_ID;
10411
10475
  var init_hydration = __esm({
@@ -10895,6 +10959,7 @@ var init_core = __esm({
10895
10959
  init_user();
10896
10960
  init_strategyState();
10897
10961
  init_userOutcome();
10962
+ init_studySession();
10898
10963
  init_hydration();
10899
10964
  init_Loggable();
10900
10965
  init_util();
@@ -10946,6 +11011,7 @@ __export(index_exports, {
10946
11011
  createOrchestrationContext: () => createOrchestrationContext,
10947
11012
  diversityRerank: () => diversityRerank,
10948
11013
  docIsDeleted: () => docIsDeleted,
11014
+ drainCapturedRuns: () => drainCapturedRuns,
10949
11015
  endSessionTracking: () => endSessionTracking,
10950
11016
  ensureAppDataDirectory: () => ensureAppDataDirectory,
10951
11017
  getActiveController: () => getActiveController,
@@ -10959,6 +11025,7 @@ __export(index_exports, {
10959
11025
  getRegisteredNavigator: () => getRegisteredNavigator,
10960
11026
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
10961
11027
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
11028
+ getRunsForSession: () => getRunsForSession,
10962
11029
  getSrsBacklogDebug: () => getSrsBacklogDebug,
10963
11030
  getStrategyPressureDebug: () => getStrategyPressureDebug,
10964
11031
  getStudySource: () => getStudySource,
@@ -10976,12 +11043,14 @@ __export(index_exports, {
10976
11043
  isReview: () => isReview,
10977
11044
  log: () => log,
10978
11045
  makeScheduledCardId: () => makeScheduledCardId,
11046
+ makeStudySessionId: () => makeStudySessionId,
10979
11047
  mixerDebugAPI: () => mixerDebugAPI,
10980
11048
  mountMixerDebugger: () => mountMixerDebugger,
10981
11049
  mountPipelineDebugger: () => mountPipelineDebugger,
10982
11050
  mountSessionDebugger: () => mountSessionDebugger,
10983
11051
  mountUserDBDebugger: () => mountUserDBDebugger,
10984
11052
  newInterval: () => newInterval,
11053
+ newSessionId: () => newSessionId,
10985
11054
  parseCardHistoryID: () => parseCardHistoryID,
10986
11055
  pipelineDebugAPI: () => pipelineDebugAPI,
10987
11056
  processCustomQuestionsData: () => processCustomQuestionsData,
@@ -11000,6 +11069,7 @@ __export(index_exports, {
11000
11069
  runPeriodUpdate: () => runPeriodUpdate,
11001
11070
  scoreAccuracyInZone: () => scoreAccuracyInZone,
11002
11071
  sessionDebugAPI: () => sessionDebugAPI,
11072
+ setDebugSessionId: () => setDebugSessionId,
11003
11073
  snapshotQueues: () => snapshotQueues,
11004
11074
  startSessionTracking: () => startSessionTracking,
11005
11075
  toggleSessionOverlay: () => toggleSessionOverlay,
@@ -11661,7 +11731,9 @@ var ResponseProcessor = class {
11661
11731
  courseRegistrationDoc,
11662
11732
  currentCard,
11663
11733
  courseId,
11664
- cardId
11734
+ cardId,
11735
+ maxSessionViews,
11736
+ sessionViews
11665
11737
  );
11666
11738
  } else {
11667
11739
  result = this.processIncorrectResponse(
@@ -11696,7 +11768,7 @@ var ResponseProcessor = class {
11696
11768
  /**
11697
11769
  * Handles processing for correct responses: SRS scheduling and ELO updates.
11698
11770
  */
11699
- processCorrectResponse(cardRecord, history, studySessionItem, courseRegistrationDoc, currentCard, courseId, cardId) {
11771
+ processCorrectResponse(cardRecord, history, studySessionItem, courseRegistrationDoc, currentCard, courseId, cardId, maxSessionViews, sessionViews) {
11700
11772
  if (cardRecord.priorAttemps === 0) {
11701
11773
  const skipSrs = currentCard.card.tags.includes("srs:skip");
11702
11774
  if (!skipSrs) {
@@ -11744,12 +11816,16 @@ var ResponseProcessor = class {
11744
11816
  shouldClearFeedbackShadow: true
11745
11817
  };
11746
11818
  } else {
11819
+ const budgetSpent = sessionViews >= maxSessionViews;
11747
11820
  logger.info(
11748
- "[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO)"
11821
+ `[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); sessionViews=${sessionViews}/${maxSessionViews} -> ${budgetSpent ? "dismiss-success" : "marked-failed"}`
11749
11822
  );
11750
11823
  const { globalScore } = this.parsePerformance(cardRecord.performance);
11751
11824
  return {
11752
- nextCardAction: "marked-failed",
11825
+ // Budget spent: the learner did get it right, so retire the card as a
11826
+ // success rather than penalising it ('dismiss-failed' would apply an
11827
+ // ELO penalty for an answer that was correct).
11828
+ nextCardAction: budgetSpent ? "dismiss-success" : "marked-failed",
11753
11829
  shouldLoadNextCard: true,
11754
11830
  isCorrect: true,
11755
11831
  performanceScore: globalScore,
@@ -12122,6 +12198,8 @@ var ItemQueue = class {
12122
12198
  // src/study/SessionController.ts
12123
12199
  init_couch();
12124
12200
  init_core();
12201
+ init_types_legacy();
12202
+ init_studySession();
12125
12203
  init_recording();
12126
12204
 
12127
12205
  // src/util/index.ts
@@ -14325,8 +14403,7 @@ function clearStaleSessionDebugState() {
14325
14403
  clearSrsBacklogDebug();
14326
14404
  clearStrategyPressureDebug();
14327
14405
  }
14328
- function startSessionTracking(supplyQLength, failedQLength) {
14329
- const sessionId = `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
14406
+ function startSessionTracking(sessionId, supplyQLength, failedQLength) {
14330
14407
  activeSession = {
14331
14408
  sessionId,
14332
14409
  startTime: /* @__PURE__ */ new Date(),
@@ -14709,6 +14786,24 @@ var SessionController = class _SessionController extends Loggable {
14709
14786
  * `this`; constructed once so observers can rely on referential identity.
14710
14787
  */
14711
14788
  _sessionControls = null;
14789
+ /**
14790
+ * Minted at construction so the bootstrap pipeline run in `prepareSession()`
14791
+ * can carry it. Stamped onto every CardRecord and pipeline run this session.
14792
+ */
14793
+ sessionId;
14794
+ /** Host-supplied. Without it, no durable session doc is written. */
14795
+ _courseId;
14796
+ _stateSnapshotProvider;
14797
+ _sessionDoc = null;
14798
+ /**
14799
+ * Awaited by the close path — the open write is slow (time-boxed snapshot)
14800
+ * and would otherwise land last, leaving a finished session marked `open`.
14801
+ */
14802
+ _openDocPromise = null;
14803
+ _runLog = [];
14804
+ static MAX_LOGGED_RUNS = 100;
14805
+ /** Guards `endSession()` against the several termination paths racing it. */
14806
+ _sessionClosed = false;
14712
14807
  startTime;
14713
14808
  endTime;
14714
14809
  _secondsRemaining;
@@ -14742,6 +14837,8 @@ var SessionController = class _SessionController extends Loggable {
14742
14837
  */
14743
14838
  constructor(sources, time, dataLayer, getViewComponent, mixer, options) {
14744
14839
  super();
14840
+ this.sessionId = newSessionId();
14841
+ setDebugSessionId(this.sessionId);
14745
14842
  this.dataLayer = dataLayer;
14746
14843
  this.mixer = mixer || new QuotaRoundRobinMixer();
14747
14844
  this.srsService = new SrsService(dataLayer.getUserDB());
@@ -14764,7 +14861,10 @@ var SessionController = class _SessionController extends Loggable {
14764
14861
  if (options?.outcomeObservers?.length) {
14765
14862
  this._outcomeObservers = [...options.outcomeObservers];
14766
14863
  }
14864
+ this._courseId = options?.courseId;
14865
+ this._stateSnapshotProvider = options?.stateSnapshotProvider;
14767
14866
  this.log(`Session constructed:
14867
+ sessionId: ${this.sessionId}
14768
14868
  startTime: ${this.startTime}
14769
14869
  endTime: ${this.endTime}
14770
14870
  defaultBatchLimit: ${this._defaultBatchLimit}`);
@@ -14809,6 +14909,7 @@ var SessionController = class _SessionController extends Loggable {
14809
14909
  }
14810
14910
  clearStaleSessionDebugState();
14811
14911
  const wellIndicated = await this.getWeightedContent();
14912
+ this._recordRuns("bootstrap");
14812
14913
  this._wellIndicatedRemaining = wellIndicated;
14813
14914
  if (wellIndicated >= 0 && wellIndicated < _SessionController.MIN_WELL_INDICATED) {
14814
14915
  this.log(
@@ -14816,11 +14917,72 @@ var SessionController = class _SessionController extends Loggable {
14816
14917
  );
14817
14918
  }
14818
14919
  await this.hydrationService.ensureHydratedCards();
14819
- startSessionTracking(this.supplyQ.length, this.failedQ.length);
14920
+ startSessionTracking(this.sessionId, this.supplyQ.length, this.failedQ.length);
14921
+ this._openDocPromise = this._openSessionDoc();
14820
14922
  this._intervalHandle = setInterval(() => {
14821
14923
  this.tick();
14822
14924
  }, 1e3);
14823
14925
  }
14926
+ /** Label the runs the last plan produced. The pipeline can't know the why. */
14927
+ _recordRuns(label, mode) {
14928
+ for (const run of drainCapturedRuns()) {
14929
+ if (this._runLog.length >= _SessionController.MAX_LOGGED_RUNS) break;
14930
+ this._runLog.push({
14931
+ runId: run.runId,
14932
+ at: run.timestamp.toISOString(),
14933
+ label,
14934
+ ...mode ? { mode } : {},
14935
+ generatedCount: run.generatedCount,
14936
+ finalCount: run.finalCount,
14937
+ reviewsSelected: run.reviewsSelected,
14938
+ newSelected: run.newSelected
14939
+ });
14940
+ }
14941
+ }
14942
+ /** Time-boxed and isolated — a bad provider degrades the record, not the session. */
14943
+ async _captureState(phase) {
14944
+ if (!this._stateSnapshotProvider) return void 0;
14945
+ const TIMEOUT_MS = 3e3;
14946
+ try {
14947
+ return await Promise.race([
14948
+ Promise.resolve(this._stateSnapshotProvider(phase)),
14949
+ new Promise((resolve) => setTimeout(() => resolve(void 0), TIMEOUT_MS))
14950
+ ]);
14951
+ } catch (e) {
14952
+ this.log(`[Session] state snapshot (${phase}) failed: ${e}`);
14953
+ return void 0;
14954
+ }
14955
+ }
14956
+ /** Writing at open is what makes an unclosed session visible at all. */
14957
+ async _openSessionDoc() {
14958
+ if (!this._courseId) return;
14959
+ try {
14960
+ const user = this.dataLayer.getUserDB();
14961
+ const doc = {
14962
+ _id: makeStudySessionId(this._courseId, user.getUsername(), this.sessionId),
14963
+ docType: "STUDY_SESSION" /* STUDY_SESSION */,
14964
+ sessionId: this.sessionId,
14965
+ courseId: this._courseId,
14966
+ userId: user.getUsername(),
14967
+ startTime: this.startTime.toISOString(),
14968
+ status: "open",
14969
+ plannedSeconds: Math.round((this.endTime.valueOf() - this.startTime.valueOf()) / 1e3),
14970
+ config: {
14971
+ defaultBatchLimit: this._defaultBatchLimit,
14972
+ sourceCount: this.sources.length,
14973
+ initHints: this._sessionHints
14974
+ },
14975
+ initialQueues: { supplyQ: this.supplyQ.length, failedQ: this.failedQ.length },
14976
+ runs: [...this._runLog],
14977
+ stateAtStart: await this._captureState("start")
14978
+ };
14979
+ this._sessionDoc = doc;
14980
+ await user.putStudySession(doc);
14981
+ this.log(`[Session] Opened session record ${doc._id}`);
14982
+ } catch (e) {
14983
+ logger.warn(`[SessionController] Failed to open session record: ${e}`);
14984
+ }
14985
+ }
14824
14986
  /**
14825
14987
  * Request a mid-session replan. Re-runs the pipeline with current user state
14826
14988
  * and atomically replaces (or merges into) the supplyQ contents. Safe to call
@@ -15001,6 +15163,7 @@ var SessionController = class _SessionController extends Loggable {
15001
15163
  };
15002
15164
  });
15003
15165
  return {
15166
+ sessionId: this.sessionId,
15004
15167
  secondsRemaining: this.secondsRemaining,
15005
15168
  hasCardGuarantee: this.hasCardGuarantee,
15006
15169
  minCardsGuarantee: this._minCardsGuarantee,
@@ -15160,6 +15323,7 @@ var SessionController = class _SessionController extends Loggable {
15160
15323
  additive: mode === "merge",
15161
15324
  limit
15162
15325
  });
15326
+ this._recordRuns(opts.label ?? "(auto)", mode);
15163
15327
  this._wellIndicatedRemaining = wellIndicated;
15164
15328
  if (limit !== void 0 && limit < this._defaultBatchLimit) {
15165
15329
  this._suppressQualityReplan = true;
@@ -15471,6 +15635,7 @@ var SessionController = class _SessionController extends Loggable {
15471
15635
  if (this._secondsRemaining <= 0 && this.failedQ.length === 0 && this._minCardsGuarantee <= 0) {
15472
15636
  this._currentCard = null;
15473
15637
  endSessionTracking();
15638
+ void this._terminate();
15474
15639
  return null;
15475
15640
  }
15476
15641
  const WEDGE_MAX_EMPTY_STREAK = 3;
@@ -15500,6 +15665,7 @@ var SessionController = class _SessionController extends Loggable {
15500
15665
  if (!nextItem) {
15501
15666
  this._currentCard = null;
15502
15667
  endSessionTracking();
15668
+ void this._terminate();
15503
15669
  return null;
15504
15670
  }
15505
15671
  let card = this.hydrationService.getHydratedCard(nextItem.cardID);
@@ -15531,8 +15697,15 @@ var SessionController = class _SessionController extends Loggable {
15531
15697
  this.log(`Exhausted ${MAX_SKIP} skip attempts finding a hydratable card`);
15532
15698
  this._currentCard = null;
15533
15699
  endSessionTracking();
15700
+ void this._terminate();
15534
15701
  return null;
15535
15702
  }
15703
+ /** Not awaited — the host renders the end screen off `nextCard()`'s null. */
15704
+ _terminate() {
15705
+ void this.endSession().catch((e) => {
15706
+ logger.warn(`[SessionController] endSession failed: ${e}`);
15707
+ });
15708
+ }
15536
15709
  /**
15537
15710
  * Public API for processing user responses to cards.
15538
15711
  * @param cardRecord User's response record
@@ -15642,7 +15815,16 @@ var SessionController = class _SessionController extends Loggable {
15642
15815
  * This method aggregates all responses from the session and records a
15643
15816
  * UserOutcomeRecord if evolutionary orchestration is enabled.
15644
15817
  */
15645
- async endSession() {
15818
+ /**
15819
+ * Idempotent. Called from every `nextCard()` path that returns null; hosts
15820
+ * should also call it with `'abandoned'` when tearing down mid-session.
15821
+ */
15822
+ async endSession(reason = "closed") {
15823
+ if (this._sessionClosed) return;
15824
+ this._sessionClosed = true;
15825
+ clearInterval(this._intervalHandle);
15826
+ setDebugSessionId(void 0);
15827
+ await this._closeSessionDoc(reason);
15646
15828
  if (!this._sessionRecord || this._sessionRecord.length === 0) {
15647
15829
  return;
15648
15830
  }
@@ -15679,6 +15861,38 @@ var SessionController = class _SessionController extends Loggable {
15679
15861
  strategies
15680
15862
  );
15681
15863
  }
15864
+ async _closeSessionDoc(reason) {
15865
+ if (this._openDocPromise) await this._openDocPromise;
15866
+ const doc = this._sessionDoc;
15867
+ if (!doc) return;
15868
+ const records = this._sessionRecord.flatMap((r) => r.records);
15869
+ const questionRecords = records.filter(isQuestionRecord);
15870
+ try {
15871
+ const closed = {
15872
+ ...doc,
15873
+ status: reason,
15874
+ endTime: (/* @__PURE__ */ new Date()).toISOString(),
15875
+ tally: {
15876
+ cardsPresented: this._sessionRecord.length,
15877
+ responses: records.length,
15878
+ correct: questionRecords.filter((r) => r.isCorrect).length,
15879
+ incorrect: questionRecords.filter((r) => !r.isCorrect).length,
15880
+ failedQRemaining: this.failedQ.length,
15881
+ secondsRemaining: Math.max(0, this._secondsRemaining)
15882
+ },
15883
+ runs: [...this._runLog],
15884
+ finalHints: this._sessionHints,
15885
+ stateAtEnd: await this._captureState("end")
15886
+ };
15887
+ this._sessionDoc = closed;
15888
+ await this.dataLayer.getUserDB().putStudySession(closed);
15889
+ this.log(
15890
+ `[Session] Session record ${closed._id} -> ${reason} (${closed.tally.cardsPresented} cards, ${closed.tally.responses} responses, ${this._runLog.length} pipeline runs)`
15891
+ );
15892
+ } catch (e) {
15893
+ logger.warn(`[SessionController] Failed to close session record: ${e}`);
15894
+ }
15895
+ }
15682
15896
  };
15683
15897
 
15684
15898
  // src/study/index.ts
@@ -15727,6 +15941,7 @@ init_userDBHelpers();
15727
15941
  createOrchestrationContext,
15728
15942
  diversityRerank,
15729
15943
  docIsDeleted,
15944
+ drainCapturedRuns,
15730
15945
  endSessionTracking,
15731
15946
  ensureAppDataDirectory,
15732
15947
  getActiveController,
@@ -15740,6 +15955,7 @@ init_userDBHelpers();
15740
15955
  getRegisteredNavigator,
15741
15956
  getRegisteredNavigatorNames,
15742
15957
  getRegisteredNavigatorRole,
15958
+ getRunsForSession,
15743
15959
  getSrsBacklogDebug,
15744
15960
  getStrategyPressureDebug,
15745
15961
  getStudySource,
@@ -15757,12 +15973,14 @@ init_userDBHelpers();
15757
15973
  isReview,
15758
15974
  log,
15759
15975
  makeScheduledCardId,
15976
+ makeStudySessionId,
15760
15977
  mixerDebugAPI,
15761
15978
  mountMixerDebugger,
15762
15979
  mountPipelineDebugger,
15763
15980
  mountSessionDebugger,
15764
15981
  mountUserDBDebugger,
15765
15982
  newInterval,
15983
+ newSessionId,
15766
15984
  parseCardHistoryID,
15767
15985
  pipelineDebugAPI,
15768
15986
  processCustomQuestionsData,
@@ -15781,6 +15999,7 @@ init_userDBHelpers();
15781
15999
  runPeriodUpdate,
15782
16000
  scoreAccuracyInZone,
15783
16001
  sessionDebugAPI,
16002
+ setDebugSessionId,
15784
16003
  snapshotQueues,
15785
16004
  startSessionTracking,
15786
16005
  toggleSessionOverlay,