@vue-skuilder/db 0.2.21 → 0.2.23

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-BvOpKUeU.d.ts} +442 -79
  2. package/dist/{contentSource-Bazgkf4C.d.ts → contentSource-DT9NaX69.d.cts} +442 -79
  3. package/dist/core/index.d.cts +84 -342
  4. package/dist/core/index.d.ts +84 -342
  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-CY2B2lyW.d.ts} +1 -1
  10. package/dist/{dataLayerProvider-DifVCcIS.d.cts → dataLayerProvider-wY6s_4x9.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-BLLT5BYE.d.ts → index-BkBJlGDX.d.ts} +1 -1
  24. package/dist/{index-k9NFHpS1.d.cts → index-D7WdMDAs.d.cts} +1 -1
  25. package/dist/index.d.cts +51 -14
  26. package/dist/index.d.ts +51 -14
  27. package/dist/index.js +240 -12
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +235 -12
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/{types-BFUa1pa3.d.cts → types-DjiFOZxJ.d.cts} +1 -1
  32. package/dist/{types-legacy-4tlwHnXo.d.cts → types-legacy-CrwyZIvI.d.cts} +10 -2
  33. package/dist/{types-legacy-4tlwHnXo.d.ts → types-legacy-CrwyZIvI.d.ts} +10 -2
  34. package/dist/{types-CHgpWQAY.d.ts → types-uJ2Xn3_X.d.ts} +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 +125 -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 +188 -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
@@ -13,6 +13,15 @@ import {
13
13
  } from '@db/impl/couch';
14
14
 
15
15
  import { CardRecord, CardHistory, CourseRegistrationDoc, QuestionRecord, isQuestionRecord } from '@db/core';
16
+ import { DocType } from '@db/core/types/types-legacy';
17
+ import {
18
+ makeStudySessionId,
19
+ newSessionId,
20
+ type SessionStateSnapshot,
21
+ type SessionStateSnapshotProvider,
22
+ type StudySessionDoc,
23
+ type StudySessionRunSummary,
24
+ } from '@db/core/types/studySession';
16
25
  import { recordUserOutcome } from '@db/core/orchestration/recording';
17
26
  import { Loggable } from '@db/util';
