@vue-skuilder/db 0.1.23 → 0.1.25

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 (80) hide show
  1. package/dist/{contentSource-BP9hznNV.d.ts → contentSource-BmnmvH8C.d.ts} +268 -3
  2. package/dist/{contentSource-DsJadoBU.d.cts → contentSource-DfBbaLA-.d.cts} +268 -3
  3. package/dist/core/index.d.cts +310 -6
  4. package/dist/core/index.d.ts +310 -6
  5. package/dist/core/index.js +2606 -666
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +2564 -639
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-CHYrQ5pB.d.cts → dataLayerProvider-BeRXVMs5.d.cts} +1 -1
  10. package/dist/{dataLayerProvider-MDTxXq2l.d.ts → dataLayerProvider-CG9GfaAY.d.ts} +1 -1
  11. package/dist/impl/couch/index.d.cts +11 -3
  12. package/dist/impl/couch/index.d.ts +11 -3
  13. package/dist/impl/couch/index.js +2336 -656
  14. package/dist/impl/couch/index.js.map +1 -1
  15. package/dist/impl/couch/index.mjs +2316 -631
  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 +2312 -632
  20. package/dist/impl/static/index.js.map +1 -1
  21. package/dist/impl/static/index.mjs +2315 -630
  22. package/dist/impl/static/index.mjs.map +1 -1
  23. package/dist/{index-Dj0SEgk3.d.ts → index-BWvO-_rJ.d.ts} +1 -1
  24. package/dist/{index-B_j6u5E4.d.cts → index-Ba7hYbHj.d.cts} +1 -1
  25. package/dist/index.d.cts +278 -20
  26. package/dist/index.d.ts +278 -20
  27. package/dist/index.js +3603 -720
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +3529 -674
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/{types-DQaXnuoc.d.ts → types-CJrLM1Ew.d.ts} +1 -1
  32. package/dist/{types-Bn0itutr.d.cts → types-W8n-B6HG.d.cts} +1 -1
  33. package/dist/{types-legacy-DDY4N-Uq.d.cts → types-legacy-JXDxinpU.d.cts} +5 -1
  34. package/dist/{types-legacy-DDY4N-Uq.d.ts → types-legacy-JXDxinpU.d.ts} +5 -1
  35. package/dist/util/packer/index.d.cts +3 -3
  36. package/dist/util/packer/index.d.ts +3 -3
  37. package/docs/brainstorm-navigation-paradigm.md +40 -34
  38. package/docs/future-orchestration-vision.md +216 -0
  39. package/docs/navigators-architecture.md +210 -9
  40. package/docs/todo-review-urgency-adaptation.md +205 -0
  41. package/docs/todo-strategy-authoring.md +8 -6
  42. package/package.json +3 -3
  43. package/src/core/index.ts +2 -0
  44. package/src/core/interfaces/contentSource.ts +7 -0
  45. package/src/core/interfaces/userDB.ts +50 -0
  46. package/src/core/navigators/Pipeline.ts +132 -5
  47. package/src/core/navigators/PipelineAssembler.ts +21 -22
  48. package/src/core/navigators/PipelineDebugger.ts +426 -0
  49. package/src/core/navigators/filters/WeightedFilter.ts +141 -0
  50. package/src/core/navigators/filters/types.ts +4 -0
  51. package/src/core/navigators/generators/CompositeGenerator.ts +82 -19
  52. package/src/core/navigators/generators/elo.ts +14 -1
  53. package/src/core/navigators/generators/srs.ts +146 -18
  54. package/src/core/navigators/generators/types.ts +4 -0
  55. package/src/core/navigators/index.ts +203 -13
  56. package/src/core/orchestration/gradient.ts +133 -0
  57. package/src/core/orchestration/index.ts +210 -0
  58. package/src/core/orchestration/learning.ts +250 -0
  59. package/src/core/orchestration/recording.ts +92 -0
  60. package/src/core/orchestration/signal.ts +67 -0
  61. package/src/core/types/contentNavigationStrategy.ts +38 -0
  62. package/src/core/types/learningState.ts +77 -0
  63. package/src/core/types/types-legacy.ts +4 -0
  64. package/src/core/types/userOutcome.ts +51 -0
  65. package/src/courseConfigRegistration.ts +107 -0
  66. package/src/factory.ts +6 -0
  67. package/src/impl/common/BaseUserDB.ts +16 -0
  68. package/src/impl/couch/user-course-relDB.ts +12 -0
  69. package/src/study/MixerDebugger.ts +555 -0
  70. package/src/study/SessionController.ts +159 -20
  71. package/src/study/SessionDebugger.ts +442 -0
  72. package/src/study/SourceMixer.ts +36 -17
  73. package/src/study/TODO-session-scheduling.md +133 -0
  74. package/src/study/index.ts +2 -0
  75. package/src/study/services/EloService.ts +79 -4
  76. package/src/study/services/ResponseProcessor.ts +130 -72
  77. package/src/study/services/SrsService.ts +9 -0
  78. package/tests/core/navigators/Pipeline.test.ts +2 -0
  79. package/tests/core/navigators/PipelineAssembler.test.ts +4 -4
  80. package/docs/todo-evolutionary-orchestration.md +0 -310
@@ -5,6 +5,11 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __glob = (map) => (path2) => {
9
+ var fn = map[path2];
10
+ if (fn) return fn();
11
+ throw new Error("Module not found in bundle: " + path2);
12
+ };
8
13
  var __esm = (fn, res) => function __init() {
9
14
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
15
  };
@@ -115,7 +120,9 @@ var init_types_legacy = __esm({
115
120
  ["VIEW" /* VIEW */]: "VIEW",
116
121
  ["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
117
122
  ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
118
- ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE"
123
+ ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE",
124
+ ["USER_OUTCOME" /* USER_OUTCOME */]: "USER_OUTCOME",
125
+ ["STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */]: "STRATEGY_LEARNING_STATE"
119
126
  };
120
127
  }
121
128
  });
@@ -420,6 +427,15 @@ var init_user_course_relDB = __esm({
420
427
  void this.user.updateCourseSettings(this._courseId, updates);
421
428
  }
422
429
  }
