@vue-skuilder/db 0.1.23 → 0.1.25

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/dist/{contentSource-BP9hznNV.d.ts → contentSource-BmnmvH8C.d.ts} +268 -3
  2. package/dist/{contentSource-DsJadoBU.d.cts → contentSource-DfBbaLA-.d.cts} +268 -3
  3. package/dist/core/index.d.cts +310 -6
  4. package/dist/core/index.d.ts +310 -6
  5. package/dist/core/index.js +2606 -666
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +2564 -639
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-CHYrQ5pB.d.cts → dataLayerProvider-BeRXVMs5.d.cts} +1 -1
  10. package/dist/{dataLayerProvider-MDTxXq2l.d.ts → dataLayerProvider-CG9GfaAY.d.ts} +1 -1
  11. package/dist/impl/couch/index.d.cts +11 -3
  12. package/dist/impl/couch/index.d.ts +11 -3
  13. package/dist/impl/couch/index.js +2336 -656
  14. package/dist/impl/couch/index.js.map +1 -1
  15. package/dist/impl/couch/index.mjs +2316 -631
  16. package/dist/impl/couch/index.mjs.map +1 -1
  17. package/dist/impl/static/index.d.cts +4 -4
  18. package/dist/impl/static/index.d.ts +4 -4
  19. package/dist/impl/static/index.js +2312 -632
  20. package/dist/impl/static/index.js.map +1 -1
  21. package/dist/impl/static/index.mjs +2315 -630
  22. package/dist/impl/static/index.mjs.map +1 -1
  23. package/dist/{index-Dj0SEgk3.d.ts → index-BWvO-_rJ.d.ts} +1 -1
  24. package/dist/{index-B_j6u5E4.d.cts → index-Ba7hYbHj.d.cts} +1 -1
  25. package/dist/index.d.cts +278 -20
  26. package/dist/index.d.ts +278 -20
  27. package/dist/index.js +3603 -720
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +3529 -674
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/{types-DQaXnuoc.d.ts → types-CJrLM1Ew.d.ts} +1 -1
  32. package/dist/{types-Bn0itutr.d.cts → types-W8n-B6HG.d.cts} +1 -1
  33. package/dist/{types-legacy-DDY4N-Uq.d.cts → types-legacy-JXDxinpU.d.cts} +5 -1
  34. package/dist/{types-legacy-DDY4N-Uq.d.ts → types-legacy-JXDxinpU.d.ts} +5 -1
  35. package/dist/util/packer/index.d.cts +3 -3
  36. package/dist/util/packer/index.d.ts +3 -3
  37. package/docs/brainstorm-navigation-paradigm.md +40 -34
  38. package/docs/future-orchestration-vision.md +216 -0
  39. package/docs/navigators-architecture.md +210 -9
  40. package/docs/todo-review-urgency-adaptation.md +205 -0
  41. package/docs/todo-strategy-authoring.md +8 -6
  42. package/package.json +3 -3
  43. package/src/core/index.ts +2 -0
  44. package/src/core/interfaces/contentSource.ts +7 -0
  45. package/src/core/interfaces/userDB.ts +50 -0
  46. package/src/core/navigators/Pipeline.ts +132 -5
  47. package/src/core/navigators/PipelineAssembler.ts +21 -22
  48. package/src/core/navigators/PipelineDebugger.ts +426 -0
  49. package/src/core/navigators/filters/WeightedFilter.ts +141 -0
  50. package/src/core/navigators/filters/types.ts +4 -0
  51. package/src/core/navigators/generators/CompositeGenerator.ts +82 -19
  52. package/src/core/navigators/generators/elo.ts +14 -1
  53. package/src/core/navigators/generators/srs.ts +146 -18
  54. package/src/core/navigators/generators/types.ts +4 -0
  55. package/src/core/navigators/index.ts +203 -13
  56. package/src/core/orchestration/gradient.ts +133 -0
  57. package/src/core/orchestration/index.ts +210 -0
  58. package/src/core/orchestration/learning.ts +250 -0
  59. package/src/core/orchestration/recording.ts +92 -0
  60. package/src/core/orchestration/signal.ts +67 -0
  61. package/src/core/types/contentNavigationStrategy.ts +38 -0
  62. package/src/core/types/learningState.ts +77 -0
  63. package/src/core/types/types-legacy.ts +4 -0
  64. package/src/core/types/userOutcome.ts +51 -0
  65. package/src/courseConfigRegistration.ts +107 -0
  66. package/src/factory.ts +6 -0
  67. package/src/impl/common/BaseUserDB.ts +16 -0
  68. package/src/impl/couch/user-course-relDB.ts +12 -0
  69. package/src/study/MixerDebugger.ts +555 -0
  70. package/src/study/SessionController.ts +159 -20
  71. package/src/study/SessionDebugger.ts +442 -0
  72. package/src/study/SourceMixer.ts +36 -17
  73. package/src/study/TODO-session-scheduling.md +133 -0
  74. package/src/study/index.ts +2 -0
  75. package/src/study/services/EloService.ts +79 -4
  76. package/src/study/services/ResponseProcessor.ts +130 -72
  77. package/src/study/services/SrsService.ts +9 -0
  78. package/tests/core/navigators/Pipeline.test.ts +2 -0
  79. package/tests/core/navigators/PipelineAssembler.test.ts +4 -4
  80. package/docs/todo-evolutionary-orchestration.md +0 -310
@@ -5,6 +5,11 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __glob = (map) => (path2) => {
9
+ var fn = map[path2];
10
+ if (fn) return fn();
11
+ throw new Error("Module not found in bundle: " + path2);
12
+ };
8
13
  var __esm = (fn, res) => function __init() {
9
14
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
15
  };
@@ -118,6 +123,8 @@ var init_types_legacy = __esm({
118
123
  DocType2["TAG"] = "TAG";
119
124
  DocType2["NAVIGATION_STRATEGY"] = "NAVIGATION_STRATEGY";
120
125
  DocType2["STRATEGY_STATE"] = "STRATEGY_STATE";
126
+ DocType2["USER_OUTCOME"] = "USER_OUTCOME";
127
+ DocType2["STRATEGY_LEARNING_STATE"] = "STRATEGY_LEARNING_STATE";
121
128
  return DocType2;
122
129
  })(DocType || {});
