@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
@@ -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,81 @@ 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
+ });
566
+ }
567
+ }
568
+
569
+ /** Time-boxed and isolated — a bad provider degrades the record, not the session. */
570
+ private async _captureState(
571
+ phase: 'start' | 'end'
572
+ ): Promise<SessionStateSnapshot | undefined> {
573
+ if (!this._stateSnapshotProvider) return undefined;
574
+ const TIMEOUT_MS = 3000;
575
+ try {
576
+ return await Promise.race([
577
+ Promise.resolve(this._stateSnapshotProvider(phase)),
578
+ new Promise<undefined>((resolve) => setTimeout(() => resolve(undefined), TIMEOUT_MS)),
579
+ ]);
580
+ } catch (e) {
581
+ this.log(`[Session] state snapshot (${phase}) failed: ${e}`);
582
+ return undefined;
583
+ }
584
+ }
585
+
586
+ /** Writing at open is what makes an unclosed session visible at all. */
587
+ private async _openSessionDoc(): Promise<void> {
588
+ if (!this._courseId) return;
589
+ try {
590
+ const user = this.dataLayer.getUserDB();
591
+ const doc: StudySessionDoc = {
592
+ _id: makeStudySessionId(this._courseId, user.getUsername(), this.sessionId),
593
+ docType: DocType.STUDY_SESSION,
594
+ sessionId: this.sessionId,
595
+ courseId: this._courseId,
596
+ userId: user.getUsername(),
597
+ startTime: this.startTime.toISOString(),
598
+ status: 'open',
599
+ plannedSeconds: Math.round((this.endTime.valueOf() - this.startTime.valueOf()) / 1000),
600
+ config: {
601
+ defaultBatchLimit: this._defaultBatchLimit,
602
+ sourceCount: this.sources.length,
603
+ initHints: this._sessionHints,
604
+ },
605
+ initialQueues: { supplyQ: this.supplyQ.length, failedQ: this.failedQ.length },
606
+ runs: [...this._runLog],
607
+ stateAtStart: await this._captureState('start'),
608
+ };
609
+ this._sessionDoc = doc;
610
+ await user.putStudySession(doc);
611
+ this.log(`[Session] Opened session record ${doc._id}`);
612
+ } catch (e) {
613
+ logger.warn(`[SessionController] Failed to open session record: ${e}`);
614
+ }
615
+ }
616
+
504
617
  /**
505
618
  * Request a mid-session replan. Re-runs the pipeline with current user state
506
619
  * and atomically replaces (or merges into) the supplyQ contents. Safe to call
@@ -757,6 +870,7 @@ export class SessionController<TView = unknown> extends Loggable {
757
870
  };
758
871
  });
759
872
  return {
873
+ sessionId: this.sessionId,
760
874
  secondsRemaining: this.secondsRemaining,
761
875
  hasCardGuarantee: this.hasCardGuarantee,
762
876
  minCardsGuarantee: this._minCardsGuarantee,
@@ -945,6 +1059,7 @@ export class SessionController<TView = unknown> extends Loggable {
945
1059
  additive: mode === 'merge',
946
1060
  limit,
947
1061
  });
1062
+ this._recordRuns(opts.label ?? '(auto)', mode);
948
1063
  this._wellIndicatedRemaining = wellIndicated;
949
1064
 
950
1065
  // Burst replan: suppress quality-based auto-replan so the background
@@ -1463,6 +1578,7 @@ export class SessionController<TView = unknown> extends Loggable {
1463
1578
  if (this._secondsRemaining <= 0 && this.failedQ.length === 0 && this._minCardsGuarantee <= 0) {
1464
1579
  this._currentCard = null;
1465
1580
  endSessionTracking();
1581
+ void this._terminate();
1466
1582
  return null;
1467
1583
  }
1468
1584
 
@@ -1515,6 +1631,7 @@ export class SessionController<TView = unknown> extends Loggable {
1515
1631
  if (!nextItem) {
1516
1632
  this._currentCard = null;
1517
1633
  endSessionTracking();
1634
+ void this._terminate();
1518
1635
  return null;
1519
1636
  }
1520
1637
 
@@ -1571,9 +1688,17 @@ export class SessionController<TView = unknown> extends Loggable {
1571
1688
  this.log(`Exhausted ${MAX_SKIP} skip attempts finding a hydratable card`);
1572
1689
  this._currentCard = null;
1573
1690
  endSessionTracking();
1691
+ void this._terminate();
1574
1692
  return null;
1575
1693
  }
1576
1694
 
1695
+ /** Not awaited — the host renders the end screen off `nextCard()`'s null. */
1696
+ private _terminate(): void {
1697
+ void this.endSession().catch((e) => {
1698
+ logger.warn(`[SessionController] endSession failed: ${e}`);
1699
+ });
1700
+ }
1701
+
1577
1702
  /**
1578
1703
  * Public API for processing user responses to cards.
1579
1704
  * @param cardRecord User's response record
@@ -1742,7 +1867,20 @@ export class SessionController<TView = unknown> extends Loggable {
1742
1867
  * This method aggregates all responses from the session and records a
1743
1868
  * UserOutcomeRecord if evolutionary orchestration is enabled.
1744
1869
  */