430
+ async getStrategyState(strategyKey) {
431
+ return this.user.getStrategyState(this._courseId, strategyKey);
432
+ }
433
+ async putStrategyState(strategyKey, data) {
434
+ return this.user.putStrategyState(this._courseId, strategyKey, data);
435
+ }
436
+ async deleteStrategyState(strategyKey) {
437
+ return this.user.deleteStrategyState(this._courseId, strategyKey);
438
+ }
423
439
  async getReviewstoDate(targetDate) {
424
440
  const allReviews = await this.user.getPendingReviews(this._courseId);
425
441
  logger.debug(
@@ -490,351 +506,309 @@ var init_courseLookupDB = __esm({
490
506
  }
491
507
  });
492
508
 
493
- // src/core/navigators/index.ts
494
- function isGenerator(impl) {
495
- return NavigatorRoles[impl] === "generator" /* GENERATOR */;
509
+ // src/core/navigators/PipelineDebugger.ts
510
+ var PipelineDebugger_exports = {};
511
+ __export(PipelineDebugger_exports, {
512
+ buildRunReport: () => buildRunReport,
513
+ captureRun: () => captureRun,
514
+ mountPipelineDebugger: () => mountPipelineDebugger,
515
+ pipelineDebugAPI: () => pipelineDebugAPI
516
+ });
517
+ function getOrigin(card) {
518
+ const firstEntry = card.provenance[0];
519
+ if (!firstEntry) return "unknown";
520
+ const reason = firstEntry.reason?.toLowerCase() || "";
521
+ if (reason.includes("new card")) return "new";
522
+ if (reason.includes("review")) return "review";
523
+ return "unknown";
496
524
  }
497
- function isFilter(impl) {
498
- return NavigatorRoles[impl] === "filter" /* FILTER */;
525
+ function captureRun(report) {
526
+ const fullReport = {
527
+ ...report,
528
+ runId: `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
529
+ timestamp: /* @__PURE__ */ new Date()
530
+ };
531
+ runHistory.unshift(fullReport);
532
+ if (runHistory.length > MAX_RUNS) {
533
+ runHistory.pop();
534
+ }
499
535
  }
500
- var NavigatorRoles, ContentNavigator;
501
- var init_navigators = __esm({
502
- "src/core/navigators/index.ts"() {
536
+ function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards) {
537
+ const selectedIds = new Set(selectedCards.map((c) => c.cardId));
538
+ const cards = allCards.map((card) => ({
539
+ cardId: card.cardId,
540
+ courseId: card.courseId,
541
+ origin: getOrigin(card),
542
+ finalScore: card.score,
543
+ provenance: card.provenance,
544
+ selected: selectedIds.has(card.cardId)
545
+ }));
546
+ const reviewsSelected = selectedCards.filter((c) => getOrigin(c) === "review").length;
547
+ const newSelected = selectedCards.filter((c) => getOrigin(c) === "new").length;
548
+ return {
549
+ courseId,
550
+ courseName,
551
+ generatorName,
552
+ generators,
553
+ generatedCount,
554
+ filters,
555
+ finalCount: selectedCards.length,
556
+ reviewsSelected,
557
+ newSelected,
558
+ cards
559
+ };
560
+ }
561
+ function formatProvenance(provenance) {
562
+ return provenance.map((p) => {
563
+ const actionSymbol = p.action === "generated" ? "\u{1F3B2}" : p.action === "boosted" ? "\u2B06\uFE0F" : p.action === "penalized" ? "\u2B07\uFE0F" : "\u27A1\uFE0F";
564
+ return ` ${actionSymbol} ${p.strategyName}: ${p.score.toFixed(3)} - ${p.reason}`;
565
+ }).join("\n");
566
+ }
567
+ function printRunSummary(run) {
568
+ console.group(`\u{1F50D} Pipeline Run: ${run.courseId} (${run.courseName || "unnamed"})`);
569
+ logger.info(`Run ID: ${run.runId}`);
570
+ logger.info(`Time: ${run.timestamp.toISOString()}`);
571
+ logger.info(`Generator: ${run.generatorName} \u2192 ${run.generatedCount} candidates`);
572
+ if (run.generators && run.generators.length > 0) {
573
+ console.group("Generator breakdown:");
574
+ for (const g of run.generators) {
575
+ logger.info(
576
+ ` ${g.name}: ${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} reviews, top: ${g.topScore.toFixed(2)})`
577
+ );
578
+ }
579
+ console.groupEnd();
580
+ }
581
+ if (run.filters.length > 0) {
582
+ console.group("Filter impact:");
583
+ for (const f of run.filters) {
584
+ logger.info(` ${f.name}: \u2191${f.boosted} \u2193${f.penalized} =${f.passed} \u2715${f.removed}`);
585
+ }
586
+ console.groupEnd();
587
+ }
588
+ logger.info(
589
+ `Result: ${run.finalCount} cards selected (${run.newSelected} new, ${run.reviewsSelected} reviews)`
590
+ );
591
+ console.groupEnd();
592
+ }
593
+ function mountPipelineDebugger() {
594
+ if (typeof window === "undefined") return;
595
+ const win = window;
596
+ win.skuilder = win.skuilder || {};
597
+ win.skuilder.pipeline = pipelineDebugAPI;
598
+ }
599
+ var MAX_RUNS, runHistory, pipelineDebugAPI;
600
+ var init_PipelineDebugger = __esm({
601
+ "src/core/navigators/PipelineDebugger.ts"() {
503
602
  "use strict";
504
603
  init_logger();
505
- NavigatorRoles = {
506
- ["elo" /* ELO */]: "generator" /* GENERATOR */,
507
- ["srs" /* SRS */]: "generator" /* GENERATOR */,
508
- ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
509
- ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
510
- ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
511
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
512
- };
513
- ContentNavigator = class {
514
- /** User interface for this navigation session */
515
- user;
516
- /** Course interface for this navigation session */
517
- course;
518
- /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
519
- strategyName;
520
- /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
521
- strategyId;
604
+ MAX_RUNS = 10;
605
+ runHistory = [];
606
+ pipelineDebugAPI = {
522
607
  /**
523
- * Constructor for standard navigators.
524
- * Call this from subclass constructors to initialize common fields.
525
- *
526
- * Note: CompositeGenerator and Pipeline call super() without args, then set
527
- * user/course fields directly if needed.
608
+ * Get raw run history for programmatic access.
528
609
  */
529
- constructor(user, course, strategyData) {
530
- this.user = user;
531
- this.course = course;
532
- if (strategyData) {
533
- this.strategyName = strategyData.name;
534
- this.strategyId = strategyData._id;
535
- }
536
- }
537
- // ============================================================================
538
- // STRATEGY STATE HELPERS
539
- // ============================================================================
540
- //
541
- // These methods allow strategies to persist their own state (user preferences,
542
- // learned patterns, temporal tracking) in the user database.
543
- //
544
- // ============================================================================
610
+ get runs() {
611
+ return [...runHistory];
612
+ },
545
613
  /**
546
- * Unique key identifying this strategy for state storage.
547
- *
548
- * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
549
- * Override in subclasses if multiple instances of the same strategy type
550
- * need separate state storage.
614
+ * Show summary of a specific pipeline run.
551
615
  */
552
- get strategyKey() {
553
- return this.constructor.name;
554
- }
616
+ showRun(idOrIndex = 0) {
617
+ if (runHistory.length === 0) {
618
+ logger.info("[Pipeline Debug] No runs captured yet.");
619
+ return;
620
+ }
621
+ let run;
622
+ if (typeof idOrIndex === "number") {
623
+ run = runHistory[idOrIndex];
624
+ if (!run) {
625
+ logger.info(
626
+ `[Pipeline Debug] No run found at index ${idOrIndex}. History length: ${runHistory.length}`
627
+ );
628
+ return;
629
+ }
630
+ } else {
631
+ run = runHistory.find((r) => r.runId.endsWith(idOrIndex));
632
+ if (!run) {
633
+ logger.info(`[Pipeline Debug] No run found matching ID '${idOrIndex}'.`);
634
+ return;
635
+ }
636
+ }
637
+ printRunSummary(run);
638
+ },
555
639
  /**
556
- * Get this strategy's persisted state for the current course.
557
- *
558
- * @returns The strategy's data payload, or null if no state exists
559
- * @throws Error if user or course is not initialized
640
+ * Show summary of the last pipeline run.
560
641
  */
561
- async getStrategyState() {
562
- if (!this.user || !this.course) {
563
- throw new Error(
564
- `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
565
- );
566
- }
567
- return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
568
- }
642
+ showLastRun() {
643
+ this.showRun(0);
644
+ },
569
645
  /**
570
- * Persist this strategy's state for the current course.
571
- *
572
- * @param data - The strategy's data payload to store
573
- * @throws Error if user or course is not initialized
646
+ * Show detailed provenance for a specific card.
574
647
  */
575
- async putStrategyState(data) {
576
- if (!this.user || !this.course) {
577
- throw new Error(
578
- `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
579
- );
648
+ showCard(cardId) {
649
+ for (const run of runHistory) {
650
+ const card = run.cards.find((c) => c.cardId === cardId);
651
+ if (card) {
652
+ console.group(`\u{1F3B4} Card: ${cardId}`);
653
+ logger.info(`Course: ${card.courseId}`);
654
+ logger.info(`Origin: ${card.origin}`);
655
+ logger.info(`Final score: ${card.finalScore.toFixed(3)}`);
656
+ logger.info(`Selected: ${card.selected ? "Yes \u2705" : "No \u274C"}`);
657
+ logger.info("Provenance:");
658
+ logger.info(formatProvenance(card.provenance));
659
+ console.groupEnd();
660
+ return;
661
+ }
580
662
  }
581
- return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
582
- }
663
+ logger.info(`[Pipeline Debug] Card '${cardId}' not found in recent runs.`);
664
+ },
583
665
  /**
584
- * Factory method to create navigator instances dynamically.
585
- *
586
- * @param user - User interface
587
- * @param course - Course interface
588
- * @param strategyData - Strategy configuration document
589
- * @returns the runtime object used to steer a study session.
666
+ * Explain why reviews may or may not have been selected.
590
667
  */
591
- static async create(user, course, strategyData) {
592
- const implementingClass = strategyData.implementingClass;
593
- let NavigatorImpl;
594
- const variations = [".ts", ".js", ""];
595
- const dirs = ["filters", "generators"];
596
- for (const ext of variations) {
597
- for (const dir of dirs) {
598
- const loadFrom = `./${dir}/${implementingClass}${ext}`;
599
- try {
600
- const module2 = await import(loadFrom);
601
- NavigatorImpl = module2.default;
602
- break;
603
- } catch (e) {
604
- logger.debug(`Failed to load extension from ${loadFrom}:`, e);
668
+ explainReviews() {
669
+ if (runHistory.length === 0) {
670
+ logger.info("[Pipeline Debug] No runs captured yet.");
671
+ return;
672
+ }
673
+ console.group("\u{1F4CB} Review Selection Analysis");
674
+ for (const run of runHistory) {
675
+ console.group(`Run: ${run.courseId} @ ${run.timestamp.toLocaleTimeString()}`);
676
+ const allReviews = run.cards.filter((c) => c.origin === "review");
677
+ const selectedReviews = allReviews.filter((c) => c.selected);
678
+ if (allReviews.length === 0) {
679
+ logger.info("\u274C No reviews were generated. Check SRS logs for why.");
680
+ } else if (selectedReviews.length === 0) {
681
+ logger.info(`\u26A0\uFE0F ${allReviews.length} reviews generated but none selected.`);
682
+ logger.info("Possible reasons:");
683
+ const topNewScore = Math.max(
684
+ ...run.cards.filter((c) => c.origin === "new" && c.selected).map((c) => c.finalScore),
685
+ 0
686
+ );
687
+ const topReviewScore = Math.max(...allReviews.map((c) => c.finalScore), 0);
688
+ if (topReviewScore < topNewScore) {
689
+ logger.info(
690
+ ` - New cards scored higher (top new: ${topNewScore.toFixed(2)}, top review: ${topReviewScore.toFixed(2)})`
691
+ );
692
+ }
693
+ const topReview = allReviews.sort((a, b) => b.finalScore - a.finalScore)[0];
694
+ if (topReview) {
695
+ logger.info(` - Top review score: ${topReview.finalScore.toFixed(3)}`);
696
+ logger.info(" - Its provenance:");
697
+ logger.info(formatProvenance(topReview.provenance));
605
698
  }
699
+ } else {
700
+ logger.info(`\u2705 ${selectedReviews.length}/${allReviews.length} reviews selected.`);
701
+ logger.info("Top selected review:");
702
+ const topSelected = selectedReviews.sort((a, b) => b.finalScore - a.finalScore)[0];
703
+ logger.info(formatProvenance(topSelected.provenance));
606
704
  }
705
+ console.groupEnd();
607
706
  }
608
- if (!NavigatorImpl) {
609
- throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
707
+ console.groupEnd();
708
+ },
709
+ /**
710
+ * Show all runs in compact format.
711
+ */
712
+ listRuns() {
713
+ if (runHistory.length === 0) {
714
+ logger.info("[Pipeline Debug] No runs captured yet.");
715
+ return;
610
716
  }
611
- return new NavigatorImpl(user, course, strategyData);
612
- }
717
+ console.table(
718
+ runHistory.map((r) => ({
719
+ id: r.runId.slice(-8),
720
+ time: r.timestamp.toLocaleTimeString(),
721
+ course: r.courseName || r.courseId.slice(0, 8),
722
+ generated: r.generatedCount,
723
+ selected: r.finalCount,
724
+ new: r.newSelected,
725
+ reviews: r.reviewsSelected
726
+ }))
727
+ );
728
+ },
613
729
  /**
614
- * Get cards with suitability scores and provenance trails.
615
- *
616
- * **This is the PRIMARY API for navigation strategies.**
617
- *
618
- * Returns cards ranked by suitability score (0-1). Higher scores indicate
619
- * better candidates for presentation. Each card includes a provenance trail
620
- * documenting how strategies contributed to the final score.
621
- *
622
- * ## Implementation Required
623
- * All navigation strategies MUST override this method. The base class does
624
- * not provide a default implementation.
625
- *
626
- * ## For Generators
627
- * Override this method to generate candidates and compute scores based on
628
- * your strategy's logic (e.g., ELO proximity, review urgency). Create the
629
- * initial provenance entry with action='generated'.
630
- *
631
- * ## For Filters
632
- * Filters should implement the CardFilter interface instead and be composed
633
- * via Pipeline. Filters do not directly implement getWeightedCards().
634
- *
635
- * @param limit - Maximum cards to return
636
- * @returns Cards sorted by score descending, with provenance trails
730
+ * Export run history as JSON for bug reports.
637
731
  */
638
- async getWeightedCards(_limit) {
639
- throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
732
+ export() {
733
+ const json = JSON.stringify(runHistory, null, 2);
734
+ logger.info("[Pipeline Debug] Run history exported. Copy the returned string or use:");
735
+ logger.info(" copy(window.skuilder.pipeline.export())");
736
+ return json;
737
+ },
738
+ /**
739
+ * Clear run history.
740
+ */
741
+ clear() {
742
+ runHistory.length = 0;
743
+ logger.info("[Pipeline Debug] Run history cleared.");
744
+ },
745
+ /**
746
+ * Show help.
747
+ */
748
+ help() {
749
+ logger.info(`
750
+ \u{1F527} Pipeline Debug API
751
+
752
+ Commands:
753
+ .showLastRun() Show summary of most recent pipeline run
754
+ .showRun(id|index) Show summary of a specific run (by index or ID suffix)
755
+ .showCard(cardId) Show provenance trail for a specific card
756
+ .explainReviews() Analyze why reviews were/weren't selected
757
+ .listRuns() List all captured runs in table format
758
+ .export() Export run history as JSON for bug reports
759
+ .clear() Clear run history
760
+ .runs Access raw run history array
761
+ .help() Show this help message
762
+
763
+ Example:
764
+ window.skuilder.pipeline.showLastRun()
765
+ window.skuilder.pipeline.showRun(1)
766
+ window.skuilder.pipeline.showCard('abc123')
767
+ `);
640
768
  }
641
769
  };
770
+ mountPipelineDebugger();
642
771
  }
643
772
  });
644
773
 
645
- // src/core/navigators/Pipeline.ts
646
- function logPipelineConfig(generator, filters) {
647
- const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
648
- logger.info(
649
- `[Pipeline] Configuration:
650
- Generator: ${generator.name}
651
- Filters:${filterList}`
652
- );
653
- }
654
- function logTagHydration(cards, tagsByCard) {
655
- const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
656
- const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
657
- logger.debug(
658
- `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
659
- );
660
- }
661
- function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores) {
662
- const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
663
- logger.info(
664
- `[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})`
665
- );
666
- }
667
- function logCardProvenance(cards, maxCards = 3) {
668
- const cardsToLog = cards.slice(0, maxCards);
669
- logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
670
- for (const card of cardsToLog) {
671
- logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
672
- for (const entry of card.provenance) {
673
- const scoreChange = entry.score.toFixed(3);
674
- const action = entry.action.padEnd(9);
675
- logger.debug(
676
- `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
677
- );
678
- }
679
- }
680
- }
681
- var import_common5, Pipeline;
682
- var init_Pipeline = __esm({
683
- "src/core/navigators/Pipeline.ts"() {
774
+ // src/core/navigators/generators/CompositeGenerator.ts
775
+ var CompositeGenerator_exports = {};
776
+ __export(CompositeGenerator_exports, {
777
+ AggregationMode: () => AggregationMode,
778
+ default: () => CompositeGenerator
779
+ });
780
+ var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
781
+ var init_CompositeGenerator = __esm({
782
+ "src/core/navigators/generators/CompositeGenerator.ts"() {
684
783
  "use strict";
685
- import_common5 = require("@vue-skuilder/common");
686
784
  init_navigators();
687
785
  init_logger();
688
- Pipeline = class extends ContentNavigator {
689
- generator;
690
- filters;
691
- /**
692
- * Create a new pipeline.
693
- *
694
- * @param generator - The generator (or CompositeGenerator) that produces candidates
695
- * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
696
- * @param user - User database interface
697
- * @param course - Course database interface
698
- */
699
- constructor(generator, filters, user, course) {
786
+ AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
787
+ AggregationMode2["MAX"] = "max";
788
+ AggregationMode2["AVERAGE"] = "average";
789
+ AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
790
+ return AggregationMode2;
791
+ })(AggregationMode || {});
792
+ DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
793
+ FREQUENCY_BOOST_FACTOR = 0.1;
794
+ CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
795
+ /** Human-readable name for CardGenerator interface */
796
+ name = "Composite Generator";
797
+ generators;
798
+ aggregationMode;
799
+ constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
700
800
  super();
701
- this.generator = generator;
702
- this.filters = filters;
703
- this.user = user;
704
- this.course = course;
705
- course.getCourseConfig().then((cfg) => {
706
- logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);
707
- }).catch((e) => {
708
- logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);
709
- });
710
- logPipelineConfig(generator, filters);
801
+ this.generators = generators;
802
+ this.aggregationMode = aggregationMode;
803
+ if (generators.length === 0) {
804
+ throw new Error("CompositeGenerator requires at least one generator");
805
+ }
806
+ logger.debug(
807
+ `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
808
+ );
711
809
  }
712
810
  /**
713
- * Get weighted cards by running generator and applying filters.
714
- *
715
- * 1. Build shared context (user ELO, etc.)
716
- * 2. Get candidates from generator (passing context)
717
- * 3. Batch hydrate tags for all candidates
718
- * 4. Apply each filter sequentially
719
- * 5. Remove zero-score cards
720
- * 6. Sort by score descending
721
- * 7. Return top N
722
- *
723
- * @param limit - Maximum number of cards to return
724
- * @returns Cards sorted by score descending
725
- */
726
- async getWeightedCards(limit) {
727
- const context = await this.buildContext();
728
- const overFetchMultiplier = 2 + this.filters.length * 0.5;
729
- const fetchLimit = Math.ceil(limit * overFetchMultiplier);
730
- logger.debug(
731
- `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
732
- );
733
- let cards = await this.generator.getWeightedCards(fetchLimit, context);
734
- const generatedCount = cards.length;
735
- logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
736
- cards = await this.hydrateTags(cards);
737
- for (const filter of this.filters) {
738
- const beforeCount = cards.length;
739
- cards = await filter.transform(cards, context);
740
- logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeCount} \u2192 ${cards.length} cards`);
741
- }
742
- cards = cards.filter((c) => c.score > 0);
743
- cards.sort((a, b) => b.score - a.score);
744
- const result = cards.slice(0, limit);
745
- const topScores = result.slice(0, 3).map((c) => c.score);
746
- logExecutionSummary(
747
- this.generator.name,
748
- generatedCount,
749
- this.filters.length,
750
- result.length,
751
- topScores
752
- );
753
- logCardProvenance(result, 3);
754
- return result;
755
- }
756
- /**
757
- * Batch hydrate tags for all cards.
758
- *
759
- * Fetches tags for all cards in a single database query and attaches them
760
- * to the WeightedCard objects. Filters can then use card.tags instead of
761
- * making individual getAppliedTags() calls.
762
- *
763
- * @param cards - Cards to hydrate
764
- * @returns Cards with tags populated
765
- */
766
- async hydrateTags(cards) {
767
- if (cards.length === 0) {
768
- return cards;
769
- }
770
- const cardIds = cards.map((c) => c.cardId);
771
- const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
772
- logTagHydration(cards, tagsByCard);
773
- return cards.map((card) => ({
774
- ...card,
775
- tags: tagsByCard.get(card.cardId) ?? []
776
- }));
777
- }
778
- /**
779
- * Build shared context for generator and filters.
780
- *
781
- * Called once per getWeightedCards() invocation.
782
- * Contains data that the generator and multiple filters might need.
783
- *
784
- * The context satisfies both GeneratorContext and FilterContext interfaces.
785
- */
786
- async buildContext() {
787
- let userElo = 1e3;
788
- try {
789
- const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
790
- const courseElo = (0, import_common5.toCourseElo)(courseReg.elo);
791
- userElo = courseElo.global.score;
792
- } catch (e) {
793
- logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
794
- }
795
- return {
796
- user: this.user,
797
- course: this.course,
798
- userElo
799
- };
800
- }
801
- /**
802
- * Get the course ID for this pipeline.
803
- */
804
- getCourseID() {
805
- return this.course.getCourseID();
806
- }
807
- };
808
- }
809
- });
810
-
811
- // src/core/navigators/generators/CompositeGenerator.ts
812
- var DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
813
- var init_CompositeGenerator = __esm({
814
- "src/core/navigators/generators/CompositeGenerator.ts"() {
815
- "use strict";
816
- init_navigators();
817
- init_logger();
818
- DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
819
- FREQUENCY_BOOST_FACTOR = 0.1;
820
- CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
821
- /** Human-readable name for CardGenerator interface */
822
- name = "Composite Generator";
823
- generators;
824
- aggregationMode;
825
- constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
826
- super();
827
- this.generators = generators;
828
- this.aggregationMode = aggregationMode;
829
- if (generators.length === 0) {
830
- throw new Error("CompositeGenerator requires at least one generator");
831
- }
832
- logger.debug(
833
- `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
834
- );
835
- }
836
- /**
837
- * Creates a CompositeGenerator from strategy data.
811
+ * Creates a CompositeGenerator from strategy data.
838
812
  *
839
813
  * This is a convenience factory for use by PipelineAssembler.
840
814
  */
@@ -865,22 +839,55 @@ var init_CompositeGenerator = __esm({
865
839
  const results = await Promise.all(
866
840
  this.generators.map((g) => g.getWeightedCards(limit, context))
867
841
  );
842
+ const generatorSummaries = [];
843
+ results.forEach((cards, index) => {
844
+ const gen = this.generators[index];
845
+ const genName = gen.name || `Generator ${index}`;
846
+ const newCards = cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
847
+ const reviewCards = cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
848
+ if (cards.length > 0) {
849
+ const topScore = Math.max(...cards.map((c) => c.score)).toFixed(2);
850
+ const parts = [];
851
+ if (newCards.length > 0) parts.push(`${newCards.length} new`);
852
+ if (reviewCards.length > 0) parts.push(`${reviewCards.length} reviews`);
853
+ const breakdown = parts.length > 0 ? parts.join(", ") : `${cards.length} cards`;
854
+ generatorSummaries.push(`${genName}: ${breakdown} (top: ${topScore})`);
855
+ } else {
856
+ generatorSummaries.push(`${genName}: 0 cards`);
857
+ }
858
+ });
859
+ logger.info(`[Composite] Generator breakdown: ${generatorSummaries.join(" | ")}`);
868
860
  const byCardId = /* @__PURE__ */ new Map();
869
- for (const cards of results) {
861
+ results.forEach((cards, index) => {
862
+ const gen = this.generators[index];
863
+ let weight = gen.learnable?.weight ?? 1;
864
+ let deviation;
865
+ if (gen.learnable && !gen.staticWeight && context.orchestration) {
866
+ const strategyId = gen.strategyId;
867
+ if (strategyId) {
868
+ weight = context.orchestration.getEffectiveWeight(strategyId, gen.learnable);
869
+ deviation = context.orchestration.getDeviation(strategyId);
870
+ }
871
+ }
870
872
  for (const card of cards) {
873
+ if (card.provenance.length > 0) {
874
+ card.provenance[0].effectiveWeight = weight;
875
+ card.provenance[0].deviation = deviation;
876
+ }
871
877
  const existing = byCardId.get(card.cardId) || [];
872
- existing.push(card);
878
+ existing.push({ card, weight });
873
879
  byCardId.set(card.cardId, existing);
874
880
  }
875
- }
881
+ });
876
882
  const merged = [];
877
- for (const [, cards] of byCardId) {
878
- const aggregatedScore = this.aggregateScores(cards);
883
+ for (const [, items] of byCardId) {
884
+ const cards = items.map((i) => i.card);
885
+ const aggregatedScore = this.aggregateScores(items);
879
886
  const finalScore = Math.min(1, aggregatedScore);
880
887
  const mergedProvenance = cards.flatMap((c) => c.provenance);
881
888
  const initialScore = cards[0].score;
882
889
  const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
883
- const reason = this.buildAggregationReason(cards, finalScore);
890
+ const reason = this.buildAggregationReason(items, finalScore);
884
891
  merged.push({
885
892
  ...cards[0],
886
893
  score: finalScore,
@@ -902,22 +909,26 @@ var init_CompositeGenerator = __esm({
902
909
  /**
903
910
  * Build human-readable reason for score aggregation.
904
911
  */
905
- buildAggregationReason(cards, finalScore) {
912
+ buildAggregationReason(items, finalScore) {
913
+ const cards = items.map((i) => i.card);
906
914
  const count = cards.length;
907
915
  const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
908
916
  if (count === 1) {
909
- return `Single generator, score ${finalScore.toFixed(2)}`;
917
+ const weightMsg = Math.abs(items[0].weight - 1) > 1e-3 ? ` (w=${items[0].weight.toFixed(2)})` : "";
918
+ return `Single generator, score ${finalScore.toFixed(2)}${weightMsg}`;
910
919
  }
911
920
  const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
912
921
  switch (this.aggregationMode) {
913
922
  case "max" /* MAX */:
914
923
  return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
915
924
  case "average" /* AVERAGE */:
916
- return `Average of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
925
+ return `Weighted Avg of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
917
926
  case "frequencyBoost" /* FREQUENCY_BOOST */: {
918
- const avg = cards.reduce((sum, c) => sum + c.score, 0) / count;
927
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
928
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
929
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
919
930
  const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
920
- return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
931
+ return `Frequency boost from ${count} generators (${strategies}): w-avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
921
932
  }
922
933
  default:
923
934
  return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
@@ -926,16 +937,22 @@ var init_CompositeGenerator = __esm({
926
937
  /**
927
938
  * Aggregate scores from multiple generators for the same card.
928
939
  */
929
- aggregateScores(cards) {
930
- const scores = cards.map((c) => c.score);
940
+ aggregateScores(items) {
941
+ const scores = items.map((i) => i.card.score);
931
942
  switch (this.aggregationMode) {
932
943
  case "max" /* MAX */:
933
944
  return Math.max(...scores);
934
- case "average" /* AVERAGE */:
935
- return scores.reduce((sum, s) => sum + s, 0) / scores.length;
945
+ case "average" /* AVERAGE */: {
946
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
947
+ if (totalWeight === 0) return 0;
948
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
949
+ return weightedSum / totalWeight;
950
+ }
936
951
  case "frequencyBoost" /* FREQUENCY_BOOST */: {
937
- const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
938
- const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (cards.length - 1);
952
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
953
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
954
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
955
+ const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (items.length - 1);
939
956
  return avg * frequencyBoost;
940
957
  }
941
958
  default:
@@ -946,134 +963,18 @@ var init_CompositeGenerator = __esm({
946
963
  }
947
964
  });
948
965
 
949
- // src/core/navigators/PipelineAssembler.ts
950
- var PipelineAssembler;
951
- var init_PipelineAssembler = __esm({
952
- "src/core/navigators/PipelineAssembler.ts"() {
953
- "use strict";
954
- init_navigators();
955
- init_Pipeline();
956
- init_types_legacy();
957
- init_logger();
958
- init_CompositeGenerator();
959
- PipelineAssembler = class {
960
- /**
961
- * Assembles a navigation pipeline from strategy documents.
962
- *
963
- * 1. Separates into generators and filters by role
964
- * 2. Validates at least one generator exists (or creates default ELO)
965
- * 3. Instantiates generators - wraps multiple in CompositeGenerator
966
- * 4. Instantiates filters
967
- * 5. Returns Pipeline(generator, filters)
968
- *
969
- * @param input - Strategy documents plus user/course interfaces
970
- * @returns Assembled pipeline and any warnings
971
- */
972
- async assemble(input) {
973
- const { strategies, user, course } = input;
974
- const warnings = [];
975
- if (strategies.length === 0) {
976
- return {
977
- pipeline: null,
978
- generatorStrategies: [],
979
- filterStrategies: [],
980
- warnings
981
- };
982
- }
983
- const generatorStrategies = [];
984
- const filterStrategies = [];
985
- for (const s of strategies) {
986
- if (isGenerator(s.implementingClass)) {
987
- generatorStrategies.push(s);
988
- } else if (isFilter(s.implementingClass)) {
989
- filterStrategies.push(s);
990
- } else {
991
- warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
992
- }
993
- }
994
- if (generatorStrategies.length === 0) {
995
- if (filterStrategies.length > 0) {
996
- logger.debug(
997
- "[PipelineAssembler] No generator found, using default ELO with configured filters"
998
- );
999
- generatorStrategies.push(this.makeDefaultEloStrategy(course.getCourseID()));
1000
- } else {
1001
- warnings.push("No generator strategy found");
1002
- return {
1003
- pipeline: null,
1004
- generatorStrategies: [],
1005
- filterStrategies: [],
1006
- warnings
1007
- };
1008
- }
1009
- }
1010
- let generator;
1011
- if (generatorStrategies.length === 1) {
1012
- const nav = await ContentNavigator.create(user, course, generatorStrategies[0]);
1013
- generator = nav;
1014
- logger.debug(`[PipelineAssembler] Using single generator: ${generatorStrategies[0].name}`);
1015
- } else {
1016
- logger.debug(
1017
- `[PipelineAssembler] Using CompositeGenerator for ${generatorStrategies.length} generators: ${generatorStrategies.map((g) => g.name).join(", ")}`
1018
- );
1019
- generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
1020
- }
1021
- const filters = [];
1022
- const sortedFilterStrategies = [...filterStrategies].sort(
1023
- (a, b) => a.name.localeCompare(b.name)
1024
- );
1025
- for (const filterStrategy of sortedFilterStrategies) {
1026
- try {
1027
- const nav = await ContentNavigator.create(user, course, filterStrategy);
1028
- if ("transform" in nav && typeof nav.transform === "function") {
1029
- filters.push(nav);
1030
- logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
1031
- } else {
1032
- warnings.push(
1033
- `Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
1034
- );
1035
- }
1036
- } catch (e) {
1037
- warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
1038
- }
1039
- }
1040
- const pipeline = new Pipeline(generator, filters, user, course);
1041
- logger.debug(
1042
- `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
1043
- );
1044
- return {
1045
- pipeline,
1046
- generatorStrategies,
1047
- filterStrategies: sortedFilterStrategies,
1048
- warnings
1049
- };
1050
- }
1051
- /**
1052
- * Creates a default ELO generator strategy.
1053
- * Used when filters are configured but no generator is specified.
1054
- */
1055
- makeDefaultEloStrategy(courseId) {
1056
- return {
1057
- _id: "NAVIGATION_STRATEGY-ELO-default",
1058
- course: courseId,
1059
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1060
- name: "ELO (default)",
1061
- description: "Default ELO-based generator",
1062
- implementingClass: "elo" /* ELO */,
1063
- serializedData: ""
1064
- };
1065
- }
1066
- };
1067
- }
1068
- });
1069
-
1070
966
  // src/core/navigators/generators/elo.ts
1071
- var import_common6, ELONavigator;
967
+ var elo_exports = {};
968
+ __export(elo_exports, {
969
+ default: () => ELONavigator
970
+ });
971
+ var import_common5, ELONavigator;
1072
972
  var init_elo = __esm({
1073
973
  "src/core/navigators/generators/elo.ts"() {
1074
974
  "use strict";
1075
975
  init_navigators();
1076
- import_common6 = require("@vue-skuilder/common");
976
+ import_common5 = require("@vue-skuilder/common");
977
+ init_logger();
1077
978
  ELONavigator = class extends ContentNavigator {
1078
979
  /** Human-readable name for CardGenerator interface */
1079
980
  name;
@@ -1102,7 +1003,7 @@ var init_elo = __esm({
1102
1003
  userGlobalElo = context.userElo;
1103
1004
  } else {
1104
1005
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1105
- const userElo = (0, import_common6.toCourseElo)(courseReg.elo);
1006
+ const userElo = (0, import_common5.toCourseElo)(courseReg.elo);
1106
1007
  userGlobalElo = userElo.global.score;
1107
1008
  }
1108
1009
  const activeCards = await this.user.getActiveCards();
@@ -1133,205 +1034,1961 @@ var init_elo = __esm({
1133
1034
  };
1134
1035
  });
1135
1036
  scored.sort((a, b) => b.score - a.score);
1136
- return scored.slice(0, limit);
1037
+ const result = scored.slice(0, limit);
1038
+ if (result.length > 0) {
1039
+ const topScores = result.slice(0, 3).map((c) => c.score.toFixed(2)).join(", ");
1040
+ logger.info(
1041
+ `[ELO] Course ${this.course.getCourseID()}: ${result.length} new cards (top scores: ${topScores})`
1042
+ );
1043
+ } else {
1044
+ logger.info(`[ELO] Course ${this.course.getCourseID()}: No new cards available`);
1045
+ }
1046
+ return result;
1137
1047
  }
1138
1048
  };
1139
1049
  }
1140
1050
  });
1141
1051
 
1052
+ // src/core/navigators/generators/index.ts
1053
+ var generators_exports = {};
1054
+ var init_generators = __esm({
1055
+ "src/core/navigators/generators/index.ts"() {
1056
+ "use strict";
1057
+ }
1058
+ });
1059
+
1142
1060
  // src/core/navigators/generators/srs.ts
1143
- var import_moment3, SRSNavigator;
1061
+ var srs_exports = {};
1062
+ __export(srs_exports, {
1063
+ default: () => SRSNavigator
1064
+ });
1065
+ var import_moment3, DEFAULT_HEALTHY_BACKLOG, MAX_BACKLOG_PRESSURE, SRSNavigator;
1144
1066
  var init_srs = __esm({
1145
1067
  "src/core/navigators/generators/srs.ts"() {
1146
1068
  "use strict";
1147
1069
  import_moment3 = __toESM(require("moment"), 1);
1148
1070
  init_navigators();
1149
1071
  init_logger();
1072
+ DEFAULT_HEALTHY_BACKLOG = 20;
1073
+ MAX_BACKLOG_PRESSURE = 0.5;
1150
1074
  SRSNavigator = class extends ContentNavigator {
1151
1075
  /** Human-readable name for CardGenerator interface */
1152
1076
  name;
1077
+ /** Healthy backlog threshold - when exceeded, backlog pressure kicks in */
1078
+ healthyBacklog;
1153
1079
  constructor(user, course, strategyData) {
1154
1080
  super(user, course, strategyData);
1155
1081
  this.name = strategyData?.name || "SRS";
1082
+ const config = this.parseConfig(strategyData?.serializedData);
1083
+ this.healthyBacklog = config.healthyBacklog ?? DEFAULT_HEALTHY_BACKLOG;
1084
+ }
1085
+ /**
1086
+ * Parse configuration from serialized JSON.
1087
+ */
1088
+ parseConfig(serializedData) {
1089
+ if (!serializedData) return {};
1090
+ try {
1091
+ return JSON.parse(serializedData);
1092
+ } catch {
1093
+ logger.warn("[SRS] Failed to parse strategy config, using defaults");
1094
+ return {};
1095
+ }
1096
+ }
1097
+ /**
1098
+ * Get review cards scored by urgency.
1099
+ *
1100
+ * Score formula combines:
1101
+ * - Relative overdueness: hoursOverdue / intervalHours
1102
+ * - Interval recency: exponential decay favoring shorter intervals
1103
+ * - Backlog pressure: boost when due reviews exceed healthy threshold
1104
+ *
1105
+ * Cards not yet due are excluded (not scored as 0).
1106
+ *
1107
+ * This method supports both the legacy signature (limit only) and the
1108
+ * CardGenerator interface signature (limit, context).
1109
+ *
1110
+ * @param limit - Maximum number of cards to return
1111
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1112
+ */
1113
+ async getWeightedCards(limit, _context) {
1114
+ if (!this.user || !this.course) {
1115
+ throw new Error("SRSNavigator requires user and course to be set");
1116
+ }
1117
+ const courseId = this.course.getCourseID();
1118
+ const reviews = await this.user.getPendingReviews(courseId);
1119
+ const now = import_moment3.default.utc();
1120
+ const dueReviews = reviews.filter((r) => now.isAfter(import_moment3.default.utc(r.reviewTime)));
1121
+ const backlogPressure = this.computeBacklogPressure(dueReviews.length);
1122
+ if (dueReviews.length > 0) {
1123
+ const pressureNote = backlogPressure > 0 ? ` [backlog pressure: +${backlogPressure.toFixed(2)}]` : ` [healthy backlog]`;
1124
+ logger.info(
1125
+ `[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)${pressureNote}`
1126
+ );
1127
+ } else if (reviews.length > 0) {
1128
+ const sortedByDue = [...reviews].sort(
1129
+ (a, b) => import_moment3.default.utc(a.reviewTime).diff(import_moment3.default.utc(b.reviewTime))
1130
+ );
1131
+ const nextDue = sortedByDue[0];
1132
+ const nextDueTime = import_moment3.default.utc(nextDue.reviewTime);
1133
+ const untilDue = import_moment3.default.duration(nextDueTime.diff(now));
1134
+ const untilDueStr = untilDue.asHours() < 1 ? `${Math.round(untilDue.asMinutes())}m` : untilDue.asHours() < 24 ? `${Math.round(untilDue.asHours())}h` : `${Math.round(untilDue.asDays())}d`;
1135
+ logger.info(
1136
+ `[SRS] Course ${courseId}: 0 reviews due now (${reviews.length} scheduled, next in ${untilDueStr})`
1137
+ );
1138
+ } else {
1139
+ logger.info(`[SRS] Course ${courseId}: No reviews scheduled`);
1140
+ }
1141
+ const scored = dueReviews.map((review) => {
1142
+ const { score, reason } = this.computeUrgencyScore(review, now, backlogPressure);
1143
+ return {
1144
+ cardId: review.cardId,
1145
+ courseId: review.courseId,
1146
+ score,
1147
+ reviewID: review._id,
1148
+ provenance: [
1149
+ {
1150
+ strategy: "srs",
1151
+ strategyName: this.strategyName || this.name,
1152
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1153
+ action: "generated",
1154
+ score,
1155
+ reason
1156
+ }
1157
+ ]
1158
+ };
1159
+ });
1160
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1161
+ }
1162
+ /**
1163
+ * Compute backlog pressure based on number of due reviews.
1164
+ *
1165
+ * Backlog pressure is 0 when at or below healthy threshold,
1166
+ * and increases linearly above it, maxing out at MAX_BACKLOG_PRESSURE.
1167
+ *
1168
+ * Examples (with default healthyBacklog=20):
1169
+ * - 10 due reviews → 0.00 (healthy)
1170
+ * - 20 due reviews → 0.00 (at threshold)
1171
+ * - 40 due reviews → 0.25 (2x threshold)
1172
+ * - 60 due reviews → 0.50 (3x threshold, maxed)
1173
+ *
1174
+ * @param dueCount - Number of reviews currently due
1175
+ * @returns Backlog pressure score to add to urgency (0 to MAX_BACKLOG_PRESSURE)
1176
+ */
1177
+ computeBacklogPressure(dueCount) {
1178
+ if (dueCount <= this.healthyBacklog) {
1179
+ return 0;
1180
+ }
1181
+ const excess = dueCount - this.healthyBacklog;
1182
+ const pressure = excess / this.healthyBacklog * (MAX_BACKLOG_PRESSURE / 2);
1183
+ return Math.min(MAX_BACKLOG_PRESSURE, pressure);
1184
+ }
1185
+ /**
1186
+ * Compute urgency score for a review card.
1187
+ *
1188
+ * Three factors:
1189
+ * 1. Relative overdueness = hoursOverdue / intervalHours
1190
+ * - 2 days overdue on 3-day interval = 0.67 (urgent)
1191
+ * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1192
+ *
1193
+ * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1194
+ * - 24h interval → ~1.0 (very recent learning)
1195
+ * - 30 days (720h) → ~0.56
1196
+ * - 180 days → ~0.30
1197
+ *
1198
+ * 3. Backlog pressure = global boost when review backlog exceeds healthy threshold
1199
+ * - At healthy backlog: 0
1200
+ * - At 2x healthy: +0.25
1201
+ * - At 3x+ healthy: +0.50 (max)
1202
+ *
1203
+ * Combined: base 0.5 + (urgency factors * 0.45) + backlog pressure
1204
+ * Result range: 0.5 to 1.0 (uncapped to allow high-urgency reviews to compete with new cards)
1205
+ *
1206
+ * @param review - The scheduled card to score
1207
+ * @param now - Current time
1208
+ * @param backlogPressure - Pre-computed backlog pressure (0 to 0.5)
1209
+ */
1210
+ computeUrgencyScore(review, now, backlogPressure) {
1211
+ const scheduledAt = import_moment3.default.utc(review.scheduledAt);
1212
+ const due = import_moment3.default.utc(review.reviewTime);
1213
+ const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1214
+ const hoursOverdue = now.diff(due, "hours");
1215
+ const relativeOverdue = hoursOverdue / intervalHours;
1216
+ const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1217
+ const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1218
+ const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1219
+ const baseScore = 0.5 + urgency * 0.45;
1220
+ const score = Math.min(1, baseScore + backlogPressure);
1221
+ const reasonParts = [
1222
+ `${Math.round(hoursOverdue)}h overdue`,
1223
+ `interval: ${Math.round(intervalHours)}h`,
1224
+ `relative: ${relativeOverdue.toFixed(2)}`,
1225
+ `recency: ${recencyFactor.toFixed(2)}`
1226
+ ];
1227
+ if (backlogPressure > 0) {
1228
+ reasonParts.push(`backlog: +${backlogPressure.toFixed(2)}`);
1229
+ }
1230
+ reasonParts.push("review");
1231
+ const reason = reasonParts.join(", ");
1232
+ return { score, reason };
1233
+ }
1234
+ };
1235
+ }
1236
+ });
1237
+
1238
+ // src/core/navigators/generators/types.ts
1239
+ var types_exports = {};
1240
+ var init_types = __esm({
1241
+ "src/core/navigators/generators/types.ts"() {
1242
+ "use strict";
1243
+ }
1244
+ });
1245
+
1246
+ // import("./generators/**/*") in src/core/navigators/index.ts
1247
+ var globImport_generators;
1248
+ var init_ = __esm({
1249
+ 'import("./generators/**/*") in src/core/navigators/index.ts'() {
1250
+ globImport_generators = __glob({
1251
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
1252
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
1253
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
1254
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
1255
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports))
1256
+ });
1257
+ }
1258
+ });
1259
+
1260
+ // src/core/types/contentNavigationStrategy.ts
1261
+ var DEFAULT_LEARNABLE_WEIGHT;
1262
+ var init_contentNavigationStrategy = __esm({
1263
+ "src/core/types/contentNavigationStrategy.ts"() {
1264
+ "use strict";
1265
+ DEFAULT_LEARNABLE_WEIGHT = {
1266
+ weight: 1,
1267
+ confidence: 0.1,
1268
+ // Low confidence initially = wide exploration
1269
+ sampleSize: 0
1270
+ };
1271
+ }
1272
+ });
1273
+
1274
+ // src/core/navigators/filters/WeightedFilter.ts
1275
+ var WeightedFilter_exports = {};
1276
+ __export(WeightedFilter_exports, {
1277
+ WeightedFilter: () => WeightedFilter
1278
+ });
1279
+ var WeightedFilter;
1280
+ var init_WeightedFilter = __esm({
1281
+ "src/core/navigators/filters/WeightedFilter.ts"() {
1282
+ "use strict";
1283
+ init_contentNavigationStrategy();
1284
+ WeightedFilter = class {
1285
+ name;
1286
+ inner;
1287
+ learnable;
1288
+ staticWeight;
1289
+ strategyId;
1290
+ constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
1291
+ this.inner = inner;
1292
+ this.name = inner.name;
1293
+ this.learnable = learnable;
1294
+ this.staticWeight = staticWeight;
1295
+ this.strategyId = strategyId;
1296
+ }
1297
+ /**
1298
+ * Apply the inner filter, then scale its effect by the configured weight.
1299
+ */
1300
+ async transform(cards, context) {
1301
+ let effectiveWeight = this.learnable.weight;
1302
+ let deviation;
1303
+ if (!this.staticWeight && context.orchestration) {
1304
+ const strategyId = this.strategyId || this.inner.strategyId || this.name;
1305
+ effectiveWeight = context.orchestration.getEffectiveWeight(strategyId, this.learnable);
1306
+ deviation = context.orchestration.getDeviation(strategyId);
1307
+ }
1308
+ if (Math.abs(effectiveWeight - 1) < 1e-3) {
1309
+ return this.inner.transform(cards, context);
1310
+ }
1311
+ const originalScores = /* @__PURE__ */ new Map();
1312
+ for (const card of cards) {
1313
+ originalScores.set(card.cardId, card.score);
1314
+ }
1315
+ const transformedCards = await this.inner.transform(cards, context);
1316
+ return transformedCards.map((card) => {
1317
+ const originalScore = originalScores.get(card.cardId);
1318
+ if (originalScore === void 0 || originalScore === 0 || card.score === 0) {
1319
+ return card;
1320
+ }
1321
+ const rawEffect = card.score / originalScore;
1322
+ if (Math.abs(rawEffect - 1) < 1e-4) {
1323
+ return card;
1324
+ }
1325
+ const weightedEffect = Math.pow(rawEffect, effectiveWeight);
1326
+ const newScore = originalScore * weightedEffect;
1327
+ const lastProvIndex = card.provenance.length - 1;
1328
+ const lastProv = card.provenance[lastProvIndex];
1329
+ if (lastProv) {
1330
+ const updatedProvenance = [...card.provenance];
1331
+ updatedProvenance[lastProvIndex] = {
1332
+ ...lastProv,
1333
+ score: newScore,
1334
+ effectiveWeight,
1335
+ deviation
1336
+ // We can optionally append to the reason, but the structured field is key
1337
+ };
1338
+ return {
1339
+ ...card,
1340
+ score: newScore,
1341
+ provenance: updatedProvenance
1342
+ };
1343
+ }
1344
+ return {
1345
+ ...card,
1346
+ score: newScore
1347
+ };
1348
+ });
1349
+ }
1350
+ };
1351
+ }
1352
+ });
1353
+
1354
+ // src/core/navigators/filters/eloDistance.ts
1355
+ var eloDistance_exports = {};
1356
+ __export(eloDistance_exports, {
1357
+ DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1358
+ DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1359
+ DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1360
+ createEloDistanceFilter: () => createEloDistanceFilter
1361
+ });
1362
+ function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1363
+ const normalizedDistance = distance / halfLife;
1364
+ const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1365
+ return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1366
+ }
1367
+ function createEloDistanceFilter(config) {
1368
+ const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1369
+ const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1370
+ const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1371
+ return {
1372
+ name: "ELO Distance Filter",
1373
+ async transform(cards, context) {
1374
+ const { course, userElo } = context;
1375
+ const cardIds = cards.map((c) => c.cardId);
1376
+ const cardElos = await course.getCardEloData(cardIds);
1377
+ return cards.map((card, i) => {
1378
+ const cardElo = cardElos[i]?.global?.score ?? 1e3;
1379
+ const distance = Math.abs(cardElo - userElo);
1380
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1381
+ const newScore = card.score * multiplier;
1382
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1383
+ return {
1384
+ ...card,
1385
+ score: newScore,
1386
+ provenance: [
1387
+ ...card.provenance,
1388
+ {
1389
+ strategy: "eloDistance",
1390
+ strategyName: "ELO Distance Filter",
1391
+ strategyId: "ELO_DISTANCE_FILTER",
1392
+ action,
1393
+ score: newScore,
1394
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1395
+ }
1396
+ ]
1397
+ };
1398
+ });
1399
+ }
1400
+ };
1401
+ }
1402
+ var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1403
+ var init_eloDistance = __esm({
1404
+ "src/core/navigators/filters/eloDistance.ts"() {
1405
+ "use strict";
1406
+ DEFAULT_HALF_LIFE = 200;
1407
+ DEFAULT_MIN_MULTIPLIER = 0.3;
1408
+ DEFAULT_MAX_MULTIPLIER = 1;
1409
+ }
1410
+ });
1411
+
1412
+ // src/core/navigators/filters/hierarchyDefinition.ts
1413
+ var hierarchyDefinition_exports = {};
1414
+ __export(hierarchyDefinition_exports, {
1415
+ default: () => HierarchyDefinitionNavigator
1416
+ });
1417
+ var import_common6, DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1418
+ var init_hierarchyDefinition = __esm({
1419
+ "src/core/navigators/filters/hierarchyDefinition.ts"() {
1420
+ "use strict";
1421
+ init_navigators();
1422
+ import_common6 = require("@vue-skuilder/common");
1423
+ DEFAULT_MIN_COUNT = 3;
1424
+ HierarchyDefinitionNavigator = class extends ContentNavigator {
1425
+ config;
1426
+ /** Human-readable name for CardFilter interface */
1427
+ name;
1428
+ constructor(user, course, strategyData) {
1429
+ super(user, course, strategyData);
1430
+ this.config = this.parseConfig(strategyData.serializedData);
1431
+ this.name = strategyData.name || "Hierarchy Definition";
1432
+ }
1433
+ parseConfig(serializedData) {
1434
+ try {
1435
+ const parsed = JSON.parse(serializedData);
1436
+ return {
1437
+ prerequisites: parsed.prerequisites || {}
1438
+ };
1439
+ } catch {
1440
+ return {
1441
+ prerequisites: {}
1442
+ };
1443
+ }
1444
+ }
1445
+ /**
1446
+ * Check if a specific prerequisite is satisfied
1447
+ */
1448
+ isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1449
+ if (!userTagElo) return false;
1450
+ const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1451
+ if (userTagElo.count < minCount) return false;
1452
+ if (prereq.masteryThreshold?.minElo !== void 0) {
1453
+ return userTagElo.score >= prereq.masteryThreshold.minElo;
1454
+ } else {
1455
+ return userTagElo.score >= userGlobalElo;
1456
+ }
1457
+ }
1458
+ /**
1459
+ * Get the set of tags the user has mastered.
1460
+ * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1461
+ */
1462
+ async getMasteredTags(context) {
1463
+ const mastered = /* @__PURE__ */ new Set();
1464
+ try {
1465
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1466
+ const userElo = (0, import_common6.toCourseElo)(courseReg.elo);
1467
+ for (const prereqs of Object.values(this.config.prerequisites)) {
1468
+ for (const prereq of prereqs) {
1469
+ const tagElo = userElo.tags[prereq.tag];
1470
+ if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1471
+ mastered.add(prereq.tag);
1472
+ }
1473
+ }
1474
+ }
1475
+ } catch {
1476
+ }
1477
+ return mastered;
1478
+ }
1479
+ /**
1480
+ * Get the set of tags that are unlocked (prerequisites met)
1481
+ */
1482
+ getUnlockedTags(masteredTags) {
1483
+ const unlocked = /* @__PURE__ */ new Set();
1484
+ for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1485
+ const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1486
+ if (allPrereqsMet) {
1487
+ unlocked.add(tagId);
1488
+ }
1489
+ }
1490
+ return unlocked;
1491
+ }
1492
+ /**
1493
+ * Check if a tag has prerequisites defined in config
1494
+ */
1495
+ hasPrerequisites(tagId) {
1496
+ return tagId in this.config.prerequisites;
1497
+ }
1498
+ /**
1499
+ * Check if a card is unlocked and generate reason.
1500
+ */
1501
+ async checkCardUnlock(card, _course, unlockedTags, masteredTags) {
1502
+ try {
1503
+ const cardTags = card.tags ?? [];
1504
+ const lockedTags = cardTags.filter(
1505
+ (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1506
+ );
1507
+ if (lockedTags.length === 0) {
1508
+ const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1509
+ return {
1510
+ isUnlocked: true,
1511
+ reason: `Prerequisites met, tags: ${tagList}`
1512
+ };
1513
+ }
1514
+ const missingPrereqs = lockedTags.flatMap((tag) => {
1515
+ const prereqs = this.config.prerequisites[tag] || [];
1516
+ return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1517
+ });
1518
+ return {
1519
+ isUnlocked: false,
1520
+ reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1521
+ };
1522
+ } catch {
1523
+ return {
1524
+ isUnlocked: true,
1525
+ reason: "Prerequisites check skipped (tag lookup failed)"
1526
+ };
1527
+ }
1528
+ }
1529
+ /**
1530
+ * CardFilter.transform implementation.
1531
+ *
1532
+ * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1533
+ */
1534
+ async transform(cards, context) {
1535
+ const masteredTags = await this.getMasteredTags(context);
1536
+ const unlockedTags = this.getUnlockedTags(masteredTags);
1537
+ const gated = [];
1538
+ for (const card of cards) {
1539
+ const { isUnlocked, reason } = await this.checkCardUnlock(
1540
+ card,
1541
+ context.course,
1542
+ unlockedTags,
1543
+ masteredTags
1544
+ );
1545
+ const finalScore = isUnlocked ? card.score : 0;
1546
+ const action = isUnlocked ? "passed" : "penalized";
1547
+ gated.push({
1548
+ ...card,
1549
+ score: finalScore,
1550
+ provenance: [
1551
+ ...card.provenance,
1552
+ {
1553
+ strategy: "hierarchyDefinition",
1554
+ strategyName: this.strategyName || this.name,
1555
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1556
+ action,
1557
+ score: finalScore,
1558
+ reason
1559
+ }
1560
+ ]
1561
+ });
1562
+ }
1563
+ return gated;
1564
+ }
1565
+ /**
1566
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1567
+ *
1568
+ * Use transform() via Pipeline instead.
1569
+ */
1570
+ async getWeightedCards(_limit) {
1571
+ throw new Error(
1572
+ "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1573
+ );
1574
+ }
1575
+ };
1576
+ }
1577
+ });
1578
+
1579
+ // src/core/navigators/filters/userTagPreference.ts
1580
+ var userTagPreference_exports = {};
1581
+ __export(userTagPreference_exports, {
1582
+ default: () => UserTagPreferenceFilter
1583
+ });
1584
+ var UserTagPreferenceFilter;
1585
+ var init_userTagPreference = __esm({
1586
+ "src/core/navigators/filters/userTagPreference.ts"() {
1587
+ "use strict";
1588
+ init_navigators();
1589
+ UserTagPreferenceFilter = class extends ContentNavigator {
1590
+ _strategyData;
1591
+ /** Human-readable name for CardFilter interface */
1592
+ name;
1593
+ constructor(user, course, strategyData) {
1594
+ super(user, course, strategyData);
1595
+ this._strategyData = strategyData;
1596
+ this.name = strategyData.name || "User Tag Preferences";
1597
+ }
1598
+ /**
1599
+ * Compute multiplier for a card based on its tags and user preferences.
1600
+ * Returns the maximum multiplier among all matching tags, or 1.0 if no matches.
1601
+ */
1602
+ computeMultiplier(cardTags, boostMap) {
1603
+ const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== void 0);
1604
+ if (multipliers.length === 0) {
1605
+ return 1;
1606
+ }
1607
+ return Math.max(...multipliers);
1608
+ }
1609
+ /**
1610
+ * Build human-readable reason for the filter's decision.
1611
+ */
1612
+ buildReason(cardTags, boostMap, multiplier) {
1613
+ const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);
1614
+ if (multiplier === 0) {
1615
+ return `Excluded by user preference: ${matchingTags.join(", ")} (${multiplier}x)`;
1616
+ }
1617
+ if (multiplier < 1) {
1618
+ return `Penalized by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1619
+ }
1620
+ if (multiplier > 1) {
1621
+ return `Boosted by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1622
+ }
1623
+ return "No matching user preferences";
1624
+ }
1625
+ /**
1626
+ * CardFilter.transform implementation.
1627
+ *
1628
+ * Apply user tag preferences:
1629
+ * 1. Read preferences from strategy state
1630
+ * 2. If no preferences, pass through unchanged
1631
+ * 3. For each card:
1632
+ * - Look up tag in boost record
1633
+ * - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)
1634
+ * - If multiple tags match: use max multiplier
1635
+ * - Append provenance with clear reason
1636
+ */
1637
+ async transform(cards, _context) {
1638
+ const prefs = await this.getStrategyState();
1639
+ if (!prefs || Object.keys(prefs.boost).length === 0) {
1640
+ return cards.map((card) => ({
1641
+ ...card,
1642
+ provenance: [
1643
+ ...card.provenance,
1644
+ {
1645
+ strategy: "userTagPreference",
1646
+ strategyName: this.strategyName || this.name,
1647
+ strategyId: this.strategyId || this._strategyData._id,
1648
+ action: "passed",
1649
+ score: card.score,
1650
+ reason: "No user tag preferences configured"
1651
+ }
1652
+ ]
1653
+ }));
1654
+ }
1655
+ const adjusted = await Promise.all(
1656
+ cards.map(async (card) => {
1657
+ const cardTags = card.tags ?? [];
1658
+ const multiplier = this.computeMultiplier(cardTags, prefs.boost);
1659
+ const finalScore = Math.min(1, card.score * multiplier);
1660
+ let action;
1661
+ if (multiplier === 0 || multiplier < 1) {
1662
+ action = "penalized";
1663
+ } else if (multiplier > 1) {
1664
+ action = "boosted";
1665
+ } else {
1666
+ action = "passed";
1667
+ }
1668
+ return {
1669
+ ...card,
1670
+ score: finalScore,
1671
+ provenance: [
1672
+ ...card.provenance,
1673
+ {
1674
+ strategy: "userTagPreference",
1675
+ strategyName: this.strategyName || this.name,
1676
+ strategyId: this.strategyId || this._strategyData._id,
1677
+ action,
1678
+ score: finalScore,
1679
+ reason: this.buildReason(cardTags, prefs.boost, multiplier)
1680
+ }
1681
+ ]
1682
+ };
1683
+ })
1684
+ );
1685
+ return adjusted;
1686
+ }
1687
+ /**
1688
+ * Legacy getWeightedCards - throws as filters should not be used as generators.
1689
+ */
1690
+ async getWeightedCards(_limit) {
1691
+ throw new Error(
1692
+ "UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1693
+ );
1694
+ }
1695
+ };
1696
+ }
1697
+ });
1698
+
1699
+ // src/core/navigators/filters/index.ts
1700
+ var filters_exports = {};
1701
+ __export(filters_exports, {
1702
+ UserTagPreferenceFilter: () => UserTagPreferenceFilter,
1703
+ createEloDistanceFilter: () => createEloDistanceFilter
1704
+ });
1705
+ var init_filters = __esm({
1706
+ "src/core/navigators/filters/index.ts"() {
1707
+ "use strict";
1708
+ init_eloDistance();
1709
+ init_userTagPreference();
1710
+ }
1711
+ });
1712
+
1713
+ // src/core/navigators/filters/inferredPreferenceStub.ts
1714
+ var inferredPreferenceStub_exports = {};
1715
+ __export(inferredPreferenceStub_exports, {
1716
+ INFERRED_PREFERENCE_NAVIGATOR_STUB: () => INFERRED_PREFERENCE_NAVIGATOR_STUB
1717
+ });
1718
+ var INFERRED_PREFERENCE_NAVIGATOR_STUB;
1719
+ var init_inferredPreferenceStub = __esm({
1720
+ "src/core/navigators/filters/inferredPreferenceStub.ts"() {
1721
+ "use strict";
1722
+ INFERRED_PREFERENCE_NAVIGATOR_STUB = true;
1723
+ }
1724
+ });
1725
+
1726
+ // src/core/navigators/filters/interferenceMitigator.ts
1727
+ var interferenceMitigator_exports = {};
1728
+ __export(interferenceMitigator_exports, {
1729
+ default: () => InterferenceMitigatorNavigator
1730
+ });
1731
+ var import_common7, DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1732
+ var init_interferenceMitigator = __esm({
1733
+ "src/core/navigators/filters/interferenceMitigator.ts"() {
1734
+ "use strict";
1735
+ init_navigators();
1736
+ import_common7 = require("@vue-skuilder/common");
1737
+ DEFAULT_MIN_COUNT2 = 10;
1738
+ DEFAULT_MIN_ELAPSED_DAYS = 3;
1739
+ DEFAULT_INTERFERENCE_DECAY = 0.8;
1740
+ InterferenceMitigatorNavigator = class extends ContentNavigator {
1741
+ config;
1742
+ /** Human-readable name for CardFilter interface */
1743
+ name;
1744
+ /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1745
+ interferenceMap;
1746
+ constructor(user, course, strategyData) {
1747
+ super(user, course, strategyData);
1748
+ this.config = this.parseConfig(strategyData.serializedData);
1749
+ this.interferenceMap = this.buildInterferenceMap();
1750
+ this.name = strategyData.name || "Interference Mitigator";
1751
+ }
1752
+ parseConfig(serializedData) {
1753
+ try {
1754
+ const parsed = JSON.parse(serializedData);
1755
+ let sets = parsed.interferenceSets || [];
1756
+ if (sets.length > 0 && Array.isArray(sets[0])) {
1757
+ sets = sets.map((tags) => ({ tags }));
1758
+ }
1759
+ return {
1760
+ interferenceSets: sets,
1761
+ maturityThreshold: {
1762
+ minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1763
+ minElo: parsed.maturityThreshold?.minElo,
1764
+ minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1765
+ },
1766
+ defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1767
+ };
1768
+ } catch {
1769
+ return {
1770
+ interferenceSets: [],
1771
+ maturityThreshold: {
1772
+ minCount: DEFAULT_MIN_COUNT2,
1773
+ minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1774
+ },
1775
+ defaultDecay: DEFAULT_INTERFERENCE_DECAY
1776
+ };
1777
+ }
1778
+ }
1779
+ /**
1780
+ * Build a map from each tag to its interference partners with decay coefficients.
1781
+ * If tags A, B, C are in an interference group with decay 0.8, then:
1782
+ * - A interferes with B (decay 0.8) and C (decay 0.8)
1783
+ * - B interferes with A (decay 0.8) and C (decay 0.8)
1784
+ * - etc.
1785
+ */
1786
+ buildInterferenceMap() {
1787
+ const map = /* @__PURE__ */ new Map();
1788
+ for (const group of this.config.interferenceSets) {
1789
+ const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
1790
+ for (const tag of group.tags) {
1791
+ if (!map.has(tag)) {
1792
+ map.set(tag, []);
1793
+ }
1794
+ const partners = map.get(tag);
1795
+ for (const other of group.tags) {
1796
+ if (other !== tag) {
1797
+ const existing = partners.find((p) => p.partner === other);
1798
+ if (existing) {
1799
+ existing.decay = Math.max(existing.decay, decay);
1800
+ } else {
1801
+ partners.push({ partner: other, decay });
1802
+ }
1803
+ }
1804
+ }
1805
+ }
1806
+ }
1807
+ return map;
1808
+ }
1809
+ /**
1810
+ * Get the set of tags that are currently immature for this user.
1811
+ * A tag is immature if the user has interacted with it but hasn't
1812
+ * reached the maturity threshold.
1813
+ */
1814
+ async getImmatureTags(context) {
1815
+ const immature = /* @__PURE__ */ new Set();
1816
+ try {
1817
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1818
+ const userElo = (0, import_common7.toCourseElo)(courseReg.elo);
1819
+ const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
1820
+ const minElo = this.config.maturityThreshold?.minElo;
1821
+ const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
1822
+ const minCountForElapsed = minElapsedDays * 2;
1823
+ for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
1824
+ if (tagElo.count === 0) continue;
1825
+ const belowCount = tagElo.count < minCount;
1826
+ const belowElo = minElo !== void 0 && tagElo.score < minElo;
1827
+ const belowElapsed = tagElo.count < minCountForElapsed;
1828
+ if (belowCount || belowElo || belowElapsed) {
1829
+ immature.add(tagId);
1830
+ }
1831
+ }
1832
+ } catch {
1833
+ }
1834
+ return immature;
1835
+ }
1836
+ /**
1837
+ * Get all tags that interfere with any immature tag, along with their decay coefficients.
1838
+ * These are the tags we want to avoid introducing.
1839
+ */
1840
+ getTagsToAvoid(immatureTags) {
1841
+ const avoid = /* @__PURE__ */ new Map();
1842
+ for (const immatureTag of immatureTags) {
1843
+ const partners = this.interferenceMap.get(immatureTag);
1844
+ if (partners) {
1845
+ for (const { partner, decay } of partners) {
1846
+ if (!immatureTags.has(partner)) {
1847
+ const existing = avoid.get(partner) ?? 0;
1848
+ avoid.set(partner, Math.max(existing, decay));
1849
+ }
1850
+ }
1851
+ }
1852
+ }
1853
+ return avoid;
1854
+ }
1855
+ /**
1856
+ * Compute interference score reduction for a card.
1857
+ * Returns: { multiplier, interfering tags, reason }
1858
+ */
1859
+ computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
1860
+ if (tagsToAvoid.size === 0) {
1861
+ return {
1862
+ multiplier: 1,
1863
+ interferingTags: [],
1864
+ reason: "No interference detected"
1865
+ };
1866
+ }
1867
+ let multiplier = 1;
1868
+ const interferingTags = [];
1869
+ for (const tag of cardTags) {
1870
+ const decay = tagsToAvoid.get(tag);
1871
+ if (decay !== void 0) {
1872
+ interferingTags.push(tag);
1873
+ multiplier *= 1 - decay;
1874
+ }
1875
+ }
1876
+ if (interferingTags.length === 0) {
1877
+ return {
1878
+ multiplier: 1,
1879
+ interferingTags: [],
1880
+ reason: "No interference detected"
1881
+ };
1882
+ }
1883
+ const causingTags = /* @__PURE__ */ new Set();
1884
+ for (const tag of interferingTags) {
1885
+ for (const immatureTag of immatureTags) {
1886
+ const partners = this.interferenceMap.get(immatureTag);
1887
+ if (partners?.some((p) => p.partner === tag)) {
1888
+ causingTags.add(immatureTag);
1889
+ }
1890
+ }
1891
+ }
1892
+ const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
1893
+ return { multiplier, interferingTags, reason };
1894
+ }
1895
+ /**
1896
+ * CardFilter.transform implementation.
1897
+ *
1898
+ * Apply interference-aware scoring. Cards with tags that interfere with
1899
+ * immature learnings get reduced scores.
1900
+ */
1901
+ async transform(cards, context) {
1902
+ const immatureTags = await this.getImmatureTags(context);
1903
+ const tagsToAvoid = this.getTagsToAvoid(immatureTags);
1904
+ const adjusted = [];
1905
+ for (const card of cards) {
1906
+ const cardTags = card.tags ?? [];
1907
+ const { multiplier, reason } = this.computeInterferenceEffect(
1908
+ cardTags,
1909
+ tagsToAvoid,
1910
+ immatureTags
1911
+ );
1912
+ const finalScore = card.score * multiplier;
1913
+ const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
1914
+ adjusted.push({
1915
+ ...card,
1916
+ score: finalScore,
1917
+ provenance: [
1918
+ ...card.provenance,
1919
+ {
1920
+ strategy: "interferenceMitigator",
1921
+ strategyName: this.strategyName || this.name,
1922
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
1923
+ action,
1924
+ score: finalScore,
1925
+ reason
1926
+ }
1927
+ ]
1928
+ });
1929
+ }
1930
+ return adjusted;
1931
+ }
1932
+ /**
1933
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1934
+ *
1935
+ * Use transform() via Pipeline instead.
1936
+ */
1937
+ async getWeightedCards(_limit) {
1938
+ throw new Error(
1939
+ "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1940
+ );
1941
+ }
1942
+ };
1943
+ }
1944
+ });
1945
+
1946
+ // src/core/navigators/filters/relativePriority.ts
1947
+ var relativePriority_exports = {};
1948
+ __export(relativePriority_exports, {
1949
+ default: () => RelativePriorityNavigator
1950
+ });
1951
+ var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
1952
+ var init_relativePriority = __esm({
1953
+ "src/core/navigators/filters/relativePriority.ts"() {
1954
+ "use strict";
1955
+ init_navigators();
1956
+ DEFAULT_PRIORITY = 0.5;
1957
+ DEFAULT_PRIORITY_INFLUENCE = 0.5;
1958
+ DEFAULT_COMBINE_MODE = "max";
1959
+ RelativePriorityNavigator = class extends ContentNavigator {
1960
+ config;
1961
+ /** Human-readable name for CardFilter interface */
1962
+ name;
1963
+ constructor(user, course, strategyData) {
1964
+ super(user, course, strategyData);
1965
+ this.config = this.parseConfig(strategyData.serializedData);
1966
+ this.name = strategyData.name || "Relative Priority";
1967
+ }
1968
+ parseConfig(serializedData) {
1969
+ try {
1970
+ const parsed = JSON.parse(serializedData);
1971
+ return {
1972
+ tagPriorities: parsed.tagPriorities || {},
1973
+ defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
1974
+ combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
1975
+ priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
1976
+ };
1977
+ } catch {
1978
+ return {
1979
+ tagPriorities: {},
1980
+ defaultPriority: DEFAULT_PRIORITY,
1981
+ combineMode: DEFAULT_COMBINE_MODE,
1982
+ priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
1983
+ };
1984
+ }
1985
+ }
1986
+ /**
1987
+ * Look up the priority for a tag.
1988
+ */
1989
+ getTagPriority(tagId) {
1990
+ return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
1991
+ }
1992
+ /**
1993
+ * Compute combined priority for a card based on its tags.
1994
+ */
1995
+ computeCardPriority(cardTags) {
1996
+ if (cardTags.length === 0) {
1997
+ return this.config.defaultPriority ?? DEFAULT_PRIORITY;
1998
+ }
1999
+ const priorities = cardTags.map((tag) => this.getTagPriority(tag));
2000
+ switch (this.config.combineMode) {
2001
+ case "max":
2002
+ return Math.max(...priorities);
2003
+ case "min":
2004
+ return Math.min(...priorities);
2005
+ case "average":
2006
+ return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
2007
+ default:
2008
+ return Math.max(...priorities);
2009
+ }
2010
+ }
2011
+ /**
2012
+ * Compute boost factor based on priority.
2013
+ *
2014
+ * The formula: 1 + (priority - 0.5) * priorityInfluence
2015
+ *
2016
+ * This creates a multiplier centered around 1.0:
2017
+ * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
2018
+ * - Priority 0.5 with any influence → 1.00 (neutral)
2019
+ * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
2020
+ */
2021
+ computeBoostFactor(priority) {
2022
+ const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
2023
+ return 1 + (priority - 0.5) * influence;
2024
+ }
2025
+ /**
2026
+ * Build human-readable reason for priority adjustment.
2027
+ */
2028
+ buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
2029
+ if (cardTags.length === 0) {
2030
+ return `No tags, neutral priority (${priority.toFixed(2)})`;
2031
+ }
2032
+ const tagList = cardTags.slice(0, 3).join(", ");
2033
+ const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
2034
+ if (boostFactor === 1) {
2035
+ return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
2036
+ } else if (boostFactor > 1) {
2037
+ return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
2038
+ } else {
2039
+ return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
2040
+ }
2041
+ }
2042
+ /**
2043
+ * CardFilter.transform implementation.
2044
+ *
2045
+ * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
2046
+ * cards with low-priority tags get reduced scores.
2047
+ */
2048
+ async transform(cards, _context) {
2049
+ const adjusted = await Promise.all(
2050
+ cards.map(async (card) => {
2051
+ const cardTags = card.tags ?? [];
2052
+ const priority = this.computeCardPriority(cardTags);
2053
+ const boostFactor = this.computeBoostFactor(priority);
2054
+ const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
2055
+ const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
2056
+ const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
2057
+ return {
2058
+ ...card,
2059
+ score: finalScore,
2060
+ provenance: [
2061
+ ...card.provenance,
2062
+ {
2063
+ strategy: "relativePriority",
2064
+ strategyName: this.strategyName || this.name,
2065
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
2066
+ action,
2067
+ score: finalScore,
2068
+ reason
2069
+ }
2070
+ ]
2071
+ };
2072
+ })
2073
+ );
2074
+ return adjusted;
2075
+ }
2076
+ /**
2077
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
2078
+ *
2079
+ * Use transform() via Pipeline instead.
2080
+ */
2081
+ async getWeightedCards(_limit) {
2082
+ throw new Error(
2083
+ "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
2084
+ );
2085
+ }
2086
+ };
2087
+ }
2088
+ });
2089
+
2090
+ // src/core/navigators/filters/types.ts
2091
+ var types_exports2 = {};
2092
+ var init_types2 = __esm({
2093
+ "src/core/navigators/filters/types.ts"() {
2094
+ "use strict";
2095
+ }
2096
+ });
2097
+
2098
+ // src/core/navigators/filters/userGoalStub.ts
2099
+ var userGoalStub_exports = {};
2100
+ __export(userGoalStub_exports, {
2101
+ USER_GOAL_NAVIGATOR_STUB: () => USER_GOAL_NAVIGATOR_STUB
2102
+ });
2103
+ var USER_GOAL_NAVIGATOR_STUB;
2104
+ var init_userGoalStub = __esm({
2105
+ "src/core/navigators/filters/userGoalStub.ts"() {
2106
+ "use strict";
2107
+ USER_GOAL_NAVIGATOR_STUB = true;
2108
+ }
2109
+ });
2110
+
2111
+ // import("./filters/**/*") in src/core/navigators/index.ts
2112
+ var globImport_filters;
2113
+ var init_2 = __esm({
2114
+ 'import("./filters/**/*") in src/core/navigators/index.ts'() {
2115
+ globImport_filters = __glob({
2116
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
2117
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2118
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2119
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2120
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
2121
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2122
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2123
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
2124
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
2125
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
2126
+ });
2127
+ }
2128
+ });
2129
+
2130
+ // src/core/orchestration/gradient.ts
2131
+ var init_gradient = __esm({
2132
+ "src/core/orchestration/gradient.ts"() {
2133
+ "use strict";
2134
+ init_logger();
2135
+ }
2136
+ });
2137
+
2138
+ // src/core/orchestration/learning.ts
2139
+ var init_learning = __esm({
2140
+ "src/core/orchestration/learning.ts"() {
2141
+ "use strict";
2142
+ init_contentNavigationStrategy();
2143
+ init_types_legacy();
2144
+ init_logger();
2145
+ }
2146
+ });
2147
+
2148
+ // src/core/orchestration/signal.ts
2149
+ var init_signal = __esm({
2150
+ "src/core/orchestration/signal.ts"() {
2151
+ "use strict";
2152
+ }
2153
+ });
2154
+
2155
+ // src/core/orchestration/recording.ts
2156
+ var init_recording = __esm({
2157
+ "src/core/orchestration/recording.ts"() {
2158
+ "use strict";
2159
+ init_signal();
2160
+ init_types_legacy();
2161
+ init_logger();
2162
+ }
2163
+ });
2164
+
2165
+ // src/core/orchestration/index.ts
2166
+ function fnv1a(str) {
2167
+ let hash = 2166136261;
2168
+ for (let i = 0; i < str.length; i++) {
2169
+ hash ^= str.charCodeAt(i);
2170
+ hash = Math.imul(hash, 16777619);
2171
+ }
2172
+ return hash >>> 0;
2173
+ }
2174
+ function computeDeviation(userId, strategyId, salt) {
2175
+ const input = `${userId}:${strategyId}:${salt}`;
2176
+ const hash = fnv1a(input);
2177
+ const normalized = hash / 4294967296;
2178
+ return normalized * 2 - 1;
2179
+ }
2180
+ function computeSpread(confidence) {
2181
+ const clampedConfidence = Math.max(0, Math.min(1, confidence));
2182
+ return MAX_SPREAD - clampedConfidence * (MAX_SPREAD - MIN_SPREAD);
2183
+ }
2184
+ function computeEffectiveWeight(learnable, userId, strategyId, salt) {
2185
+ const deviation = computeDeviation(userId, strategyId, salt);
2186
+ const spread = computeSpread(learnable.confidence);
2187
+ const adjustment = deviation * spread * learnable.weight;
2188
+ const effective = learnable.weight + adjustment;
2189
+ return Math.max(MIN_WEIGHT, Math.min(MAX_WEIGHT, effective));
2190
+ }
2191
+ async function createOrchestrationContext(user, course) {
2192
+ let courseConfig;
2193
+ try {
2194
+ courseConfig = await course.getCourseConfig();
2195
+ } catch (e) {
2196
+ logger.error(`[Orchestration] Failed to load course config: ${e}`);
2197
+ courseConfig = {
2198
+ name: "Unknown",
2199
+ description: "",
2200
+ public: false,
2201
+ deleted: false,
2202
+ creator: "",
2203
+ admins: [],
2204
+ moderators: [],
2205
+ dataShapes: [],
2206
+ questionTypes: [],
2207
+ orchestration: { salt: "default" }
2208
+ };
2209
+ }
2210
+ const userId = user.getUsername();
2211
+ const salt = courseConfig.orchestration?.salt || "default_salt";
2212
+ return {
2213
+ user,
2214
+ course,
2215
+ userId,
2216
+ courseConfig,
2217
+ getEffectiveWeight(strategyId, learnable) {
2218
+ return computeEffectiveWeight(learnable, userId, strategyId, salt);
2219
+ },
2220
+ getDeviation(strategyId) {
2221
+ return computeDeviation(userId, strategyId, salt);
2222
+ }
2223
+ };
2224
+ }
2225
+ var MIN_SPREAD, MAX_SPREAD, MIN_WEIGHT, MAX_WEIGHT;
2226
+ var init_orchestration = __esm({
2227
+ "src/core/orchestration/index.ts"() {
2228
+ "use strict";
2229
+ init_logger();
2230
+ init_gradient();
2231
+ init_learning();
2232
+ init_signal();
2233
+ init_recording();
2234
+ MIN_SPREAD = 0.1;
2235
+ MAX_SPREAD = 0.5;
2236
+ MIN_WEIGHT = 0.1;
2237
+ MAX_WEIGHT = 3;
2238
+ }
2239
+ });
2240
+
2241
+ // src/core/navigators/Pipeline.ts
2242
+ var Pipeline_exports = {};
2243
+ __export(Pipeline_exports, {
2244
+ Pipeline: () => Pipeline
2245
+ });
2246
+ function logPipelineConfig(generator, filters) {
2247
+ const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
2248
+ logger.info(
2249
+ `[Pipeline] Configuration:
2250
+ Generator: ${generator.name}
2251
+ Filters:${filterList}`
2252
+ );
2253
+ }
2254
+ function logTagHydration(cards, tagsByCard) {
2255
+ const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
2256
+ const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
2257
+ logger.debug(
2258
+ `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
2259
+ );
2260
+ }
2261
+ function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores, filterImpacts) {
2262
+ const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
2263
+ let filterSummary = "";
2264
+ if (filterImpacts.length > 0) {
2265
+ const impacts = filterImpacts.map((f) => {
2266
+ const parts = [];
2267
+ if (f.boosted > 0) parts.push(`+${f.boosted}`);
2268
+ if (f.penalized > 0) parts.push(`-${f.penalized}`);
2269
+ if (f.passed > 0) parts.push(`=${f.passed}`);
2270
+ return `${f.name}: ${parts.join("/")}`;
2271
+ });
2272
+ filterSummary = `
2273
+ Filter impact: ${impacts.join(", ")}`;
2274
+ }
2275
+ logger.info(
2276
+ `[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})` + filterSummary + `
2277
+ \u{1F4A1} Inspect: window.skuilder.pipeline`
2278
+ );
2279
+ }
2280
+ function logCardProvenance(cards, maxCards = 3) {
2281
+ const cardsToLog = cards.slice(0, maxCards);
2282
+ logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
2283
+ for (const card of cardsToLog) {
2284
+ logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
2285
+ for (const entry of card.provenance) {
2286
+ const scoreChange = entry.score.toFixed(3);
2287
+ const action = entry.action.padEnd(9);
2288
+ logger.debug(
2289
+ `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
2290
+ );
2291
+ }
2292
+ }
2293
+ }
2294
+ var import_common8, Pipeline;
2295
+ var init_Pipeline = __esm({
2296
+ "src/core/navigators/Pipeline.ts"() {
2297
+ "use strict";
2298
+ import_common8 = require("@vue-skuilder/common");
2299
+ init_navigators();
2300
+ init_logger();
2301
+ init_orchestration();
2302
+ init_PipelineDebugger();
2303
+ Pipeline = class extends ContentNavigator {
2304
+ generator;
2305
+ filters;
2306
+ /**
2307
+ * Create a new pipeline.
2308
+ *
2309
+ * @param generator - The generator (or CompositeGenerator) that produces candidates
2310
+ * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
2311
+ * @param user - User database interface
2312
+ * @param course - Course database interface
2313
+ */
2314
+ constructor(generator, filters, user, course) {
2315
+ super();
2316
+ this.generator = generator;
2317
+ this.filters = filters;
2318
+ this.user = user;
2319
+ this.course = course;
2320
+ course.getCourseConfig().then((cfg) => {
2321
+ logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);
2322
+ }).catch((e) => {
2323
+ logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);
2324
+ });
2325
+ logPipelineConfig(generator, filters);
2326
+ }
2327
+ /**
2328
+ * Get weighted cards by running generator and applying filters.
2329
+ *
2330
+ * 1. Build shared context (user ELO, etc.)
2331
+ * 2. Get candidates from generator (passing context)
2332
+ * 3. Batch hydrate tags for all candidates
2333
+ * 4. Apply each filter sequentially
2334
+ * 5. Remove zero-score cards
2335
+ * 6. Sort by score descending
2336
+ * 7. Return top N
2337
+ *
2338
+ * @param limit - Maximum number of cards to return
2339
+ * @returns Cards sorted by score descending
2340
+ */
2341
+ async getWeightedCards(limit) {
2342
+ const context = await this.buildContext();
2343
+ const overFetchMultiplier = 2 + this.filters.length * 0.5;
2344
+ const fetchLimit = Math.ceil(limit * overFetchMultiplier);
2345
+ logger.debug(
2346
+ `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
2347
+ );
2348
+ let cards = await this.generator.getWeightedCards(fetchLimit, context);
2349
+ const generatedCount = cards.length;
2350
+ let generatorSummaries;
2351
+ if (this.generator.generators) {
2352
+ const genMap = /* @__PURE__ */ new Map();
2353
+ for (const card of cards) {
2354
+ const firstProv = card.provenance[0];
2355
+ if (firstProv) {
2356
+ const genName = firstProv.strategyName;
2357
+ if (!genMap.has(genName)) {
2358
+ genMap.set(genName, { cards: [] });
2359
+ }
2360
+ genMap.get(genName).cards.push(card);
2361
+ }
2362
+ }
2363
+ generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {
2364
+ const newCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
2365
+ const reviewCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
2366
+ return {
2367
+ name,
2368
+ cardCount: data.cards.length,
2369
+ newCount: newCards.length,
2370
+ reviewCount: reviewCards.length,
2371
+ topScore: Math.max(...data.cards.map((c) => c.score), 0)
2372
+ };
2373
+ });
2374
+ }
2375
+ logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
2376
+ cards = await this.hydrateTags(cards);
2377
+ const allCardsBeforeFiltering = [...cards];
2378
+ const filterImpacts = [];
2379
+ for (const filter of this.filters) {
2380
+ const beforeCount = cards.length;
2381
+ const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));
2382
+ cards = await filter.transform(cards, context);
2383
+ let boosted = 0, penalized = 0, passed = 0;
2384
+ const removed = beforeCount - cards.length;
2385
+ for (const card of cards) {
2386
+ const before = beforeScores.get(card.cardId) ?? 0;
2387
+ if (card.score > before) boosted++;
2388
+ else if (card.score < before) penalized++;
2389
+ else passed++;
2390
+ }
2391
+ filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
2392
+ logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeScores.size} \u2192 ${cards.length} cards (\u2191${boosted} \u2193${penalized} =${passed})`);
2393
+ }
2394
+ cards = cards.filter((c) => c.score > 0);
2395
+ cards.sort((a, b) => b.score - a.score);
2396
+ const result = cards.slice(0, limit);
2397
+ const topScores = result.slice(0, 3).map((c) => c.score);
2398
+ logExecutionSummary(
2399
+ this.generator.name,
2400
+ generatedCount,
2401
+ this.filters.length,
2402
+ result.length,
2403
+ topScores,
2404
+ filterImpacts
2405
+ );
2406
+ logCardProvenance(result, 3);
2407
+ try {
2408
+ const courseName = await this.course?.getCourseConfig().then((c) => c.name).catch(() => void 0);
2409
+ const report = buildRunReport(
2410
+ this.course?.getCourseID() || "unknown",
2411
+ courseName,
2412
+ this.generator.name,
2413
+ generatorSummaries,
2414
+ generatedCount,
2415
+ filterImpacts,
2416
+ allCardsBeforeFiltering,
2417
+ result
2418
+ );
2419
+ captureRun(report);
2420
+ } catch (e) {
2421
+ logger.debug(`[Pipeline] Failed to capture debug run: ${e}`);
2422
+ }
2423
+ return result;
2424
+ }
2425
+ /**
2426
+ * Batch hydrate tags for all cards.
2427
+ *
2428
+ * Fetches tags for all cards in a single database query and attaches them
2429
+ * to the WeightedCard objects. Filters can then use card.tags instead of
2430
+ * making individual getAppliedTags() calls.
2431
+ *
2432
+ * @param cards - Cards to hydrate
2433
+ * @returns Cards with tags populated
2434
+ */
2435
+ async hydrateTags(cards) {
2436
+ if (cards.length === 0) {
2437
+ return cards;
2438
+ }
2439
+ const cardIds = cards.map((c) => c.cardId);
2440
+ const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
2441
+ logTagHydration(cards, tagsByCard);
2442
+ return cards.map((card) => ({
2443
+ ...card,
2444
+ tags: tagsByCard.get(card.cardId) ?? []
2445
+ }));
2446
+ }
2447
+ /**
2448
+ * Build shared context for generator and filters.
2449
+ *
2450
+ * Called once per getWeightedCards() invocation.
2451
+ * Contains data that the generator and multiple filters might need.
2452
+ *
2453
+ * The context satisfies both GeneratorContext and FilterContext interfaces.
2454
+ */
2455
+ async buildContext() {
2456
+ let userElo = 1e3;
2457
+ try {
2458
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
2459
+ const courseElo = (0, import_common8.toCourseElo)(courseReg.elo);
2460
+ userElo = courseElo.global.score;
2461
+ } catch (e) {
2462
+ logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
2463
+ }
2464
+ const orchestration = await createOrchestrationContext(this.user, this.course);
2465
+ return {
2466
+ user: this.user,
2467
+ course: this.course,
2468
+ userElo,
2469
+ orchestration
2470
+ };
2471
+ }
2472
+ /**
2473
+ * Get the course ID for this pipeline.
2474
+ */
2475
+ getCourseID() {
2476
+ return this.course.getCourseID();
2477
+ }
2478
+ /**
2479
+ * Get orchestration context for outcome recording.
2480
+ */
2481
+ async getOrchestrationContext() {
2482
+ return createOrchestrationContext(this.user, this.course);
2483
+ }
2484
+ /**
2485
+ * Get IDs of all strategies in this pipeline.
2486
+ * Used to record which strategies contributed to an outcome.
2487
+ */
2488
+ getStrategyIds() {
2489
+ const ids = [];
2490
+ const extractId = (obj) => {
2491
+ if (obj.strategyId) return obj.strategyId;
2492
+ return null;
2493
+ };
2494
+ const genId = extractId(this.generator);
2495
+ if (genId) ids.push(genId);
2496
+ if (this.generator.generators && Array.isArray(this.generator.generators)) {
2497
+ this.generator.generators.forEach((g) => {
2498
+ const subId = extractId(g);
2499
+ if (subId) ids.push(subId);
2500
+ });
2501
+ }
2502
+ for (const filter of this.filters) {
2503
+ const fId = extractId(filter);
2504
+ if (fId) ids.push(fId);
2505
+ }
2506
+ return [...new Set(ids)];
2507
+ }
2508
+ };
2509
+ }
2510
+ });
2511
+
2512
+ // src/core/navigators/defaults.ts
2513
+ var defaults_exports = {};
2514
+ __export(defaults_exports, {
2515
+ createDefaultEloStrategy: () => createDefaultEloStrategy,
2516
+ createDefaultPipeline: () => createDefaultPipeline,
2517
+ createDefaultSrsStrategy: () => createDefaultSrsStrategy
2518
+ });
2519
+ function createDefaultEloStrategy(courseId) {
2520
+ return {
2521
+ _id: "NAVIGATION_STRATEGY-ELO-default",
2522
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
2523
+ name: "ELO (default)",
2524
+ description: "Default ELO-based navigation strategy for new cards",
2525
+ implementingClass: "elo" /* ELO */,
2526
+ course: courseId,
2527
+ serializedData: ""
2528
+ };
2529
+ }
2530
+ function createDefaultSrsStrategy(courseId) {
2531
+ return {
2532
+ _id: "NAVIGATION_STRATEGY-SRS-default",
2533
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
2534
+ name: "SRS (default)",
2535
+ description: "Default SRS-based navigation strategy for reviews",
2536
+ implementingClass: "srs" /* SRS */,
2537
+ course: courseId,
2538
+ serializedData: ""
2539
+ };
2540
+ }
2541
+ function createDefaultPipeline(user, course) {
2542
+ const courseId = course.getCourseID();
2543
+ const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
2544
+ const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
2545
+ const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
2546
+ const eloDistanceFilter = createEloDistanceFilter();
2547
+ return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
2548
+ }
2549
+ var init_defaults = __esm({
2550
+ "src/core/navigators/defaults.ts"() {
2551
+ "use strict";
2552
+ init_navigators();
2553
+ init_Pipeline();
2554
+ init_CompositeGenerator();
2555
+ init_elo();
2556
+ init_srs();
2557
+ init_eloDistance();
2558
+ init_types_legacy();
2559
+ }
2560
+ });
2561
+
2562
+ // src/core/navigators/PipelineAssembler.ts
2563
+ var PipelineAssembler_exports = {};
2564
+ __export(PipelineAssembler_exports, {
2565
+ PipelineAssembler: () => PipelineAssembler
2566
+ });
2567
+ var PipelineAssembler;
2568
+ var init_PipelineAssembler = __esm({
2569
+ "src/core/navigators/PipelineAssembler.ts"() {
2570
+ "use strict";
2571
+ init_navigators();
2572
+ init_WeightedFilter();
2573
+ init_Pipeline();
2574
+ init_logger();
2575
+ init_CompositeGenerator();
2576
+ init_defaults();
2577
+ PipelineAssembler = class {
2578
+ /**
2579
+ * Assembles a navigation pipeline from strategy documents.
2580
+ *
2581
+ * 1. Separates into generators and filters by role
2582
+ * 2. Validates at least one generator exists (or creates default ELO)
2583
+ * 3. Instantiates generators - wraps multiple in CompositeGenerator
2584
+ * 4. Instantiates filters
2585
+ * 5. Returns Pipeline(generator, filters)
2586
+ *
2587
+ * @param input - Strategy documents plus user/course interfaces
2588
+ * @returns Assembled pipeline and any warnings
2589
+ */
2590
+ async assemble(input) {
2591
+ const { strategies, user, course } = input;
2592
+ const warnings = [];
2593
+ if (strategies.length === 0) {
2594
+ return {
2595
+ pipeline: null,
2596
+ generatorStrategies: [],
2597
+ filterStrategies: [],
2598
+ warnings
2599
+ };
2600
+ }
2601
+ const generatorStrategies = [];
2602
+ const filterStrategies = [];
2603
+ for (const s of strategies) {
2604
+ if (isGenerator(s.implementingClass)) {
2605
+ generatorStrategies.push(s);
2606
+ } else if (isFilter(s.implementingClass)) {
2607
+ filterStrategies.push(s);
2608
+ } else {
2609
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
2610
+ }
2611
+ }
2612
+ if (generatorStrategies.length === 0) {
2613
+ if (filterStrategies.length > 0) {
2614
+ logger.debug(
2615
+ "[PipelineAssembler] No generator found, using default ELO and SRS with configured filters"
2616
+ );
2617
+ const courseId = course.getCourseID();
2618
+ generatorStrategies.push(createDefaultEloStrategy(courseId));
2619
+ generatorStrategies.push(createDefaultSrsStrategy(courseId));
2620
+ } else {
2621
+ warnings.push("No generator strategy found");
2622
+ return {
2623
+ pipeline: null,
2624
+ generatorStrategies: [],
2625
+ filterStrategies: [],
2626
+ warnings
2627
+ };
2628
+ }
2629
+ }
2630
+ let generator;
2631
+ if (generatorStrategies.length === 1) {
2632
+ const nav = await ContentNavigator.create(user, course, generatorStrategies[0]);
2633
+ generator = nav;
2634
+ logger.debug(`[PipelineAssembler] Using single generator: ${generatorStrategies[0].name}`);
2635
+ } else {
2636
+ logger.debug(
2637
+ `[PipelineAssembler] Using CompositeGenerator for ${generatorStrategies.length} generators: ${generatorStrategies.map((g) => g.name).join(", ")}`
2638
+ );
2639
+ generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
2640
+ }
2641
+ const filters = [];
2642
+ const sortedFilterStrategies = [...filterStrategies].sort(
2643
+ (a, b) => a.name.localeCompare(b.name)
2644
+ );
2645
+ for (const filterStrategy of sortedFilterStrategies) {
2646
+ try {
2647
+ const nav = await ContentNavigator.create(user, course, filterStrategy);
2648
+ if ("transform" in nav && typeof nav.transform === "function") {
2649
+ let filter = nav;
2650
+ if (filterStrategy.learnable) {
2651
+ filter = new WeightedFilter(
2652
+ filter,
2653
+ filterStrategy.learnable,
2654
+ filterStrategy.staticWeight,
2655
+ filterStrategy._id
2656
+ );
2657
+ }
2658
+ filters.push(filter);
2659
+ logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
2660
+ } else {
2661
+ warnings.push(
2662
+ `Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
2663
+ );
2664
+ }
2665
+ } catch (e) {
2666
+ warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
2667
+ }
2668
+ }
2669
+ const pipeline = new Pipeline(generator, filters, user, course);
2670
+ logger.debug(
2671
+ `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
2672
+ );
2673
+ return {
2674
+ pipeline,
2675
+ generatorStrategies,
2676
+ filterStrategies: sortedFilterStrategies,
2677
+ warnings
2678
+ };
2679
+ }
2680
+ };
2681
+ }
2682
+ });
2683
+
2684
+ // import("./**/*") in src/core/navigators/index.ts
2685
+ var globImport;
2686
+ var init_3 = __esm({
2687
+ 'import("./**/*") in src/core/navigators/index.ts'() {
2688
+ globImport = __glob({
2689
+ "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
2690
+ "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
2691
+ "./PipelineDebugger.ts": () => Promise.resolve().then(() => (init_PipelineDebugger(), PipelineDebugger_exports)),
2692
+ "./defaults.ts": () => Promise.resolve().then(() => (init_defaults(), defaults_exports)),
2693
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
2694
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2695
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2696
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2697
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
2698
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2699
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2700
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
2701
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
2702
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
2703
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
2704
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
2705
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
2706
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
2707
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
2708
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
2709
+ });
2710
+ }
2711
+ });
2712
+
2713
+ // src/core/navigators/index.ts
2714
+ var navigators_exports = {};
2715
+ __export(navigators_exports, {
2716
+ ContentNavigator: () => ContentNavigator,
2717
+ NavigatorRole: () => NavigatorRole,
2718
+ NavigatorRoles: () => NavigatorRoles,
2719
+ Navigators: () => Navigators,
2720
+ getCardOrigin: () => getCardOrigin,
2721
+ getRegisteredNavigator: () => getRegisteredNavigator,
2722
+ getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
2723
+ hasRegisteredNavigator: () => hasRegisteredNavigator,
2724
+ initializeNavigatorRegistry: () => initializeNavigatorRegistry,
2725
+ isFilter: () => isFilter,
2726
+ isGenerator: () => isGenerator,
2727
+ mountPipelineDebugger: () => mountPipelineDebugger,
2728
+ pipelineDebugAPI: () => pipelineDebugAPI,
2729
+ registerNavigator: () => registerNavigator
2730
+ });
2731
+ function registerNavigator(implementingClass, constructor) {
2732
+ navigatorRegistry.set(implementingClass, constructor);
2733
+ logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}`);
2734
+ }
2735
+ function getRegisteredNavigator(implementingClass) {
2736
+ return navigatorRegistry.get(implementingClass);
2737
+ }
2738
+ function hasRegisteredNavigator(implementingClass) {
2739
+ return navigatorRegistry.has(implementingClass);
2740
+ }
2741
+ function getRegisteredNavigatorNames() {
2742
+ return Array.from(navigatorRegistry.keys());
2743
+ }
2744
+ async function initializeNavigatorRegistry() {
2745
+ logger.debug("[NavigatorRegistry] Initializing built-in navigators...");
2746
+ const [eloModule, srsModule] = await Promise.all([
2747
+ Promise.resolve().then(() => (init_elo(), elo_exports)),
2748
+ Promise.resolve().then(() => (init_srs(), srs_exports))
2749
+ ]);
2750
+ registerNavigator("elo", eloModule.default);
2751
+ registerNavigator("srs", srsModule.default);
2752
+ const [
2753
+ hierarchyModule,
2754
+ interferenceModule,
2755
+ relativePriorityModule,
2756
+ userTagPreferenceModule
2757
+ ] = await Promise.all([
2758
+ Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2759
+ Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2760
+ Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2761
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
2762
+ ]);
2763
+ registerNavigator("hierarchyDefinition", hierarchyModule.default);
2764
+ registerNavigator("interferenceMitigator", interferenceModule.default);
2765
+ registerNavigator("relativePriority", relativePriorityModule.default);
2766
+ registerNavigator("userTagPreference", userTagPreferenceModule.default);
2767
+ logger.debug(
2768
+ `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
2769
+ );
2770
+ }
2771
+ function getCardOrigin(card) {
2772
+ if (card.provenance.length === 0) {
2773
+ throw new Error("Card has no provenance - cannot determine origin");
2774
+ }
2775
+ const firstEntry = card.provenance[0];
2776
+ const reason = firstEntry.reason.toLowerCase();
2777
+ if (reason.includes("failed")) {
2778
+ return "failed";
2779
+ }
2780
+ if (reason.includes("review")) {
2781
+ return "review";
2782
+ }
2783
+ return "new";
2784
+ }
2785
+ function isGenerator(impl) {
2786
+ return NavigatorRoles[impl] === "generator" /* GENERATOR */;
2787
+ }
2788
+ function isFilter(impl) {
2789
+ return NavigatorRoles[impl] === "filter" /* FILTER */;
2790
+ }
2791
+ var navigatorRegistry, Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
2792
+ var init_navigators = __esm({
2793
+ "src/core/navigators/index.ts"() {
2794
+ "use strict";
2795
+ init_PipelineDebugger();
2796
+ init_logger();
2797
+ init_();
2798
+ init_2();
2799
+ init_3();
2800
+ navigatorRegistry = /* @__PURE__ */ new Map();
2801
+ Navigators = /* @__PURE__ */ ((Navigators2) => {
2802
+ Navigators2["ELO"] = "elo";
2803
+ Navigators2["SRS"] = "srs";
2804
+ Navigators2["HIERARCHY"] = "hierarchyDefinition";
2805
+ Navigators2["INTERFERENCE"] = "interferenceMitigator";
2806
+ Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
2807
+ Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
2808
+ return Navigators2;
2809
+ })(Navigators || {});
2810
+ NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
2811
+ NavigatorRole2["GENERATOR"] = "generator";
2812
+ NavigatorRole2["FILTER"] = "filter";
2813
+ return NavigatorRole2;
2814
+ })(NavigatorRole || {});
2815
+ NavigatorRoles = {
2816
+ ["elo" /* ELO */]: "generator" /* GENERATOR */,
2817
+ ["srs" /* SRS */]: "generator" /* GENERATOR */,
2818
+ ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
2819
+ ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
2820
+ ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
2821
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
2822
+ };
2823
+ ContentNavigator = class {
2824
+ /** User interface for this navigation session */
2825
+ user;
2826
+ /** Course interface for this navigation session */
2827
+ course;
2828
+ /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
2829
+ strategyName;
2830
+ /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
2831
+ strategyId;
2832
+ /** Evolutionary weighting configuration */
2833
+ learnable;
2834
+ /** Whether to bypass deviation (manual/static weighting) */
2835
+ staticWeight;
2836
+ /**
2837
+ * Constructor for standard navigators.
2838
+ * Call this from subclass constructors to initialize common fields.
2839
+ *
2840
+ * Note: CompositeGenerator and Pipeline call super() without args, then set
2841
+ * user/course fields directly if needed.
2842
+ */
2843
+ constructor(user, course, strategyData) {
2844
+ this.user = user;
2845
+ this.course = course;
2846
+ if (strategyData) {
2847
+ this.strategyName = strategyData.name;
2848
+ this.strategyId = strategyData._id;
2849
+ this.learnable = strategyData.learnable;
2850
+ this.staticWeight = strategyData.staticWeight;
2851
+ }
2852
+ }
2853
+ // ============================================================================
2854
+ // STRATEGY STATE HELPERS
2855
+ // ============================================================================
2856
+ //
2857
+ // These methods allow strategies to persist their own state (user preferences,
2858
+ // learned patterns, temporal tracking) in the user database.
2859
+ //
2860
+ // ============================================================================
2861
+ /**
2862
+ * Unique key identifying this strategy for state storage.
2863
+ *
2864
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
2865
+ * Override in subclasses if multiple instances of the same strategy type
2866
+ * need separate state storage.
2867
+ */
2868
+ get strategyKey() {
2869
+ return this.constructor.name;
1156
2870
  }
1157
2871
  /**
1158
- * Get review cards scored by urgency.
2872
+ * Get this strategy's persisted state for the current course.
1159
2873
  *
1160
- * Score formula combines:
1161
- * - Relative overdueness: hoursOverdue / intervalHours
1162
- * - Interval recency: exponential decay favoring shorter intervals
2874
+ * @returns The strategy's data payload, or null if no state exists
2875
+ * @throws Error if user or course is not initialized
2876
+ */
2877
+ async getStrategyState() {
2878
+ if (!this.user || !this.course) {
2879
+ throw new Error(
2880
+ `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2881
+ );
2882
+ }
2883
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
2884
+ }
2885
+ /**
2886
+ * Persist this strategy's state for the current course.
1163
2887
  *
1164
- * Cards not yet due are excluded (not scored as 0).
2888
+ * @param data - The strategy's data payload to store
2889
+ * @throws Error if user or course is not initialized
2890
+ */
2891
+ async putStrategyState(data) {
2892
+ if (!this.user || !this.course) {
2893
+ throw new Error(
2894
+ `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2895
+ );
2896
+ }
2897
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
2898
+ }
2899
+ /**
2900
+ * Factory method to create navigator instances.
1165
2901
  *
1166
- * This method supports both the legacy signature (limit only) and the
1167
- * CardGenerator interface signature (limit, context).
2902
+ * First checks the navigator registry for a pre-registered constructor.
2903
+ * If not found, falls back to dynamic import (for custom navigators).
1168
2904
  *
1169
- * @param limit - Maximum number of cards to return
1170
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
2905
+ * For reliable operation in test environments, call initializeNavigatorRegistry()
2906
+ * before using this method.
2907
+ *
2908
+ * @param user - User interface
2909
+ * @param course - Course interface
2910
+ * @param strategyData - Strategy configuration document
2911
+ * @returns the runtime object used to steer a study session.
1171
2912
  */
1172
- async getWeightedCards(limit, _context) {
1173
- if (!this.user || !this.course) {
1174
- throw new Error("SRSNavigator requires user and course to be set");
2913
+ static async create(user, course, strategyData) {
2914
+ const implementingClass = strategyData.implementingClass;
2915
+ const RegisteredImpl = getRegisteredNavigator(implementingClass);
2916
+ if (RegisteredImpl) {
2917
+ logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);
2918
+ return new RegisteredImpl(user, course, strategyData);
1175
2919
  }
1176
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1177
- const now = import_moment3.default.utc();
1178
- const dueReviews = reviews.filter((r) => now.isAfter(import_moment3.default.utc(r.reviewTime)));
1179
- const scored = dueReviews.map((review) => {
1180
- const { score, reason } = this.computeUrgencyScore(review, now);
1181
- return {
1182
- cardId: review.cardId,
1183
- courseId: review.courseId,
1184
- score,
1185
- reviewID: review._id,
1186
- provenance: [
1187
- {
1188
- strategy: "srs",
1189
- strategyName: this.strategyName || this.name,
1190
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1191
- action: "generated",
1192
- score,
1193
- reason
1194
- }
1195
- ]
1196
- };
1197
- });
1198
- logger.debug(`[srsNav] got ${scored.length} weighted cards`);
1199
- return scored.sort((a, b) => b.score - a.score).slice(0, limit);
2920
+ logger.debug(
2921
+ `[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`
2922
+ );
2923
+ let NavigatorImpl;
2924
+ const variations = [".ts", ".js", ""];
2925
+ for (const ext of variations) {
2926
+ try {
2927
+ const module2 = await globImport_generators(`./generators/${implementingClass}${ext}`);
2928
+ NavigatorImpl = module2.default;
2929
+ if (NavigatorImpl) break;
2930
+ } catch (e) {
2931
+ logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);
2932
+ }
2933
+ try {
2934
+ const module2 = await globImport_filters(`./filters/${implementingClass}${ext}`);
2935
+ NavigatorImpl = module2.default;
2936
+ if (NavigatorImpl) break;
2937
+ } catch (e) {
2938
+ logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);
2939
+ }
2940
+ try {
2941
+ const module2 = await globImport(`./${implementingClass}${ext}`);
2942
+ NavigatorImpl = module2.default;
2943
+ if (NavigatorImpl) break;
2944
+ } catch (e) {
2945
+ logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);
2946
+ }
2947
+ if (NavigatorImpl) break;
2948
+ }
2949
+ if (!NavigatorImpl) {
2950
+ throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
2951
+ }
2952
+ return new NavigatorImpl(user, course, strategyData);
1200
2953
  }
1201
2954
  /**
1202
- * Compute urgency score for a review card.
2955
+ * Get cards with suitability scores and provenance trails.
1203
2956
  *
1204
- * Two factors:
1205
- * 1. Relative overdueness = hoursOverdue / intervalHours
1206
- * - 2 days overdue on 3-day interval = 0.67 (urgent)
1207
- * - 2 days overdue on 180-day interval = 0.01 (not urgent)
2957
+ * **This is the PRIMARY API for navigation strategies.**
1208
2958
  *
1209
- * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1210
- * - 24h interval ~1.0 (very recent learning)
1211
- * - 30 days (720h) ~0.56
1212
- * - 180 days → ~0.30
2959
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
2960
+ * better candidates for presentation. Each card includes a provenance trail
2961
+ * documenting how strategies contributed to the final score.
2962
+ *
2963
+ * ## Implementation Required
2964
+ * All navigation strategies MUST override this method. The base class does
2965
+ * not provide a default implementation.
2966
+ *
2967
+ * ## For Generators
2968
+ * Override this method to generate candidates and compute scores based on
2969
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
2970
+ * initial provenance entry with action='generated'.
1213
2971
  *
1214
- * Combined: base 0.5 + weighted average of factors * 0.45
1215
- * Result range: approximately 0.5 to 0.95
2972
+ * ## For Filters
2973
+ * Filters should implement the CardFilter interface instead and be composed
2974
+ * via Pipeline. Filters do not directly implement getWeightedCards().
2975
+ *
2976
+ * @param limit - Maximum cards to return
2977
+ * @returns Cards sorted by score descending, with provenance trails
1216
2978
  */
1217
- computeUrgencyScore(review, now) {
1218
- const scheduledAt = import_moment3.default.utc(review.scheduledAt);
1219
- const due = import_moment3.default.utc(review.reviewTime);
1220
- const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1221
- const hoursOverdue = now.diff(due, "hours");
1222
- const relativeOverdue = hoursOverdue / intervalHours;
1223
- const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1224
- const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1225
- const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1226
- const score = Math.min(0.95, 0.5 + urgency * 0.45);
1227
- const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
1228
- return { score, reason };
2979
+ async getWeightedCards(_limit) {
2980
+ throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
1229
2981
  }
1230
2982
  };
1231
2983
  }