123
130
  DocTypePrefixes = {
@@ -132,7 +139,9 @@ var init_types_legacy = __esm({
132
139
  ["VIEW" /* VIEW */]: "VIEW",
133
140
  ["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
134
141
  ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
135
- ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE"
142
+ ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE",
143
+ ["USER_OUTCOME" /* USER_OUTCOME */]: "USER_OUTCOME",
144
+ ["STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */]: "STRATEGY_LEARNING_STATE"
136
145
  };
137
146
  }
138
147
  });
@@ -462,6 +471,15 @@ var init_user_course_relDB = __esm({
462
471
  void this.user.updateCourseSettings(this._courseId, updates);
463
472
  }
464
473
  }
474
+ async getStrategyState(strategyKey) {
475
+ return this.user.getStrategyState(this._courseId, strategyKey);
476
+ }
477
+ async putStrategyState(strategyKey, data) {
478
+ return this.user.putStrategyState(this._courseId, strategyKey, data);
479
+ }
480
+ async deleteStrategyState(strategyKey) {
481
+ return this.user.deleteStrategyState(this._courseId, strategyKey);
482
+ }
465
483
  async getReviewstoDate(targetDate) {
466
484
  const allReviews = await this.user.getPendingReviews(this._courseId);
467
485
  logger.debug(
@@ -701,359 +719,289 @@ var init_courseLookupDB = __esm({
701
719
  }
702
720
  });
703
721
 
704
- // src/core/navigators/index.ts
705
- function getCardOrigin(card) {
706
- if (card.provenance.length === 0) {
707
- throw new Error("Card has no provenance - cannot determine origin");
708
- }
722
+ // src/core/navigators/PipelineDebugger.ts
723
+ var PipelineDebugger_exports = {};
724
+ __export(PipelineDebugger_exports, {
725
+ buildRunReport: () => buildRunReport,
726
+ captureRun: () => captureRun,
727
+ mountPipelineDebugger: () => mountPipelineDebugger,
728
+ pipelineDebugAPI: () => pipelineDebugAPI
729
+ });
730
+ function getOrigin(card) {
709
731
  const firstEntry = card.provenance[0];
710
- const reason = firstEntry.reason.toLowerCase();
711
- if (reason.includes("failed")) {
712
- return "failed";
713
- }
714
- if (reason.includes("review")) {
715
- return "review";
732
+ if (!firstEntry) return "unknown";
733
+ const reason = firstEntry.reason?.toLowerCase() || "";
734
+ if (reason.includes("new card")) return "new";
735
+ if (reason.includes("review")) return "review";
736
+ return "unknown";
737
+ }
738
+ function captureRun(report) {
739
+ const fullReport = {
740
+ ...report,
741
+ runId: `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
742
+ timestamp: /* @__PURE__ */ new Date()
743
+ };
744
+ runHistory.unshift(fullReport);
745
+ if (runHistory.length > MAX_RUNS) {
746
+ runHistory.pop();
716
747
  }
717
- return "new";
718
748
  }
719
- function isGenerator(impl) {
720
- return NavigatorRoles[impl] === "generator" /* GENERATOR */;
749
+ function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards) {
750
+ const selectedIds = new Set(selectedCards.map((c) => c.cardId));
751
+ const cards = allCards.map((card) => ({
752
+ cardId: card.cardId,
753
+ courseId: card.courseId,
754
+ origin: getOrigin(card),
755
+ finalScore: card.score,
756
+ provenance: card.provenance,
757
+ selected: selectedIds.has(card.cardId)
758
+ }));
759
+ const reviewsSelected = selectedCards.filter((c) => getOrigin(c) === "review").length;
760
+ const newSelected = selectedCards.filter((c) => getOrigin(c) === "new").length;
761
+ return {
762
+ courseId,
763
+ courseName,
764
+ generatorName,
765
+ generators,
766
+ generatedCount,
767
+ filters,
768
+ finalCount: selectedCards.length,
769
+ reviewsSelected,
770
+ newSelected,
771
+ cards
772
+ };
721
773
  }
722
- function isFilter(impl) {
723
- return NavigatorRoles[impl] === "filter" /* FILTER */;
774
+ function formatProvenance(provenance) {
775
+ return provenance.map((p) => {
776
+ const actionSymbol = p.action === "generated" ? "\u{1F3B2}" : p.action === "boosted" ? "\u2B06\uFE0F" : p.action === "penalized" ? "\u2B07\uFE0F" : "\u27A1\uFE0F";
777
+ return ` ${actionSymbol} ${p.strategyName}: ${p.score.toFixed(3)} - ${p.reason}`;
778
+ }).join("\n");
724
779
  }
725
- var Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
726
- var init_navigators = __esm({
727
- "src/core/navigators/index.ts"() {
780
+ function printRunSummary(run) {
781
+ console.group(`\u{1F50D} Pipeline Run: ${run.courseId} (${run.courseName || "unnamed"})`);
782
+ logger.info(`Run ID: ${run.runId}`);
783
+ logger.info(`Time: ${run.timestamp.toISOString()}`);
784
+ logger.info(`Generator: ${run.generatorName} \u2192 ${run.generatedCount} candidates`);
785
+ if (run.generators && run.generators.length > 0) {
786
+ console.group("Generator breakdown:");
787
+ for (const g of run.generators) {
788
+ logger.info(
789
+ ` ${g.name}: ${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} reviews, top: ${g.topScore.toFixed(2)})`
790
+ );
791
+ }
792
+ console.groupEnd();
793
+ }
794
+ if (run.filters.length > 0) {
795
+ console.group("Filter impact:");
796
+ for (const f of run.filters) {
797
+ logger.info(` ${f.name}: \u2191${f.boosted} \u2193${f.penalized} =${f.passed} \u2715${f.removed}`);
798
+ }
799
+ console.groupEnd();
800
+ }
801
+ logger.info(
802
+ `Result: ${run.finalCount} cards selected (${run.newSelected} new, ${run.reviewsSelected} reviews)`
803
+ );
804
+ console.groupEnd();
805
+ }
806
+ function mountPipelineDebugger() {
807
+ if (typeof window === "undefined") return;
808
+ const win = window;
809
+ win.skuilder = win.skuilder || {};
810
+ win.skuilder.pipeline = pipelineDebugAPI;
811
+ }
812
+ var MAX_RUNS, runHistory, pipelineDebugAPI;
813
+ var init_PipelineDebugger = __esm({
814
+ "src/core/navigators/PipelineDebugger.ts"() {
728
815
  "use strict";
729
816
  init_logger();
730
- Navigators = /* @__PURE__ */ ((Navigators2) => {
731
- Navigators2["ELO"] = "elo";
732
- Navigators2["SRS"] = "srs";
733
- Navigators2["HIERARCHY"] = "hierarchyDefinition";
734
- Navigators2["INTERFERENCE"] = "interferenceMitigator";
735
- Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
736
- Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
737
- return Navigators2;
738
- })(Navigators || {});
739
- NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
740
- NavigatorRole2["GENERATOR"] = "generator";
741
- NavigatorRole2["FILTER"] = "filter";
742
- return NavigatorRole2;
743
- })(NavigatorRole || {});
744
- NavigatorRoles = {
745
- ["elo" /* ELO */]: "generator" /* GENERATOR */,
746
- ["srs" /* SRS */]: "generator" /* GENERATOR */,
747
- ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
748
- ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
749
- ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
750
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
751
- };
752
- ContentNavigator = class {
753
- /** User interface for this navigation session */
754
- user;
755
- /** Course interface for this navigation session */
756
- course;
757
- /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
758
- strategyName;
759
- /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
760
- strategyId;
817
+ MAX_RUNS = 10;
818
+ runHistory = [];
819
+ pipelineDebugAPI = {
761
820
  /**
762
- * Constructor for standard navigators.
763
- * Call this from subclass constructors to initialize common fields.
764
- *
765
- * Note: CompositeGenerator and Pipeline call super() without args, then set
766
- * user/course fields directly if needed.
821
+ * Get raw run history for programmatic access.
767
822
  */
768
- constructor(user, course, strategyData) {
769
- this.user = user;
770
- this.course = course;
771
- if (strategyData) {
772
- this.strategyName = strategyData.name;
773
- this.strategyId = strategyData._id;
774
- }
775
- }
776
- // ============================================================================
777
- // STRATEGY STATE HELPERS
778
- // ============================================================================
779
- //
780
- // These methods allow strategies to persist their own state (user preferences,
781
- // learned patterns, temporal tracking) in the user database.
782
- //
783
- // ============================================================================
823
+ get runs() {
824
+ return [...runHistory];
825
+ },
784
826
  /**
785
- * Unique key identifying this strategy for state storage.
786
- *
787
- * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
788
- * Override in subclasses if multiple instances of the same strategy type
789
- * need separate state storage.
827
+ * Show summary of a specific pipeline run.
790
828
  */
791
- get strategyKey() {
792
- return this.constructor.name;
793
- }
829
+ showRun(idOrIndex = 0) {
830
+ if (runHistory.length === 0) {
831
+ logger.info("[Pipeline Debug] No runs captured yet.");
832
+ return;
833
+ }
834
+ let run;
835
+ if (typeof idOrIndex === "number") {
836
+ run = runHistory[idOrIndex];
837
+ if (!run) {
838
+ logger.info(
839
+ `[Pipeline Debug] No run found at index ${idOrIndex}. History length: ${runHistory.length}`
840
+ );
841
+ return;
842
+ }
843
+ } else {
844
+ run = runHistory.find((r) => r.runId.endsWith(idOrIndex));
845
+ if (!run) {
846
+ logger.info(`[Pipeline Debug] No run found matching ID '${idOrIndex}'.`);
847
+ return;
848
+ }
849
+ }
850
+ printRunSummary(run);
851
+ },
794
852
  /**
795
- * Get this strategy's persisted state for the current course.
796
- *
797
- * @returns The strategy's data payload, or null if no state exists
798
- * @throws Error if user or course is not initialized
853
+ * Show summary of the last pipeline run.
799
854
  */
800
- async getStrategyState() {
801
- if (!this.user || !this.course) {
802
- throw new Error(
803
- `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
804
- );
805
- }
806
- return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
807
- }
855
+ showLastRun() {
856
+ this.showRun(0);
857
+ },
808
858
  /**
809
- * Persist this strategy's state for the current course.
810
- *
811
- * @param data - The strategy's data payload to store
812
- * @throws Error if user or course is not initialized
859
+ * Show detailed provenance for a specific card.
813
860
  */
814
- async putStrategyState(data) {
815
- if (!this.user || !this.course) {
816
- throw new Error(
817
- `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
818
- );
861
+ showCard(cardId) {
862
+ for (const run of runHistory) {
863
+ const card = run.cards.find((c) => c.cardId === cardId);
864
+ if (card) {
865
+ console.group(`\u{1F3B4} Card: ${cardId}`);
866
+ logger.info(`Course: ${card.courseId}`);
867
+ logger.info(`Origin: ${card.origin}`);
868
+ logger.info(`Final score: ${card.finalScore.toFixed(3)}`);
869
+ logger.info(`Selected: ${card.selected ? "Yes \u2705" : "No \u274C"}`);
870
+ logger.info("Provenance:");
871
+ logger.info(formatProvenance(card.provenance));
872
+ console.groupEnd();
873
+ return;
874
+ }
819
875
  }
820
- return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
821
- }
876
+ logger.info(`[Pipeline Debug] Card '${cardId}' not found in recent runs.`);
877
+ },
822
878
  /**
823
- * Factory method to create navigator instances dynamically.
824
- *
825
- * @param user - User interface
826
- * @param course - Course interface
827
- * @param strategyData - Strategy configuration document
828
- * @returns the runtime object used to steer a study session.
879
+ * Explain why reviews may or may not have been selected.
829
880
  */
830
- static async create(user, course, strategyData) {
831
- const implementingClass = strategyData.implementingClass;
832
- let NavigatorImpl;
833
- const variations = [".ts", ".js", ""];
834
- const dirs = ["filters", "generators"];
835
- for (const ext of variations) {
836
- for (const dir of dirs) {
837
- const loadFrom = `./${dir}/${implementingClass}${ext}`;
838
- try {
839
- const module2 = await import(loadFrom);
840
- NavigatorImpl = module2.default;
841
- break;
842
- } catch (e) {
843
- logger.debug(`Failed to load extension from ${loadFrom}:`, e);
881
+ explainReviews() {
882
+ if (runHistory.length === 0) {
883
+ logger.info("[Pipeline Debug] No runs captured yet.");
884
+ return;
885
+ }
886
+ console.group("\u{1F4CB} Review Selection Analysis");
887
+ for (const run of runHistory) {
888
+ console.group(`Run: ${run.courseId} @ ${run.timestamp.toLocaleTimeString()}`);
889
+ const allReviews = run.cards.filter((c) => c.origin === "review");
890
+ const selectedReviews = allReviews.filter((c) => c.selected);
891
+ if (allReviews.length === 0) {
892
+ logger.info("\u274C No reviews were generated. Check SRS logs for why.");
893
+ } else if (selectedReviews.length === 0) {
894
+ logger.info(`\u26A0\uFE0F ${allReviews.length} reviews generated but none selected.`);
895
+ logger.info("Possible reasons:");
896
+ const topNewScore = Math.max(
897
+ ...run.cards.filter((c) => c.origin === "new" && c.selected).map((c) => c.finalScore),
898
+ 0
899
+ );
900
+ const topReviewScore = Math.max(...allReviews.map((c) => c.finalScore), 0);
901
+ if (topReviewScore < topNewScore) {
902
+ logger.info(
903
+ ` - New cards scored higher (top new: ${topNewScore.toFixed(2)}, top review: ${topReviewScore.toFixed(2)})`
904
+ );
844
905
  }
906
+ const topReview = allReviews.sort((a, b) => b.finalScore - a.finalScore)[0];
907
+ if (topReview) {
908
+ logger.info(` - Top review score: ${topReview.finalScore.toFixed(3)}`);
909
+ logger.info(" - Its provenance:");
910
+ logger.info(formatProvenance(topReview.provenance));
911
+ }
912
+ } else {
913
+ logger.info(`\u2705 ${selectedReviews.length}/${allReviews.length} reviews selected.`);
914
+ logger.info("Top selected review:");
915
+ const topSelected = selectedReviews.sort((a, b) => b.finalScore - a.finalScore)[0];
916
+ logger.info(formatProvenance(topSelected.provenance));
845
917
  }
918
+ console.groupEnd();
846
919
  }
847
- if (!NavigatorImpl) {
848
- throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
920
+ console.groupEnd();
921
+ },
922
+ /**
923
+ * Show all runs in compact format.
924
+ */
925
+ listRuns() {
926
+ if (runHistory.length === 0) {
927
+ logger.info("[Pipeline Debug] No runs captured yet.");
928
+ return;
849
929
  }
850
- return new NavigatorImpl(user, course, strategyData);
851
- }
930
+ console.table(
931
+ runHistory.map((r) => ({
932
+ id: r.runId.slice(-8),
933
+ time: r.timestamp.toLocaleTimeString(),
934
+ course: r.courseName || r.courseId.slice(0, 8),
935
+ generated: r.generatedCount,
936
+ selected: r.finalCount,
937
+ new: r.newSelected,
938
+ reviews: r.reviewsSelected
939
+ }))
940
+ );
941
+ },
852
942
  /**
853
- * Get cards with suitability scores and provenance trails.
854
- *
855
- * **This is the PRIMARY API for navigation strategies.**
856
- *
857
- * Returns cards ranked by suitability score (0-1). Higher scores indicate
858
- * better candidates for presentation. Each card includes a provenance trail
859
- * documenting how strategies contributed to the final score.
860
- *
861
- * ## Implementation Required
862
- * All navigation strategies MUST override this method. The base class does
863
- * not provide a default implementation.
864
- *
865
- * ## For Generators
866
- * Override this method to generate candidates and compute scores based on
867
- * your strategy's logic (e.g., ELO proximity, review urgency). Create the
868
- * initial provenance entry with action='generated'.
869
- *
870
- * ## For Filters
871
- * Filters should implement the CardFilter interface instead and be composed
872
- * via Pipeline. Filters do not directly implement getWeightedCards().
873
- *
874
- * @param limit - Maximum cards to return
875
- * @returns Cards sorted by score descending, with provenance trails
943
+ * Export run history as JSON for bug reports.
876
944
  */
877
- async getWeightedCards(_limit) {
878
- throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
945
+ export() {
946
+ const json = JSON.stringify(runHistory, null, 2);
947
+ logger.info("[Pipeline Debug] Run history exported. Copy the returned string or use:");
948
+ logger.info(" copy(window.skuilder.pipeline.export())");
949
+ return json;
950
+ },
951
+ /**
952
+ * Clear run history.
953
+ */
954
+ clear() {
955
+ runHistory.length = 0;
956
+ logger.info("[Pipeline Debug] Run history cleared.");
957
+ },
958
+ /**
959
+ * Show help.
960
+ */
961
+ help() {
962
+ logger.info(`
963
+ \u{1F527} Pipeline Debug API
964
+
965
+ Commands:
966
+ .showLastRun() Show summary of most recent pipeline run
967
+ .showRun(id|index) Show summary of a specific run (by index or ID suffix)
968
+ .showCard(cardId) Show provenance trail for a specific card
969
+ .explainReviews() Analyze why reviews were/weren't selected
970
+ .listRuns() List all captured runs in table format
971
+ .export() Export run history as JSON for bug reports
972
+ .clear() Clear run history
973
+ .runs Access raw run history array
974
+ .help() Show this help message
975
+
976
+ Example:
977
+ window.skuilder.pipeline.showLastRun()
978
+ window.skuilder.pipeline.showRun(1)
979
+ window.skuilder.pipeline.showCard('abc123')
980
+ `);
879
981
  }
880
982
  };
983
+ mountPipelineDebugger();
881
984
  }
882
985
  });
883
986
 
884
- // src/core/navigators/Pipeline.ts
885
- function logPipelineConfig(generator, filters) {
886
- const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
887
- logger.info(
888
- `[Pipeline] Configuration:
889
- Generator: ${generator.name}
890
- Filters:${filterList}`
891
- );
892
- }
893
- function logTagHydration(cards, tagsByCard) {
894
- const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
895
- const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
896
- logger.debug(
897
- `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
898
- );
899
- }
900
- function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores) {
901
- const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
902
- logger.info(
903
- `[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})`
904
- );
905
- }
906
- function logCardProvenance(cards, maxCards = 3) {
907
- const cardsToLog = cards.slice(0, maxCards);
908
- logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
909
- for (const card of cardsToLog) {
910
- logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
911
- for (const entry of card.provenance) {
912
- const scoreChange = entry.score.toFixed(3);
913
- const action = entry.action.padEnd(9);
914
- logger.debug(
915
- `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
916
- );
917
- }
918
- }
919
- }
920
- var import_common5, Pipeline;
921
- var init_Pipeline = __esm({
922
- "src/core/navigators/Pipeline.ts"() {
923
- "use strict";
924
- import_common5 = require("@vue-skuilder/common");
925
- init_navigators();
926
- init_logger();
927
- Pipeline = class extends ContentNavigator {
928
- generator;
929
- filters;
930
- /**
931
- * Create a new pipeline.
932
- *
933
- * @param generator - The generator (or CompositeGenerator) that produces candidates
934
- * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
935
- * @param user - User database interface
936
- * @param course - Course database interface
937
- */
938
- constructor(generator, filters, user, course) {
939
- super();
940
- this.generator = generator;
941
- this.filters = filters;
942
- this.user = user;
943
- this.course = course;
944
- course.getCourseConfig().then((cfg) => {
945
- logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);
946
- }).catch((e) => {
947
- logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);
948
- });
949
- logPipelineConfig(generator, filters);
950
- }
951
- /**
952
- * Get weighted cards by running generator and applying filters.
953
- *
954
- * 1. Build shared context (user ELO, etc.)
955
- * 2. Get candidates from generator (passing context)
956
- * 3. Batch hydrate tags for all candidates
957
- * 4. Apply each filter sequentially
958
- * 5. Remove zero-score cards
959
- * 6. Sort by score descending
960
- * 7. Return top N
961
- *
962
- * @param limit - Maximum number of cards to return
963
- * @returns Cards sorted by score descending
964
- */
965
- async getWeightedCards(limit) {
966
- const context = await this.buildContext();
967
- const overFetchMultiplier = 2 + this.filters.length * 0.5;
968
- const fetchLimit = Math.ceil(limit * overFetchMultiplier);
969
- logger.debug(
970
- `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
971
- );
972
- let cards = await this.generator.getWeightedCards(fetchLimit, context);
973
- const generatedCount = cards.length;
974
- logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
975
- cards = await this.hydrateTags(cards);
976
- for (const filter of this.filters) {
977
- const beforeCount = cards.length;
978
- cards = await filter.transform(cards, context);
979
- logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeCount} \u2192 ${cards.length} cards`);
980
- }
981
- cards = cards.filter((c) => c.score > 0);
982
- cards.sort((a, b) => b.score - a.score);
983
- const result = cards.slice(0, limit);
984
- const topScores = result.slice(0, 3).map((c) => c.score);
985
- logExecutionSummary(
986
- this.generator.name,
987
- generatedCount,
988
- this.filters.length,
989
- result.length,
990
- topScores
991
- );
992
- logCardProvenance(result, 3);
993
- return result;
994
- }
995
- /**
996
- * Batch hydrate tags for all cards.
997
- *
998
- * Fetches tags for all cards in a single database query and attaches them
999
- * to the WeightedCard objects. Filters can then use card.tags instead of
1000
- * making individual getAppliedTags() calls.
1001
- *
1002
- * @param cards - Cards to hydrate
1003
- * @returns Cards with tags populated
1004
- */
1005
- async hydrateTags(cards) {
1006
- if (cards.length === 0) {
1007
- return cards;
1008
- }
1009
- const cardIds = cards.map((c) => c.cardId);
1010
- const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
1011
- logTagHydration(cards, tagsByCard);
1012
- return cards.map((card) => ({
1013
- ...card,
1014
- tags: tagsByCard.get(card.cardId) ?? []
1015
- }));
1016
- }
1017
- /**
1018
- * Build shared context for generator and filters.
1019
- *
1020
- * Called once per getWeightedCards() invocation.
1021
- * Contains data that the generator and multiple filters might need.
1022
- *
1023
- * The context satisfies both GeneratorContext and FilterContext interfaces.
1024
- */
1025
- async buildContext() {
1026
- let userElo = 1e3;
1027
- try {
1028
- const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1029
- const courseElo = (0, import_common5.toCourseElo)(courseReg.elo);
1030
- userElo = courseElo.global.score;
1031
- } catch (e) {
1032
- logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
1033
- }
1034
- return {
1035
- user: this.user,
1036
- course: this.course,
1037
- userElo
1038
- };
1039
- }
1040
- /**
1041
- * Get the course ID for this pipeline.
1042
- */
1043
- getCourseID() {
1044
- return this.course.getCourseID();
1045
- }
1046
- };
1047
- }
1048
- });
1049
-
1050
- // src/core/navigators/generators/CompositeGenerator.ts
1051
- var DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
1052
- var init_CompositeGenerator = __esm({
1053
- "src/core/navigators/generators/CompositeGenerator.ts"() {
987
+ // src/core/navigators/generators/CompositeGenerator.ts
988
+ var CompositeGenerator_exports = {};
989
+ __export(CompositeGenerator_exports, {
990
+ AggregationMode: () => AggregationMode,
991
+ default: () => CompositeGenerator
992
+ });
993
+ var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
994
+ var init_CompositeGenerator = __esm({
995
+ "src/core/navigators/generators/CompositeGenerator.ts"() {
1054
996
  "use strict";
1055
997
  init_navigators();
1056
998
  init_logger();
999
+ AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
1000
+ AggregationMode2["MAX"] = "max";
1001
+ AggregationMode2["AVERAGE"] = "average";
1002
+ AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
1003
+ return AggregationMode2;
1004
+ })(AggregationMode || {});
1057
1005
  DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
1058
1006
  FREQUENCY_BOOST_FACTOR = 0.1;
1059
1007
  CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
@@ -1104,22 +1052,55 @@ var init_CompositeGenerator = __esm({
1104
1052
  const results = await Promise.all(
1105
1053
  this.generators.map((g) => g.getWeightedCards(limit, context))
1106
1054
  );
1055
+ const generatorSummaries = [];
1056
+ results.forEach((cards, index) => {
1057
+ const gen = this.generators[index];
1058
+ const genName = gen.name || `Generator ${index}`;
1059
+ const newCards = cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
1060
+ const reviewCards = cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
1061
+ if (cards.length > 0) {
1062
+ const topScore = Math.max(...cards.map((c) => c.score)).toFixed(2);
1063
+ const parts = [];
1064
+ if (newCards.length > 0) parts.push(`${newCards.length} new`);
1065
+ if (reviewCards.length > 0) parts.push(`${reviewCards.length} reviews`);
1066
+ const breakdown = parts.length > 0 ? parts.join(", ") : `${cards.length} cards`;
1067
+ generatorSummaries.push(`${genName}: ${breakdown} (top: ${topScore})`);
1068
+ } else {
1069
+ generatorSummaries.push(`${genName}: 0 cards`);
1070
+ }
1071
+ });
1072
+ logger.info(`[Composite] Generator breakdown: ${generatorSummaries.join(" | ")}`);
1107
1073
  const byCardId = /* @__PURE__ */ new Map();
1108
- for (const cards of results) {
1074
+ results.forEach((cards, index) => {
1075
+ const gen = this.generators[index];
1076
+ let weight = gen.learnable?.weight ?? 1;
1077
+ let deviation;
1078
+ if (gen.learnable && !gen.staticWeight && context.orchestration) {
1079
+ const strategyId = gen.strategyId;
1080
+ if (strategyId) {
1081
+ weight = context.orchestration.getEffectiveWeight(strategyId, gen.learnable);
1082
+ deviation = context.orchestration.getDeviation(strategyId);
1083
+ }
1084
+ }
1109
1085
  for (const card of cards) {
1086
+ if (card.provenance.length > 0) {
1087
+ card.provenance[0].effectiveWeight = weight;
1088
+ card.provenance[0].deviation = deviation;
1089
+ }
1110
1090
  const existing = byCardId.get(card.cardId) || [];
1111
- existing.push(card);
1091
+ existing.push({ card, weight });
1112
1092
  byCardId.set(card.cardId, existing);
1113
1093
  }
1114
- }
1094
+ });
1115
1095
  const merged = [];
1116
- for (const [, cards] of byCardId) {
1117
- const aggregatedScore = this.aggregateScores(cards);
1096
+ for (const [, items] of byCardId) {
1097
+ const cards = items.map((i) => i.card);
1098
+ const aggregatedScore = this.aggregateScores(items);
1118
1099
  const finalScore = Math.min(1, aggregatedScore);
1119
1100
  const mergedProvenance = cards.flatMap((c) => c.provenance);
1120
1101
  const initialScore = cards[0].score;
1121
1102
  const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
1122
- const reason = this.buildAggregationReason(cards, finalScore);
1103
+ const reason = this.buildAggregationReason(items, finalScore);
1123
1104
  merged.push({
1124
1105
  ...cards[0],
1125
1106
  score: finalScore,
@@ -1141,22 +1122,26 @@ var init_CompositeGenerator = __esm({
1141
1122
  /**
1142
1123
  * Build human-readable reason for score aggregation.
1143
1124
  */
1144
- buildAggregationReason(cards, finalScore) {
1125
+ buildAggregationReason(items, finalScore) {
1126
+ const cards = items.map((i) => i.card);
1145
1127
  const count = cards.length;
1146
1128
  const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
1147
1129
  if (count === 1) {
1148
- return `Single generator, score ${finalScore.toFixed(2)}`;
1130
+ const weightMsg = Math.abs(items[0].weight - 1) > 1e-3 ? ` (w=${items[0].weight.toFixed(2)})` : "";
1131
+ return `Single generator, score ${finalScore.toFixed(2)}${weightMsg}`;
1149
1132
  }
1150
1133
  const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
1151
1134
  switch (this.aggregationMode) {
1152
1135
  case "max" /* MAX */:
1153
1136
  return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
1154
1137
  case "average" /* AVERAGE */:
1155
- return `Average of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
1138
+ return `Weighted Avg of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
1156
1139
  case "frequencyBoost" /* FREQUENCY_BOOST */: {
1157
- const avg = cards.reduce((sum, c) => sum + c.score, 0) / count;
1140
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
1141
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
1142
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
1158
1143
  const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
1159
- return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
1144
+ return `Frequency boost from ${count} generators (${strategies}): w-avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
1160
1145
  }
1161
1146
  default:
1162
1147
  return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
@@ -1165,16 +1150,22 @@ var init_CompositeGenerator = __esm({
1165
1150
  /**
1166
1151
  * Aggregate scores from multiple generators for the same card.
1167
1152
  */
1168
- aggregateScores(cards) {
1169
- const scores = cards.map((c) => c.score);
1153
+ aggregateScores(items) {
1154
+ const scores = items.map((i) => i.card.score);
1170
1155
  switch (this.aggregationMode) {
1171
1156
  case "max" /* MAX */:
1172
1157
  return Math.max(...scores);
1173
- case "average" /* AVERAGE */:
1174
- return scores.reduce((sum, s) => sum + s, 0) / scores.length;
1158
+ case "average" /* AVERAGE */: {
1159
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
1160
+ if (totalWeight === 0) return 0;
1161
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
1162
+ return weightedSum / totalWeight;
1163
+ }
1175
1164
  case "frequencyBoost" /* FREQUENCY_BOOST */: {
1176
- const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
1177
- const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (cards.length - 1);
1165
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
1166
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
1167
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
1168
+ const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (items.length - 1);
1178
1169
  return avg * frequencyBoost;
1179
1170
  }
1180
1171
  default:
@@ -1185,134 +1176,18 @@ var init_CompositeGenerator = __esm({
1185
1176
  }
1186
1177
  });
1187
1178
 
1188
- // src/core/navigators/PipelineAssembler.ts
1189
- var PipelineAssembler;
1190
- var init_PipelineAssembler = __esm({
1191
- "src/core/navigators/PipelineAssembler.ts"() {
1192
- "use strict";
1193
- init_navigators();
1194
- init_Pipeline();
1195
- init_types_legacy();
1196
- init_logger();
1197
- init_CompositeGenerator();
1198
- PipelineAssembler = class {
1199
- /**
1200
- * Assembles a navigation pipeline from strategy documents.
1201
- *
1202
- * 1. Separates into generators and filters by role
1203
- * 2. Validates at least one generator exists (or creates default ELO)
1204
- * 3. Instantiates generators - wraps multiple in CompositeGenerator
1205
- * 4. Instantiates filters
1206
- * 5. Returns Pipeline(generator, filters)
1207
- *
1208
- * @param input - Strategy documents plus user/course interfaces
1209
- * @returns Assembled pipeline and any warnings
1210
- */
1211
- async assemble(input) {
1212
- const { strategies, user, course } = input;
1213
- const warnings = [];
1214
- if (strategies.length === 0) {
1215
- return {
1216
- pipeline: null,
1217
- generatorStrategies: [],
1218
- filterStrategies: [],
1219
- warnings
1220
- };
1221
- }
1222
- const generatorStrategies = [];
1223
- const filterStrategies = [];
1224
- for (const s of strategies) {
1225
- if (isGenerator(s.implementingClass)) {
1226
- generatorStrategies.push(s);
1227
- } else if (isFilter(s.implementingClass)) {
1228
- filterStrategies.push(s);
1229
- } else {
1230
- warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
1231
- }
1232
- }
1233
- if (generatorStrategies.length === 0) {
1234
- if (filterStrategies.length > 0) {
1235
- logger.debug(
1236
- "[PipelineAssembler] No generator found, using default ELO with configured filters"
1237
- );
1238
- generatorStrategies.push(this.makeDefaultEloStrategy(course.getCourseID()));
1239
- } else {
1240
- warnings.push("No generator strategy found");
1241
- return {
1242
- pipeline: null,
1243
- generatorStrategies: [],
1244
- filterStrategies: [],
1245
- warnings
1246
- };
1247
- }
1248
- }
1249
- let generator;
1250
- if (generatorStrategies.length === 1) {
1251
- const nav = await ContentNavigator.create(user, course, generatorStrategies[0]);
1252
- generator = nav;
1253
- logger.debug(`[PipelineAssembler] Using single generator: ${generatorStrategies[0].name}`);
1254
- } else {
1255
- logger.debug(
1256
- `[PipelineAssembler] Using CompositeGenerator for ${generatorStrategies.length} generators: ${generatorStrategies.map((g) => g.name).join(", ")}`
1257
- );
1258
- generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
1259
- }
1260
- const filters = [];
1261
- const sortedFilterStrategies = [...filterStrategies].sort(
1262
- (a, b) => a.name.localeCompare(b.name)
1263
- );
1264
- for (const filterStrategy of sortedFilterStrategies) {
1265
- try {
1266
- const nav = await ContentNavigator.create(user, course, filterStrategy);
1267
- if ("transform" in nav && typeof nav.transform === "function") {
1268
- filters.push(nav);
1269
- logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
1270
- } else {
1271
- warnings.push(
1272
- `Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
1273
- );
1274
- }
1275
- } catch (e) {
1276
- warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
1277
- }
1278
- }
1279
- const pipeline = new Pipeline(generator, filters, user, course);
1280
- logger.debug(
1281
- `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
1282
- );
1283
- return {
1284
- pipeline,
1285
- generatorStrategies,
1286
- filterStrategies: sortedFilterStrategies,
1287
- warnings
1288
- };
1289
- }
1290
- /**
1291
- * Creates a default ELO generator strategy.
1292
- * Used when filters are configured but no generator is specified.
1293
- */
1294
- makeDefaultEloStrategy(courseId) {
1295
- return {
1296
- _id: "NAVIGATION_STRATEGY-ELO-default",
1297
- course: courseId,
1298
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1299
- name: "ELO (default)",
1300
- description: "Default ELO-based generator",
1301
- implementingClass: "elo" /* ELO */,
1302
- serializedData: ""
1303
- };
1304
- }
1305
- };
1306
- }
1307
- });
1308
-
1309
1179
  // src/core/navigators/generators/elo.ts
1310
- var import_common6, ELONavigator;
1180
+ var elo_exports = {};
1181
+ __export(elo_exports, {
1182
+ default: () => ELONavigator
1183
+ });
1184
+ var import_common5, ELONavigator;
1311
1185
  var init_elo = __esm({
1312
1186
  "src/core/navigators/generators/elo.ts"() {
1313
1187
  "use strict";
1314
1188
  init_navigators();
1315
- import_common6 = require("@vue-skuilder/common");
1189
+ import_common5 = require("@vue-skuilder/common");
1190
+ init_logger();
1316
1191
  ELONavigator = class extends ContentNavigator {
1317
1192
  /** Human-readable name for CardGenerator interface */
1318
1193
  name;
@@ -1341,7 +1216,7 @@ var init_elo = __esm({
1341
1216
  userGlobalElo = context.userElo;
1342
1217
  } else {
1343
1218
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1344
- const userElo = (0, import_common6.toCourseElo)(courseReg.elo);
1219
+ const userElo = (0, import_common5.toCourseElo)(courseReg.elo);
1345
1220
  userGlobalElo = userElo.global.score;
1346
1221
  }
1347
1222
  const activeCards = await this.user.getActiveCards();
@@ -1372,199 +1247,2201 @@ var init_elo = __esm({
1372
1247
  };
1373
1248
  });
1374
1249
  scored.sort((a, b) => b.score - a.score);
1375
- return scored.slice(0, limit);
1250
+ const result = scored.slice(0, limit);
1251
+ if (result.length > 0) {
1252
+ const topScores = result.slice(0, 3).map((c) => c.score.toFixed(2)).join(", ");
1253
+ logger.info(
1254
+ `[ELO] Course ${this.course.getCourseID()}: ${result.length} new cards (top scores: ${topScores})`
1255
+ );
1256
+ } else {
1257
+ logger.info(`[ELO] Course ${this.course.getCourseID()}: No new cards available`);
1258
+ }
1259
+ return result;
1260
+ }
1261
+ };
1262
+ }
1263
+ });
1264
+
1265
+ // src/core/navigators/generators/index.ts
1266
+ var generators_exports = {};
1267
+ var init_generators = __esm({
1268
+ "src/core/navigators/generators/index.ts"() {
1269
+ "use strict";
1270
+ }
1271
+ });
1272
+
1273
+ // src/core/navigators/generators/srs.ts
1274
+ var srs_exports = {};
1275
+ __export(srs_exports, {
1276
+ default: () => SRSNavigator
1277
+ });
1278
+ var import_moment3, DEFAULT_HEALTHY_BACKLOG, MAX_BACKLOG_PRESSURE, SRSNavigator;
1279
+ var init_srs = __esm({
1280
+ "src/core/navigators/generators/srs.ts"() {
1281
+ "use strict";
1282
+ import_moment3 = __toESM(require("moment"), 1);
1283
+ init_navigators();
1284
+ init_logger();
1285
+ DEFAULT_HEALTHY_BACKLOG = 20;
1286
+ MAX_BACKLOG_PRESSURE = 0.5;
1287
+ SRSNavigator = class extends ContentNavigator {
1288
+ /** Human-readable name for CardGenerator interface */
1289
+ name;
1290
+ /** Healthy backlog threshold - when exceeded, backlog pressure kicks in */
1291
+ healthyBacklog;
1292
+ constructor(user, course, strategyData) {
1293
+ super(user, course, strategyData);
1294
+ this.name = strategyData?.name || "SRS";
1295
+ const config = this.parseConfig(strategyData?.serializedData);
1296
+ this.healthyBacklog = config.healthyBacklog ?? DEFAULT_HEALTHY_BACKLOG;
1297
+ }
1298
+ /**
1299
+ * Parse configuration from serialized JSON.
1300
+ */
1301
+ parseConfig(serializedData) {
1302
+ if (!serializedData) return {};
1303
+ try {
1304
+ return JSON.parse(serializedData);
1305
+ } catch {
1306
+ logger.warn("[SRS] Failed to parse strategy config, using defaults");
1307
+ return {};
1308
+ }
1309
+ }
1310
+ /**
1311
+ * Get review cards scored by urgency.
1312
+ *
1313
+ * Score formula combines:
1314
+ * - Relative overdueness: hoursOverdue / intervalHours
1315
+ * - Interval recency: exponential decay favoring shorter intervals
1316
+ * - Backlog pressure: boost when due reviews exceed healthy threshold
1317
+ *
1318
+ * Cards not yet due are excluded (not scored as 0).
1319
+ *
1320
+ * This method supports both the legacy signature (limit only) and the
1321
+ * CardGenerator interface signature (limit, context).
1322
+ *
1323
+ * @param limit - Maximum number of cards to return
1324
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1325
+ */
1326
+ async getWeightedCards(limit, _context) {
1327
+ if (!this.user || !this.course) {
1328
+ throw new Error("SRSNavigator requires user and course to be set");
1329
+ }
1330
+ const courseId = this.course.getCourseID();
1331
+ const reviews = await this.user.getPendingReviews(courseId);
1332
+ const now = import_moment3.default.utc();
1333
+ const dueReviews = reviews.filter((r) => now.isAfter(import_moment3.default.utc(r.reviewTime)));
1334
+ const backlogPressure = this.computeBacklogPressure(dueReviews.length);
1335
+ if (dueReviews.length > 0) {
1336
+ const pressureNote = backlogPressure > 0 ? ` [backlog pressure: +${backlogPressure.toFixed(2)}]` : ` [healthy backlog]`;
1337
+ logger.info(
1338
+ `[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)${pressureNote}`
1339
+ );
1340
+ } else if (reviews.length > 0) {
1341
+ const sortedByDue = [...reviews].sort(
1342
+ (a, b) => import_moment3.default.utc(a.reviewTime).diff(import_moment3.default.utc(b.reviewTime))
1343
+ );
1344
+ const nextDue = sortedByDue[0];
1345
+ const nextDueTime = import_moment3.default.utc(nextDue.reviewTime);
1346
+ const untilDue = import_moment3.default.duration(nextDueTime.diff(now));
1347
+ const untilDueStr = untilDue.asHours() < 1 ? `${Math.round(untilDue.asMinutes())}m` : untilDue.asHours() < 24 ? `${Math.round(untilDue.asHours())}h` : `${Math.round(untilDue.asDays())}d`;
1348
+ logger.info(
1349
+ `[SRS] Course ${courseId}: 0 reviews due now (${reviews.length} scheduled, next in ${untilDueStr})`
1350
+ );
1351
+ } else {
1352
+ logger.info(`[SRS] Course ${courseId}: No reviews scheduled`);
1353
+ }
1354
+ const scored = dueReviews.map((review) => {
1355
+ const { score, reason } = this.computeUrgencyScore(review, now, backlogPressure);
1356
+ return {
1357
+ cardId: review.cardId,
1358
+ courseId: review.courseId,
1359
+ score,
1360
+ reviewID: review._id,
1361
+ provenance: [
1362
+ {
1363
+ strategy: "srs",
1364
+ strategyName: this.strategyName || this.name,
1365
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1366
+ action: "generated",
1367
+ score,
1368
+ reason
1369
+ }
1370
+ ]
1371
+ };
1372
+ });
1373
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1374
+ }
1375
+ /**
1376
+ * Compute backlog pressure based on number of due reviews.
1377
+ *
1378
+ * Backlog pressure is 0 when at or below healthy threshold,
1379
+ * and increases linearly above it, maxing out at MAX_BACKLOG_PRESSURE.
1380
+ *
1381
+ * Examples (with default healthyBacklog=20):
1382
+ * - 10 due reviews → 0.00 (healthy)
1383
+ * - 20 due reviews → 0.00 (at threshold)
1384
+ * - 40 due reviews → 0.25 (2x threshold)
1385
+ * - 60 due reviews → 0.50 (3x threshold, maxed)
1386
+ *
1387
+ * @param dueCount - Number of reviews currently due
1388
+ * @returns Backlog pressure score to add to urgency (0 to MAX_BACKLOG_PRESSURE)
1389
+ */
1390
+ computeBacklogPressure(dueCount) {
1391
+ if (dueCount <= this.healthyBacklog) {
1392
+ return 0;
1393
+ }
1394
+ const excess = dueCount - this.healthyBacklog;
1395
+ const pressure = excess / this.healthyBacklog * (MAX_BACKLOG_PRESSURE / 2);
1396
+ return Math.min(MAX_BACKLOG_PRESSURE, pressure);
1397
+ }
1398
+ /**
1399
+ * Compute urgency score for a review card.
1400
+ *
1401
+ * Three factors:
1402
+ * 1. Relative overdueness = hoursOverdue / intervalHours
1403
+ * - 2 days overdue on 3-day interval = 0.67 (urgent)
1404
+ * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1405
+ *
1406
+ * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1407
+ * - 24h interval → ~1.0 (very recent learning)
1408
+ * - 30 days (720h) → ~0.56
1409
+ * - 180 days → ~0.30
1410
+ *
1411
+ * 3. Backlog pressure = global boost when review backlog exceeds healthy threshold
1412
+ * - At healthy backlog: 0
1413
+ * - At 2x healthy: +0.25
1414
+ * - At 3x+ healthy: +0.50 (max)
1415
+ *
1416
+ * Combined: base 0.5 + (urgency factors * 0.45) + backlog pressure
1417
+ * Result range: 0.5 to 1.0 (uncapped to allow high-urgency reviews to compete with new cards)
1418
+ *
1419
+ * @param review - The scheduled card to score
1420
+ * @param now - Current time
1421
+ * @param backlogPressure - Pre-computed backlog pressure (0 to 0.5)
1422
+ */
1423
+ computeUrgencyScore(review, now, backlogPressure) {
1424
+ const scheduledAt = import_moment3.default.utc(review.scheduledAt);
1425
+ const due = import_moment3.default.utc(review.reviewTime);
1426
+ const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1427
+ const hoursOverdue = now.diff(due, "hours");
1428
+ const relativeOverdue = hoursOverdue / intervalHours;
1429
+ const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1430
+ const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1431
+ const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1432
+ const baseScore = 0.5 + urgency * 0.45;
1433
+ const score = Math.min(1, baseScore + backlogPressure);
1434
+ const reasonParts = [
1435
+ `${Math.round(hoursOverdue)}h overdue`,
1436
+ `interval: ${Math.round(intervalHours)}h`,
1437
+ `relative: ${relativeOverdue.toFixed(2)}`,
1438
+ `recency: ${recencyFactor.toFixed(2)}`
1439
+ ];
1440
+ if (backlogPressure > 0) {
1441
+ reasonParts.push(`backlog: +${backlogPressure.toFixed(2)}`);
1442
+ }
1443
+ reasonParts.push("review");
1444
+ const reason = reasonParts.join(", ");
1445
+ return { score, reason };
1446
+ }
1447
+ };
1448
+ }
1449
+ });
1450
+
1451
+ // src/core/navigators/generators/types.ts
1452
+ var types_exports = {};
1453
+ var init_types = __esm({
1454
+ "src/core/navigators/generators/types.ts"() {
1455
+ "use strict";
1456
+ }
1457
+ });
1458
+
1459
+ // import("./generators/**/*") in src/core/navigators/index.ts
1460
+ var globImport_generators;
1461
+ var init_ = __esm({
1462
+ 'import("./generators/**/*") in src/core/navigators/index.ts'() {
1463
+ globImport_generators = __glob({
1464
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
1465
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
1466
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
1467
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
1468
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports))
1469
+ });
1470
+ }
1471
+ });
1472
+
1473
+ // src/core/types/contentNavigationStrategy.ts
1474
+ var DEFAULT_LEARNABLE_WEIGHT;
1475
+ var init_contentNavigationStrategy = __esm({
1476
+ "src/core/types/contentNavigationStrategy.ts"() {
1477
+ "use strict";
1478
+ DEFAULT_LEARNABLE_WEIGHT = {
1479
+ weight: 1,
1480
+ confidence: 0.1,
1481
+ // Low confidence initially = wide exploration
1482
+ sampleSize: 0
1483
+ };
1484
+ }
1485
+ });
1486
+
1487
+ // src/core/navigators/filters/WeightedFilter.ts
1488
+ var WeightedFilter_exports = {};
1489
+ __export(WeightedFilter_exports, {
1490
+ WeightedFilter: () => WeightedFilter
1491
+ });
1492
+ var WeightedFilter;
1493
+ var init_WeightedFilter = __esm({
1494
+ "src/core/navigators/filters/WeightedFilter.ts"() {
1495
+ "use strict";
1496
+ init_contentNavigationStrategy();
1497
+ WeightedFilter = class {
1498
+ name;
1499
+ inner;
1500
+ learnable;
1501
+ staticWeight;
1502
+ strategyId;
1503
+ constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
1504
+ this.inner = inner;
1505
+ this.name = inner.name;
1506
+ this.learnable = learnable;
1507
+ this.staticWeight = staticWeight;
1508
+ this.strategyId = strategyId;
1509
+ }
1510
+ /**
1511
+ * Apply the inner filter, then scale its effect by the configured weight.
1512
+ */
1513
+ async transform(cards, context) {
1514
+ let effectiveWeight = this.learnable.weight;
1515
+ let deviation;
1516
+ if (!this.staticWeight && context.orchestration) {
1517
+ const strategyId = this.strategyId || this.inner.strategyId || this.name;
1518
+ effectiveWeight = context.orchestration.getEffectiveWeight(strategyId, this.learnable);
1519
+ deviation = context.orchestration.getDeviation(strategyId);
1520
+ }
1521
+ if (Math.abs(effectiveWeight - 1) < 1e-3) {
1522
+ return this.inner.transform(cards, context);
1523
+ }
1524
+ const originalScores = /* @__PURE__ */ new Map();
1525
+ for (const card of cards) {
1526
+ originalScores.set(card.cardId, card.score);
1527
+ }
1528
+ const transformedCards = await this.inner.transform(cards, context);
1529
+ return transformedCards.map((card) => {
1530
+ const originalScore = originalScores.get(card.cardId);
1531
+ if (originalScore === void 0 || originalScore === 0 || card.score === 0) {
1532
+ return card;
1533
+ }
1534
+ const rawEffect = card.score / originalScore;
1535
+ if (Math.abs(rawEffect - 1) < 1e-4) {
1536
+ return card;
1537
+ }
1538
+ const weightedEffect = Math.pow(rawEffect, effectiveWeight);
1539
+ const newScore = originalScore * weightedEffect;
1540
+ const lastProvIndex = card.provenance.length - 1;
1541
+ const lastProv = card.provenance[lastProvIndex];
1542
+ if (lastProv) {
1543
+ const updatedProvenance = [...card.provenance];
1544
+ updatedProvenance[lastProvIndex] = {
1545
+ ...lastProv,
1546
+ score: newScore,
1547
+ effectiveWeight,
1548
+ deviation
1549
+ // We can optionally append to the reason, but the structured field is key
1550
+ };
1551
+ return {
1552
+ ...card,
1553
+ score: newScore,
1554
+ provenance: updatedProvenance
1555
+ };
1556
+ }
1557
+ return {
1558
+ ...card,
1559
+ score: newScore
1560
+ };
1561
+ });
1562
+ }
1563
+ };
1564
+ }
1565
+ });
1566
+
1567
+ // src/core/navigators/filters/eloDistance.ts
1568
+ var eloDistance_exports = {};
1569
+ __export(eloDistance_exports, {
1570
+ DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1571
+ DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1572
+ DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1573
+ createEloDistanceFilter: () => createEloDistanceFilter
1574
+ });
1575
+ function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1576
+ const normalizedDistance = distance / halfLife;
1577
+ const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1578
+ return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1579
+ }
1580
+ function createEloDistanceFilter(config) {
1581
+ const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1582
+ const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1583
+ const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1584
+ return {
1585
+ name: "ELO Distance Filter",
1586
+ async transform(cards, context) {
1587
+ const { course, userElo } = context;
1588
+ const cardIds = cards.map((c) => c.cardId);
1589
+ const cardElos = await course.getCardEloData(cardIds);
1590
+ return cards.map((card, i) => {
1591
+ const cardElo = cardElos[i]?.global?.score ?? 1e3;
1592
+ const distance = Math.abs(cardElo - userElo);
1593
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1594
+ const newScore = card.score * multiplier;
1595
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1596
+ return {
1597
+ ...card,
1598
+ score: newScore,
1599
+ provenance: [
1600
+ ...card.provenance,
1601
+ {
1602
+ strategy: "eloDistance",
1603
+ strategyName: "ELO Distance Filter",
1604
+ strategyId: "ELO_DISTANCE_FILTER",
1605
+ action,
1606
+ score: newScore,
1607
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1608
+ }
1609
+ ]
1610
+ };
1611
+ });
1612
+ }
1613
+ };
1614
+ }
1615
+ var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1616
+ var init_eloDistance = __esm({
1617
+ "src/core/navigators/filters/eloDistance.ts"() {
1618
+ "use strict";
1619
+ DEFAULT_HALF_LIFE = 200;
1620
+ DEFAULT_MIN_MULTIPLIER = 0.3;
1621
+ DEFAULT_MAX_MULTIPLIER = 1;
1622
+ }
1623
+ });
1624
+
1625
+ // src/core/navigators/filters/hierarchyDefinition.ts
1626
+ var hierarchyDefinition_exports = {};
1627
+ __export(hierarchyDefinition_exports, {
1628
+ default: () => HierarchyDefinitionNavigator
1629
+ });
1630
+ var import_common6, DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1631
+ var init_hierarchyDefinition = __esm({
1632
+ "src/core/navigators/filters/hierarchyDefinition.ts"() {
1633
+ "use strict";
1634
+ init_navigators();
1635
+ import_common6 = require("@vue-skuilder/common");
1636
+ DEFAULT_MIN_COUNT = 3;
1637
+ HierarchyDefinitionNavigator = class extends ContentNavigator {
1638
+ config;
1639
+ /** Human-readable name for CardFilter interface */
1640
+ name;
1641
+ constructor(user, course, strategyData) {
1642
+ super(user, course, strategyData);
1643
+ this.config = this.parseConfig(strategyData.serializedData);
1644
+ this.name = strategyData.name || "Hierarchy Definition";
1645
+ }
1646
+ parseConfig(serializedData) {
1647
+ try {
1648
+ const parsed = JSON.parse(serializedData);
1649
+ return {
1650
+ prerequisites: parsed.prerequisites || {}
1651
+ };
1652
+ } catch {
1653
+ return {
1654
+ prerequisites: {}
1655
+ };
1656
+ }
1657
+ }
1658
+ /**
1659
+ * Check if a specific prerequisite is satisfied
1660
+ */
1661
+ isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1662
+ if (!userTagElo) return false;
1663
+ const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1664
+ if (userTagElo.count < minCount) return false;
1665
+ if (prereq.masteryThreshold?.minElo !== void 0) {
1666
+ return userTagElo.score >= prereq.masteryThreshold.minElo;
1667
+ } else {
1668
+ return userTagElo.score >= userGlobalElo;
1669
+ }
1670
+ }
1671
+ /**
1672
+ * Get the set of tags the user has mastered.
1673
+ * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1674
+ */
1675
+ async getMasteredTags(context) {
1676
+ const mastered = /* @__PURE__ */ new Set();
1677
+ try {
1678
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1679
+ const userElo = (0, import_common6.toCourseElo)(courseReg.elo);
1680
+ for (const prereqs of Object.values(this.config.prerequisites)) {
1681
+ for (const prereq of prereqs) {
1682
+ const tagElo = userElo.tags[prereq.tag];
1683
+ if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1684
+ mastered.add(prereq.tag);
1685
+ }
1686
+ }
1687
+ }
1688
+ } catch {
1689
+ }
1690
+ return mastered;
1691
+ }
1692
+ /**
1693
+ * Get the set of tags that are unlocked (prerequisites met)
1694
+ */
1695
+ getUnlockedTags(masteredTags) {
1696
+ const unlocked = /* @__PURE__ */ new Set();
1697
+ for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1698
+ const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1699
+ if (allPrereqsMet) {
1700
+ unlocked.add(tagId);
1701
+ }
1702
+ }
1703
+ return unlocked;
1704
+ }
1705
+ /**
1706
+ * Check if a tag has prerequisites defined in config
1707
+ */
1708
+ hasPrerequisites(tagId) {
1709
+ return tagId in this.config.prerequisites;
1710
+ }
1711
+ /**
1712
+ * Check if a card is unlocked and generate reason.
1713
+ */
1714
+ async checkCardUnlock(card, _course, unlockedTags, masteredTags) {
1715
+ try {
1716
+ const cardTags = card.tags ?? [];
1717
+ const lockedTags = cardTags.filter(
1718
+ (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1719
+ );
1720
+ if (lockedTags.length === 0) {
1721
+ const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1722
+ return {
1723
+ isUnlocked: true,
1724
+ reason: `Prerequisites met, tags: ${tagList}`
1725
+ };
1726
+ }
1727
+ const missingPrereqs = lockedTags.flatMap((tag) => {
1728
+ const prereqs = this.config.prerequisites[tag] || [];
1729
+ return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1730
+ });
1731
+ return {
1732
+ isUnlocked: false,
1733
+ reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1734
+ };
1735
+ } catch {
1736
+ return {
1737
+ isUnlocked: true,
1738
+ reason: "Prerequisites check skipped (tag lookup failed)"
1739
+ };
1740
+ }
1741
+ }
1742
+ /**
1743
+ * CardFilter.transform implementation.
1744
+ *
1745
+ * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1746
+ */
1747
+ async transform(cards, context) {
1748
+ const masteredTags = await this.getMasteredTags(context);
1749
+ const unlockedTags = this.getUnlockedTags(masteredTags);
1750
+ const gated = [];
1751
+ for (const card of cards) {
1752
+ const { isUnlocked, reason } = await this.checkCardUnlock(
1753
+ card,
1754
+ context.course,
1755
+ unlockedTags,
1756
+ masteredTags
1757
+ );
1758
+ const finalScore = isUnlocked ? card.score : 0;
1759
+ const action = isUnlocked ? "passed" : "penalized";
1760
+ gated.push({
1761
+ ...card,
1762
+ score: finalScore,
1763
+ provenance: [
1764
+ ...card.provenance,
1765
+ {
1766
+ strategy: "hierarchyDefinition",
1767
+ strategyName: this.strategyName || this.name,
1768
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1769
+ action,
1770
+ score: finalScore,
1771
+ reason
1772
+ }
1773
+ ]
1774
+ });
1775
+ }
1776
+ return gated;
1777
+ }
1778
+ /**
1779
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1780
+ *
1781
+ * Use transform() via Pipeline instead.
1782
+ */
1783
+ async getWeightedCards(_limit) {
1784
+ throw new Error(
1785
+ "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1786
+ );
1787
+ }
1788
+ };
1789
+ }
1790
+ });
1791
+
1792
+ // src/core/navigators/filters/userTagPreference.ts
1793
+ var userTagPreference_exports = {};
1794
+ __export(userTagPreference_exports, {
1795
+ default: () => UserTagPreferenceFilter
1796
+ });
1797
+ var UserTagPreferenceFilter;
1798
+ var init_userTagPreference = __esm({
1799
+ "src/core/navigators/filters/userTagPreference.ts"() {
1800
+ "use strict";
1801
+ init_navigators();
1802
+ UserTagPreferenceFilter = class extends ContentNavigator {
1803
+ _strategyData;
1804
+ /** Human-readable name for CardFilter interface */
1805
+ name;
1806
+ constructor(user, course, strategyData) {
1807
+ super(user, course, strategyData);
1808
+ this._strategyData = strategyData;
1809
+ this.name = strategyData.name || "User Tag Preferences";
1810
+ }
1811
+ /**
1812
+ * Compute multiplier for a card based on its tags and user preferences.
1813
+ * Returns the maximum multiplier among all matching tags, or 1.0 if no matches.
1814
+ */
1815
+ computeMultiplier(cardTags, boostMap) {
1816
+ const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== void 0);
1817
+ if (multipliers.length === 0) {
1818
+ return 1;
1819
+ }
1820
+ return Math.max(...multipliers);
1821
+ }
1822
+ /**
1823
+ * Build human-readable reason for the filter's decision.
1824
+ */
1825
+ buildReason(cardTags, boostMap, multiplier) {
1826
+ const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);
1827
+ if (multiplier === 0) {
1828
+ return `Excluded by user preference: ${matchingTags.join(", ")} (${multiplier}x)`;
1829
+ }
1830
+ if (multiplier < 1) {
1831
+ return `Penalized by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1832
+ }
1833
+ if (multiplier > 1) {
1834
+ return `Boosted by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1835
+ }
1836
+ return "No matching user preferences";
1837
+ }
1838
+ /**
1839
+ * CardFilter.transform implementation.
1840
+ *
1841
+ * Apply user tag preferences:
1842
+ * 1. Read preferences from strategy state
1843
+ * 2. If no preferences, pass through unchanged
1844
+ * 3. For each card:
1845
+ * - Look up tag in boost record
1846
+ * - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)
1847
+ * - If multiple tags match: use max multiplier
1848
+ * - Append provenance with clear reason
1849
+ */
1850
+ async transform(cards, _context) {
1851
+ const prefs = await this.getStrategyState();
1852
+ if (!prefs || Object.keys(prefs.boost).length === 0) {
1853
+ return cards.map((card) => ({
1854
+ ...card,
1855
+ provenance: [
1856
+ ...card.provenance,
1857
+ {
1858
+ strategy: "userTagPreference",
1859
+ strategyName: this.strategyName || this.name,
1860
+ strategyId: this.strategyId || this._strategyData._id,
1861
+ action: "passed",
1862
+ score: card.score,
1863
+ reason: "No user tag preferences configured"
1864
+ }
1865
+ ]
1866
+ }));
1867
+ }
1868
+ const adjusted = await Promise.all(
1869
+ cards.map(async (card) => {
1870
+ const cardTags = card.tags ?? [];
1871
+ const multiplier = this.computeMultiplier(cardTags, prefs.boost);
1872
+ const finalScore = Math.min(1, card.score * multiplier);
1873
+ let action;
1874
+ if (multiplier === 0 || multiplier < 1) {
1875
+ action = "penalized";
1876
+ } else if (multiplier > 1) {
1877
+ action = "boosted";
1878
+ } else {
1879
+ action = "passed";
1880
+ }
1881
+ return {
1882
+ ...card,
1883
+ score: finalScore,
1884
+ provenance: [
1885
+ ...card.provenance,
1886
+ {
1887
+ strategy: "userTagPreference",
1888
+ strategyName: this.strategyName || this.name,
1889
+ strategyId: this.strategyId || this._strategyData._id,
1890
+ action,
1891
+ score: finalScore,
1892
+ reason: this.buildReason(cardTags, prefs.boost, multiplier)
1893
+ }
1894
+ ]
1895
+ };
1896
+ })
1897
+ );
1898
+ return adjusted;
1899
+ }
1900
+ /**
1901
+ * Legacy getWeightedCards - throws as filters should not be used as generators.
1902
+ */
1903
+ async getWeightedCards(_limit) {
1904
+ throw new Error(
1905
+ "UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1906
+ );
1907
+ }
1908
+ };
1909
+ }
1910
+ });
1911
+
1912
+ // src/core/navigators/filters/index.ts
1913
+ var filters_exports = {};
1914
+ __export(filters_exports, {
1915
+ UserTagPreferenceFilter: () => UserTagPreferenceFilter,
1916
+ createEloDistanceFilter: () => createEloDistanceFilter
1917
+ });
1918
+ var init_filters = __esm({
1919
+ "src/core/navigators/filters/index.ts"() {
1920
+ "use strict";
1921
+ init_eloDistance();
1922
+ init_userTagPreference();
1923
+ }
1924
+ });
1925
+
1926
+ // src/core/navigators/filters/inferredPreferenceStub.ts
1927
+ var inferredPreferenceStub_exports = {};
1928
+ __export(inferredPreferenceStub_exports, {
1929
+ INFERRED_PREFERENCE_NAVIGATOR_STUB: () => INFERRED_PREFERENCE_NAVIGATOR_STUB
1930
+ });
1931
+ var INFERRED_PREFERENCE_NAVIGATOR_STUB;
1932
+ var init_inferredPreferenceStub = __esm({
1933
+ "src/core/navigators/filters/inferredPreferenceStub.ts"() {
1934
+ "use strict";
1935
+ INFERRED_PREFERENCE_NAVIGATOR_STUB = true;
1936
+ }
1937
+ });
1938
+
1939
+ // src/core/navigators/filters/interferenceMitigator.ts
1940
+ var interferenceMitigator_exports = {};
1941
+ __export(interferenceMitigator_exports, {
1942
+ default: () => InterferenceMitigatorNavigator
1943
+ });
1944
+ var import_common7, DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1945
+ var init_interferenceMitigator = __esm({
1946
+ "src/core/navigators/filters/interferenceMitigator.ts"() {
1947
+ "use strict";
1948
+ init_navigators();
1949
+ import_common7 = require("@vue-skuilder/common");
1950
+ DEFAULT_MIN_COUNT2 = 10;
1951
+ DEFAULT_MIN_ELAPSED_DAYS = 3;
1952
+ DEFAULT_INTERFERENCE_DECAY = 0.8;
1953
+ InterferenceMitigatorNavigator = class extends ContentNavigator {
1954
+ config;
1955
+ /** Human-readable name for CardFilter interface */
1956
+ name;
1957
+ /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1958
+ interferenceMap;
1959
+ constructor(user, course, strategyData) {
1960
+ super(user, course, strategyData);
1961
+ this.config = this.parseConfig(strategyData.serializedData);
1962
+ this.interferenceMap = this.buildInterferenceMap();
1963
+ this.name = strategyData.name || "Interference Mitigator";
1964
+ }
1965
+ parseConfig(serializedData) {
1966
+ try {
1967
+ const parsed = JSON.parse(serializedData);
1968
+ let sets = parsed.interferenceSets || [];
1969
+ if (sets.length > 0 && Array.isArray(sets[0])) {
1970
+ sets = sets.map((tags) => ({ tags }));
1971
+ }
1972
+ return {
1973
+ interferenceSets: sets,
1974
+ maturityThreshold: {
1975
+ minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1976
+ minElo: parsed.maturityThreshold?.minElo,
1977
+ minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1978
+ },
1979
+ defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1980
+ };
1981
+ } catch {
1982
+ return {
1983
+ interferenceSets: [],
1984
+ maturityThreshold: {
1985
+ minCount: DEFAULT_MIN_COUNT2,
1986
+ minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1987
+ },
1988
+ defaultDecay: DEFAULT_INTERFERENCE_DECAY
1989
+ };
1990
+ }
1991
+ }
1992
+ /**
1993
+ * Build a map from each tag to its interference partners with decay coefficients.
1994
+ * If tags A, B, C are in an interference group with decay 0.8, then:
1995
+ * - A interferes with B (decay 0.8) and C (decay 0.8)
1996
+ * - B interferes with A (decay 0.8) and C (decay 0.8)
1997
+ * - etc.
1998
+ */
1999
+ buildInterferenceMap() {
2000
+ const map = /* @__PURE__ */ new Map();
2001
+ for (const group of this.config.interferenceSets) {
2002
+ const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
2003
+ for (const tag of group.tags) {
2004
+ if (!map.has(tag)) {
2005
+ map.set(tag, []);
2006
+ }
2007
+ const partners = map.get(tag);
2008
+ for (const other of group.tags) {
2009
+ if (other !== tag) {
2010
+ const existing = partners.find((p) => p.partner === other);
2011
+ if (existing) {
2012
+ existing.decay = Math.max(existing.decay, decay);
2013
+ } else {
2014
+ partners.push({ partner: other, decay });
2015
+ }
2016
+ }
2017
+ }
2018
+ }
2019
+ }
2020
+ return map;
2021
+ }
2022
+ /**
2023
+ * Get the set of tags that are currently immature for this user.
2024
+ * A tag is immature if the user has interacted with it but hasn't
2025
+ * reached the maturity threshold.
2026
+ */
2027
+ async getImmatureTags(context) {
2028
+ const immature = /* @__PURE__ */ new Set();
2029
+ try {
2030
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
2031
+ const userElo = (0, import_common7.toCourseElo)(courseReg.elo);
2032
+ const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
2033
+ const minElo = this.config.maturityThreshold?.minElo;
2034
+ const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
2035
+ const minCountForElapsed = minElapsedDays * 2;
2036
+ for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
2037
+ if (tagElo.count === 0) continue;
2038
+ const belowCount = tagElo.count < minCount;
2039
+ const belowElo = minElo !== void 0 && tagElo.score < minElo;
2040
+ const belowElapsed = tagElo.count < minCountForElapsed;
2041
+ if (belowCount || belowElo || belowElapsed) {
2042
+ immature.add(tagId);
2043
+ }
2044
+ }
2045
+ } catch {
2046
+ }
2047
+ return immature;
2048
+ }
2049
+ /**
2050
+ * Get all tags that interfere with any immature tag, along with their decay coefficients.
2051
+ * These are the tags we want to avoid introducing.
2052
+ */
2053
+ getTagsToAvoid(immatureTags) {
2054
+ const avoid = /* @__PURE__ */ new Map();
2055
+ for (const immatureTag of immatureTags) {
2056
+ const partners = this.interferenceMap.get(immatureTag);
2057
+ if (partners) {
2058
+ for (const { partner, decay } of partners) {
2059
+ if (!immatureTags.has(partner)) {
2060
+ const existing = avoid.get(partner) ?? 0;
2061
+ avoid.set(partner, Math.max(existing, decay));
2062
+ }
2063
+ }
2064
+ }
2065
+ }
2066
+ return avoid;
2067
+ }
2068
+ /**
2069
+ * Compute interference score reduction for a card.
2070
+ * Returns: { multiplier, interfering tags, reason }
2071
+ */
2072
+ computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
2073
+ if (tagsToAvoid.size === 0) {
2074
+ return {
2075
+ multiplier: 1,
2076
+ interferingTags: [],
2077
+ reason: "No interference detected"
2078
+ };
2079
+ }
2080
+ let multiplier = 1;
2081
+ const interferingTags = [];
2082
+ for (const tag of cardTags) {
2083
+ const decay = tagsToAvoid.get(tag);
2084
+ if (decay !== void 0) {
2085
+ interferingTags.push(tag);
2086
+ multiplier *= 1 - decay;
2087
+ }
2088
+ }
2089
+ if (interferingTags.length === 0) {
2090
+ return {
2091
+ multiplier: 1,
2092
+ interferingTags: [],
2093
+ reason: "No interference detected"
2094
+ };
2095
+ }
2096
+ const causingTags = /* @__PURE__ */ new Set();
2097
+ for (const tag of interferingTags) {
2098
+ for (const immatureTag of immatureTags) {
2099
+ const partners = this.interferenceMap.get(immatureTag);
2100
+ if (partners?.some((p) => p.partner === tag)) {
2101
+ causingTags.add(immatureTag);
2102
+ }
2103
+ }
2104
+ }
2105
+ const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
2106
+ return { multiplier, interferingTags, reason };
2107
+ }
2108
+ /**
2109
+ * CardFilter.transform implementation.
2110
+ *
2111
+ * Apply interference-aware scoring. Cards with tags that interfere with
2112
+ * immature learnings get reduced scores.
2113
+ */
2114
+ async transform(cards, context) {
2115
+ const immatureTags = await this.getImmatureTags(context);
2116
+ const tagsToAvoid = this.getTagsToAvoid(immatureTags);
2117
+ const adjusted = [];
2118
+ for (const card of cards) {
2119
+ const cardTags = card.tags ?? [];
2120
+ const { multiplier, reason } = this.computeInterferenceEffect(
2121
+ cardTags,
2122
+ tagsToAvoid,
2123
+ immatureTags
2124
+ );
2125
+ const finalScore = card.score * multiplier;
2126
+ const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
2127
+ adjusted.push({
2128
+ ...card,
2129
+ score: finalScore,
2130
+ provenance: [
2131
+ ...card.provenance,
2132
+ {
2133
+ strategy: "interferenceMitigator",
2134
+ strategyName: this.strategyName || this.name,
2135
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
2136
+ action,
2137
+ score: finalScore,
2138
+ reason
2139
+ }
2140
+ ]
2141
+ });
2142
+ }
2143
+ return adjusted;
2144
+ }
2145
+ /**
2146
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
2147
+ *
2148
+ * Use transform() via Pipeline instead.
2149
+ */
2150
+ async getWeightedCards(_limit) {
2151
+ throw new Error(
2152
+ "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
2153
+ );
2154
+ }
2155
+ };
2156
+ }
2157
+ });
2158
+
2159
+ // src/core/navigators/filters/relativePriority.ts
2160
+ var relativePriority_exports = {};
2161
+ __export(relativePriority_exports, {
2162
+ default: () => RelativePriorityNavigator
2163
+ });
2164
+ var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
2165
+ var init_relativePriority = __esm({
2166
+ "src/core/navigators/filters/relativePriority.ts"() {
2167
+ "use strict";
2168
+ init_navigators();
2169
+ DEFAULT_PRIORITY = 0.5;
2170
+ DEFAULT_PRIORITY_INFLUENCE = 0.5;
2171
+ DEFAULT_COMBINE_MODE = "max";
2172
+ RelativePriorityNavigator = class extends ContentNavigator {
2173
+ config;
2174
+ /** Human-readable name for CardFilter interface */
2175
+ name;
2176
+ constructor(user, course, strategyData) {
2177
+ super(user, course, strategyData);
2178
+ this.config = this.parseConfig(strategyData.serializedData);
2179
+ this.name = strategyData.name || "Relative Priority";
2180
+ }
2181
+ parseConfig(serializedData) {
2182
+ try {
2183
+ const parsed = JSON.parse(serializedData);
2184
+ return {
2185
+ tagPriorities: parsed.tagPriorities || {},
2186
+ defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
2187
+ combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
2188
+ priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
2189
+ };
2190
+ } catch {
2191
+ return {
2192
+ tagPriorities: {},
2193
+ defaultPriority: DEFAULT_PRIORITY,
2194
+ combineMode: DEFAULT_COMBINE_MODE,
2195
+ priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
2196
+ };
2197
+ }
2198
+ }
2199
+ /**
2200
+ * Look up the priority for a tag.
2201
+ */
2202
+ getTagPriority(tagId) {
2203
+ return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
2204
+ }
2205
+ /**
2206
+ * Compute combined priority for a card based on its tags.
2207
+ */
2208
+ computeCardPriority(cardTags) {
2209
+ if (cardTags.length === 0) {
2210
+ return this.config.defaultPriority ?? DEFAULT_PRIORITY;
2211
+ }
2212
+ const priorities = cardTags.map((tag) => this.getTagPriority(tag));
2213
+ switch (this.config.combineMode) {
2214
+ case "max":
2215
+ return Math.max(...priorities);
2216
+ case "min":
2217
+ return Math.min(...priorities);
2218
+ case "average":
2219
+ return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
2220
+ default:
2221
+ return Math.max(...priorities);
2222
+ }
2223
+ }
2224
+ /**
2225
+ * Compute boost factor based on priority.
2226
+ *
2227
+ * The formula: 1 + (priority - 0.5) * priorityInfluence
2228
+ *
2229
+ * This creates a multiplier centered around 1.0:
2230
+ * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
2231
+ * - Priority 0.5 with any influence → 1.00 (neutral)
2232
+ * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
2233
+ */
2234
+ computeBoostFactor(priority) {
2235
+ const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
2236
+ return 1 + (priority - 0.5) * influence;
2237
+ }
2238
+ /**
2239
+ * Build human-readable reason for priority adjustment.
2240
+ */
2241
+ buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
2242
+ if (cardTags.length === 0) {
2243
+ return `No tags, neutral priority (${priority.toFixed(2)})`;
2244
+ }
2245
+ const tagList = cardTags.slice(0, 3).join(", ");
2246
+ const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
2247
+ if (boostFactor === 1) {
2248
+ return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
2249
+ } else if (boostFactor > 1) {
2250
+ return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
2251
+ } else {
2252
+ return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
2253
+ }
2254
+ }
2255
+ /**
2256
+ * CardFilter.transform implementation.
2257
+ *
2258
+ * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
2259
+ * cards with low-priority tags get reduced scores.
2260
+ */
2261
+ async transform(cards, _context) {
2262
+ const adjusted = await Promise.all(
2263
+ cards.map(async (card) => {
2264
+ const cardTags = card.tags ?? [];
2265
+ const priority = this.computeCardPriority(cardTags);
2266
+ const boostFactor = this.computeBoostFactor(priority);
2267
+ const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
2268
+ const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
2269
+ const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
2270
+ return {
2271
+ ...card,
2272
+ score: finalScore,
2273
+ provenance: [
2274
+ ...card.provenance,
2275
+ {
2276
+ strategy: "relativePriority",
2277
+ strategyName: this.strategyName || this.name,
2278
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
2279
+ action,
2280
+ score: finalScore,
2281
+ reason
2282
+ }
2283
+ ]
2284
+ };
2285
+ })
2286
+ );
2287
+ return adjusted;
2288
+ }
2289
+ /**
2290
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
2291
+ *
2292
+ * Use transform() via Pipeline instead.
2293
+ */
2294
+ async getWeightedCards(_limit) {
2295
+ throw new Error(
2296
+ "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
2297
+ );
2298
+ }
2299
+ };
2300
+ }
2301
+ });
2302
+
2303
+ // src/core/navigators/filters/types.ts
2304
+ var types_exports2 = {};
2305
+ var init_types2 = __esm({
2306
+ "src/core/navigators/filters/types.ts"() {
2307
+ "use strict";
2308
+ }
2309
+ });
2310
+
2311
+ // src/core/navigators/filters/userGoalStub.ts
2312
+ var userGoalStub_exports = {};
2313
+ __export(userGoalStub_exports, {
2314
+ USER_GOAL_NAVIGATOR_STUB: () => USER_GOAL_NAVIGATOR_STUB
2315
+ });
2316
+ var USER_GOAL_NAVIGATOR_STUB;
2317
+ var init_userGoalStub = __esm({
2318
+ "src/core/navigators/filters/userGoalStub.ts"() {
2319
+ "use strict";
2320
+ USER_GOAL_NAVIGATOR_STUB = true;
2321
+ }
2322
+ });
2323
+
2324
+ // import("./filters/**/*") in src/core/navigators/index.ts
2325
+ var globImport_filters;
2326
+ var init_2 = __esm({
2327
+ 'import("./filters/**/*") in src/core/navigators/index.ts'() {
2328
+ globImport_filters = __glob({
2329
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
2330
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2331
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2332
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2333
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
2334
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2335
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2336
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
2337
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
2338
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
2339
+ });
2340
+ }
2341
+ });
2342
+
2343
+ // src/core/orchestration/gradient.ts
2344
+ function aggregateOutcomesForGradient(outcomes, strategyId) {
2345
+ const observations = [];
2346
+ for (const outcome of outcomes) {
2347
+ const deviation = outcome.deviations[strategyId];
2348
+ if (deviation === void 0) {
2349
+ continue;
2350
+ }
2351
+ observations.push({
2352
+ deviation,
2353
+ outcomeValue: outcome.outcomeValue,
2354
+ weight: 1
2355
+ });
2356
+ }
2357
+ logger.debug(
2358
+ `[Orchestration] Aggregated ${observations.length} observations for strategy ${strategyId}`
2359
+ );
2360
+ return observations;
2361
+ }
2362
+ function computeStrategyGradient(observations) {
2363
+ const n = observations.length;
2364
+ if (n < 3) {
2365
+ logger.debug(`[Orchestration] Insufficient observations for gradient (${n} < 3)`);
2366
+ return null;
2367
+ }
2368
+ let sumX = 0;
2369
+ let sumY = 0;
2370
+ let sumW = 0;
2371
+ for (const obs of observations) {
2372
+ const w = obs.weight ?? 1;
2373
+ sumX += obs.deviation * w;
2374
+ sumY += obs.outcomeValue * w;
2375
+ sumW += w;
2376
+ }
2377
+ const meanX = sumX / sumW;
2378
+ const meanY = sumY / sumW;
2379
+ let numerator = 0;
2380
+ let denominator = 0;
2381
+ let ssTotal = 0;
2382
+ for (const obs of observations) {
2383
+ const w = obs.weight ?? 1;
2384
+ const dx = obs.deviation - meanX;
2385
+ const dy = obs.outcomeValue - meanY;
2386
+ numerator += w * dx * dy;
2387
+ denominator += w * dx * dx;
2388
+ ssTotal += w * dy * dy;
2389
+ }
2390
+ if (denominator < 1e-10) {
2391
+ logger.debug(`[Orchestration] No variance in deviations, cannot compute gradient`);
2392
+ return {
2393
+ gradient: 0,
2394
+ intercept: meanY,
2395
+ rSquared: 0,
2396
+ sampleSize: n
2397
+ };
2398
+ }
2399
+ const gradient = numerator / denominator;
2400
+ const intercept = meanY - gradient * meanX;
2401
+ let ssResidual = 0;
2402
+ for (const obs of observations) {
2403
+ const w = obs.weight ?? 1;
2404
+ const predicted = gradient * obs.deviation + intercept;
2405
+ const residual = obs.outcomeValue - predicted;
2406
+ ssResidual += w * residual * residual;
2407
+ }
2408
+ const rSquared = ssTotal > 1e-10 ? 1 - ssResidual / ssTotal : 0;
2409
+ logger.debug(
2410
+ `[Orchestration] Computed gradient: ${gradient.toFixed(4)}, intercept: ${intercept.toFixed(4)}, R\xB2: ${rSquared.toFixed(4)}, n=${n}`
2411
+ );
2412
+ return {
2413
+ gradient,
2414
+ intercept,
2415
+ rSquared: Math.max(0, Math.min(1, rSquared)),
2416
+ // Clamp to [0,1]
2417
+ sampleSize: n
2418
+ };
2419
+ }
2420
+ var init_gradient = __esm({
2421
+ "src/core/orchestration/gradient.ts"() {
2422
+ "use strict";
2423
+ init_logger();
2424
+ }
2425
+ });
2426
+
2427
+ // src/core/orchestration/learning.ts
2428
+ function updateStrategyWeight(current, gradient) {
2429
+ if (gradient.sampleSize < MIN_OBSERVATIONS_FOR_UPDATE) {
2430
+ logger.debug(
2431
+ `[Orchestration] Insufficient samples (${gradient.sampleSize} < ${MIN_OBSERVATIONS_FOR_UPDATE}), keeping current weight`
2432
+ );
2433
+ return {
2434
+ ...current,
2435
+ sampleSize: current.sampleSize + gradient.sampleSize
2436
+ };
2437
+ }
2438
+ const isReliable = gradient.rSquared >= MIN_R_SQUARED_FOR_GRADIENT;
2439
+ const isFlat = Math.abs(gradient.gradient) < FLAT_GRADIENT_THRESHOLD;
2440
+ let newWeight = current.weight;
2441
+ let newConfidence = current.confidence;
2442
+ if (!isReliable || isFlat) {
2443
+ const confidenceGain = 0.05 * (1 - current.confidence);
2444
+ newConfidence = Math.min(1, current.confidence + confidenceGain);
2445
+ logger.debug(
2446
+ `[Orchestration] Flat/unreliable gradient (|g|=${Math.abs(gradient.gradient).toFixed(4)}, R\xB2=${gradient.rSquared.toFixed(4)}). Increasing confidence: ${current.confidence.toFixed(3)} \u2192 ${newConfidence.toFixed(3)}`
2447
+ );
2448
+ } else {
2449
+ let delta = gradient.gradient * LEARNING_RATE;
2450
+ delta = Math.max(-MAX_WEIGHT_DELTA, Math.min(MAX_WEIGHT_DELTA, delta));
2451
+ newWeight = current.weight + delta;
2452
+ newWeight = Math.max(0.1, Math.min(3, newWeight));
2453
+ const confidenceGain = 0.02 * (1 - current.confidence);
2454
+ newConfidence = Math.min(1, current.confidence + confidenceGain);
2455
+ logger.debug(
2456
+ `[Orchestration] Adjusting weight: ${current.weight.toFixed(3)} \u2192 ${newWeight.toFixed(3)} (gradient=${gradient.gradient.toFixed(4)}, delta=${delta.toFixed(4)})`
2457
+ );
2458
+ }
2459
+ return {
2460
+ weight: newWeight,
2461
+ confidence: newConfidence,
2462
+ sampleSize: current.sampleSize + gradient.sampleSize
2463
+ };
2464
+ }
2465
+ function updateLearningState(courseId, strategyId, currentWeight, gradient, existing) {
2466
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2467
+ const id = `STRATEGY_LEARNING_STATE::${courseId}::${strategyId}`;
2468
+ const historyEntry = {
2469
+ timestamp: now,
2470
+ weight: currentWeight.weight,
2471
+ confidence: currentWeight.confidence,
2472
+ gradient: gradient.gradient
2473
+ };
2474
+ let history = existing?.history ?? [];
2475
+ history = [...history, historyEntry];
2476
+ if (history.length > MAX_HISTORY_LENGTH) {
2477
+ history = history.slice(history.length - MAX_HISTORY_LENGTH);
2478
+ }
2479
+ const state = {
2480
+ _id: id,
2481
+ _rev: existing?._rev,
2482
+ docType: "STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */,
2483
+ courseId,
2484
+ strategyId,
2485
+ currentWeight,
2486
+ regression: {
2487
+ gradient: gradient.gradient,
2488
+ intercept: gradient.intercept,
2489
+ rSquared: gradient.rSquared,
2490
+ sampleSize: gradient.sampleSize,
2491
+ computedAt: now
2492
+ },
2493
+ history,
2494
+ updatedAt: now
2495
+ };
2496
+ return state;
2497
+ }
2498
+ function runPeriodUpdate(input) {
2499
+ const { courseId, strategyId, currentWeight, gradient, existingState } = input;
2500
+ logger.info(
2501
+ `[Orchestration] Running period update for strategy ${strategyId} (${gradient.sampleSize} observations)`
2502
+ );
2503
+ const newWeight = updateStrategyWeight(currentWeight, gradient);
2504
+ const updated = newWeight.weight !== currentWeight.weight;
2505
+ const learningState = updateLearningState(
2506
+ courseId,
2507
+ strategyId,
2508
+ newWeight,
2509
+ gradient,
2510
+ existingState
2511
+ );
2512
+ logger.info(
2513
+ `[Orchestration] Period update complete for ${strategyId}: weight ${currentWeight.weight.toFixed(3)} \u2192 ${newWeight.weight.toFixed(3)}, confidence ${currentWeight.confidence.toFixed(3)} \u2192 ${newWeight.confidence.toFixed(3)}`
2514
+ );
2515
+ return {
2516
+ strategyId,
2517
+ previousWeight: currentWeight,
2518
+ newWeight,
2519
+ gradient,
2520
+ learningState,
2521
+ updated
2522
+ };
2523
+ }
2524
+ function getDefaultLearnableWeight() {
2525
+ return { ...DEFAULT_LEARNABLE_WEIGHT };
2526
+ }
2527
+ var MIN_OBSERVATIONS_FOR_UPDATE, LEARNING_RATE, MAX_WEIGHT_DELTA, MIN_R_SQUARED_FOR_GRADIENT, FLAT_GRADIENT_THRESHOLD, MAX_HISTORY_LENGTH;
2528
+ var init_learning = __esm({
2529
+ "src/core/orchestration/learning.ts"() {
2530
+ "use strict";
2531
+ init_contentNavigationStrategy();
2532
+ init_types_legacy();
2533
+ init_logger();
2534
+ MIN_OBSERVATIONS_FOR_UPDATE = 10;
2535
+ LEARNING_RATE = 0.1;
2536
+ MAX_WEIGHT_DELTA = 0.3;
2537
+ MIN_R_SQUARED_FOR_GRADIENT = 0.05;
2538
+ FLAT_GRADIENT_THRESHOLD = 0.02;
2539
+ MAX_HISTORY_LENGTH = 100;
2540
+ }
2541
+ });
2542
+
2543
+ // src/core/orchestration/signal.ts
2544
+ function computeOutcomeSignal(records, config = {}) {
2545
+ if (!records || records.length === 0) {
2546
+ return null;
2547
+ }
2548
+ const target = config.targetAccuracy ?? 0.85;
2549
+ const tolerance = config.tolerance ?? 0.05;
2550
+ let correct = 0;
2551
+ for (const r of records) {
2552
+ if (r.isCorrect) correct++;
2553
+ }
2554
+ const accuracy = correct / records.length;
2555
+ return scoreAccuracyInZone(accuracy, target, tolerance);
2556
+ }
2557
+ function scoreAccuracyInZone(accuracy, target, tolerance) {
2558
+ const dist = Math.abs(accuracy - target);
2559
+ if (dist <= tolerance) {
2560
+ return 1;
2561
+ }
2562
+ const excess = dist - tolerance;
2563
+ const slope = 2.5;
2564
+ return Math.max(0, 1 - excess * slope);
2565
+ }
2566
+ var init_signal = __esm({
2567
+ "src/core/orchestration/signal.ts"() {
2568
+ "use strict";
2569
+ }
2570
+ });
2571
+
2572
+ // src/core/orchestration/recording.ts
2573
+ async function recordUserOutcome(context, periodStart, periodEnd, records, activeStrategyIds, eloStart = 0, eloEnd = 0, config) {
2574
+ const { user, course, userId } = context;
2575
+ const courseId = course.getCourseID();
2576
+ const outcomeValue = computeOutcomeSignal(records, config);
2577
+ if (outcomeValue === null) {
2578
+ logger.debug(
2579
+ `[Orchestration] No outcome signal computed for ${userId} (insufficient data). Skipping record.`
2580
+ );
2581
+ return;
2582
+ }
2583
+ const deviations = {};
2584
+ for (const strategyId of activeStrategyIds) {
2585
+ deviations[strategyId] = context.getDeviation(strategyId);
2586
+ }
2587
+ const id = `USER_OUTCOME::${courseId}::${userId}::${periodEnd}`;
2588
+ const record = {
2589
+ _id: id,
2590
+ docType: "USER_OUTCOME" /* USER_OUTCOME */,
2591
+ courseId,
2592
+ userId,
2593
+ periodStart,
2594
+ periodEnd,
2595
+ outcomeValue,
2596
+ deviations,
2597
+ metadata: {
2598
+ sessionsCount: 1,
2599
+ // Assumes recording is triggered per-session currently
2600
+ cardsSeen: records.length,
2601
+ eloStart,
2602
+ eloEnd,
2603
+ signalType: "accuracy_in_zone"
2604
+ }
2605
+ };
2606
+ try {
2607
+ await user.putUserOutcome(record);
2608
+ logger.debug(
2609
+ `[Orchestration] Recorded outcome ${outcomeValue.toFixed(3)} for ${userId} (doc: ${id})`
2610
+ );
2611
+ } catch (e) {
2612
+ logger.error(`[Orchestration] Failed to record outcome: ${e}`);
2613
+ }
2614
+ }
2615
+ var init_recording = __esm({
2616
+ "src/core/orchestration/recording.ts"() {
2617
+ "use strict";
2618
+ init_signal();
2619
+ init_types_legacy();
2620
+ init_logger();
2621
+ }
2622
+ });
2623
+
2624
+ // src/core/orchestration/index.ts
2625
+ function fnv1a(str) {
2626
+ let hash = 2166136261;
2627
+ for (let i = 0; i < str.length; i++) {
2628
+ hash ^= str.charCodeAt(i);
2629
+ hash = Math.imul(hash, 16777619);
2630
+ }
2631
+ return hash >>> 0;
2632
+ }
2633
+ function computeDeviation(userId, strategyId, salt) {
2634
+ const input = `${userId}:${strategyId}:${salt}`;
2635
+ const hash = fnv1a(input);
2636
+ const normalized = hash / 4294967296;
2637
+ return normalized * 2 - 1;
2638
+ }
2639
+ function computeSpread(confidence) {
2640
+ const clampedConfidence = Math.max(0, Math.min(1, confidence));
2641
+ return MAX_SPREAD - clampedConfidence * (MAX_SPREAD - MIN_SPREAD);
2642
+ }
2643
+ function computeEffectiveWeight(learnable, userId, strategyId, salt) {
2644
+ const deviation = computeDeviation(userId, strategyId, salt);
2645
+ const spread = computeSpread(learnable.confidence);
2646
+ const adjustment = deviation * spread * learnable.weight;
2647
+ const effective = learnable.weight + adjustment;
2648
+ return Math.max(MIN_WEIGHT, Math.min(MAX_WEIGHT, effective));
2649
+ }
2650
+ async function createOrchestrationContext(user, course) {
2651
+ let courseConfig;
2652
+ try {
2653
+ courseConfig = await course.getCourseConfig();
2654
+ } catch (e) {
2655
+ logger.error(`[Orchestration] Failed to load course config: ${e}`);
2656
+ courseConfig = {
2657
+ name: "Unknown",
2658
+ description: "",
2659
+ public: false,
2660
+ deleted: false,
2661
+ creator: "",
2662
+ admins: [],
2663
+ moderators: [],
2664
+ dataShapes: [],
2665
+ questionTypes: [],
2666
+ orchestration: { salt: "default" }
2667
+ };
2668
+ }
2669
+ const userId = user.getUsername();
2670
+ const salt = courseConfig.orchestration?.salt || "default_salt";
2671
+ return {
2672
+ user,
2673
+ course,
2674
+ userId,
2675
+ courseConfig,
2676
+ getEffectiveWeight(strategyId, learnable) {
2677
+ return computeEffectiveWeight(learnable, userId, strategyId, salt);
2678
+ },
2679
+ getDeviation(strategyId) {
2680
+ return computeDeviation(userId, strategyId, salt);
2681
+ }
2682
+ };
2683
+ }
2684
+ var MIN_SPREAD, MAX_SPREAD, MIN_WEIGHT, MAX_WEIGHT;
2685
+ var init_orchestration = __esm({
2686
+ "src/core/orchestration/index.ts"() {
2687
+ "use strict";
2688
+ init_logger();
2689
+ init_gradient();
2690
+ init_learning();
2691
+ init_signal();
2692
+ init_recording();
2693
+ MIN_SPREAD = 0.1;
2694
+ MAX_SPREAD = 0.5;
2695
+ MIN_WEIGHT = 0.1;
2696
+ MAX_WEIGHT = 3;
2697
+ }
2698
+ });
2699
+
2700
+ // src/core/navigators/Pipeline.ts
2701
+ var Pipeline_exports = {};
2702
+ __export(Pipeline_exports, {
2703
+ Pipeline: () => Pipeline
2704
+ });
2705
+ function logPipelineConfig(generator, filters) {
2706
+ const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
2707
+ logger.info(
2708
+ `[Pipeline] Configuration:
2709
+ Generator: ${generator.name}
2710
+ Filters:${filterList}`
2711
+ );
2712
+ }
2713
+ function logTagHydration(cards, tagsByCard) {
2714
+ const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
2715
+ const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
2716
+ logger.debug(
2717
+ `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
2718
+ );
2719
+ }
2720
+ function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores, filterImpacts) {
2721
+ const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
2722
+ let filterSummary = "";
2723
+ if (filterImpacts.length > 0) {
2724
+ const impacts = filterImpacts.map((f) => {
2725
+ const parts = [];
2726
+ if (f.boosted > 0) parts.push(`+${f.boosted}`);
2727
+ if (f.penalized > 0) parts.push(`-${f.penalized}`);
2728
+ if (f.passed > 0) parts.push(`=${f.passed}`);
2729
+ return `${f.name}: ${parts.join("/")}`;
2730
+ });
2731
+ filterSummary = `
2732
+ Filter impact: ${impacts.join(", ")}`;
2733
+ }
2734
+ logger.info(
2735
+ `[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})` + filterSummary + `
2736
+ \u{1F4A1} Inspect: window.skuilder.pipeline`
2737
+ );
2738
+ }
2739
+ function logCardProvenance(cards, maxCards = 3) {
2740
+ const cardsToLog = cards.slice(0, maxCards);
2741
+ logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
2742
+ for (const card of cardsToLog) {
2743
+ logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
2744
+ for (const entry of card.provenance) {
2745
+ const scoreChange = entry.score.toFixed(3);
2746
+ const action = entry.action.padEnd(9);
2747
+ logger.debug(
2748
+ `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
2749
+ );
2750
+ }
2751
+ }
2752
+ }
2753
+ var import_common8, Pipeline;
2754
+ var init_Pipeline = __esm({
2755
+ "src/core/navigators/Pipeline.ts"() {
2756
+ "use strict";
2757
+ import_common8 = require("@vue-skuilder/common");
2758
+ init_navigators();
2759
+ init_logger();
2760
+ init_orchestration();
2761
+ init_PipelineDebugger();
2762
+ Pipeline = class extends ContentNavigator {
2763
+ generator;
2764
+ filters;
2765
+ /**
2766
+ * Create a new pipeline.
2767
+ *
2768
+ * @param generator - The generator (or CompositeGenerator) that produces candidates
2769
+ * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
2770
+ * @param user - User database interface
2771
+ * @param course - Course database interface
2772
+ */
2773
+ constructor(generator, filters, user, course) {
2774
+ super();
2775
+ this.generator = generator;
2776
+ this.filters = filters;
2777
+ this.user = user;
2778
+ this.course = course;
2779
+ course.getCourseConfig().then((cfg) => {
2780
+ logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);
2781
+ }).catch((e) => {
2782
+ logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);
2783
+ });
2784
+ logPipelineConfig(generator, filters);
2785
+ }
2786
+ /**
2787
+ * Get weighted cards by running generator and applying filters.
2788
+ *
2789
+ * 1. Build shared context (user ELO, etc.)
2790
+ * 2. Get candidates from generator (passing context)
2791
+ * 3. Batch hydrate tags for all candidates
2792
+ * 4. Apply each filter sequentially
2793
+ * 5. Remove zero-score cards
2794
+ * 6. Sort by score descending
2795
+ * 7. Return top N
2796
+ *
2797
+ * @param limit - Maximum number of cards to return
2798
+ * @returns Cards sorted by score descending
2799
+ */
2800
+ async getWeightedCards(limit) {
2801
+ const context = await this.buildContext();
2802
+ const overFetchMultiplier = 2 + this.filters.length * 0.5;
2803
+ const fetchLimit = Math.ceil(limit * overFetchMultiplier);
2804
+ logger.debug(
2805
+ `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
2806
+ );
2807
+ let cards = await this.generator.getWeightedCards(fetchLimit, context);
2808
+ const generatedCount = cards.length;
2809
+ let generatorSummaries;
2810
+ if (this.generator.generators) {
2811
+ const genMap = /* @__PURE__ */ new Map();
2812
+ for (const card of cards) {
2813
+ const firstProv = card.provenance[0];
2814
+ if (firstProv) {
2815
+ const genName = firstProv.strategyName;
2816
+ if (!genMap.has(genName)) {
2817
+ genMap.set(genName, { cards: [] });
2818
+ }
2819
+ genMap.get(genName).cards.push(card);
2820
+ }
2821
+ }
2822
+ generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {
2823
+ const newCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
2824
+ const reviewCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
2825
+ return {
2826
+ name,
2827
+ cardCount: data.cards.length,
2828
+ newCount: newCards.length,
2829
+ reviewCount: reviewCards.length,
2830
+ topScore: Math.max(...data.cards.map((c) => c.score), 0)
2831
+ };
2832
+ });
2833
+ }
2834
+ logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
2835
+ cards = await this.hydrateTags(cards);
2836
+ const allCardsBeforeFiltering = [...cards];
2837
+ const filterImpacts = [];
2838
+ for (const filter of this.filters) {
2839
+ const beforeCount = cards.length;
2840
+ const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));
2841
+ cards = await filter.transform(cards, context);
2842
+ let boosted = 0, penalized = 0, passed = 0;
2843
+ const removed = beforeCount - cards.length;
2844
+ for (const card of cards) {
2845
+ const before = beforeScores.get(card.cardId) ?? 0;
2846
+ if (card.score > before) boosted++;
2847
+ else if (card.score < before) penalized++;
2848
+ else passed++;
2849
+ }
2850
+ filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
2851
+ logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeScores.size} \u2192 ${cards.length} cards (\u2191${boosted} \u2193${penalized} =${passed})`);
2852
+ }
2853
+ cards = cards.filter((c) => c.score > 0);
2854
+ cards.sort((a, b) => b.score - a.score);
2855
+ const result = cards.slice(0, limit);
2856
+ const topScores = result.slice(0, 3).map((c) => c.score);
2857
+ logExecutionSummary(
2858
+ this.generator.name,
2859
+ generatedCount,
2860
+ this.filters.length,
2861
+ result.length,
2862
+ topScores,
2863
+ filterImpacts
2864
+ );
2865
+ logCardProvenance(result, 3);
2866
+ try {
2867
+ const courseName = await this.course?.getCourseConfig().then((c) => c.name).catch(() => void 0);
2868
+ const report = buildRunReport(
2869
+ this.course?.getCourseID() || "unknown",
2870
+ courseName,
2871
+ this.generator.name,
2872
+ generatorSummaries,
2873
+ generatedCount,
2874
+ filterImpacts,
2875
+ allCardsBeforeFiltering,
2876
+ result
2877
+ );
2878
+ captureRun(report);
2879
+ } catch (e) {
2880
+ logger.debug(`[Pipeline] Failed to capture debug run: ${e}`);
2881
+ }
2882
+ return result;
2883
+ }
2884
+ /**
2885
+ * Batch hydrate tags for all cards.
2886
+ *
2887
+ * Fetches tags for all cards in a single database query and attaches them
2888
+ * to the WeightedCard objects. Filters can then use card.tags instead of
2889
+ * making individual getAppliedTags() calls.
2890
+ *
2891
+ * @param cards - Cards to hydrate
2892
+ * @returns Cards with tags populated
2893
+ */
2894
+ async hydrateTags(cards) {
2895
+ if (cards.length === 0) {
2896
+ return cards;
2897
+ }
2898
+ const cardIds = cards.map((c) => c.cardId);
2899
+ const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
2900
+ logTagHydration(cards, tagsByCard);
2901
+ return cards.map((card) => ({
2902
+ ...card,
2903
+ tags: tagsByCard.get(card.cardId) ?? []
2904
+ }));
2905
+ }
2906
+ /**
2907
+ * Build shared context for generator and filters.
2908
+ *
2909
+ * Called once per getWeightedCards() invocation.
2910
+ * Contains data that the generator and multiple filters might need.
2911
+ *
2912
+ * The context satisfies both GeneratorContext and FilterContext interfaces.
2913
+ */
2914
+ async buildContext() {
2915
+ let userElo = 1e3;
2916
+ try {
2917
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
2918
+ const courseElo = (0, import_common8.toCourseElo)(courseReg.elo);
2919
+ userElo = courseElo.global.score;
2920
+ } catch (e) {
2921
+ logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
2922
+ }
2923
+ const orchestration = await createOrchestrationContext(this.user, this.course);
2924
+ return {
2925
+ user: this.user,
2926
+ course: this.course,
2927
+ userElo,
2928
+ orchestration
2929
+ };
2930
+ }
2931
+ /**
2932
+ * Get the course ID for this pipeline.
2933
+ */
2934
+ getCourseID() {
2935
+ return this.course.getCourseID();
2936
+ }
2937
+ /**
2938
+ * Get orchestration context for outcome recording.
2939
+ */
2940
+ async getOrchestrationContext() {
2941
+ return createOrchestrationContext(this.user, this.course);
2942
+ }
2943
+ /**
2944
+ * Get IDs of all strategies in this pipeline.
2945
+ * Used to record which strategies contributed to an outcome.
2946
+ */
2947
+ getStrategyIds() {
2948
+ const ids = [];
2949
+ const extractId = (obj) => {
2950
+ if (obj.strategyId) return obj.strategyId;
2951
+ return null;
2952
+ };
2953
+ const genId = extractId(this.generator);
2954
+ if (genId) ids.push(genId);
2955
+ if (this.generator.generators && Array.isArray(this.generator.generators)) {
2956
+ this.generator.generators.forEach((g) => {
2957
+ const subId = extractId(g);
2958
+ if (subId) ids.push(subId);
2959
+ });
2960
+ }
2961
+ for (const filter of this.filters) {
2962
+ const fId = extractId(filter);
2963
+ if (fId) ids.push(fId);
2964
+ }
2965
+ return [...new Set(ids)];
2966
+ }
2967
+ };
2968
+ }
2969
+ });
2970
+
2971
+ // src/core/navigators/defaults.ts
2972
+ var defaults_exports = {};
2973
+ __export(defaults_exports, {
2974
+ createDefaultEloStrategy: () => createDefaultEloStrategy,
2975
+ createDefaultPipeline: () => createDefaultPipeline,
2976
+ createDefaultSrsStrategy: () => createDefaultSrsStrategy
2977
+ });
2978
+ function createDefaultEloStrategy(courseId) {
2979
+ return {
2980
+ _id: "NAVIGATION_STRATEGY-ELO-default",
2981
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
2982
+ name: "ELO (default)",
2983
+ description: "Default ELO-based navigation strategy for new cards",
2984
+ implementingClass: "elo" /* ELO */,
2985
+ course: courseId,
2986
+ serializedData: ""
2987
+ };
2988
+ }
2989
+ function createDefaultSrsStrategy(courseId) {
2990
+ return {
2991
+ _id: "NAVIGATION_STRATEGY-SRS-default",
2992
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
2993
+ name: "SRS (default)",
2994
+ description: "Default SRS-based navigation strategy for reviews",
2995
+ implementingClass: "srs" /* SRS */,
2996
+ course: courseId,
2997
+ serializedData: ""
2998
+ };
2999
+ }
3000
+ function createDefaultPipeline(user, course) {
3001
+ const courseId = course.getCourseID();
3002
+ const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
3003
+ const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
3004
+ const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
3005
+ const eloDistanceFilter = createEloDistanceFilter();
3006
+ return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
3007
+ }
3008
+ var init_defaults = __esm({
3009
+ "src/core/navigators/defaults.ts"() {
3010
+ "use strict";
3011
+ init_navigators();
3012
+ init_Pipeline();
3013
+ init_CompositeGenerator();
3014
+ init_elo();
3015
+ init_srs();
3016
+ init_eloDistance();
3017
+ init_types_legacy();
3018
+ }
3019
+ });
3020
+
3021
+ // src/core/navigators/PipelineAssembler.ts
3022
+ var PipelineAssembler_exports = {};
3023
+ __export(PipelineAssembler_exports, {
3024
+ PipelineAssembler: () => PipelineAssembler
3025
+ });
3026
+ var PipelineAssembler;
3027
+ var init_PipelineAssembler = __esm({
3028
+ "src/core/navigators/PipelineAssembler.ts"() {
3029
+ "use strict";
3030
+ init_navigators();
3031
+ init_WeightedFilter();
3032
+ init_Pipeline();
3033
+ init_logger();
3034
+ init_CompositeGenerator();
3035
+ init_defaults();
3036
+ PipelineAssembler = class {
3037
+ /**
3038
+ * Assembles a navigation pipeline from strategy documents.
3039
+ *
3040
+ * 1. Separates into generators and filters by role
3041
+ * 2. Validates at least one generator exists (or creates default ELO)
3042
+ * 3. Instantiates generators - wraps multiple in CompositeGenerator
3043
+ * 4. Instantiates filters
3044
+ * 5. Returns Pipeline(generator, filters)
3045
+ *
3046
+ * @param input - Strategy documents plus user/course interfaces
3047
+ * @returns Assembled pipeline and any warnings
3048
+ */
3049
+ async assemble(input) {
3050
+ const { strategies, user, course } = input;
3051
+ const warnings = [];
3052
+ if (strategies.length === 0) {
3053
+ return {
3054
+ pipeline: null,
3055
+ generatorStrategies: [],
3056
+ filterStrategies: [],
3057
+ warnings
3058
+ };
3059
+ }
3060
+ const generatorStrategies = [];
3061
+ const filterStrategies = [];
3062
+ for (const s of strategies) {
3063
+ if (isGenerator(s.implementingClass)) {
3064
+ generatorStrategies.push(s);
3065
+ } else if (isFilter(s.implementingClass)) {
3066
+ filterStrategies.push(s);
3067
+ } else {
3068
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
3069
+ }
3070
+ }
3071
+ if (generatorStrategies.length === 0) {
3072
+ if (filterStrategies.length > 0) {
3073
+ logger.debug(
3074
+ "[PipelineAssembler] No generator found, using default ELO and SRS with configured filters"
3075
+ );
3076
+ const courseId = course.getCourseID();
3077
+ generatorStrategies.push(createDefaultEloStrategy(courseId));
3078
+ generatorStrategies.push(createDefaultSrsStrategy(courseId));
3079
+ } else {
3080
+ warnings.push("No generator strategy found");
3081
+ return {
3082
+ pipeline: null,
3083
+ generatorStrategies: [],
3084
+ filterStrategies: [],
3085
+ warnings
3086
+ };
3087
+ }
3088
+ }
3089
+ let generator;
3090
+ if (generatorStrategies.length === 1) {
3091
+ const nav = await ContentNavigator.create(user, course, generatorStrategies[0]);
3092
+ generator = nav;
3093
+ logger.debug(`[PipelineAssembler] Using single generator: ${generatorStrategies[0].name}`);
3094
+ } else {
3095
+ logger.debug(
3096
+ `[PipelineAssembler] Using CompositeGenerator for ${generatorStrategies.length} generators: ${generatorStrategies.map((g) => g.name).join(", ")}`
3097
+ );
3098
+ generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
3099
+ }
3100
+ const filters = [];
3101
+ const sortedFilterStrategies = [...filterStrategies].sort(
3102
+ (a, b) => a.name.localeCompare(b.name)
3103
+ );
3104
+ for (const filterStrategy of sortedFilterStrategies) {
3105
+ try {
3106
+ const nav = await ContentNavigator.create(user, course, filterStrategy);
3107
+ if ("transform" in nav && typeof nav.transform === "function") {
3108
+ let filter = nav;
3109
+ if (filterStrategy.learnable) {
3110
+ filter = new WeightedFilter(
3111
+ filter,
3112
+ filterStrategy.learnable,
3113
+ filterStrategy.staticWeight,
3114
+ filterStrategy._id
3115
+ );
3116
+ }
3117
+ filters.push(filter);
3118
+ logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
3119
+ } else {
3120
+ warnings.push(
3121
+ `Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
3122
+ );
3123
+ }
3124
+ } catch (e) {
3125
+ warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
3126
+ }
3127
+ }
3128
+ const pipeline = new Pipeline(generator, filters, user, course);
3129
+ logger.debug(
3130
+ `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
3131
+ );
3132
+ return {
3133
+ pipeline,
3134
+ generatorStrategies,
3135
+ filterStrategies: sortedFilterStrategies,
3136
+ warnings
3137
+ };
3138
+ }
3139
+ };
3140
+ }
3141
+ });
3142
+
3143
+ // import("./**/*") in src/core/navigators/index.ts
3144
+ var globImport;
3145
+ var init_3 = __esm({
3146
+ 'import("./**/*") in src/core/navigators/index.ts'() {
3147
+ globImport = __glob({
3148
+ "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
3149
+ "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
3150
+ "./PipelineDebugger.ts": () => Promise.resolve().then(() => (init_PipelineDebugger(), PipelineDebugger_exports)),
3151
+ "./defaults.ts": () => Promise.resolve().then(() => (init_defaults(), defaults_exports)),
3152
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
3153
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
3154
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
3155
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
3156
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
3157
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
3158
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
3159
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
3160
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
3161
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
3162
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
3163
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
3164
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
3165
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
3166
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
3167
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
3168
+ });
3169
+ }
3170
+ });
3171
+
3172
+ // src/core/navigators/index.ts
3173
+ var navigators_exports = {};
3174
+ __export(navigators_exports, {
3175
+ ContentNavigator: () => ContentNavigator,
3176
+ NavigatorRole: () => NavigatorRole,
3177
+ NavigatorRoles: () => NavigatorRoles,
3178
+ Navigators: () => Navigators,
3179
+ getCardOrigin: () => getCardOrigin,
3180
+ getRegisteredNavigator: () => getRegisteredNavigator,
3181
+ getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
3182
+ hasRegisteredNavigator: () => hasRegisteredNavigator,
3183
+ initializeNavigatorRegistry: () => initializeNavigatorRegistry,
3184
+ isFilter: () => isFilter,
3185
+ isGenerator: () => isGenerator,
3186
+ mountPipelineDebugger: () => mountPipelineDebugger,
3187
+ pipelineDebugAPI: () => pipelineDebugAPI,
3188
+ registerNavigator: () => registerNavigator
3189
+ });
3190
+ function registerNavigator(implementingClass, constructor) {
3191
+ navigatorRegistry.set(implementingClass, constructor);
3192
+ logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}`);
3193
+ }
3194
+ function getRegisteredNavigator(implementingClass) {
3195
+ return navigatorRegistry.get(implementingClass);
3196
+ }
3197
+ function hasRegisteredNavigator(implementingClass) {
3198
+ return navigatorRegistry.has(implementingClass);
3199
+ }
3200
+ function getRegisteredNavigatorNames() {
3201
+ return Array.from(navigatorRegistry.keys());
3202
+ }
3203
+ async function initializeNavigatorRegistry() {
3204
+ logger.debug("[NavigatorRegistry] Initializing built-in navigators...");
3205
+ const [eloModule, srsModule] = await Promise.all([
3206
+ Promise.resolve().then(() => (init_elo(), elo_exports)),
3207
+ Promise.resolve().then(() => (init_srs(), srs_exports))
3208
+ ]);
3209
+ registerNavigator("elo", eloModule.default);
3210
+ registerNavigator("srs", srsModule.default);
3211
+ const [
3212
+ hierarchyModule,
3213
+ interferenceModule,
3214
+ relativePriorityModule,
3215
+ userTagPreferenceModule
3216
+ ] = await Promise.all([
3217
+ Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
3218
+ Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
3219
+ Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
3220
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
3221
+ ]);
3222
+ registerNavigator("hierarchyDefinition", hierarchyModule.default);
3223
+ registerNavigator("interferenceMitigator", interferenceModule.default);
3224
+ registerNavigator("relativePriority", relativePriorityModule.default);
3225
+ registerNavigator("userTagPreference", userTagPreferenceModule.default);
3226
+ logger.debug(
3227
+ `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
3228
+ );
3229
+ }
3230
+ function getCardOrigin(card) {
3231
+ if (card.provenance.length === 0) {
3232
+ throw new Error("Card has no provenance - cannot determine origin");
3233
+ }
3234
+ const firstEntry = card.provenance[0];
3235
+ const reason = firstEntry.reason.toLowerCase();
3236
+ if (reason.includes("failed")) {
3237
+ return "failed";
3238
+ }
3239
+ if (reason.includes("review")) {
3240
+ return "review";
3241
+ }
3242
+ return "new";
3243
+ }
3244
+ function isGenerator(impl) {
3245
+ return NavigatorRoles[impl] === "generator" /* GENERATOR */;
3246
+ }
3247
+ function isFilter(impl) {
3248
+ return NavigatorRoles[impl] === "filter" /* FILTER */;
3249
+ }
3250
+ var navigatorRegistry, Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
3251
+ var init_navigators = __esm({
3252
+ "src/core/navigators/index.ts"() {
3253
+ "use strict";
3254
+ init_PipelineDebugger();
3255
+ init_logger();
3256
+ init_();
3257
+ init_2();
3258
+ init_3();
3259
+ navigatorRegistry = /* @__PURE__ */ new Map();
3260
+ Navigators = /* @__PURE__ */ ((Navigators2) => {
3261
+ Navigators2["ELO"] = "elo";
3262
+ Navigators2["SRS"] = "srs";
3263
+ Navigators2["HIERARCHY"] = "hierarchyDefinition";
3264
+ Navigators2["INTERFERENCE"] = "interferenceMitigator";
3265
+ Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
3266
+ Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
3267
+ return Navigators2;
3268
+ })(Navigators || {});
3269
+ NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
3270
+ NavigatorRole2["GENERATOR"] = "generator";
3271
+ NavigatorRole2["FILTER"] = "filter";
3272
+ return NavigatorRole2;
3273
+ })(NavigatorRole || {});
3274
+ NavigatorRoles = {
3275
+ ["elo" /* ELO */]: "generator" /* GENERATOR */,
3276
+ ["srs" /* SRS */]: "generator" /* GENERATOR */,
3277
+ ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
3278
+ ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
3279
+ ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
3280
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
3281
+ };
3282
+ ContentNavigator = class {
3283
+ /** User interface for this navigation session */
3284
+ user;
3285
+ /** Course interface for this navigation session */
3286
+ course;
3287
+ /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
3288
+ strategyName;
3289
+ /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
3290
+ strategyId;
3291
+ /** Evolutionary weighting configuration */
3292
+ learnable;
3293
+ /** Whether to bypass deviation (manual/static weighting) */
3294
+ staticWeight;
3295
+ /**
3296
+ * Constructor for standard navigators.
3297
+ * Call this from subclass constructors to initialize common fields.
3298
+ *
3299
+ * Note: CompositeGenerator and Pipeline call super() without args, then set
3300
+ * user/course fields directly if needed.
3301
+ */
3302
+ constructor(user, course, strategyData) {
3303
+ this.user = user;
3304
+ this.course = course;
3305
+ if (strategyData) {
3306
+ this.strategyName = strategyData.name;
3307
+ this.strategyId = strategyData._id;
3308
+ this.learnable = strategyData.learnable;
3309
+ this.staticWeight = strategyData.staticWeight;
3310
+ }
3311
+ }
3312
+ // ============================================================================
3313
+ // STRATEGY STATE HELPERS
3314
+ // ============================================================================
3315
+ //
3316
+ // These methods allow strategies to persist their own state (user preferences,
3317
+ // learned patterns, temporal tracking) in the user database.
3318
+ //
3319
+ // ============================================================================
3320
+ /**
3321
+ * Unique key identifying this strategy for state storage.
3322
+ *
3323
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
3324
+ * Override in subclasses if multiple instances of the same strategy type
3325
+ * need separate state storage.
3326
+ */
3327
+ get strategyKey() {
3328
+ return this.constructor.name;
1376
3329
  }
1377
- };
1378
- }
1379
- });
1380
-
1381
- // src/core/navigators/generators/srs.ts
1382
- var import_moment3, SRSNavigator;
1383
- var init_srs = __esm({
1384
- "src/core/navigators/generators/srs.ts"() {
1385
- "use strict";
1386
- import_moment3 = __toESM(require("moment"), 1);
1387
- init_navigators();
1388
- init_logger();
1389
- SRSNavigator = class extends ContentNavigator {
1390
- /** Human-readable name for CardGenerator interface */
1391
- name;
1392
- constructor(user, course, strategyData) {
1393
- super(user, course, strategyData);
1394
- this.name = strategyData?.name || "SRS";
3330
+ /**
3331
+ * Get this strategy's persisted state for the current course.
3332
+ *
3333
+ * @returns The strategy's data payload, or null if no state exists
3334
+ * @throws Error if user or course is not initialized
3335
+ */
3336
+ async getStrategyState() {
3337
+ if (!this.user || !this.course) {
3338
+ throw new Error(
3339
+ `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
3340
+ );
3341
+ }
3342
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
1395
3343
  }
1396
3344
  /**
1397
- * Get review cards scored by urgency.
3345
+ * Persist this strategy's state for the current course.
1398
3346
  *
1399
- * Score formula combines:
1400
- * - Relative overdueness: hoursOverdue / intervalHours
1401
- * - Interval recency: exponential decay favoring shorter intervals
3347
+ * @param data - The strategy's data payload to store
3348
+ * @throws Error if user or course is not initialized
3349
+ */
3350
+ async putStrategyState(data) {
3351
+ if (!this.user || !this.course) {
3352
+ throw new Error(
3353
+ `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
3354
+ );
3355
+ }
3356
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
3357
+ }
3358
+ /**
3359
+ * Factory method to create navigator instances.
1402
3360
  *
1403
- * Cards not yet due are excluded (not scored as 0).
3361
+ * First checks the navigator registry for a pre-registered constructor.
3362
+ * If not found, falls back to dynamic import (for custom navigators).
1404
3363
  *
1405
- * This method supports both the legacy signature (limit only) and the
1406
- * CardGenerator interface signature (limit, context).
3364
+ * For reliable operation in test environments, call initializeNavigatorRegistry()
3365
+ * before using this method.
1407
3366
  *
1408
- * @param limit - Maximum number of cards to return
1409
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
3367
+ * @param user - User interface
3368
+ * @param course - Course interface
3369
+ * @param strategyData - Strategy configuration document
3370
+ * @returns the runtime object used to steer a study session.
1410
3371
  */
1411
- async getWeightedCards(limit, _context) {
1412
- if (!this.user || !this.course) {
1413
- throw new Error("SRSNavigator requires user and course to be set");
3372
+ static async create(user, course, strategyData) {
3373
+ const implementingClass = strategyData.implementingClass;
3374
+ const RegisteredImpl = getRegisteredNavigator(implementingClass);
3375
+ if (RegisteredImpl) {
3376
+ logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);
3377
+ return new RegisteredImpl(user, course, strategyData);
1414
3378
  }
1415
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1416
- const now = import_moment3.default.utc();
1417
- const dueReviews = reviews.filter((r) => now.isAfter(import_moment3.default.utc(r.reviewTime)));
1418
- const scored = dueReviews.map((review) => {
1419
- const { score, reason } = this.computeUrgencyScore(review, now);
1420
- return {
1421
- cardId: review.cardId,
1422
- courseId: review.courseId,
1423
- score,
1424
- reviewID: review._id,
1425
- provenance: [
1426
- {
1427
- strategy: "srs",
1428
- strategyName: this.strategyName || this.name,
1429
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1430
- action: "generated",
1431
- score,
1432
- reason
1433
- }
1434
- ]
1435
- };
1436
- });
1437
- logger.debug(`[srsNav] got ${scored.length} weighted cards`);
1438
- return scored.sort((a, b) => b.score - a.score).slice(0, limit);
3379
+ logger.debug(
3380
+ `[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`
3381
+ );
3382
+ let NavigatorImpl;
3383
+ const variations = [".ts", ".js", ""];
3384
+ for (const ext of variations) {
3385
+ try {
3386
+ const module2 = await globImport_generators(`./generators/${implementingClass}${ext}`);
3387
+ NavigatorImpl = module2.default;
3388
+ if (NavigatorImpl) break;
3389
+ } catch (e) {
3390
+ logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);
3391
+ }
3392
+ try {
3393
+ const module2 = await globImport_filters(`./filters/${implementingClass}${ext}`);
3394
+ NavigatorImpl = module2.default;
3395
+ if (NavigatorImpl) break;
3396
+ } catch (e) {
3397
+ logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);
3398
+ }
3399
+ try {
3400
+ const module2 = await globImport(`./${implementingClass}${ext}`);
3401
+ NavigatorImpl = module2.default;
3402
+ if (NavigatorImpl) break;
3403
+ } catch (e) {
3404
+ logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);
3405
+ }
3406
+ if (NavigatorImpl) break;
3407
+ }
3408
+ if (!NavigatorImpl) {
3409
+ throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
3410
+ }
3411
+ return new NavigatorImpl(user, course, strategyData);
1439
3412
  }
1440
3413
  /**
1441
- * Compute urgency score for a review card.
3414
+ * Get cards with suitability scores and provenance trails.
1442
3415
  *
1443
- * Two factors:
1444
- * 1. Relative overdueness = hoursOverdue / intervalHours
1445
- * - 2 days overdue on 3-day interval = 0.67 (urgent)
1446
- * - 2 days overdue on 180-day interval = 0.01 (not urgent)
3416
+ * **This is the PRIMARY API for navigation strategies.**
1447
3417
  *
1448
- * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1449
- * - 24h interval ~1.0 (very recent learning)
1450
- * - 30 days (720h) ~0.56
1451
- * - 180 days → ~0.30
3418
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
3419
+ * better candidates for presentation. Each card includes a provenance trail
3420
+ * documenting how strategies contributed to the final score.
3421
+ *
3422
+ * ## Implementation Required
3423
+ * All navigation strategies MUST override this method. The base class does
3424
+ * not provide a default implementation.
3425
+ *
3426
+ * ## For Generators
3427
+ * Override this method to generate candidates and compute scores based on
3428
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
3429
+ * initial provenance entry with action='generated'.
3430
+ *
3431
+ * ## For Filters
3432
+ * Filters should implement the CardFilter interface instead and be composed
3433
+ * via Pipeline. Filters do not directly implement getWeightedCards().
1452
3434
  *
1453
- * Combined: base 0.5 + weighted average of factors * 0.45
1454
- * Result range: approximately 0.5 to 0.95
3435
+ * @param limit - Maximum cards to return
3436
+ * @returns Cards sorted by score descending, with provenance trails
1455
3437
  */
1456
- computeUrgencyScore(review, now) {
1457
- const scheduledAt = import_moment3.default.utc(review.scheduledAt);
1458
- const due = import_moment3.default.utc(review.reviewTime);
1459
- const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1460
- const hoursOverdue = now.diff(due, "hours");
1461
- const relativeOverdue = hoursOverdue / intervalHours;
1462
- const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1463
- const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1464
- const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1465
- const score = Math.min(0.95, 0.5 + urgency * 0.45);
1466
- const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
1467
- return { score, reason };
3438
+ async getWeightedCards(_limit) {
3439
+ throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
1468
3440
  }
1469
3441
  };
1470
3442
  }
1471
3443
  });