18
27
  import {
@@ -20,6 +29,8 @@ import {
20
29
  WeightedCard,
21
30
  getSrsBacklogDebug,
22
31
  getStrategyPressureDebug,
32
+ setDebugSessionId,
33
+ drainCapturedRuns,
23
34
  } from '@db/core/navigators';
24
35
  import { ReplanHints } from '@db/core/navigators/generators/types';
25
36
  import { mergeHints } from '@db/core/navigators/Pipeline';
@@ -349,6 +360,30 @@ export class SessionController<TView = unknown> extends Loggable {
349
360
  */
350
361
  private _sessionControls: SessionControls | null = null;
351
362
 
363
+ /**
364
+ * Minted at construction so the bootstrap pipeline run in `prepareSession()`
365
+ * can carry it. Stamped onto every CardRecord and pipeline run this session.
366
+ */
367
+ public readonly sessionId: string;
368
+
369
+ /** Host-supplied. Without it, no durable session doc is written. */
370
+ private _courseId?: string;
371
+ private _stateSnapshotProvider?: SessionStateSnapshotProvider;
372
+
373
+ private _sessionDoc: StudySessionDoc | null = null;
374
+
375
+ /**
376
+ * Awaited by the close path — the open write is slow (time-boxed snapshot)
377
+ * and would otherwise land last, leaving a finished session marked `open`.
378
+ */
379
+ private _openDocPromise: Promise<void> | null = null;
380
+
381
+ private _runLog: StudySessionRunSummary[] = [];
382
+ private static readonly MAX_LOGGED_RUNS = 100;
383
+
384
+ /** Guards `endSession()` against the several termination paths racing it. */
385
+ private _sessionClosed: boolean = false;
386
+
352
387
  private startTime: Date;
353
388
  private endTime: Date;
354
389
  private _secondsRemaining: number;
@@ -390,10 +425,16 @@ export class SessionController<TView = unknown> extends Loggable {
390
425
  options?: {
391
426
  defaultBatchLimit?: number;
392
427
  outcomeObservers?: OutcomeObserver[];
428
+ /** Omit to run without durable session recording. */
429
+ courseId?: string;
430
+ stateSnapshotProvider?: SessionStateSnapshotProvider;
393
431
  }
394
432
  ) {
395
433
  super();
396
434
 
435
+ this.sessionId = newSessionId();
436
+ setDebugSessionId(this.sessionId);
437
+
397
438
  this.dataLayer = dataLayer;
398
439
  this.mixer = mixer || new QuotaRoundRobinMixer();
399
440
  this.srsService = new SrsService(dataLayer.getUserDB());
@@ -420,8 +461,11 @@ export class SessionController<TView = unknown> extends Loggable {
420
461
  if (options?.outcomeObservers?.length) {
421
462
  this._outcomeObservers = [...options.outcomeObservers];
422
463
  }
464
+ this._courseId = options?.courseId;
465
+ this._stateSnapshotProvider = options?.stateSnapshotProvider;
423
466
 
424
467
  this.log(`Session constructed:
468
+ sessionId: ${this.sessionId}
425
469
  startTime: ${this.startTime}
426
470
  endTime: ${this.endTime}
427
471
  defaultBatchLimit: ${this._defaultBatchLimit}`);
@@ -485,6 +529,7 @@ export class SessionController<TView = unknown> extends Loggable {
485
529
  clearStaleSessionDebugState();
486
530
 
487
531
  const wellIndicated = await this.getWeightedContent();
532
+ this._recordRuns('bootstrap');
488
533
  this._wellIndicatedRemaining = wellIndicated;
489
534
  if (wellIndicated >= 0 && wellIndicated < SessionController.MIN_WELL_INDICATED) {
490
535
  this.log(
@@ -494,13 +539,90 @@ export class SessionController<TView = unknown> extends Loggable {
494
539
  await this.hydrationService.ensureHydratedCards();
495
540
 
496
541
  // Start session tracking for debugging
497
- startSessionTracking(this.supplyQ.length, this.failedQ.length);
542
+ startSessionTracking(this.sessionId, this.supplyQ.length, this.failedQ.length);
543
+
544
+ // Not awaited — a session must never block on an analytics write.
545
+ this._openDocPromise = this._openSessionDoc();
498
546
 
499
547
  this._intervalHandle = setInterval(() => {
500
548
  this.tick();
501
549
  }, 1000);
502
550
  }
503
551
 
552
+ /** Label the runs the last plan produced. The pipeline can't know the why. */
553
+ private _recordRuns(label: string, mode?: string): void {
554
+ for (const run of drainCapturedRuns()) {
555
+ if (this._runLog.length >= SessionController.MAX_LOGGED_RUNS) break;
556
+ this._runLog.push({
557
+ runId: run.runId,
558
+ at: run.timestamp.toISOString(),
559
+ label,
560
+ ...(mode ? { mode } : {}),
561
+ generatedCount: run.generatedCount,
562
+ finalCount: run.finalCount,
563
+ reviewsSelected: run.reviewsSelected,
564
+ newSelected: run.newSelected,
565
+ // Compact detail projected off the full report so a persisted run is
566
+ // self-explanatory once the in-memory ring buffer has rolled over.
567
+ // Per-card provenance (`run.cards`) is intentionally left out — it's
568
+ // the dominant memory cost and not worth persisting per run.
569
+ ...(typeof run.userElo === 'number' ? { userElo: run.userElo } : {}),
570
+ ...(run.generators ? { generators: run.generators } : {}),
571
+ ...(run.filters ? { filters: run.filters } : {}),
572
+ ...(run.hints ? { hints: run.hints } : {}),
573
+ ...(run.discardedTail ? { discardedTail: run.discardedTail } : {}),
574
+ });
575
+ }
576
+ }
577
+
578
+ /** Time-boxed and isolated — a bad provider degrades the record, not the session. */
579
+ private async _captureState(
580
+ phase: 'start' | 'end'
581
+ ): Promise<SessionStateSnapshot | undefined> {
582
+ if (!this._stateSnapshotProvider) return undefined;
583
+ const TIMEOUT_MS = 3000;
584
+ try {
585
+ return await Promise.race([
586
+ Promise.resolve(this._stateSnapshotProvider(phase)),
587
+ new Promise<undefined>((resolve) => setTimeout(() => resolve(undefined), TIMEOUT_MS)),
588
+ ]);
589
+ } catch (e) {
590
+ this.log(`[Session] state snapshot (${phase}) failed: ${e}`);
591
+ return undefined;
592
+ }
593
+ }
594
+
595
+ /** Writing at open is what makes an unclosed session visible at all. */
596
+ private async _openSessionDoc(): Promise<void> {
597
+ if (!this._courseId) return;
598
+ try {
599
+ const user = this.dataLayer.getUserDB();
600
+ const doc: StudySessionDoc = {
601
+ _id: makeStudySessionId(this._courseId, user.getUsername(), this.sessionId),
602
+ docType: DocType.STUDY_SESSION,
603
+ sessionId: this.sessionId,
604
+ courseId: this._courseId,
605
+ userId: user.getUsername(),
606
+ startTime: this.startTime.toISOString(),
607
+ status: 'open',
608
+ plannedSeconds: Math.round((this.endTime.valueOf() - this.startTime.valueOf()) / 1000),
609
+ config: {
610
+ defaultBatchLimit: this._defaultBatchLimit,
611
+ sourceCount: this.sources.length,
612
+ initHints: this._sessionHints,
613
+ },
614
+ initialQueues: { supplyQ: this.supplyQ.length, failedQ: this.failedQ.length },
615
+ runs: [...this._runLog],
616
+ stateAtStart: await this._captureState('start'),
617
+ };
618
+ this._sessionDoc = doc;
619
+ await user.putStudySession(doc);
620
+ this.log(`[Session] Opened session record ${doc._id}`);
621
+ } catch (e) {
622
+ logger.warn(`[SessionController] Failed to open session record: ${e}`);
623
+ }
624
+ }
625
+
504
626
  /**
505
627
  * Request a mid-session replan. Re-runs the pipeline with current user state
506
628
  * and atomically replaces (or merges into) the supplyQ contents. Safe to call
@@ -757,6 +879,7 @@ export class SessionController<TView = unknown> extends Loggable {
757
879
  };
758
880
  });
759
881
  return {
882
+ sessionId: this.sessionId,
760
883
  secondsRemaining: this.secondsRemaining,
761
884
  hasCardGuarantee: this.hasCardGuarantee,
762
885
  minCardsGuarantee: this._minCardsGuarantee,
@@ -945,6 +1068,7 @@ export class SessionController<TView = unknown> extends Loggable {
945
1068
  additive: mode === 'merge',
946
1069
  limit,
947
1070
  });
1071
+ this._recordRuns(opts.label ?? '(auto)', mode);
948
1072
  this._wellIndicatedRemaining = wellIndicated;
949
1073
 
950
1074
  // Burst replan: suppress quality-based auto-replan so the background
@@ -1463,6 +1587,7 @@ export class SessionController<TView = unknown> extends Loggable {
1463
1587
  if (this._secondsRemaining <= 0 && this.failedQ.length === 0 && this._minCardsGuarantee <= 0) {
1464
1588
  this._currentCard = null;
1465
1589
  endSessionTracking();
1590
+ void this._terminate();
1466
1591
  return null;
1467
1592
  }
1468
1593
 
@@ -1515,6 +1640,7 @@ export class SessionController<TView = unknown> extends Loggable {
1515
1640
  if (!nextItem) {
1516
1641
  this._currentCard = null;
1517
1642
  endSessionTracking();
1643
+ void this._terminate();
1518
1644
  return null;
1519
1645
  }
1520
1646
 
@@ -1571,9 +1697,17 @@ export class SessionController<TView = unknown> extends Loggable {
1571
1697
  this.log(`Exhausted ${MAX_SKIP} skip attempts finding a hydratable card`);
1572
1698
  this._currentCard = null;
1573
1699
  endSessionTracking();
1700
+ void this._terminate();
1574
1701
  return null;
1575
1702
  }
1576
1703
 
1704
+ /** Not awaited — the host renders the end screen off `nextCard()`'s null. */
1705
+ private _terminate(): void {
1706
+ void this.endSession().catch((e) => {
1707
+ logger.warn(`[SessionController] endSession failed: ${e}`);
1708
+ });
1709
+ }
1710
+
1577
1711
  /**
1578
1712
  * Public API for processing user responses to cards.
1579
1713
  * @param cardRecord User's response record
@@ -1742,7 +1876,20 @@ export class SessionController<TView = unknown> extends Loggable {
1742
1876
  * This method aggregates all responses from the session and records a
1743
1877
  * UserOutcomeRecord if evolutionary orchestration is enabled.
1744
1878
  */
1745
- public async endSession(): Promise<void> {
1879
+ /**
1880
+ * Idempotent. Called from every `nextCard()` path that returns null; hosts
1881
+ * should also call it with `'abandoned'` when tearing down mid-session.
1882
+ */
1883
+ public async endSession(reason: 'closed' | 'abandoned' = 'closed'): Promise<void> {
1884
+ if (this._sessionClosed) return;
1885
+ this._sessionClosed = true;
1886
+
1887
+ clearInterval(this._intervalHandle);
1888
+ setDebugSessionId(undefined);
1889
+
1890
+ // Closed even with zero responses — "answered nothing" is itself a finding.
1891
+ await this._closeSessionDoc(reason);
1892
+
1746
1893
  if (!this._sessionRecord || this._sessionRecord.length === 0) {
1747
1894
  return;
1748
1895
  }
@@ -1797,4 +1944,43 @@ export class SessionController<TView = unknown> extends Loggable {
1797
1944
  strategies
1798
1945
  );
1799
1946
  }
1947
+
1948
+ private async _closeSessionDoc(reason: 'closed' | 'abandoned'): Promise<void> {
1949
+ // Ordered behind the open write; it swallows its own errors.
1950
+ if (this._openDocPromise) await this._openDocPromise;
1951
+
1952
+ const doc = this._sessionDoc;
1953
+ if (!doc) return;
1954
+
1955
+ const records = this._sessionRecord.flatMap((r) => r.records);
1956
+ const questionRecords = records.filter(isQuestionRecord);
1957
+
1958
+ try {
1959
+ const closed: StudySessionDoc = {
1960
+ ...doc,
1961
+ status: reason,
1962
+ endTime: new Date().toISOString(),
1963
+ tally: {
1964
+ cardsPresented: this._sessionRecord.length,
1965
+ responses: records.length,
1966
+ correct: questionRecords.filter((r) => r.isCorrect).length,
1967
+ incorrect: questionRecords.filter((r) => !r.isCorrect).length,
1968
+ failedQRemaining: this.failedQ.length,
1969
+ secondsRemaining: Math.max(0, this._secondsRemaining),
1970
+ },
1971
+ runs: [...this._runLog],
1972
+ finalHints: this._sessionHints,
1973
+ stateAtEnd: await this._captureState('end'),
1974
+ };
1975
+ this._sessionDoc = closed;
1976
+ await this.dataLayer.getUserDB().putStudySession(closed);
1977
+ this.log(
1978
+ `[Session] Session record ${closed._id} -> ${reason} ` +
1979
+ `(${closed.tally!.cardsPresented} cards, ${closed.tally!.responses} responses, ` +
1980
+ `${this._runLog.length} pipeline runs)`
1981
+ );
1982
+ } catch (e) {
1983
+ logger.warn(`[SessionController] Failed to close session record: ${e}`);
1984
+ }
1985
+ }
1800
1986
  }
@@ -87,14 +87,15 @@ export function clearStaleSessionDebugState(): void {
87
87
  }
88
88
 
89
89
  /**
90
- * Start tracking a new session.
90
+ * Start tracking a new session. The id is owned by `SessionController` — it is
91
+ * minted at construction so pipeline runs from `prepareSession()` onward can
92
+ * carry it.
91
93
  */
92
94
  export function startSessionTracking(
95
+ sessionId: string,
93
96
  supplyQLength: number,
94
97
  failedQLength: number
95
98
  ): void {
96
- const sessionId = `session-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
97
-
98
99
  activeSession = {
99
100
  sessionId,
100
101
  startTime: new Date(),
@@ -59,6 +59,7 @@ export interface SessionDrawnCardDebug {
59
59
 
60
60
  /** Live snapshot of the controller, read fresh on each overlay tick. */
61
61
  export interface SessionDebugSnapshot {
62
+ sessionId: string;
62
63
  secondsRemaining: number;
63
64
  hasCardGuarantee: boolean;
64
65
  minCardsGuarantee: number;
@@ -128,7 +128,9 @@ export class ResponseProcessor {
128
128
  courseRegistrationDoc,
129
129
  currentCard,
130
130
  courseId,
131
- cardId
131
+ cardId,
132
+ maxSessionViews,
133
+ sessionViews
132
134
  );
133
135
  } else {
134
136
  // Handle incorrect responses
@@ -178,7 +180,9 @@ export class ResponseProcessor {
178
180
  courseRegistrationDoc: CourseRegistrationDoc,
179
181
  currentCard: StudySessionRecord,
180
182
  courseId: string,
181
- cardId: string
183
+ cardId: string,
184
+ maxSessionViews: number,
185
+ sessionViews: number
182
186
  ): ResponseResult {
183
187
  // Only schedule and update ELO for first-time attempts
184
188
  if (cardRecord.priorAttemps === 0) {
@@ -250,14 +254,38 @@ export class ResponseProcessor {
250
254
  shouldClearFeedbackShadow: true,
251
255
  };
252
256
  } else {
257
+ // Correct, but not on the first attempt of this presentation.
258
+ //
259
+ // Re-present the card for consolidation — but only while there is
260
+ // session-view budget left. This branch used to return 'marked-failed'
261
+ // unconditionally, with no reference to sessionViews/maxSessionViews,
262
+ // which made a *correct* answer the one outcome that could never end a
263
+ // card's life in a session:
264
+ //
265
+ // present -> stumble -> get it right -> back to failedQ
266
+ // -> re-present -> stumble -> get it right -> back to failedQ -> ...
267
+ //
268
+ // The incorrect path spends the budget (`sessionViews >= maxSessionViews`
269
+ // -> 'dismiss-failed'), so the only escape was to keep answering *wrong*
270
+ // until the card was dismissed. When supplyQ is thin the loop is also
271
+ // tight rather than merely long: `_shouldInterleaveFailed` returns true
272
+ // immediately with no supply available, so the same card is redrawn on
273
+ // the very next `nextCard()` and the session reads as hung.
274
+ const budgetSpent = sessionViews >= maxSessionViews;
275
+
253
276
  logger.info(
254
- '[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO)'
277
+ `[ResponseProcessor] Processed correct response (retry attempt - no scheduling/ELO); ` +
278
+ `sessionViews=${sessionViews}/${maxSessionViews} -> ` +
279
+ `${budgetSpent ? 'dismiss-success' : 'marked-failed'}`
255
280
  );
256
281
 
257
282
  const { globalScore } = this.parsePerformance(cardRecord.performance);
258
283
 
259
284
  return {
260
- nextCardAction: 'marked-failed',
285
+ // Budget spent: the learner did get it right, so retire the card as a
286
+ // success rather than penalising it ('dismiss-failed' would apply an
287
+ // ELO penalty for an answer that was correct).
288
+ nextCardAction: budgetSpent ? 'dismiss-success' : 'marked-failed',
261
289
  shouldLoadNextCard: true,
262
290
  isCorrect: true,
263
291
  performanceScore: globalScore,