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