1472
3444
 
1473
- // src/core/navigators/filters/eloDistance.ts
1474
- function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1475
- const normalizedDistance = distance / halfLife;
1476
- const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1477
- return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1478
- }
1479
- function createEloDistanceFilter(config) {
1480
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1481
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1482
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1483
- return {
1484
- name: "ELO Distance Filter",
1485
- async transform(cards, context) {
1486
- const { course, userElo } = context;
1487
- const cardIds = cards.map((c) => c.cardId);
1488
- const cardElos = await course.getCardEloData(cardIds);
1489
- return cards.map((card, i) => {
1490
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
1491
- const distance = Math.abs(cardElo - userElo);
1492
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1493
- const newScore = card.score * multiplier;
1494
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1495
- return {
1496
- ...card,
1497
- score: newScore,
1498
- provenance: [
1499
- ...card.provenance,
1500
- {
1501
- strategy: "eloDistance",
1502
- strategyName: "ELO Distance Filter",
1503
- strategyId: "ELO_DISTANCE_FILTER",
1504
- action,
1505
- score: newScore,
1506
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1507
- }
1508
- ]
1509
- };
1510
- });
1511
- }
1512
- };
1513
- }
1514
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1515
- var init_eloDistance = __esm({
1516
- "src/core/navigators/filters/eloDistance.ts"() {
1517
- "use strict";
1518
- DEFAULT_HALF_LIFE = 200;
1519
- DEFAULT_MIN_MULTIPLIER = 0.3;
1520
- DEFAULT_MAX_MULTIPLIER = 1;
1521
- }
1522
- });
1523
-
1524
- // src/core/navigators/defaults.ts
1525
- function createDefaultEloStrategy(courseId) {
1526
- return {
1527
- _id: "NAVIGATION_STRATEGY-ELO-default",
1528
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1529
- name: "ELO (default)",
1530
- description: "Default ELO-based navigation strategy for new cards",
1531
- implementingClass: "elo" /* ELO */,
1532
- course: courseId,
1533
- serializedData: ""
1534
- };
1535
- }
1536
- function createDefaultSrsStrategy(courseId) {
1537
- return {
1538
- _id: "NAVIGATION_STRATEGY-SRS-default",
1539
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1540
- name: "SRS (default)",
1541
- description: "Default SRS-based navigation strategy for reviews",
1542
- implementingClass: "srs" /* SRS */,
1543
- course: courseId,
1544
- serializedData: ""
1545
- };
1546
- }
1547
- function createDefaultPipeline(user, course) {
1548
- const courseId = course.getCourseID();
1549
- const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
1550
- const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
1551
- const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
1552
- const eloDistanceFilter = createEloDistanceFilter();
1553
- return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
1554
- }
1555
- var init_defaults = __esm({
1556
- "src/core/navigators/defaults.ts"() {
1557
- "use strict";
1558
- init_navigators();
1559
- init_Pipeline();
1560
- init_CompositeGenerator();
1561
- init_elo();
1562
- init_srs();
1563
- init_eloDistance();
1564
- init_types_legacy();
1565
- }
1566
- });
1567
-
1568
3445
  // src/impl/couch/courseDB.ts