1745
- public async endSession(): Promise<void> {
1870
+ /**
1871
+ * Idempotent. Called from every `nextCard()` path that returns null; hosts
1872
+ * should also call it with `'abandoned'` when tearing down mid-session.
1873
+ */
1874
+ public async endSession(reason: 'closed' | 'abandoned' = 'closed'): Promise<void> {
1875
+ if (this._sessionClosed) return;
1876
+ this._sessionClosed = true;
1877
+
1878
+ clearInterval(this._intervalHandle);
1879
+ setDebugSessionId(undefined);
1880
+
1881
+ // Closed even with zero responses — "answered nothing" is itself a finding.
1882
+ await this._closeSessionDoc(reason);
1883
+
1746
1884
  if (!this._sessionRecord || this._sessionRecord.length === 0) {
1747
1885
  return;
1748
1886
  }
@@ -1797,4 +1935,43 @@ export class SessionController<TView = unknown> extends Loggable {
1797
1935
  strategies
1798
1936
  );
1799
1937
  }
1938
+
1939
+ private async _closeSessionDoc(reason: 'closed' | 'abandoned'): Promise<void> {
1940
+ // Ordered behind the open write; it swallows its own errors.
1941
+ if (this._openDocPromise) await this._openDocPromise;
1942
+
1943
+ const doc = this._sessionDoc;
1944
+ if (!doc) return;
1945
+
1946
+ const records = this._sessionRecord.flatMap((r) => r.records);
1947
+ const questionRecords = records.filter(isQuestionRecord);
1948
+
1949
+ try {
1950
+ const closed: StudySessionDoc = {
1951
+ ...doc,
1952
+ status: reason,
1953
+ endTime: new Date().toISOString(),
1954
+ tally: {
1955
+ cardsPresented: this._sessionRecord.length,
1956
+ responses: records.length,
1957
+ correct: questionRecords.filter((r) => r.isCorrect).length,
1958
+ incorrect: questionRecords.filter((r) => !r.isCorrect).length,
1959
+ failedQRemaining: this.failedQ.length,
1960
+ secondsRemaining: Math.max(0, this._secondsRemaining),
1961
+ },
1962
+ runs: [...this._runLog],
1963
+ finalHints: this._sessionHints,
1964
+ stateAtEnd: await this._captureState('end'),
1965
+ };
1966
+ this._sessionDoc = closed;
1967
+ await this.dataLayer.getUserDB().putStudySession(closed);
1968
+ this.log(
1969
+ `[Session] Session record ${closed._id} -> ${reason} ` +
1970
+ `(${closed.tally!.cardsPresented} cards, ${closed.tally!.responses} responses, ` +
1971
+ `${this._runLog.length} pipeline runs)`
1972
+ );
1973
+ } catch (e) {
1974
+ logger.warn(`[SessionController] Failed to close session record: ${e}`);
1975
+ }
1976
+ }
1800
1977
  }
@@ -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,