1232
2984
  });
1233
2985
 
1234
- // src/core/navigators/filters/eloDistance.ts
1235
- function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1236
- const normalizedDistance = distance / halfLife;
1237
- const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1238
- return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1239
- }
1240
- function createEloDistanceFilter(config) {
1241
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1242
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1243
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1244
- return {
1245
- name: "ELO Distance Filter",
1246
- async transform(cards, context) {
1247
- const { course, userElo } = context;
1248
- const cardIds = cards.map((c) => c.cardId);
1249
- const cardElos = await course.getCardEloData(cardIds);
1250
- return cards.map((card, i) => {
1251
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
1252
- const distance = Math.abs(cardElo - userElo);
1253
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1254
- const newScore = card.score * multiplier;
1255
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1256
- return {
1257
- ...card,
1258
- score: newScore,
1259
- provenance: [
1260
- ...card.provenance,
1261
- {
1262
- strategy: "eloDistance",
1263
- strategyName: "ELO Distance Filter",
1264
- strategyId: "ELO_DISTANCE_FILTER",
1265
- action,
1266
- score: newScore,
1267
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1268
- }
1269
- ]
1270
- };
1271
- });
1272
- }
1273
- };
1274
- }
1275
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1276
- var init_eloDistance = __esm({
1277
- "src/core/navigators/filters/eloDistance.ts"() {
1278
- "use strict";
1279
- DEFAULT_HALF_LIFE = 200;
1280
- DEFAULT_MIN_MULTIPLIER = 0.3;
1281
- DEFAULT_MAX_MULTIPLIER = 1;
1282
- }
1283
- });
1284
-
1285
- // src/core/navigators/defaults.ts
1286
- function createDefaultEloStrategy(courseId) {
1287
- return {
1288
- _id: "NAVIGATION_STRATEGY-ELO-default",
1289
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1290
- name: "ELO (default)",
1291
- description: "Default ELO-based navigation strategy for new cards",
1292
- implementingClass: "elo" /* ELO */,
1293
- course: courseId,
1294
- serializedData: ""
1295
- };
1296
- }
1297
- function createDefaultSrsStrategy(courseId) {
1298
- return {
1299
- _id: "NAVIGATION_STRATEGY-SRS-default",
1300
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1301
- name: "SRS (default)",
1302
- description: "Default SRS-based navigation strategy for reviews",
1303
- implementingClass: "srs" /* SRS */,
1304
- course: courseId,
1305
- serializedData: ""
1306
- };
1307
- }
1308
- function createDefaultPipeline(user, course) {
1309
- const courseId = course.getCourseID();
1310
- const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
1311
- const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
1312
- const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
1313
- const eloDistanceFilter = createEloDistanceFilter();
1314
- return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
1315
- }
1316
- var init_defaults = __esm({
1317
- "src/core/navigators/defaults.ts"() {
1318
- "use strict";
1319
- init_navigators();
1320
- init_Pipeline();
1321
- init_CompositeGenerator();
1322
- init_elo();
1323
- init_srs();
1324
- init_eloDistance();
1325
- init_types_legacy();
1326
- }
1327
- });
1328
-
1329
2986
  // src/impl/couch/courseDB.ts