1569
3446
  function randIntWeightedTowardZero(n) {
1570
3447
  return Math.floor(Math.random() * Math.random() * Math.random() * n);
@@ -1641,11 +3518,11 @@ ${JSON.stringify(config)}
1641
3518
  function isSuccessRow(row) {
1642
3519
  return "doc" in row && row.doc !== null && row.doc !== void 0;
1643
3520
  }
1644
- var import_common7, CourseDB;
3521
+ var import_common9, CourseDB;
1645
3522
  var init_courseDB = __esm({
1646
3523
  "src/impl/couch/courseDB.ts"() {
1647
3524
  "use strict";
1648
- import_common7 = require("@vue-skuilder/common");
3525
+ import_common9 = require("@vue-skuilder/common");
1649
3526
  init_couch();
1650
3527
  init_updateQueue();
1651
3528
  init_types_legacy();
@@ -1722,14 +3599,14 @@ var init_courseDB = __esm({
1722
3599
  docs.rows.forEach((r) => {
1723
3600
  if (isSuccessRow(r)) {
1724
3601
  if (r.doc && r.doc.elo) {
1725
- ret.push((0, import_common7.toCourseElo)(r.doc.elo));
3602
+ ret.push((0, import_common9.toCourseElo)(r.doc.elo));
1726
3603
  } else {
1727
3604
  logger.warn("no elo data for card: " + r.id);
1728
- ret.push((0, import_common7.blankCourseElo)());
3605
+ ret.push((0, import_common9.blankCourseElo)());
1729
3606
  }
1730
3607
  } else {
1731
3608
  logger.warn("no elo data for card: " + JSON.stringify(r));
1732
- ret.push((0, import_common7.blankCourseElo)());
3609
+ ret.push((0, import_common9.blankCourseElo)());
1733
3610
  }
1734
3611
  });
1735
3612
  return ret;
@@ -1924,7 +3801,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1924
3801
  async getCourseTagStubs() {
1925
3802
  return getCourseTagStubs(this.id);
1926
3803
  }
1927
- async addNote(codeCourse, shape, data, author, tags, uploads, elo = (0, import_common7.blankCourseElo)()) {
3804
+ async addNote(codeCourse, shape, data, author, tags, uploads, elo = (0, import_common9.blankCourseElo)()) {
1928
3805
  try {
1929
3806
  const resp = await addNote55(this.id, codeCourse, shape, data, author, tags, uploads, elo);
1930
3807
  if (resp.ok) {
@@ -1933,19 +3810,19 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1933
3810
  `[courseDB.addNote] Note added but card creation failed: ${resp.cardCreationError}`
1934
3811
  );
1935
3812
  return {
1936
- status: import_common7.Status.error,
3813
+ status: import_common9.Status.error,
1937
3814
  message: `Note was added but no cards were created: ${resp.cardCreationError}`,
1938
3815
  id: resp.id
1939
3816
  };
1940
3817
  }
1941
3818
  return {
1942
- status: import_common7.Status.ok,
3819
+ status: import_common9.Status.ok,
1943
3820
  message: "",
1944
3821
  id: resp.id
1945
3822
  };
1946
3823
  } else {
1947
3824
  return {
1948
- status: import_common7.Status.error,
3825
+ status: import_common9.Status.error,
1949
3826
  message: "Unexpected error adding note"
1950
3827
  };
1951
3828
  }
@@ -1957,7 +3834,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1957
3834
  message: ${err.message}`
1958
3835
  );
1959
3836
  return {
1960
- status: import_common7.Status.error,
3837
+ status: import_common9.Status.error,
1961
3838
  message: `Error adding note to course. ${e.reason || err.message}`
1962
3839
  };
1963
3840
  }
@@ -2085,7 +3962,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
2085
3962
  const courseDoc = (await u.getCourseRegistrationsDoc()).courses.find((c) => {
2086
3963
  return c.courseID === this.id;
2087
3964
  });
2088
- targetElo = (0, import_common7.EloToNumber)(courseDoc.elo);
3965
+ targetElo = (0, import_common9.EloToNumber)(courseDoc.elo);
2089
3966
  } catch {
2090
3967
  targetElo = 1e3;
2091
3968
  }
@@ -2428,14 +4305,14 @@ var init_auth = __esm({
2428
4305
  });
2429
4306
 
2430
4307
  // src/impl/couch/CouchDBSyncStrategy.ts
2431
- var import_common8;
4308
+ var import_common10;
2432
4309
  var init_CouchDBSyncStrategy = __esm({
2433
4310
  "src/impl/couch/CouchDBSyncStrategy.ts"() {
2434
4311
  "use strict";
2435
4312
  init_factory();
2436
4313
  init_types_legacy();
2437
4314
  init_logger();
2438
- import_common8 = require("@vue-skuilder/common");
4315
+ import_common10 = require("@vue-skuilder/common");
2439
4316
  init_common();
2440
4317
  init_pouchdb_setup();
2441
4318
  init_couch();
@@ -2621,13 +4498,13 @@ async function dropUserFromClassroom(user, classID) {
2621
4498
  async function getUserClassrooms(user) {
2622
4499
  return getOrCreateClassroomRegistrationsDoc(user);
2623
4500
  }
2624
- var import_common10, import_moment6, log3, BaseUser, userCoursesDoc, userClassroomsDoc;
4501
+ var import_common12, import_moment6, log3, BaseUser, userCoursesDoc, userClassroomsDoc;
2625
4502
  var init_BaseUserDB = __esm({
2626
4503
  "src/impl/common/BaseUserDB.ts"() {
2627
4504
  "use strict";
2628
4505
  init_core();
2629
4506
  init_util();
2630
- import_common10 = require("@vue-skuilder/common");
4507
+ import_common12 = require("@vue-skuilder/common");
2631
4508
  import_moment6 = __toESM(require("moment"), 1);
2632
4509
  init_types_legacy();
2633
4510
  init_logger();
@@ -2677,7 +4554,7 @@ Currently logged-in as ${this._username}.`
2677
4554
  );
2678
4555
  }
2679
4556
  const result = await this.syncStrategy.createAccount(username, password);
2680
- if (result.status === import_common10.Status.ok) {
4557
+ if (result.status === import_common12.Status.ok) {
2681
4558
  log3(`Account created successfully, updating username to ${username}`);
2682
4559
  this._username = username;
2683
4560
  try {
@@ -2719,7 +4596,7 @@ Currently logged-in as ${this._username}.`
2719
4596
  async resetUserData() {
2720
4597
  if (this.syncStrategy.canAuthenticate()) {
2721
4598
  return {
2722
- status: import_common10.Status.error,
4599
+ status: import_common12.Status.error,
2723
4600
  error: "Reset user data is only available for local-only mode. Use logout instead for remote sync."
2724
4601
  };
2725
4602
  }
@@ -2738,11 +4615,11 @@ Currently logged-in as ${this._username}.`
2738
4615
  await localDB.bulkDocs(docsToDelete);
2739
4616
  }
2740
4617
  await this.init();
2741
- return { status: import_common10.Status.ok };
4618
+ return { status: import_common12.Status.ok };
2742
4619
  } catch (error) {
2743
4620
  logger.error("Failed to reset user data:", error);
2744
4621
  return {
2745
- status: import_common10.Status.error,
4622
+ status: import_common12.Status.error,
2746
4623
  error: error instanceof Error ? error.message : "Unknown error during reset"
2747
4624
  };
2748
4625
  }
@@ -3469,6 +5346,19 @@ Currently logged-in as ${this._username}.`
3469
5346
  };
3470
5347
  await this.localDB.put(doc);
3471
5348
  }
5349
+ async putUserOutcome(record) {
5350
+ try {
5351
+ await this.localDB.put(record);
5352
+ } catch (err) {
5353
+ if (err.status === 409) {
5354
+ const existing = await this.localDB.get(record._id);
5355
+ record._rev = existing._rev;
5356
+ await this.localDB.put(record);
5357
+ } else {
5358
+ throw err;
5359
+ }
5360
+ }
5361
+ }
3472
5362
  async deleteStrategyState(courseId, strategyKey) {
3473
5363
  const docId = buildStrategyStateId(courseId, strategyKey);
3474
5364
  try {
@@ -3511,6 +5401,7 @@ var init_factory = __esm({
3511
5401
  "use strict";
3512
5402
  init_common();
3513
5403
  init_logger();
5404
+ init_navigators();
3514
5405
  NOT_SET = "NOT_SET";
3515
5406
  ENV = {
3516
5407
  COUCHDB_SERVER_PROTOCOL: NOT_SET,
@@ -3522,11 +5413,11 @@ var init_factory = __esm({
3522
5413
  });
3523
5414
 
3524
5415
  // src/study/TagFilteredContentSource.ts
3525
- var import_common12, TagFilteredContentSource;
5416
+ var import_common14, TagFilteredContentSource;
3526
5417
  var init_TagFilteredContentSource = __esm({
3527
5418
  "src/study/TagFilteredContentSource.ts"() {
3528
5419
  "use strict";
3529
- import_common12 = require("@vue-skuilder/common");
5420
+ import_common14 = require("@vue-skuilder/common");
3530
5421
  init_courseDB();
3531
5422
  init_logger();
3532
5423
  TagFilteredContentSource = class {
@@ -3612,7 +5503,7 @@ var init_TagFilteredContentSource = __esm({
3612
5503
  * @returns Cards sorted by score descending (all scores = 1.0)
3613
5504
  */
3614
5505
  async getWeightedCards(limit) {
3615
- if (!(0, import_common12.hasActiveFilter)(this.filter)) {
5506
+ if (!(0, import_common14.hasActiveFilter)(this.filter)) {
3616
5507
  logger.warn("[TagFilteredContentSource] getWeightedCards called with no active filter");
3617
5508
  return [];
3618
5509
  }
@@ -3700,19 +5591,19 @@ async function getStudySource(source, user) {
3700
5591
  if (source.type === "classroom") {
3701
5592
  return await StudentClassroomDB.factory(source.id, user);
3702
5593
  } else {
3703
- if ((0, import_common13.hasActiveFilter)(source.tagFilter)) {
5594
+ if ((0, import_common15.hasActiveFilter)(source.tagFilter)) {
3704
5595
  return new TagFilteredContentSource(source.id, source.tagFilter, user);
3705
5596
  }
3706
5597
  return getDataLayer().getCourseDB(source.id);
3707
5598
  }
3708
5599
  }
3709
- var import_common13;
5600
+ var import_common15;
3710
5601
  var init_contentSource = __esm({
3711
5602
  "src/core/interfaces/contentSource.ts"() {
3712
5603
  "use strict";
3713
5604
  init_factory();
3714
5605
  init_classroomDB2();
3715
- import_common13 = require("@vue-skuilder/common");
5606
+ import_common15 = require("@vue-skuilder/common");
3716
5607
  init_TagFilteredContentSource();
3717
5608
  }
3718
5609
  });
@@ -3768,6 +5659,13 @@ var init_strategyState = __esm({
3768
5659
  }
3769
5660
  });
3770
5661
 
5662
+ // src/core/types/userOutcome.ts
5663
+ var init_userOutcome = __esm({
5664
+ "src/core/types/userOutcome.ts"() {
5665
+ "use strict";
5666
+ }
5667
+ });
5668
+
3771
5669
  // src/core/bulkImport/cardProcessor.ts
3772
5670
  async function importParsedCards(parsedCards, courseDB, config) {
3773
5671
  const results = [];
@@ -3836,7 +5734,7 @@ elo: ${elo}`;
3836
5734
  misc: {}
3837
5735
  } : void 0
3838
5736
  );
3839
- if (result.status === import_common14.Status.ok) {
5737
+ if (result.status === import_common16.Status.ok) {
3840
5738
  return {
3841
5739
  originalText,
3842
5740
  status: "success",
@@ -3880,17 +5778,17 @@ function validateProcessorConfig(config) {
3880
5778
  }
3881
5779
  return { isValid: true };
3882
5780
  }
3883
- var import_common14;
5781
+ var import_common16;
3884
5782
  var init_cardProcessor = __esm({
3885
5783
  "src/core/bulkImport/cardProcessor.ts"() {
3886
5784
  "use strict";
3887
- import_common14 = require("@vue-skuilder/common");
5785
+ import_common16 = require("@vue-skuilder/common");
3888
5786
  init_logger();
3889
5787
  }
3890
5788
  });
3891
5789
 
3892
5790
  // src/core/bulkImport/types.ts
3893
- var init_types = __esm({
5791
+ var init_types3 = __esm({
3894
5792
  "src/core/bulkImport/types.ts"() {
3895
5793
  "use strict";
3896
5794
  }
@@ -3901,7 +5799,7 @@ var init_bulkImport = __esm({
3901
5799
  "src/core/bulkImport/index.ts"() {
3902
5800
  "use strict";
3903
5801
  init_cardProcessor();
3904
- init_types();
5802
+ init_types3();
3905
5803
  }
3906
5804
  });
3907
5805
 
@@ -3916,19 +5814,39 @@ __export(core_exports, {
3916
5814
  NavigatorRole: () => NavigatorRole,
3917
5815
  NavigatorRoles: () => NavigatorRoles,
3918
5816
  Navigators: () => Navigators,
5817
+ aggregateOutcomesForGradient: () => aggregateOutcomesForGradient,
3919
5818
  areQuestionRecords: () => areQuestionRecords,
3920
5819
  buildStrategyStateId: () => buildStrategyStateId,
5820
+ computeDeviation: () => computeDeviation,
5821
+ computeEffectiveWeight: () => computeEffectiveWeight,
5822
+ computeOutcomeSignal: () => computeOutcomeSignal,
5823
+ computeSpread: () => computeSpread,
5824
+ computeStrategyGradient: () => computeStrategyGradient,
5825
+ createOrchestrationContext: () => createOrchestrationContext,
3921
5826
  docIsDeleted: () => docIsDeleted,
3922
5827
  getCardHistoryID: () => getCardHistoryID,
3923
5828
  getCardOrigin: () => getCardOrigin,
5829
+ getDefaultLearnableWeight: () => getDefaultLearnableWeight,
5830
+ getRegisteredNavigator: () => getRegisteredNavigator,
5831
+ getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
3924
5832
  getStudySource: () => getStudySource,
5833
+ hasRegisteredNavigator: () => hasRegisteredNavigator,
3925
5834
  importParsedCards: () => importParsedCards,
5835
+ initializeNavigatorRegistry: () => initializeNavigatorRegistry,
3926
5836
  isFilter: () => isFilter,
3927
5837
  isGenerator: () => isGenerator,
3928
5838
  isQuestionRecord: () => isQuestionRecord,
3929
5839
  isReview: () => isReview,
3930
5840
  log: () => log,
5841
+ mountPipelineDebugger: () => mountPipelineDebugger,
3931
5842
  parseCardHistoryID: () => parseCardHistoryID,
5843
+ pipelineDebugAPI: () => pipelineDebugAPI,
5844
+ recordUserOutcome: () => recordUserOutcome,
5845
+ registerNavigator: () => registerNavigator,
5846
+ runPeriodUpdate: () => runPeriodUpdate,
5847
+ scoreAccuracyInZone: () => scoreAccuracyInZone,
5848
+ updateLearningState: () => updateLearningState,
5849
+ updateStrategyWeight: () => updateStrategyWeight,
3932
5850
  validateProcessorConfig: () => validateProcessorConfig
3933
5851
  });
3934
5852
  module.exports = __toCommonJS(core_exports);
@@ -3938,10 +5856,12 @@ var init_core = __esm({
3938
5856
  init_types_legacy();
3939
5857
  init_user();
3940
5858
  init_strategyState();
5859
+ init_userOutcome();
3941
5860
  init_Loggable();
3942
5861
  init_util();
3943
5862
  init_navigators();
3944
5863
  init_bulkImport();
5864
+ init_orchestration();
3945
5865
  }
3946
5866
  });
3947
5867
  init_core();
@@ -3955,19 +5875,39 @@ init_core();
3955
5875
  NavigatorRole,
3956
5876
  NavigatorRoles,
3957
5877
  Navigators,
5878
+ aggregateOutcomesForGradient,
3958
5879
  areQuestionRecords,
3959
5880
  buildStrategyStateId,
5881
+ computeDeviation,
5882
+ computeEffectiveWeight,
5883
+ computeOutcomeSignal,
5884
+ computeSpread,
5885
+ computeStrategyGradient,
5886
+ createOrchestrationContext,
3960
5887
  docIsDeleted,
3961
5888
  getCardHistoryID,
3962
5889
  getCardOrigin,
5890
+ getDefaultLearnableWeight,
5891
+ getRegisteredNavigator,
5892
+ getRegisteredNavigatorNames,
3963
5893
  getStudySource,
5894
+ hasRegisteredNavigator,
3964
5895
  importParsedCards,
5896
+ initializeNavigatorRegistry,
3965
5897
  isFilter,
3966
5898
  isGenerator,
3967
5899
  isQuestionRecord,
3968
5900
  isReview,
3969
5901
  log,
5902
+ mountPipelineDebugger,
3970
5903
  parseCardHistoryID,
5904
+ pipelineDebugAPI,
5905
+ recordUserOutcome,
5906
+ registerNavigator,
5907
+ runPeriodUpdate,
5908
+ scoreAccuracyInZone,
5909
+ updateLearningState,
5910
+ updateStrategyWeight,
3971
5911
  validateProcessorConfig
3972
5912
  });
3973
5913
  //# sourceMappingURL=index.js.map