1330
- var import_common7;
2987
+ var import_common9;
1331
2988
  var init_courseDB = __esm({
1332
2989
  "src/impl/couch/courseDB.ts"() {
1333
2990
  "use strict";
1334
- import_common7 = require("@vue-skuilder/common");
2991
+ import_common9 = require("@vue-skuilder/common");
1335
2992
  init_couch();
1336
2993
  init_updateQueue();
1337
2994
  init_types_legacy();
@@ -1384,14 +3041,14 @@ var init_auth = __esm({
1384
3041
  });
1385
3042
 
1386
3043
  // src/impl/couch/CouchDBSyncStrategy.ts
1387
- var import_common8;
3044
+ var import_common10;
1388
3045
  var init_CouchDBSyncStrategy = __esm({
1389
3046
  "src/impl/couch/CouchDBSyncStrategy.ts"() {
1390
3047
  "use strict";
1391
3048
  init_factory();
1392
3049
  init_types_legacy();
1393
3050
  init_logger();
1394
- import_common8 = require("@vue-skuilder/common");
3051
+ import_common10 = require("@vue-skuilder/common");
1395
3052
  init_common();
1396
3053
  init_pouchdb_setup();
1397
3054
  init_couch();
@@ -1625,13 +3282,13 @@ async function dropUserFromClassroom(user, classID) {
1625
3282
  async function getUserClassrooms(user) {
1626
3283
  return getOrCreateClassroomRegistrationsDoc(user);
1627
3284
  }
1628
- var import_common10, import_moment6, log3, BaseUser, userCoursesDoc, userClassroomsDoc;
3285
+ var import_common12, import_moment6, log3, BaseUser, userCoursesDoc, userClassroomsDoc;
1629
3286
  var init_BaseUserDB = __esm({
1630
3287
  "src/impl/common/BaseUserDB.ts"() {
1631
3288
  "use strict";
1632
3289
  init_core();
1633
3290
  init_util();
1634
- import_common10 = require("@vue-skuilder/common");
3291
+ import_common12 = require("@vue-skuilder/common");
1635
3292
  import_moment6 = __toESM(require("moment"), 1);
1636
3293
  init_types_legacy();
1637
3294
  init_logger();
@@ -1681,7 +3338,7 @@ Currently logged-in as ${this._username}.`
1681
3338
  );
1682
3339
  }
1683
3340
  const result = await this.syncStrategy.createAccount(username, password);
1684
- if (result.status === import_common10.Status.ok) {
3341
+ if (result.status === import_common12.Status.ok) {
1685
3342
  log3(`Account created successfully, updating username to ${username}`);
1686
3343
  this._username = username;
1687
3344
  try {
@@ -1723,7 +3380,7 @@ Currently logged-in as ${this._username}.`
1723
3380
  async resetUserData() {
1724
3381
  if (this.syncStrategy.canAuthenticate()) {
1725
3382
  return {
1726
- status: import_common10.Status.error,
3383
+ status: import_common12.Status.error,
1727
3384
  error: "Reset user data is only available for local-only mode. Use logout instead for remote sync."
1728
3385
  };
1729
3386
  }
@@ -1742,11 +3399,11 @@ Currently logged-in as ${this._username}.`
1742
3399
  await localDB.bulkDocs(docsToDelete);
1743
3400
  }
1744
3401
  await this.init();
1745
- return { status: import_common10.Status.ok };
3402
+ return { status: import_common12.Status.ok };
1746
3403
  } catch (error) {
1747
3404
  logger.error("Failed to reset user data:", error);
1748
3405
  return {
1749
- status: import_common10.Status.error,
3406
+ status: import_common12.Status.error,
1750
3407
  error: error instanceof Error ? error.message : "Unknown error during reset"
1751
3408
  };
1752
3409
  }
@@ -2473,6 +4130,19 @@ Currently logged-in as ${this._username}.`
2473
4130
  };
2474
4131
  await this.localDB.put(doc);
2475
4132
  }
4133
+ async putUserOutcome(record) {
4134
+ try {
4135
+ await this.localDB.put(record);
4136
+ } catch (err) {
4137
+ if (err.status === 409) {
4138
+ const existing = await this.localDB.get(record._id);
4139
+ record._rev = existing._rev;
4140
+ await this.localDB.put(record);
4141
+ } else {
4142
+ throw err;
4143
+ }
4144
+ }
4145
+ }
2476
4146
  async deleteStrategyState(courseId, strategyKey) {
2477
4147
  const docId = buildStrategyStateId(courseId, strategyKey);
2478
4148
  try {
@@ -2509,6 +4179,7 @@ var init_factory = __esm({
2509
4179
  "use strict";
2510
4180
  init_common();
2511
4181
  init_logger();
4182
+ init_navigators();
2512
4183
  NOT_SET = "NOT_SET";
2513
4184
  ENV = {
2514
4185
  COUCHDB_SERVER_PROTOCOL: NOT_SET,
@@ -2519,24 +4190,24 @@ var init_factory = __esm({
2519
4190
  });
2520
4191
 
2521
4192
  // src/study/TagFilteredContentSource.ts
2522
- var import_common12;
4193
+ var import_common14;
2523
4194
  var init_TagFilteredContentSource = __esm({
2524
4195
  "src/study/TagFilteredContentSource.ts"() {
2525
4196
  "use strict";
2526
- import_common12 = require("@vue-skuilder/common");
4197
+ import_common14 = require("@vue-skuilder/common");
2527
4198
  init_courseDB();
2528
4199
  init_logger();
2529
4200
  }
2530
4201
  });
2531
4202
 
2532
4203
  // src/core/interfaces/contentSource.ts
2533
- var import_common13;
4204
+ var import_common15;
2534
4205
  var init_contentSource = __esm({
2535
4206
  "src/core/interfaces/contentSource.ts"() {
2536
4207
  "use strict";
2537
4208
  init_factory();
2538
4209
  init_classroomDB2();
2539
- import_common13 = require("@vue-skuilder/common");
4210
+ import_common15 = require("@vue-skuilder/common");
2540
4211
  init_TagFilteredContentSource();
2541
4212
  }
2542
4213
  });
@@ -2592,18 +4263,25 @@ var init_strategyState = __esm({
2592
4263
  }
2593
4264
  });
2594
4265
 
4266
+ // src/core/types/userOutcome.ts
4267
+ var init_userOutcome = __esm({
4268
+ "src/core/types/userOutcome.ts"() {
4269
+ "use strict";
4270
+ }
4271
+ });
4272
+
2595
4273
  // src/core/bulkImport/cardProcessor.ts
2596
- var import_common14;
4274
+ var import_common16;
2597
4275
  var init_cardProcessor = __esm({
2598
4276
  "src/core/bulkImport/cardProcessor.ts"() {
2599
4277
  "use strict";
2600
- import_common14 = require("@vue-skuilder/common");
4278
+ import_common16 = require("@vue-skuilder/common");
2601
4279
  init_logger();
2602
4280
  }
2603
4281
  });
2604
4282
 
2605
4283
  // src/core/bulkImport/types.ts
2606
- var init_types = __esm({
4284
+ var init_types3 = __esm({
2607
4285
  "src/core/bulkImport/types.ts"() {
2608
4286
  "use strict";
2609
4287
  }
@@ -2614,7 +4292,7 @@ var init_bulkImport = __esm({
2614
4292
  "src/core/bulkImport/index.ts"() {
2615
4293
  "use strict";
2616
4294
  init_cardProcessor();
2617
- init_types();
4295
+ init_types3();
2618
4296
  }
2619
4297
  });
2620
4298
 
@@ -2626,10 +4304,12 @@ var init_core = __esm({
2626
4304
  init_types_legacy();
2627
4305
  init_user();
2628
4306
  init_strategyState();
4307
+ init_userOutcome();
2629
4308
  init_Loggable();
2630
4309
  init_util();
2631
4310
  init_navigators();
2632
4311
  init_bulkImport();
4312
+ init_orchestration();
2633
4313
  }
2634
4314
  });
2635
4315
 
@@ -3050,11 +4730,11 @@ var init_StaticDataUnpacker = __esm({
3050
4730
  });
3051
4731
 
3052
4732
  // src/impl/static/courseDB.ts
3053
- var import_common15, StaticCourseDB;
4733
+ var import_common17, StaticCourseDB;
3054
4734
  var init_courseDB3 = __esm({
3055
4735
  "src/impl/static/courseDB.ts"() {
3056
4736
  "use strict";
3057
- import_common15 = require("@vue-skuilder/common");
4737
+ import_common17 = require("@vue-skuilder/common");
3058
4738
  init_types_legacy();
3059
4739
  init_logger();
3060
4740
  init_defaults();
@@ -3311,7 +4991,7 @@ var init_courseDB3 = __esm({
3311
4991
  }
3312
4992
  async addNote(_codeCourse, _shape, _data, _author, _tags, _uploads, _elo) {
3313
4993
  return {
3314
- status: import_common15.Status.error,
4994
+ status: import_common17.Status.error,
3315
4995
  message: "Cannot add notes in static mode"
3316
4996
  };
3317
4997
  }