@vue-skuilder/db 0.1.22 → 0.1.24

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 (67) hide show
  1. package/dist/{contentSource-BP9hznNV.d.ts → contentSource-BotbOOfX.d.ts} +227 -3
  2. package/dist/{contentSource-DsJadoBU.d.cts → contentSource-C90LH-OH.d.cts} +227 -3
  3. package/dist/core/index.d.cts +220 -6
  4. package/dist/core/index.d.ts +220 -6
  5. package/dist/core/index.js +2052 -559
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +2035 -555
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-CHYrQ5pB.d.cts → dataLayerProvider-DGKp4zFB.d.cts} +1 -1
  10. package/dist/{dataLayerProvider-MDTxXq2l.d.ts → dataLayerProvider-SBpz9jQf.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 +1811 -574
  14. package/dist/impl/couch/index.js.map +1 -1
  15. package/dist/impl/couch/index.mjs +1792 -550
  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 +1797 -560
  20. package/dist/impl/static/index.js.map +1 -1
  21. package/dist/impl/static/index.mjs +1789 -547
  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 +150 -12
  26. package/dist/index.d.ts +150 -12
  27. package/dist/index.js +2658 -791
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2584 -747
  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 +188 -5
  40. package/docs/todo-strategy-authoring.md +8 -6
  41. package/package.json +3 -3
  42. package/src/core/index.ts +2 -0
  43. package/src/core/interfaces/contentSource.ts +7 -0
  44. package/src/core/interfaces/userDB.ts +6 -0
  45. package/src/core/navigators/Pipeline.ts +46 -0
  46. package/src/core/navigators/PipelineAssembler.ts +14 -1
  47. package/src/core/navigators/filters/WeightedFilter.ts +141 -0
  48. package/src/core/navigators/filters/types.ts +4 -0
  49. package/src/core/navigators/generators/CompositeGenerator.ts +61 -19
  50. package/src/core/navigators/generators/types.ts +4 -0
  51. package/src/core/navigators/index.ts +194 -13
  52. package/src/core/orchestration/gradient.ts +133 -0
  53. package/src/core/orchestration/index.ts +210 -0
  54. package/src/core/orchestration/learning.ts +250 -0
  55. package/src/core/orchestration/recording.ts +92 -0
  56. package/src/core/orchestration/signal.ts +67 -0
  57. package/src/core/types/contentNavigationStrategy.ts +38 -0
  58. package/src/core/types/learningState.ts +77 -0
  59. package/src/core/types/types-legacy.ts +4 -0
  60. package/src/core/types/userOutcome.ts +51 -0
  61. package/src/courseConfigRegistration.ts +546 -0
  62. package/src/factory.ts +6 -0
  63. package/src/impl/common/BaseUserDB.ts +16 -0
  64. package/src/index.ts +2 -0
  65. package/src/study/SessionController.ts +64 -1
  66. package/tests/core/navigators/Pipeline.test.ts +2 -0
  67. package/docs/todo-evolutionary-orchestration.md +0 -310
@@ -1,7 +1,17 @@
1
+ var __defProp = Object.defineProperty;
1
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __glob = (map) => (path2) => {
4
+ var fn = map[path2];
5
+ if (fn) return fn();
6
+ throw new Error("Module not found in bundle: " + path2);
7
+ };
2
8
  var __esm = (fn, res) => function __init() {
3
9
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
4
10
  };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
5
15
 
6
16
  // src/core/interfaces/adminDB.ts
7
17
  var init_adminDB = __esm({
@@ -91,6 +101,8 @@ var init_types_legacy = __esm({
91
101
  DocType2["TAG"] = "TAG";
92
102
  DocType2["NAVIGATION_STRATEGY"] = "NAVIGATION_STRATEGY";
93
103
  DocType2["STRATEGY_STATE"] = "STRATEGY_STATE";
104
+ DocType2["USER_OUTCOME"] = "USER_OUTCOME";
105
+ DocType2["STRATEGY_LEARNING_STATE"] = "STRATEGY_LEARNING_STATE";
94
106
  return DocType2;
95
107
  })(DocType || {});
96
108
  DocTypePrefixes = {
@@ -105,7 +117,9 @@ var init_types_legacy = __esm({
105
117
  ["VIEW" /* VIEW */]: "VIEW",
106
118
  ["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
107
119
  ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
108
- ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE"
120
+ ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE",
121
+ ["USER_OUTCOME" /* USER_OUTCOME */]: "USER_OUTCOME",
122
+ ["STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */]: "STRATEGY_LEARNING_STATE"
109
123
  };
110
124
  }
111
125
  });
@@ -673,198 +687,1625 @@ var init_courseLookupDB = __esm({
673
687
  }
674
688
  });
675
689
 
676
- // src/core/navigators/index.ts
677
- function getCardOrigin(card) {
678
- if (card.provenance.length === 0) {
679
- throw new Error("Card has no provenance - cannot determine origin");
680
- }
681
- const firstEntry = card.provenance[0];
682
- const reason = firstEntry.reason.toLowerCase();
683
- if (reason.includes("failed")) {
684
- return "failed";
685
- }
686
- if (reason.includes("review")) {
687
- return "review";
688
- }
689
- return "new";
690
- }
691
- function isGenerator(impl) {
692
- return NavigatorRoles[impl] === "generator" /* GENERATOR */;
693
- }
694
- function isFilter(impl) {
695
- return NavigatorRoles[impl] === "filter" /* FILTER */;
696
- }
697
- var Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
698
- var init_navigators = __esm({
699
- "src/core/navigators/index.ts"() {
690
+ // src/core/navigators/generators/CompositeGenerator.ts
691
+ var CompositeGenerator_exports = {};
692
+ __export(CompositeGenerator_exports, {
693
+ AggregationMode: () => AggregationMode,
694
+ default: () => CompositeGenerator
695
+ });
696
+ var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
697
+ var init_CompositeGenerator = __esm({
698
+ "src/core/navigators/generators/CompositeGenerator.ts"() {
700
699
  "use strict";
700
+ init_navigators();
701
701
  init_logger();
702
- Navigators = /* @__PURE__ */ ((Navigators2) => {
703
- Navigators2["ELO"] = "elo";
704
- Navigators2["SRS"] = "srs";
705
- Navigators2["HIERARCHY"] = "hierarchyDefinition";
706
- Navigators2["INTERFERENCE"] = "interferenceMitigator";
707
- Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
708
- Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
709
- return Navigators2;
710
- })(Navigators || {});
711
- NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
712
- NavigatorRole2["GENERATOR"] = "generator";
713
- NavigatorRole2["FILTER"] = "filter";
714
- return NavigatorRole2;
715
- })(NavigatorRole || {});
716
- NavigatorRoles = {
717
- ["elo" /* ELO */]: "generator" /* GENERATOR */,
718
- ["srs" /* SRS */]: "generator" /* GENERATOR */,
719
- ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
720
- ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
721
- ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
722
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
723
- };
724
- ContentNavigator = class {
725
- /** User interface for this navigation session */
726
- user;
727
- /** Course interface for this navigation session */
728
- course;
729
- /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
730
- strategyName;
731
- /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
732
- strategyId;
733
- /**
734
- * Constructor for standard navigators.
735
- * Call this from subclass constructors to initialize common fields.
736
- *
737
- * Note: CompositeGenerator and Pipeline call super() without args, then set
738
- * user/course fields directly if needed.
739
- */
740
- constructor(user, course, strategyData) {
741
- this.user = user;
742
- this.course = course;
743
- if (strategyData) {
744
- this.strategyName = strategyData.name;
745
- this.strategyId = strategyData._id;
702
+ AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
703
+ AggregationMode2["MAX"] = "max";
704
+ AggregationMode2["AVERAGE"] = "average";
705
+ AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
706
+ return AggregationMode2;
707
+ })(AggregationMode || {});
708
+ DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
709
+ FREQUENCY_BOOST_FACTOR = 0.1;
710
+ CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
711
+ /** Human-readable name for CardGenerator interface */
712
+ name = "Composite Generator";
713
+ generators;
714
+ aggregationMode;
715
+ constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
716
+ super();
717
+ this.generators = generators;
718
+ this.aggregationMode = aggregationMode;
719
+ if (generators.length === 0) {
720
+ throw new Error("CompositeGenerator requires at least one generator");
746
721
  }
722
+ logger.debug(
723
+ `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
724
+ );
747
725
  }
748
- // ============================================================================
749
- // STRATEGY STATE HELPERS
750
- // ============================================================================
751
- //
752
- // These methods allow strategies to persist their own state (user preferences,
753
- // learned patterns, temporal tracking) in the user database.
754
- //
755
- // ============================================================================
756
726
  /**
757
- * Unique key identifying this strategy for state storage.
727
+ * Creates a CompositeGenerator from strategy data.
758
728
  *
759
- * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
760
- * Override in subclasses if multiple instances of the same strategy type
761
- * need separate state storage.
729
+ * This is a convenience factory for use by PipelineAssembler.
762
730
  */
763
- get strategyKey() {
764
- return this.constructor.name;
731
+ static async fromStrategies(user, course, strategies, aggregationMode = DEFAULT_AGGREGATION_MODE) {
732
+ const generators = await Promise.all(
733
+ strategies.map((s) => ContentNavigator.create(user, course, s))
734
+ );
735
+ return new _CompositeGenerator(generators, aggregationMode);
765
736
  }
766
737
  /**
767
- * Get this strategy's persisted state for the current course.
738
+ * Get weighted cards from all generators, merge and deduplicate.
768
739
  *
769
- * @returns The strategy's data payload, or null if no state exists
770
- * @throws Error if user or course is not initialized
771
- */
772
- async getStrategyState() {
773
- if (!this.user || !this.course) {
774
- throw new Error(
775
- `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
776
- );
777
- }
778
- return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
779
- }
780
- /**
781
- * Persist this strategy's state for the current course.
740
+ * Cards appearing in multiple generators receive a score boost.
741
+ * Provenance tracks which generators produced each card and how scores were aggregated.
782
742
  *
783
- * @param data - The strategy's data payload to store
784
- * @throws Error if user or course is not initialized
743
+ * This method supports both the legacy signature (limit only) and the
744
+ * CardGenerator interface signature (limit, context).
745
+ *
746
+ * @param limit - Maximum number of cards to return
747
+ * @param context - GeneratorContext passed to child generators (required when called via Pipeline)
785
748
  */
786
- async putStrategyState(data) {
787
- if (!this.user || !this.course) {
749
+ async getWeightedCards(limit, context) {
750
+ if (!context) {
788
751
  throw new Error(
789
- `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
752
+ "CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly."
790
753
  );
791
754
  }
792
- return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
755
+ const results = await Promise.all(
756
+ this.generators.map((g) => g.getWeightedCards(limit, context))
757
+ );
758
+ const byCardId = /* @__PURE__ */ new Map();
759
+ results.forEach((cards, index) => {
760
+ const gen = this.generators[index];
761
+ let weight = gen.learnable?.weight ?? 1;
762
+ let deviation;
763
+ if (gen.learnable && !gen.staticWeight && context.orchestration) {
764
+ const strategyId = gen.strategyId;
765
+ if (strategyId) {
766
+ weight = context.orchestration.getEffectiveWeight(strategyId, gen.learnable);
767
+ deviation = context.orchestration.getDeviation(strategyId);
768
+ }
769
+ }
770
+ for (const card of cards) {
771
+ if (card.provenance.length > 0) {
772
+ card.provenance[0].effectiveWeight = weight;
773
+ card.provenance[0].deviation = deviation;
774
+ }
775
+ const existing = byCardId.get(card.cardId) || [];
776
+ existing.push({ card, weight });
777
+ byCardId.set(card.cardId, existing);
778
+ }
779
+ });
780
+ const merged = [];
781
+ for (const [, items] of byCardId) {
782
+ const cards = items.map((i) => i.card);
783
+ const aggregatedScore = this.aggregateScores(items);
784
+ const finalScore = Math.min(1, aggregatedScore);
785
+ const mergedProvenance = cards.flatMap((c) => c.provenance);
786
+ const initialScore = cards[0].score;
787
+ const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
788
+ const reason = this.buildAggregationReason(items, finalScore);
789
+ merged.push({
790
+ ...cards[0],
791
+ score: finalScore,
792
+ provenance: [
793
+ ...mergedProvenance,
794
+ {
795
+ strategy: "composite",
796
+ strategyName: "Composite Generator",
797
+ strategyId: "COMPOSITE_GENERATOR",
798
+ action,
799
+ score: finalScore,
800
+ reason
801
+ }
802
+ ]
803
+ });
804
+ }
805
+ return merged.sort((a, b) => b.score - a.score).slice(0, limit);
793
806
  }
794
807
  /**
795
- * Factory method to create navigator instances dynamically.
796
- *
797
- * @param user - User interface
798
- * @param course - Course interface
799
- * @param strategyData - Strategy configuration document
800
- * @returns the runtime object used to steer a study session.
808
+ * Build human-readable reason for score aggregation.
801
809
  */
802
- static async create(user, course, strategyData) {
803
- const implementingClass = strategyData.implementingClass;
804
- let NavigatorImpl;
805
- const variations = [".ts", ".js", ""];
806
- const dirs = ["filters", "generators"];
807
- for (const ext of variations) {
808
- for (const dir of dirs) {
809
- const loadFrom = `./${dir}/${implementingClass}${ext}`;
810
- try {
811
- const module = await import(loadFrom);
812
- NavigatorImpl = module.default;
813
- break;
814
- } catch (e) {
815
- logger.debug(`Failed to load extension from ${loadFrom}:`, e);
816
- }
817
- }
810
+ buildAggregationReason(items, finalScore) {
811
+ const cards = items.map((i) => i.card);
812
+ const count = cards.length;
813
+ const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
814
+ if (count === 1) {
815
+ const weightMsg = Math.abs(items[0].weight - 1) > 1e-3 ? ` (w=${items[0].weight.toFixed(2)})` : "";
816
+ return `Single generator, score ${finalScore.toFixed(2)}${weightMsg}`;
818
817
  }
819
- if (!NavigatorImpl) {
820
- throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
818
+ const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
819
+ switch (this.aggregationMode) {
820
+ case "max" /* MAX */:
821
+ return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
822
+ case "average" /* AVERAGE */:
823
+ return `Weighted Avg of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
824
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
825
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
826
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
827
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
828
+ const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
829
+ return `Frequency boost from ${count} generators (${strategies}): w-avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
830
+ }
831
+ default:
832
+ return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
821
833
  }
822
- return new NavigatorImpl(user, course, strategyData);
823
834
  }
824
835
  /**
825
- * Get cards with suitability scores and provenance trails.
826
- *
827
- * **This is the PRIMARY API for navigation strategies.**
828
- *
829
- * Returns cards ranked by suitability score (0-1). Higher scores indicate
830
- * better candidates for presentation. Each card includes a provenance trail
831
- * documenting how strategies contributed to the final score.
832
- *
833
- * ## Implementation Required
834
- * All navigation strategies MUST override this method. The base class does
835
- * not provide a default implementation.
836
- *
837
- * ## For Generators
838
- * Override this method to generate candidates and compute scores based on
839
- * your strategy's logic (e.g., ELO proximity, review urgency). Create the
840
- * initial provenance entry with action='generated'.
841
- *
842
- * ## For Filters
843
- * Filters should implement the CardFilter interface instead and be composed
844
- * via Pipeline. Filters do not directly implement getWeightedCards().
845
- *
846
- * @param limit - Maximum cards to return
847
- * @returns Cards sorted by score descending, with provenance trails
836
+ * Aggregate scores from multiple generators for the same card.
848
837
  */
849
- async getWeightedCards(_limit) {
850
- throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
838
+ aggregateScores(items) {
839
+ const scores = items.map((i) => i.card.score);
840
+ switch (this.aggregationMode) {
841
+ case "max" /* MAX */:
842
+ return Math.max(...scores);
843
+ case "average" /* AVERAGE */: {
844
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
845
+ if (totalWeight === 0) return 0;
846
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
847
+ return weightedSum / totalWeight;
848
+ }
849
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
850
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
851
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
852
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
853
+ const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (items.length - 1);
854
+ return avg * frequencyBoost;
855
+ }
856
+ default:
857
+ return scores[0];
858
+ }
851
859
  }
852
860
  };
853
861
  }
854
862
  });
855
863
 
856
- // src/core/navigators/Pipeline.ts
864
+ // src/core/navigators/generators/elo.ts
865
+ var elo_exports = {};
866
+ __export(elo_exports, {
867
+ default: () => ELONavigator
868
+ });
857
869
  import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
858
- function logPipelineConfig(generator, filters) {
859
- const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
860
- logger.info(
861
- `[Pipeline] Configuration:
862
- Generator: ${generator.name}
863
- Filters:${filterList}`
864
- );
865
- }
866
- function logTagHydration(cards, tagsByCard) {
867
- const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
870
+ var ELONavigator;
871
+ var init_elo = __esm({
872
+ "src/core/navigators/generators/elo.ts"() {
873
+ "use strict";
874
+ init_navigators();
875
+ ELONavigator = class extends ContentNavigator {
876
+ /** Human-readable name for CardGenerator interface */
877
+ name;
878
+ constructor(user, course, strategyData) {
879
+ super(user, course, strategyData);
880
+ this.name = strategyData?.name || "ELO";
881
+ }
882
+ /**
883
+ * Get new cards with suitability scores based on ELO distance.
884
+ *
885
+ * Cards closer to user's ELO get higher scores.
886
+ * Score formula: max(0, 1 - distance / 500)
887
+ *
888
+ * NOTE: This generator only handles NEW cards. Reviews are handled by
889
+ * SRSNavigator. Use CompositeGenerator to combine both.
890
+ *
891
+ * This method supports both the legacy signature (limit only) and the
892
+ * CardGenerator interface signature (limit, context).
893
+ *
894
+ * @param limit - Maximum number of cards to return
895
+ * @param context - Optional GeneratorContext (used when called via Pipeline)
896
+ */
897
+ async getWeightedCards(limit, context) {
898
+ let userGlobalElo;
899
+ if (context?.userElo !== void 0) {
900
+ userGlobalElo = context.userElo;
901
+ } else {
902
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
903
+ const userElo = toCourseElo2(courseReg.elo);
904
+ userGlobalElo = userElo.global.score;
905
+ }
906
+ const activeCards = await this.user.getActiveCards();
907
+ const newCards = (await this.course.getCardsCenteredAtELO(
908
+ { limit, elo: "user" },
909
+ (c) => !activeCards.some((ac) => c.cardID === ac.cardID)
910
+ )).map((c) => ({ ...c, status: "new" }));
911
+ const cardIds = newCards.map((c) => c.cardID);
912
+ const cardEloData = await this.course.getCardEloData(cardIds);
913
+ const scored = newCards.map((c, i) => {
914
+ const cardElo = cardEloData[i]?.global?.score ?? 1e3;
915
+ const distance = Math.abs(cardElo - userGlobalElo);
916
+ const score = Math.max(0, 1 - distance / 500);
917
+ return {
918
+ cardId: c.cardID,
919
+ courseId: c.courseID,
920
+ score,
921
+ provenance: [
922
+ {
923
+ strategy: "elo",
924
+ strategyName: this.strategyName || this.name,
925
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
926
+ action: "generated",
927
+ score,
928
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), new card`
929
+ }
930
+ ]
931
+ };
932
+ });
933
+ scored.sort((a, b) => b.score - a.score);
934
+ return scored.slice(0, limit);
935
+ }
936
+ };
937
+ }
938
+ });
939
+
940
+ // src/core/navigators/generators/index.ts
941
+ var generators_exports = {};
942
+ var init_generators = __esm({
943
+ "src/core/navigators/generators/index.ts"() {
944
+ "use strict";
945
+ }
946
+ });
947
+
948
+ // src/core/navigators/generators/srs.ts
949
+ var srs_exports = {};
950
+ __export(srs_exports, {
951
+ default: () => SRSNavigator
952
+ });
953
+ import moment3 from "moment";
954
+ var SRSNavigator;
955
+ var init_srs = __esm({
956
+ "src/core/navigators/generators/srs.ts"() {
957
+ "use strict";
958
+ init_navigators();
959
+ init_logger();
960
+ SRSNavigator = class extends ContentNavigator {
961
+ /** Human-readable name for CardGenerator interface */
962
+ name;
963
+ constructor(user, course, strategyData) {
964
+ super(user, course, strategyData);
965
+ this.name = strategyData?.name || "SRS";
966
+ }
967
+ /**
968
+ * Get review cards scored by urgency.
969
+ *
970
+ * Score formula combines:
971
+ * - Relative overdueness: hoursOverdue / intervalHours
972
+ * - Interval recency: exponential decay favoring shorter intervals
973
+ *
974
+ * Cards not yet due are excluded (not scored as 0).
975
+ *
976
+ * This method supports both the legacy signature (limit only) and the
977
+ * CardGenerator interface signature (limit, context).
978
+ *
979
+ * @param limit - Maximum number of cards to return
980
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
981
+ */
982
+ async getWeightedCards(limit, _context) {
983
+ if (!this.user || !this.course) {
984
+ throw new Error("SRSNavigator requires user and course to be set");
985
+ }
986
+ const reviews = await this.user.getPendingReviews(this.course.getCourseID());
987
+ const now = moment3.utc();
988
+ const dueReviews = reviews.filter((r) => now.isAfter(moment3.utc(r.reviewTime)));
989
+ const scored = dueReviews.map((review) => {
990
+ const { score, reason } = this.computeUrgencyScore(review, now);
991
+ return {
992
+ cardId: review.cardId,
993
+ courseId: review.courseId,
994
+ score,
995
+ reviewID: review._id,
996
+ provenance: [
997
+ {
998
+ strategy: "srs",
999
+ strategyName: this.strategyName || this.name,
1000
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1001
+ action: "generated",
1002
+ score,
1003
+ reason
1004
+ }
1005
+ ]
1006
+ };
1007
+ });
1008
+ logger.debug(`[srsNav] got ${scored.length} weighted cards`);
1009
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1010
+ }
1011
+ /**
1012
+ * Compute urgency score for a review card.
1013
+ *
1014
+ * Two factors:
1015
+ * 1. Relative overdueness = hoursOverdue / intervalHours
1016
+ * - 2 days overdue on 3-day interval = 0.67 (urgent)
1017
+ * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1018
+ *
1019
+ * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1020
+ * - 24h interval → ~1.0 (very recent learning)
1021
+ * - 30 days (720h) → ~0.56
1022
+ * - 180 days → ~0.30
1023
+ *
1024
+ * Combined: base 0.5 + weighted average of factors * 0.45
1025
+ * Result range: approximately 0.5 to 0.95
1026
+ */
1027
+ computeUrgencyScore(review, now) {
1028
+ const scheduledAt = moment3.utc(review.scheduledAt);
1029
+ const due = moment3.utc(review.reviewTime);
1030
+ const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1031
+ const hoursOverdue = now.diff(due, "hours");
1032
+ const relativeOverdue = hoursOverdue / intervalHours;
1033
+ const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1034
+ const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1035
+ const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1036
+ const score = Math.min(0.95, 0.5 + urgency * 0.45);
1037
+ const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
1038
+ return { score, reason };
1039
+ }
1040
+ };
1041
+ }
1042
+ });
1043
+
1044
+ // src/core/navigators/generators/types.ts
1045
+ var types_exports = {};
1046
+ var init_types = __esm({
1047
+ "src/core/navigators/generators/types.ts"() {
1048
+ "use strict";
1049
+ }
1050
+ });
1051
+
1052
+ // import("./generators/**/*") in src/core/navigators/index.ts
1053
+ var globImport_generators;
1054
+ var init_ = __esm({
1055
+ 'import("./generators/**/*") in src/core/navigators/index.ts'() {
1056
+ globImport_generators = __glob({
1057
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
1058
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
1059
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
1060
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
1061
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports))
1062
+ });
1063
+ }
1064
+ });
1065
+
1066
+ // src/core/types/contentNavigationStrategy.ts
1067
+ var DEFAULT_LEARNABLE_WEIGHT;
1068
+ var init_contentNavigationStrategy = __esm({
1069
+ "src/core/types/contentNavigationStrategy.ts"() {
1070
+ "use strict";
1071
+ DEFAULT_LEARNABLE_WEIGHT = {
1072
+ weight: 1,
1073
+ confidence: 0.1,
1074
+ // Low confidence initially = wide exploration
1075
+ sampleSize: 0
1076
+ };
1077
+ }
1078
+ });
1079
+
1080
+ // src/core/navigators/filters/WeightedFilter.ts
1081
+ var WeightedFilter_exports = {};
1082
+ __export(WeightedFilter_exports, {
1083
+ WeightedFilter: () => WeightedFilter
1084
+ });
1085
+ var WeightedFilter;
1086
+ var init_WeightedFilter = __esm({
1087
+ "src/core/navigators/filters/WeightedFilter.ts"() {
1088
+ "use strict";
1089
+ init_contentNavigationStrategy();
1090
+ WeightedFilter = class {
1091
+ name;
1092
+ inner;
1093
+ learnable;
1094
+ staticWeight;
1095
+ strategyId;
1096
+ constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
1097
+ this.inner = inner;
1098
+ this.name = inner.name;
1099
+ this.learnable = learnable;
1100
+ this.staticWeight = staticWeight;
1101
+ this.strategyId = strategyId;
1102
+ }
1103
+ /**
1104
+ * Apply the inner filter, then scale its effect by the configured weight.
1105
+ */
1106
+ async transform(cards, context) {
1107
+ let effectiveWeight = this.learnable.weight;
1108
+ let deviation;
1109
+ if (!this.staticWeight && context.orchestration) {
1110
+ const strategyId = this.strategyId || this.inner.strategyId || this.name;
1111
+ effectiveWeight = context.orchestration.getEffectiveWeight(strategyId, this.learnable);
1112
+ deviation = context.orchestration.getDeviation(strategyId);
1113
+ }
1114
+ if (Math.abs(effectiveWeight - 1) < 1e-3) {
1115
+ return this.inner.transform(cards, context);
1116
+ }
1117
+ const originalScores = /* @__PURE__ */ new Map();
1118
+ for (const card of cards) {
1119
+ originalScores.set(card.cardId, card.score);
1120
+ }
1121
+ const transformedCards = await this.inner.transform(cards, context);
1122
+ return transformedCards.map((card) => {
1123
+ const originalScore = originalScores.get(card.cardId);
1124
+ if (originalScore === void 0 || originalScore === 0 || card.score === 0) {
1125
+ return card;
1126
+ }
1127
+ const rawEffect = card.score / originalScore;
1128
+ if (Math.abs(rawEffect - 1) < 1e-4) {
1129
+ return card;
1130
+ }
1131
+ const weightedEffect = Math.pow(rawEffect, effectiveWeight);
1132
+ const newScore = originalScore * weightedEffect;
1133
+ const lastProvIndex = card.provenance.length - 1;
1134
+ const lastProv = card.provenance[lastProvIndex];
1135
+ if (lastProv) {
1136
+ const updatedProvenance = [...card.provenance];
1137
+ updatedProvenance[lastProvIndex] = {
1138
+ ...lastProv,
1139
+ score: newScore,
1140
+ effectiveWeight,
1141
+ deviation
1142
+ // We can optionally append to the reason, but the structured field is key
1143
+ };
1144
+ return {
1145
+ ...card,
1146
+ score: newScore,
1147
+ provenance: updatedProvenance
1148
+ };
1149
+ }
1150
+ return {
1151
+ ...card,
1152
+ score: newScore
1153
+ };
1154
+ });
1155
+ }
1156
+ };
1157
+ }
1158
+ });
1159
+
1160
+ // src/core/navigators/filters/eloDistance.ts
1161
+ var eloDistance_exports = {};
1162
+ __export(eloDistance_exports, {
1163
+ DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1164
+ DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1165
+ DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1166
+ createEloDistanceFilter: () => createEloDistanceFilter
1167
+ });
1168
+ function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1169
+ const normalizedDistance = distance / halfLife;
1170
+ const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1171
+ return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1172
+ }
1173
+ function createEloDistanceFilter(config) {
1174
+ const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1175
+ const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1176
+ const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1177
+ return {
1178
+ name: "ELO Distance Filter",
1179
+ async transform(cards, context) {
1180
+ const { course, userElo } = context;
1181
+ const cardIds = cards.map((c) => c.cardId);
1182
+ const cardElos = await course.getCardEloData(cardIds);
1183
+ return cards.map((card, i) => {
1184
+ const cardElo = cardElos[i]?.global?.score ?? 1e3;
1185
+ const distance = Math.abs(cardElo - userElo);
1186
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1187
+ const newScore = card.score * multiplier;
1188
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1189
+ return {
1190
+ ...card,
1191
+ score: newScore,
1192
+ provenance: [
1193
+ ...card.provenance,
1194
+ {
1195
+ strategy: "eloDistance",
1196
+ strategyName: "ELO Distance Filter",
1197
+ strategyId: "ELO_DISTANCE_FILTER",
1198
+ action,
1199
+ score: newScore,
1200
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1201
+ }
1202
+ ]
1203
+ };
1204
+ });
1205
+ }
1206
+ };
1207
+ }
1208
+ var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1209
+ var init_eloDistance = __esm({
1210
+ "src/core/navigators/filters/eloDistance.ts"() {
1211
+ "use strict";
1212
+ DEFAULT_HALF_LIFE = 200;
1213
+ DEFAULT_MIN_MULTIPLIER = 0.3;
1214
+ DEFAULT_MAX_MULTIPLIER = 1;
1215
+ }
1216
+ });
1217
+
1218
+ // src/core/navigators/filters/hierarchyDefinition.ts
1219
+ var hierarchyDefinition_exports = {};
1220
+ __export(hierarchyDefinition_exports, {
1221
+ default: () => HierarchyDefinitionNavigator
1222
+ });
1223
+ import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
1224
+ var DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1225
+ var init_hierarchyDefinition = __esm({
1226
+ "src/core/navigators/filters/hierarchyDefinition.ts"() {
1227
+ "use strict";
1228
+ init_navigators();
1229
+ DEFAULT_MIN_COUNT = 3;
1230
+ HierarchyDefinitionNavigator = class extends ContentNavigator {
1231
+ config;
1232
+ /** Human-readable name for CardFilter interface */
1233
+ name;
1234
+ constructor(user, course, strategyData) {
1235
+ super(user, course, strategyData);
1236
+ this.config = this.parseConfig(strategyData.serializedData);
1237
+ this.name = strategyData.name || "Hierarchy Definition";
1238
+ }
1239
+ parseConfig(serializedData) {
1240
+ try {
1241
+ const parsed = JSON.parse(serializedData);
1242
+ return {
1243
+ prerequisites: parsed.prerequisites || {}
1244
+ };
1245
+ } catch {
1246
+ return {
1247
+ prerequisites: {}
1248
+ };
1249
+ }
1250
+ }
1251
+ /**
1252
+ * Check if a specific prerequisite is satisfied
1253
+ */
1254
+ isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1255
+ if (!userTagElo) return false;
1256
+ const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1257
+ if (userTagElo.count < minCount) return false;
1258
+ if (prereq.masteryThreshold?.minElo !== void 0) {
1259
+ return userTagElo.score >= prereq.masteryThreshold.minElo;
1260
+ } else {
1261
+ return userTagElo.score >= userGlobalElo;
1262
+ }
1263
+ }
1264
+ /**
1265
+ * Get the set of tags the user has mastered.
1266
+ * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1267
+ */
1268
+ async getMasteredTags(context) {
1269
+ const mastered = /* @__PURE__ */ new Set();
1270
+ try {
1271
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1272
+ const userElo = toCourseElo3(courseReg.elo);
1273
+ for (const prereqs of Object.values(this.config.prerequisites)) {
1274
+ for (const prereq of prereqs) {
1275
+ const tagElo = userElo.tags[prereq.tag];
1276
+ if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1277
+ mastered.add(prereq.tag);
1278
+ }
1279
+ }
1280
+ }
1281
+ } catch {
1282
+ }
1283
+ return mastered;
1284
+ }
1285
+ /**
1286
+ * Get the set of tags that are unlocked (prerequisites met)
1287
+ */
1288
+ getUnlockedTags(masteredTags) {
1289
+ const unlocked = /* @__PURE__ */ new Set();
1290
+ for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1291
+ const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1292
+ if (allPrereqsMet) {
1293
+ unlocked.add(tagId);
1294
+ }
1295
+ }
1296
+ return unlocked;
1297
+ }
1298
+ /**
1299
+ * Check if a tag has prerequisites defined in config
1300
+ */
1301
+ hasPrerequisites(tagId) {
1302
+ return tagId in this.config.prerequisites;
1303
+ }
1304
+ /**
1305
+ * Check if a card is unlocked and generate reason.
1306
+ */
1307
+ async checkCardUnlock(card, _course, unlockedTags, masteredTags) {
1308
+ try {
1309
+ const cardTags = card.tags ?? [];
1310
+ const lockedTags = cardTags.filter(
1311
+ (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1312
+ );
1313
+ if (lockedTags.length === 0) {
1314
+ const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1315
+ return {
1316
+ isUnlocked: true,
1317
+ reason: `Prerequisites met, tags: ${tagList}`
1318
+ };
1319
+ }
1320
+ const missingPrereqs = lockedTags.flatMap((tag) => {
1321
+ const prereqs = this.config.prerequisites[tag] || [];
1322
+ return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1323
+ });
1324
+ return {
1325
+ isUnlocked: false,
1326
+ reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1327
+ };
1328
+ } catch {
1329
+ return {
1330
+ isUnlocked: true,
1331
+ reason: "Prerequisites check skipped (tag lookup failed)"
1332
+ };
1333
+ }
1334
+ }
1335
+ /**
1336
+ * CardFilter.transform implementation.
1337
+ *
1338
+ * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1339
+ */
1340
+ async transform(cards, context) {
1341
+ const masteredTags = await this.getMasteredTags(context);
1342
+ const unlockedTags = this.getUnlockedTags(masteredTags);
1343
+ const gated = [];
1344
+ for (const card of cards) {
1345
+ const { isUnlocked, reason } = await this.checkCardUnlock(
1346
+ card,
1347
+ context.course,
1348
+ unlockedTags,
1349
+ masteredTags
1350
+ );
1351
+ const finalScore = isUnlocked ? card.score : 0;
1352
+ const action = isUnlocked ? "passed" : "penalized";
1353
+ gated.push({
1354
+ ...card,
1355
+ score: finalScore,
1356
+ provenance: [
1357
+ ...card.provenance,
1358
+ {
1359
+ strategy: "hierarchyDefinition",
1360
+ strategyName: this.strategyName || this.name,
1361
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1362
+ action,
1363
+ score: finalScore,
1364
+ reason
1365
+ }
1366
+ ]
1367
+ });
1368
+ }
1369
+ return gated;
1370
+ }
1371
+ /**
1372
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1373
+ *
1374
+ * Use transform() via Pipeline instead.
1375
+ */
1376
+ async getWeightedCards(_limit) {
1377
+ throw new Error(
1378
+ "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1379
+ );
1380
+ }
1381
+ };
1382
+ }
1383
+ });
1384
+
1385
+ // src/core/navigators/filters/userTagPreference.ts
1386
+ var userTagPreference_exports = {};
1387
+ __export(userTagPreference_exports, {
1388
+ default: () => UserTagPreferenceFilter
1389
+ });
1390
+ var UserTagPreferenceFilter;
1391
+ var init_userTagPreference = __esm({
1392
+ "src/core/navigators/filters/userTagPreference.ts"() {
1393
+ "use strict";
1394
+ init_navigators();
1395
+ UserTagPreferenceFilter = class extends ContentNavigator {
1396
+ _strategyData;
1397
+ /** Human-readable name for CardFilter interface */
1398
+ name;
1399
+ constructor(user, course, strategyData) {
1400
+ super(user, course, strategyData);
1401
+ this._strategyData = strategyData;
1402
+ this.name = strategyData.name || "User Tag Preferences";
1403
+ }
1404
+ /**
1405
+ * Compute multiplier for a card based on its tags and user preferences.
1406
+ * Returns the maximum multiplier among all matching tags, or 1.0 if no matches.
1407
+ */
1408
+ computeMultiplier(cardTags, boostMap) {
1409
+ const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== void 0);
1410
+ if (multipliers.length === 0) {
1411
+ return 1;
1412
+ }
1413
+ return Math.max(...multipliers);
1414
+ }
1415
+ /**
1416
+ * Build human-readable reason for the filter's decision.
1417
+ */
1418
+ buildReason(cardTags, boostMap, multiplier) {
1419
+ const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);
1420
+ if (multiplier === 0) {
1421
+ return `Excluded by user preference: ${matchingTags.join(", ")} (${multiplier}x)`;
1422
+ }
1423
+ if (multiplier < 1) {
1424
+ return `Penalized by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1425
+ }
1426
+ if (multiplier > 1) {
1427
+ return `Boosted by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1428
+ }
1429
+ return "No matching user preferences";
1430
+ }
1431
+ /**
1432
+ * CardFilter.transform implementation.
1433
+ *
1434
+ * Apply user tag preferences:
1435
+ * 1. Read preferences from strategy state
1436
+ * 2. If no preferences, pass through unchanged
1437
+ * 3. For each card:
1438
+ * - Look up tag in boost record
1439
+ * - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)
1440
+ * - If multiple tags match: use max multiplier
1441
+ * - Append provenance with clear reason
1442
+ */
1443
+ async transform(cards, _context) {
1444
+ const prefs = await this.getStrategyState();
1445
+ if (!prefs || Object.keys(prefs.boost).length === 0) {
1446
+ return cards.map((card) => ({
1447
+ ...card,
1448
+ provenance: [
1449
+ ...card.provenance,
1450
+ {
1451
+ strategy: "userTagPreference",
1452
+ strategyName: this.strategyName || this.name,
1453
+ strategyId: this.strategyId || this._strategyData._id,
1454
+ action: "passed",
1455
+ score: card.score,
1456
+ reason: "No user tag preferences configured"
1457
+ }
1458
+ ]
1459
+ }));
1460
+ }
1461
+ const adjusted = await Promise.all(
1462
+ cards.map(async (card) => {
1463
+ const cardTags = card.tags ?? [];
1464
+ const multiplier = this.computeMultiplier(cardTags, prefs.boost);
1465
+ const finalScore = Math.min(1, card.score * multiplier);
1466
+ let action;
1467
+ if (multiplier === 0 || multiplier < 1) {
1468
+ action = "penalized";
1469
+ } else if (multiplier > 1) {
1470
+ action = "boosted";
1471
+ } else {
1472
+ action = "passed";
1473
+ }
1474
+ return {
1475
+ ...card,
1476
+ score: finalScore,
1477
+ provenance: [
1478
+ ...card.provenance,
1479
+ {
1480
+ strategy: "userTagPreference",
1481
+ strategyName: this.strategyName || this.name,
1482
+ strategyId: this.strategyId || this._strategyData._id,
1483
+ action,
1484
+ score: finalScore,
1485
+ reason: this.buildReason(cardTags, prefs.boost, multiplier)
1486
+ }
1487
+ ]
1488
+ };
1489
+ })
1490
+ );
1491
+ return adjusted;
1492
+ }
1493
+ /**
1494
+ * Legacy getWeightedCards - throws as filters should not be used as generators.
1495
+ */
1496
+ async getWeightedCards(_limit) {
1497
+ throw new Error(
1498
+ "UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1499
+ );
1500
+ }
1501
+ };
1502
+ }
1503
+ });
1504
+
1505
+ // src/core/navigators/filters/index.ts
1506
+ var filters_exports = {};
1507
+ __export(filters_exports, {
1508
+ UserTagPreferenceFilter: () => UserTagPreferenceFilter,
1509
+ createEloDistanceFilter: () => createEloDistanceFilter
1510
+ });
1511
+ var init_filters = __esm({
1512
+ "src/core/navigators/filters/index.ts"() {
1513
+ "use strict";
1514
+ init_eloDistance();
1515
+ init_userTagPreference();
1516
+ }
1517
+ });
1518
+
1519
+ // src/core/navigators/filters/inferredPreferenceStub.ts
1520
+ var inferredPreferenceStub_exports = {};
1521
+ __export(inferredPreferenceStub_exports, {
1522
+ INFERRED_PREFERENCE_NAVIGATOR_STUB: () => INFERRED_PREFERENCE_NAVIGATOR_STUB
1523
+ });
1524
+ var INFERRED_PREFERENCE_NAVIGATOR_STUB;
1525
+ var init_inferredPreferenceStub = __esm({
1526
+ "src/core/navigators/filters/inferredPreferenceStub.ts"() {
1527
+ "use strict";
1528
+ INFERRED_PREFERENCE_NAVIGATOR_STUB = true;
1529
+ }
1530
+ });
1531
+
1532
+ // src/core/navigators/filters/interferenceMitigator.ts
1533
+ var interferenceMitigator_exports = {};
1534
+ __export(interferenceMitigator_exports, {
1535
+ default: () => InterferenceMitigatorNavigator
1536
+ });
1537
+ import { toCourseElo as toCourseElo4 } from "@vue-skuilder/common";
1538
+ var DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1539
+ var init_interferenceMitigator = __esm({
1540
+ "src/core/navigators/filters/interferenceMitigator.ts"() {
1541
+ "use strict";
1542
+ init_navigators();
1543
+ DEFAULT_MIN_COUNT2 = 10;
1544
+ DEFAULT_MIN_ELAPSED_DAYS = 3;
1545
+ DEFAULT_INTERFERENCE_DECAY = 0.8;
1546
+ InterferenceMitigatorNavigator = class extends ContentNavigator {
1547
+ config;
1548
+ /** Human-readable name for CardFilter interface */
1549
+ name;
1550
+ /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1551
+ interferenceMap;
1552
+ constructor(user, course, strategyData) {
1553
+ super(user, course, strategyData);
1554
+ this.config = this.parseConfig(strategyData.serializedData);
1555
+ this.interferenceMap = this.buildInterferenceMap();
1556
+ this.name = strategyData.name || "Interference Mitigator";
1557
+ }
1558
+ parseConfig(serializedData) {
1559
+ try {
1560
+ const parsed = JSON.parse(serializedData);
1561
+ let sets = parsed.interferenceSets || [];
1562
+ if (sets.length > 0 && Array.isArray(sets[0])) {
1563
+ sets = sets.map((tags) => ({ tags }));
1564
+ }
1565
+ return {
1566
+ interferenceSets: sets,
1567
+ maturityThreshold: {
1568
+ minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1569
+ minElo: parsed.maturityThreshold?.minElo,
1570
+ minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1571
+ },
1572
+ defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1573
+ };
1574
+ } catch {
1575
+ return {
1576
+ interferenceSets: [],
1577
+ maturityThreshold: {
1578
+ minCount: DEFAULT_MIN_COUNT2,
1579
+ minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1580
+ },
1581
+ defaultDecay: DEFAULT_INTERFERENCE_DECAY
1582
+ };
1583
+ }
1584
+ }
1585
+ /**
1586
+ * Build a map from each tag to its interference partners with decay coefficients.
1587
+ * If tags A, B, C are in an interference group with decay 0.8, then:
1588
+ * - A interferes with B (decay 0.8) and C (decay 0.8)
1589
+ * - B interferes with A (decay 0.8) and C (decay 0.8)
1590
+ * - etc.
1591
+ */
1592
+ buildInterferenceMap() {
1593
+ const map = /* @__PURE__ */ new Map();
1594
+ for (const group of this.config.interferenceSets) {
1595
+ const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
1596
+ for (const tag of group.tags) {
1597
+ if (!map.has(tag)) {
1598
+ map.set(tag, []);
1599
+ }
1600
+ const partners = map.get(tag);
1601
+ for (const other of group.tags) {
1602
+ if (other !== tag) {
1603
+ const existing = partners.find((p) => p.partner === other);
1604
+ if (existing) {
1605
+ existing.decay = Math.max(existing.decay, decay);
1606
+ } else {
1607
+ partners.push({ partner: other, decay });
1608
+ }
1609
+ }
1610
+ }
1611
+ }
1612
+ }
1613
+ return map;
1614
+ }
1615
+ /**
1616
+ * Get the set of tags that are currently immature for this user.
1617
+ * A tag is immature if the user has interacted with it but hasn't
1618
+ * reached the maturity threshold.
1619
+ */
1620
+ async getImmatureTags(context) {
1621
+ const immature = /* @__PURE__ */ new Set();
1622
+ try {
1623
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1624
+ const userElo = toCourseElo4(courseReg.elo);
1625
+ const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
1626
+ const minElo = this.config.maturityThreshold?.minElo;
1627
+ const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
1628
+ const minCountForElapsed = minElapsedDays * 2;
1629
+ for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
1630
+ if (tagElo.count === 0) continue;
1631
+ const belowCount = tagElo.count < minCount;
1632
+ const belowElo = minElo !== void 0 && tagElo.score < minElo;
1633
+ const belowElapsed = tagElo.count < minCountForElapsed;
1634
+ if (belowCount || belowElo || belowElapsed) {
1635
+ immature.add(tagId);
1636
+ }
1637
+ }
1638
+ } catch {
1639
+ }
1640
+ return immature;
1641
+ }
1642
+ /**
1643
+ * Get all tags that interfere with any immature tag, along with their decay coefficients.
1644
+ * These are the tags we want to avoid introducing.
1645
+ */
1646
+ getTagsToAvoid(immatureTags) {
1647
+ const avoid = /* @__PURE__ */ new Map();
1648
+ for (const immatureTag of immatureTags) {
1649
+ const partners = this.interferenceMap.get(immatureTag);
1650
+ if (partners) {
1651
+ for (const { partner, decay } of partners) {
1652
+ if (!immatureTags.has(partner)) {
1653
+ const existing = avoid.get(partner) ?? 0;
1654
+ avoid.set(partner, Math.max(existing, decay));
1655
+ }
1656
+ }
1657
+ }
1658
+ }
1659
+ return avoid;
1660
+ }
1661
+ /**
1662
+ * Compute interference score reduction for a card.
1663
+ * Returns: { multiplier, interfering tags, reason }
1664
+ */
1665
+ computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
1666
+ if (tagsToAvoid.size === 0) {
1667
+ return {
1668
+ multiplier: 1,
1669
+ interferingTags: [],
1670
+ reason: "No interference detected"
1671
+ };
1672
+ }
1673
+ let multiplier = 1;
1674
+ const interferingTags = [];
1675
+ for (const tag of cardTags) {
1676
+ const decay = tagsToAvoid.get(tag);
1677
+ if (decay !== void 0) {
1678
+ interferingTags.push(tag);
1679
+ multiplier *= 1 - decay;
1680
+ }
1681
+ }
1682
+ if (interferingTags.length === 0) {
1683
+ return {
1684
+ multiplier: 1,
1685
+ interferingTags: [],
1686
+ reason: "No interference detected"
1687
+ };
1688
+ }
1689
+ const causingTags = /* @__PURE__ */ new Set();
1690
+ for (const tag of interferingTags) {
1691
+ for (const immatureTag of immatureTags) {
1692
+ const partners = this.interferenceMap.get(immatureTag);
1693
+ if (partners?.some((p) => p.partner === tag)) {
1694
+ causingTags.add(immatureTag);
1695
+ }
1696
+ }
1697
+ }
1698
+ const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
1699
+ return { multiplier, interferingTags, reason };
1700
+ }
1701
+ /**
1702
+ * CardFilter.transform implementation.
1703
+ *
1704
+ * Apply interference-aware scoring. Cards with tags that interfere with
1705
+ * immature learnings get reduced scores.
1706
+ */
1707
+ async transform(cards, context) {
1708
+ const immatureTags = await this.getImmatureTags(context);
1709
+ const tagsToAvoid = this.getTagsToAvoid(immatureTags);
1710
+ const adjusted = [];
1711
+ for (const card of cards) {
1712
+ const cardTags = card.tags ?? [];
1713
+ const { multiplier, reason } = this.computeInterferenceEffect(
1714
+ cardTags,
1715
+ tagsToAvoid,
1716
+ immatureTags
1717
+ );
1718
+ const finalScore = card.score * multiplier;
1719
+ const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
1720
+ adjusted.push({
1721
+ ...card,
1722
+ score: finalScore,
1723
+ provenance: [
1724
+ ...card.provenance,
1725
+ {
1726
+ strategy: "interferenceMitigator",
1727
+ strategyName: this.strategyName || this.name,
1728
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
1729
+ action,
1730
+ score: finalScore,
1731
+ reason
1732
+ }
1733
+ ]
1734
+ });
1735
+ }
1736
+ return adjusted;
1737
+ }
1738
+ /**
1739
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1740
+ *
1741
+ * Use transform() via Pipeline instead.
1742
+ */
1743
+ async getWeightedCards(_limit) {
1744
+ throw new Error(
1745
+ "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1746
+ );
1747
+ }
1748
+ };
1749
+ }
1750
+ });
1751
+
1752
+ // src/core/navigators/filters/relativePriority.ts
1753
+ var relativePriority_exports = {};
1754
+ __export(relativePriority_exports, {
1755
+ default: () => RelativePriorityNavigator
1756
+ });
1757
+ var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
1758
+ var init_relativePriority = __esm({
1759
+ "src/core/navigators/filters/relativePriority.ts"() {
1760
+ "use strict";
1761
+ init_navigators();
1762
+ DEFAULT_PRIORITY = 0.5;
1763
+ DEFAULT_PRIORITY_INFLUENCE = 0.5;
1764
+ DEFAULT_COMBINE_MODE = "max";
1765
+ RelativePriorityNavigator = class extends ContentNavigator {
1766
+ config;
1767
+ /** Human-readable name for CardFilter interface */
1768
+ name;
1769
+ constructor(user, course, strategyData) {
1770
+ super(user, course, strategyData);
1771
+ this.config = this.parseConfig(strategyData.serializedData);
1772
+ this.name = strategyData.name || "Relative Priority";
1773
+ }
1774
+ parseConfig(serializedData) {
1775
+ try {
1776
+ const parsed = JSON.parse(serializedData);
1777
+ return {
1778
+ tagPriorities: parsed.tagPriorities || {},
1779
+ defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
1780
+ combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
1781
+ priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
1782
+ };
1783
+ } catch {
1784
+ return {
1785
+ tagPriorities: {},
1786
+ defaultPriority: DEFAULT_PRIORITY,
1787
+ combineMode: DEFAULT_COMBINE_MODE,
1788
+ priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
1789
+ };
1790
+ }
1791
+ }
1792
+ /**
1793
+ * Look up the priority for a tag.
1794
+ */
1795
+ getTagPriority(tagId) {
1796
+ return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
1797
+ }
1798
+ /**
1799
+ * Compute combined priority for a card based on its tags.
1800
+ */
1801
+ computeCardPriority(cardTags) {
1802
+ if (cardTags.length === 0) {
1803
+ return this.config.defaultPriority ?? DEFAULT_PRIORITY;
1804
+ }
1805
+ const priorities = cardTags.map((tag) => this.getTagPriority(tag));
1806
+ switch (this.config.combineMode) {
1807
+ case "max":
1808
+ return Math.max(...priorities);
1809
+ case "min":
1810
+ return Math.min(...priorities);
1811
+ case "average":
1812
+ return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
1813
+ default:
1814
+ return Math.max(...priorities);
1815
+ }
1816
+ }
1817
+ /**
1818
+ * Compute boost factor based on priority.
1819
+ *
1820
+ * The formula: 1 + (priority - 0.5) * priorityInfluence
1821
+ *
1822
+ * This creates a multiplier centered around 1.0:
1823
+ * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
1824
+ * - Priority 0.5 with any influence → 1.00 (neutral)
1825
+ * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
1826
+ */
1827
+ computeBoostFactor(priority) {
1828
+ const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
1829
+ return 1 + (priority - 0.5) * influence;
1830
+ }
1831
+ /**
1832
+ * Build human-readable reason for priority adjustment.
1833
+ */
1834
+ buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
1835
+ if (cardTags.length === 0) {
1836
+ return `No tags, neutral priority (${priority.toFixed(2)})`;
1837
+ }
1838
+ const tagList = cardTags.slice(0, 3).join(", ");
1839
+ const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
1840
+ if (boostFactor === 1) {
1841
+ return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
1842
+ } else if (boostFactor > 1) {
1843
+ return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1844
+ } else {
1845
+ return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1846
+ }
1847
+ }
1848
+ /**
1849
+ * CardFilter.transform implementation.
1850
+ *
1851
+ * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
1852
+ * cards with low-priority tags get reduced scores.
1853
+ */
1854
+ async transform(cards, _context) {
1855
+ const adjusted = await Promise.all(
1856
+ cards.map(async (card) => {
1857
+ const cardTags = card.tags ?? [];
1858
+ const priority = this.computeCardPriority(cardTags);
1859
+ const boostFactor = this.computeBoostFactor(priority);
1860
+ const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
1861
+ const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
1862
+ const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
1863
+ return {
1864
+ ...card,
1865
+ score: finalScore,
1866
+ provenance: [
1867
+ ...card.provenance,
1868
+ {
1869
+ strategy: "relativePriority",
1870
+ strategyName: this.strategyName || this.name,
1871
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
1872
+ action,
1873
+ score: finalScore,
1874
+ reason
1875
+ }
1876
+ ]
1877
+ };
1878
+ })
1879
+ );
1880
+ return adjusted;
1881
+ }
1882
+ /**
1883
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1884
+ *
1885
+ * Use transform() via Pipeline instead.
1886
+ */
1887
+ async getWeightedCards(_limit) {
1888
+ throw new Error(
1889
+ "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1890
+ );
1891
+ }
1892
+ };
1893
+ }
1894
+ });
1895
+
1896
+ // src/core/navigators/filters/types.ts
1897
+ var types_exports2 = {};
1898
+ var init_types2 = __esm({
1899
+ "src/core/navigators/filters/types.ts"() {
1900
+ "use strict";
1901
+ }
1902
+ });
1903
+
1904
+ // src/core/navigators/filters/userGoalStub.ts
1905
+ var userGoalStub_exports = {};
1906
+ __export(userGoalStub_exports, {
1907
+ USER_GOAL_NAVIGATOR_STUB: () => USER_GOAL_NAVIGATOR_STUB
1908
+ });
1909
+ var USER_GOAL_NAVIGATOR_STUB;
1910
+ var init_userGoalStub = __esm({
1911
+ "src/core/navigators/filters/userGoalStub.ts"() {
1912
+ "use strict";
1913
+ USER_GOAL_NAVIGATOR_STUB = true;
1914
+ }
1915
+ });
1916
+
1917
+ // import("./filters/**/*") in src/core/navigators/index.ts
1918
+ var globImport_filters;
1919
+ var init_2 = __esm({
1920
+ 'import("./filters/**/*") in src/core/navigators/index.ts'() {
1921
+ globImport_filters = __glob({
1922
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
1923
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
1924
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
1925
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
1926
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
1927
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
1928
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
1929
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
1930
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
1931
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
1932
+ });
1933
+ }
1934
+ });
1935
+
1936
+ // src/core/orchestration/gradient.ts
1937
+ function aggregateOutcomesForGradient(outcomes, strategyId) {
1938
+ const observations = [];
1939
+ for (const outcome of outcomes) {
1940
+ const deviation = outcome.deviations[strategyId];
1941
+ if (deviation === void 0) {
1942
+ continue;
1943
+ }
1944
+ observations.push({
1945
+ deviation,
1946
+ outcomeValue: outcome.outcomeValue,
1947
+ weight: 1
1948
+ });
1949
+ }
1950
+ logger.debug(
1951
+ `[Orchestration] Aggregated ${observations.length} observations for strategy ${strategyId}`
1952
+ );
1953
+ return observations;
1954
+ }
1955
+ function computeStrategyGradient(observations) {
1956
+ const n = observations.length;
1957
+ if (n < 3) {
1958
+ logger.debug(`[Orchestration] Insufficient observations for gradient (${n} < 3)`);
1959
+ return null;
1960
+ }
1961
+ let sumX = 0;
1962
+ let sumY = 0;
1963
+ let sumW = 0;
1964
+ for (const obs of observations) {
1965
+ const w = obs.weight ?? 1;
1966
+ sumX += obs.deviation * w;
1967
+ sumY += obs.outcomeValue * w;
1968
+ sumW += w;
1969
+ }
1970
+ const meanX = sumX / sumW;
1971
+ const meanY = sumY / sumW;
1972
+ let numerator = 0;
1973
+ let denominator = 0;
1974
+ let ssTotal = 0;
1975
+ for (const obs of observations) {
1976
+ const w = obs.weight ?? 1;
1977
+ const dx = obs.deviation - meanX;
1978
+ const dy = obs.outcomeValue - meanY;
1979
+ numerator += w * dx * dy;
1980
+ denominator += w * dx * dx;
1981
+ ssTotal += w * dy * dy;
1982
+ }
1983
+ if (denominator < 1e-10) {
1984
+ logger.debug(`[Orchestration] No variance in deviations, cannot compute gradient`);
1985
+ return {
1986
+ gradient: 0,
1987
+ intercept: meanY,
1988
+ rSquared: 0,
1989
+ sampleSize: n
1990
+ };
1991
+ }
1992
+ const gradient = numerator / denominator;
1993
+ const intercept = meanY - gradient * meanX;
1994
+ let ssResidual = 0;
1995
+ for (const obs of observations) {
1996
+ const w = obs.weight ?? 1;
1997
+ const predicted = gradient * obs.deviation + intercept;
1998
+ const residual = obs.outcomeValue - predicted;
1999
+ ssResidual += w * residual * residual;
2000
+ }
2001
+ const rSquared = ssTotal > 1e-10 ? 1 - ssResidual / ssTotal : 0;
2002
+ logger.debug(
2003
+ `[Orchestration] Computed gradient: ${gradient.toFixed(4)}, intercept: ${intercept.toFixed(4)}, R\xB2: ${rSquared.toFixed(4)}, n=${n}`
2004
+ );
2005
+ return {
2006
+ gradient,
2007
+ intercept,
2008
+ rSquared: Math.max(0, Math.min(1, rSquared)),
2009
+ // Clamp to [0,1]
2010
+ sampleSize: n
2011
+ };
2012
+ }
2013
+ var init_gradient = __esm({
2014
+ "src/core/orchestration/gradient.ts"() {
2015
+ "use strict";
2016
+ init_logger();
2017
+ }
2018
+ });
2019
+
2020
+ // src/core/orchestration/learning.ts
2021
+ function updateStrategyWeight(current, gradient) {
2022
+ if (gradient.sampleSize < MIN_OBSERVATIONS_FOR_UPDATE) {
2023
+ logger.debug(
2024
+ `[Orchestration] Insufficient samples (${gradient.sampleSize} < ${MIN_OBSERVATIONS_FOR_UPDATE}), keeping current weight`
2025
+ );
2026
+ return {
2027
+ ...current,
2028
+ sampleSize: current.sampleSize + gradient.sampleSize
2029
+ };
2030
+ }
2031
+ const isReliable = gradient.rSquared >= MIN_R_SQUARED_FOR_GRADIENT;
2032
+ const isFlat = Math.abs(gradient.gradient) < FLAT_GRADIENT_THRESHOLD;
2033
+ let newWeight = current.weight;
2034
+ let newConfidence = current.confidence;
2035
+ if (!isReliable || isFlat) {
2036
+ const confidenceGain = 0.05 * (1 - current.confidence);
2037
+ newConfidence = Math.min(1, current.confidence + confidenceGain);
2038
+ logger.debug(
2039
+ `[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)}`
2040
+ );
2041
+ } else {
2042
+ let delta = gradient.gradient * LEARNING_RATE;
2043
+ delta = Math.max(-MAX_WEIGHT_DELTA, Math.min(MAX_WEIGHT_DELTA, delta));
2044
+ newWeight = current.weight + delta;
2045
+ newWeight = Math.max(0.1, Math.min(3, newWeight));
2046
+ const confidenceGain = 0.02 * (1 - current.confidence);
2047
+ newConfidence = Math.min(1, current.confidence + confidenceGain);
2048
+ logger.debug(
2049
+ `[Orchestration] Adjusting weight: ${current.weight.toFixed(3)} \u2192 ${newWeight.toFixed(3)} (gradient=${gradient.gradient.toFixed(4)}, delta=${delta.toFixed(4)})`
2050
+ );
2051
+ }
2052
+ return {
2053
+ weight: newWeight,
2054
+ confidence: newConfidence,
2055
+ sampleSize: current.sampleSize + gradient.sampleSize
2056
+ };
2057
+ }
2058
+ function updateLearningState(courseId, strategyId, currentWeight, gradient, existing) {
2059
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2060
+ const id = `STRATEGY_LEARNING_STATE::${courseId}::${strategyId}`;
2061
+ const historyEntry = {
2062
+ timestamp: now,
2063
+ weight: currentWeight.weight,
2064
+ confidence: currentWeight.confidence,
2065
+ gradient: gradient.gradient
2066
+ };
2067
+ let history = existing?.history ?? [];
2068
+ history = [...history, historyEntry];
2069
+ if (history.length > MAX_HISTORY_LENGTH) {
2070
+ history = history.slice(history.length - MAX_HISTORY_LENGTH);
2071
+ }
2072
+ const state = {
2073
+ _id: id,
2074
+ _rev: existing?._rev,
2075
+ docType: "STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */,
2076
+ courseId,
2077
+ strategyId,
2078
+ currentWeight,
2079
+ regression: {
2080
+ gradient: gradient.gradient,
2081
+ intercept: gradient.intercept,
2082
+ rSquared: gradient.rSquared,
2083
+ sampleSize: gradient.sampleSize,
2084
+ computedAt: now
2085
+ },
2086
+ history,
2087
+ updatedAt: now
2088
+ };
2089
+ return state;
2090
+ }
2091
+ function runPeriodUpdate(input) {
2092
+ const { courseId, strategyId, currentWeight, gradient, existingState } = input;
2093
+ logger.info(
2094
+ `[Orchestration] Running period update for strategy ${strategyId} (${gradient.sampleSize} observations)`
2095
+ );
2096
+ const newWeight = updateStrategyWeight(currentWeight, gradient);
2097
+ const updated = newWeight.weight !== currentWeight.weight;
2098
+ const learningState = updateLearningState(
2099
+ courseId,
2100
+ strategyId,
2101
+ newWeight,
2102
+ gradient,
2103
+ existingState
2104
+ );
2105
+ logger.info(
2106
+ `[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)}`
2107
+ );
2108
+ return {
2109
+ strategyId,
2110
+ previousWeight: currentWeight,
2111
+ newWeight,
2112
+ gradient,
2113
+ learningState,
2114
+ updated
2115
+ };
2116
+ }
2117
+ function getDefaultLearnableWeight() {
2118
+ return { ...DEFAULT_LEARNABLE_WEIGHT };
2119
+ }
2120
+ var MIN_OBSERVATIONS_FOR_UPDATE, LEARNING_RATE, MAX_WEIGHT_DELTA, MIN_R_SQUARED_FOR_GRADIENT, FLAT_GRADIENT_THRESHOLD, MAX_HISTORY_LENGTH;
2121
+ var init_learning = __esm({
2122
+ "src/core/orchestration/learning.ts"() {
2123
+ "use strict";
2124
+ init_contentNavigationStrategy();
2125
+ init_types_legacy();
2126
+ init_logger();
2127
+ MIN_OBSERVATIONS_FOR_UPDATE = 10;
2128
+ LEARNING_RATE = 0.1;
2129
+ MAX_WEIGHT_DELTA = 0.3;
2130
+ MIN_R_SQUARED_FOR_GRADIENT = 0.05;
2131
+ FLAT_GRADIENT_THRESHOLD = 0.02;
2132
+ MAX_HISTORY_LENGTH = 100;
2133
+ }
2134
+ });
2135
+
2136
+ // src/core/orchestration/signal.ts
2137
+ function computeOutcomeSignal(records, config = {}) {
2138
+ if (!records || records.length === 0) {
2139
+ return null;
2140
+ }
2141
+ const target = config.targetAccuracy ?? 0.85;
2142
+ const tolerance = config.tolerance ?? 0.05;
2143
+ let correct = 0;
2144
+ for (const r of records) {
2145
+ if (r.isCorrect) correct++;
2146
+ }
2147
+ const accuracy = correct / records.length;
2148
+ return scoreAccuracyInZone(accuracy, target, tolerance);
2149
+ }
2150
+ function scoreAccuracyInZone(accuracy, target, tolerance) {
2151
+ const dist = Math.abs(accuracy - target);
2152
+ if (dist <= tolerance) {
2153
+ return 1;
2154
+ }
2155
+ const excess = dist - tolerance;
2156
+ const slope = 2.5;
2157
+ return Math.max(0, 1 - excess * slope);
2158
+ }
2159
+ var init_signal = __esm({
2160
+ "src/core/orchestration/signal.ts"() {
2161
+ "use strict";
2162
+ }
2163
+ });
2164
+
2165
+ // src/core/orchestration/recording.ts
2166
+ async function recordUserOutcome(context, periodStart, periodEnd, records, activeStrategyIds, eloStart = 0, eloEnd = 0, config) {
2167
+ const { user, course, userId } = context;
2168
+ const courseId = course.getCourseID();
2169
+ const outcomeValue = computeOutcomeSignal(records, config);
2170
+ if (outcomeValue === null) {
2171
+ logger.debug(
2172
+ `[Orchestration] No outcome signal computed for ${userId} (insufficient data). Skipping record.`
2173
+ );
2174
+ return;
2175
+ }
2176
+ const deviations = {};
2177
+ for (const strategyId of activeStrategyIds) {
2178
+ deviations[strategyId] = context.getDeviation(strategyId);
2179
+ }
2180
+ const id = `USER_OUTCOME::${courseId}::${userId}::${periodEnd}`;
2181
+ const record = {
2182
+ _id: id,
2183
+ docType: "USER_OUTCOME" /* USER_OUTCOME */,
2184
+ courseId,
2185
+ userId,
2186
+ periodStart,
2187
+ periodEnd,
2188
+ outcomeValue,
2189
+ deviations,
2190
+ metadata: {
2191
+ sessionsCount: 1,
2192
+ // Assumes recording is triggered per-session currently
2193
+ cardsSeen: records.length,
2194
+ eloStart,
2195
+ eloEnd,
2196
+ signalType: "accuracy_in_zone"
2197
+ }
2198
+ };
2199
+ try {
2200
+ await user.putUserOutcome(record);
2201
+ logger.debug(
2202
+ `[Orchestration] Recorded outcome ${outcomeValue.toFixed(3)} for ${userId} (doc: ${id})`
2203
+ );
2204
+ } catch (e) {
2205
+ logger.error(`[Orchestration] Failed to record outcome: ${e}`);
2206
+ }
2207
+ }
2208
+ var init_recording = __esm({
2209
+ "src/core/orchestration/recording.ts"() {
2210
+ "use strict";
2211
+ init_signal();
2212
+ init_types_legacy();
2213
+ init_logger();
2214
+ }
2215
+ });
2216
+
2217
+ // src/core/orchestration/index.ts
2218
+ function fnv1a(str) {
2219
+ let hash = 2166136261;
2220
+ for (let i = 0; i < str.length; i++) {
2221
+ hash ^= str.charCodeAt(i);
2222
+ hash = Math.imul(hash, 16777619);
2223
+ }
2224
+ return hash >>> 0;
2225
+ }
2226
+ function computeDeviation(userId, strategyId, salt) {
2227
+ const input = `${userId}:${strategyId}:${salt}`;
2228
+ const hash = fnv1a(input);
2229
+ const normalized = hash / 4294967296;
2230
+ return normalized * 2 - 1;
2231
+ }
2232
+ function computeSpread(confidence) {
2233
+ const clampedConfidence = Math.max(0, Math.min(1, confidence));
2234
+ return MAX_SPREAD - clampedConfidence * (MAX_SPREAD - MIN_SPREAD);
2235
+ }
2236
+ function computeEffectiveWeight(learnable, userId, strategyId, salt) {
2237
+ const deviation = computeDeviation(userId, strategyId, salt);
2238
+ const spread = computeSpread(learnable.confidence);
2239
+ const adjustment = deviation * spread * learnable.weight;
2240
+ const effective = learnable.weight + adjustment;
2241
+ return Math.max(MIN_WEIGHT, Math.min(MAX_WEIGHT, effective));
2242
+ }
2243
+ async function createOrchestrationContext(user, course) {
2244
+ let courseConfig;
2245
+ try {
2246
+ courseConfig = await course.getCourseConfig();
2247
+ } catch (e) {
2248
+ logger.error(`[Orchestration] Failed to load course config: ${e}`);
2249
+ courseConfig = {
2250
+ name: "Unknown",
2251
+ description: "",
2252
+ public: false,
2253
+ deleted: false,
2254
+ creator: "",
2255
+ admins: [],
2256
+ moderators: [],
2257
+ dataShapes: [],
2258
+ questionTypes: [],
2259
+ orchestration: { salt: "default" }
2260
+ };
2261
+ }
2262
+ const userId = user.getUsername();
2263
+ const salt = courseConfig.orchestration?.salt || "default_salt";
2264
+ return {
2265
+ user,
2266
+ course,
2267
+ userId,
2268
+ courseConfig,
2269
+ getEffectiveWeight(strategyId, learnable) {
2270
+ return computeEffectiveWeight(learnable, userId, strategyId, salt);
2271
+ },
2272
+ getDeviation(strategyId) {
2273
+ return computeDeviation(userId, strategyId, salt);
2274
+ }
2275
+ };
2276
+ }
2277
+ var MIN_SPREAD, MAX_SPREAD, MIN_WEIGHT, MAX_WEIGHT;
2278
+ var init_orchestration = __esm({
2279
+ "src/core/orchestration/index.ts"() {
2280
+ "use strict";
2281
+ init_logger();
2282
+ init_gradient();
2283
+ init_learning();
2284
+ init_signal();
2285
+ init_recording();
2286
+ MIN_SPREAD = 0.1;
2287
+ MAX_SPREAD = 0.5;
2288
+ MIN_WEIGHT = 0.1;
2289
+ MAX_WEIGHT = 3;
2290
+ }
2291
+ });
2292
+
2293
+ // src/core/navigators/Pipeline.ts
2294
+ var Pipeline_exports = {};
2295
+ __export(Pipeline_exports, {
2296
+ Pipeline: () => Pipeline
2297
+ });
2298
+ import { toCourseElo as toCourseElo5 } from "@vue-skuilder/common";
2299
+ function logPipelineConfig(generator, filters) {
2300
+ const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
2301
+ logger.info(
2302
+ `[Pipeline] Configuration:
2303
+ Generator: ${generator.name}
2304
+ Filters:${filterList}`
2305
+ );
2306
+ }
2307
+ function logTagHydration(cards, tagsByCard) {
2308
+ const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
868
2309
  const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
869
2310
  logger.debug(
870
2311
  `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
@@ -896,6 +2337,7 @@ var init_Pipeline = __esm({
896
2337
  "use strict";
897
2338
  init_navigators();
898
2339
  init_logger();
2340
+ init_orchestration();
899
2341
  Pipeline = class extends ContentNavigator {
900
2342
  generator;
901
2343
  filters;
@@ -998,15 +2440,17 @@ var init_Pipeline = __esm({
998
2440
  let userElo = 1e3;
999
2441
  try {
1000
2442
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1001
- const courseElo = toCourseElo2(courseReg.elo);
2443
+ const courseElo = toCourseElo5(courseReg.elo);
1002
2444
  userElo = courseElo.global.score;
1003
2445
  } catch (e) {
1004
2446
  logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
1005
2447
  }
2448
+ const orchestration = await createOrchestrationContext(this.user, this.course);
1006
2449
  return {
1007
2450
  user: this.user,
1008
2451
  course: this.course,
1009
- userElo
2452
+ userElo,
2453
+ orchestration
1010
2454
  };
1011
2455
  }
1012
2456
  /**
@@ -1015,154 +2459,51 @@ var init_Pipeline = __esm({
1015
2459
  getCourseID() {
1016
2460
  return this.course.getCourseID();
1017
2461
  }
1018
- };
1019
- }
1020
- });
1021
-
1022
- // src/core/navigators/generators/CompositeGenerator.ts
1023
- var DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
1024
- var init_CompositeGenerator = __esm({
1025
- "src/core/navigators/generators/CompositeGenerator.ts"() {
1026
- "use strict";
1027
- init_navigators();
1028
- init_logger();
1029
- DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
1030
- FREQUENCY_BOOST_FACTOR = 0.1;
1031
- CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
1032
- /** Human-readable name for CardGenerator interface */
1033
- name = "Composite Generator";
1034
- generators;
1035
- aggregationMode;
1036
- constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
1037
- super();
1038
- this.generators = generators;
1039
- this.aggregationMode = aggregationMode;
1040
- if (generators.length === 0) {
1041
- throw new Error("CompositeGenerator requires at least one generator");
1042
- }
1043
- logger.debug(
1044
- `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
1045
- );
1046
- }
1047
- /**
1048
- * Creates a CompositeGenerator from strategy data.
1049
- *
1050
- * This is a convenience factory for use by PipelineAssembler.
1051
- */
1052
- static async fromStrategies(user, course, strategies, aggregationMode = DEFAULT_AGGREGATION_MODE) {
1053
- const generators = await Promise.all(
1054
- strategies.map((s) => ContentNavigator.create(user, course, s))
1055
- );
1056
- return new _CompositeGenerator(generators, aggregationMode);
1057
- }
1058
- /**
1059
- * Get weighted cards from all generators, merge and deduplicate.
1060
- *
1061
- * Cards appearing in multiple generators receive a score boost.
1062
- * Provenance tracks which generators produced each card and how scores were aggregated.
1063
- *
1064
- * This method supports both the legacy signature (limit only) and the
1065
- * CardGenerator interface signature (limit, context).
1066
- *
1067
- * @param limit - Maximum number of cards to return
1068
- * @param context - GeneratorContext passed to child generators (required when called via Pipeline)
1069
- */
1070
- async getWeightedCards(limit, context) {
1071
- if (!context) {
1072
- throw new Error(
1073
- "CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly."
1074
- );
1075
- }
1076
- const results = await Promise.all(
1077
- this.generators.map((g) => g.getWeightedCards(limit, context))
1078
- );
1079
- const byCardId = /* @__PURE__ */ new Map();
1080
- for (const cards of results) {
1081
- for (const card of cards) {
1082
- const existing = byCardId.get(card.cardId) || [];
1083
- existing.push(card);
1084
- byCardId.set(card.cardId, existing);
1085
- }
1086
- }
1087
- const merged = [];
1088
- for (const [, cards] of byCardId) {
1089
- const aggregatedScore = this.aggregateScores(cards);
1090
- const finalScore = Math.min(1, aggregatedScore);
1091
- const mergedProvenance = cards.flatMap((c) => c.provenance);
1092
- const initialScore = cards[0].score;
1093
- const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
1094
- const reason = this.buildAggregationReason(cards, finalScore);
1095
- merged.push({
1096
- ...cards[0],
1097
- score: finalScore,
1098
- provenance: [
1099
- ...mergedProvenance,
1100
- {
1101
- strategy: "composite",
1102
- strategyName: "Composite Generator",
1103
- strategyId: "COMPOSITE_GENERATOR",
1104
- action,
1105
- score: finalScore,
1106
- reason
1107
- }
1108
- ]
1109
- });
1110
- }
1111
- return merged.sort((a, b) => b.score - a.score).slice(0, limit);
1112
- }
1113
2462
  /**
1114
- * Build human-readable reason for score aggregation.
1115
- */
1116
- buildAggregationReason(cards, finalScore) {
1117
- const count = cards.length;
1118
- const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
1119
- if (count === 1) {
1120
- return `Single generator, score ${finalScore.toFixed(2)}`;
1121
- }
1122
- const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
1123
- switch (this.aggregationMode) {
1124
- case "max" /* MAX */:
1125
- return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
1126
- case "average" /* AVERAGE */:
1127
- return `Average of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
1128
- case "frequencyBoost" /* FREQUENCY_BOOST */: {
1129
- const avg = cards.reduce((sum, c) => sum + c.score, 0) / count;
1130
- const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
1131
- return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
1132
- }
1133
- default:
1134
- return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
1135
- }
2463
+ * Get orchestration context for outcome recording.
2464
+ */
2465
+ async getOrchestrationContext() {
2466
+ return createOrchestrationContext(this.user, this.course);
1136
2467
  }
1137
2468
  /**
1138
- * Aggregate scores from multiple generators for the same card.
2469
+ * Get IDs of all strategies in this pipeline.
2470
+ * Used to record which strategies contributed to an outcome.
1139
2471
  */
1140
- aggregateScores(cards) {
1141
- const scores = cards.map((c) => c.score);
1142
- switch (this.aggregationMode) {
1143
- case "max" /* MAX */:
1144
- return Math.max(...scores);
1145
- case "average" /* AVERAGE */:
1146
- return scores.reduce((sum, s) => sum + s, 0) / scores.length;
1147
- case "frequencyBoost" /* FREQUENCY_BOOST */: {
1148
- const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
1149
- const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (cards.length - 1);
1150
- return avg * frequencyBoost;
1151
- }
1152
- default:
1153
- return scores[0];
2472
+ getStrategyIds() {
2473
+ const ids = [];
2474
+ const extractId = (obj) => {
2475
+ if (obj.strategyId) return obj.strategyId;
2476
+ return null;
2477
+ };
2478
+ const genId = extractId(this.generator);
2479
+ if (genId) ids.push(genId);
2480
+ if (this.generator.generators && Array.isArray(this.generator.generators)) {
2481
+ this.generator.generators.forEach((g) => {
2482
+ const subId = extractId(g);
2483
+ if (subId) ids.push(subId);
2484
+ });
2485
+ }
2486
+ for (const filter of this.filters) {
2487
+ const fId = extractId(filter);
2488
+ if (fId) ids.push(fId);
1154
2489
  }
2490
+ return [...new Set(ids)];
1155
2491
  }
1156
2492
  };
1157
2493
  }
1158
2494
  });
1159
2495
 
1160
2496
  // src/core/navigators/PipelineAssembler.ts
2497
+ var PipelineAssembler_exports = {};
2498
+ __export(PipelineAssembler_exports, {
2499
+ PipelineAssembler: () => PipelineAssembler
2500
+ });
1161
2501
  var PipelineAssembler;
1162
2502
  var init_PipelineAssembler = __esm({
1163
2503
  "src/core/navigators/PipelineAssembler.ts"() {
1164
2504
  "use strict";
1165
2505
  init_navigators();
2506
+ init_WeightedFilter();
1166
2507
  init_Pipeline();
1167
2508
  init_types_legacy();
1168
2509
  init_logger();
@@ -1235,265 +2576,65 @@ var init_PipelineAssembler = __esm({
1235
2576
  );
1236
2577
  for (const filterStrategy of sortedFilterStrategies) {
1237
2578
  try {
1238
- const nav = await ContentNavigator.create(user, course, filterStrategy);
1239
- if ("transform" in nav && typeof nav.transform === "function") {
1240
- filters.push(nav);
1241
- logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
1242
- } else {
1243
- warnings.push(
1244
- `Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
1245
- );
1246
- }
1247
- } catch (e) {
1248
- warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
1249
- }
1250
- }
1251
- const pipeline = new Pipeline(generator, filters, user, course);
1252
- logger.debug(
1253
- `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
1254
- );
1255
- return {
1256
- pipeline,
1257
- generatorStrategies,
1258
- filterStrategies: sortedFilterStrategies,
1259
- warnings
1260
- };
1261
- }
1262
- /**
1263
- * Creates a default ELO generator strategy.
1264
- * Used when filters are configured but no generator is specified.
1265
- */
1266
- makeDefaultEloStrategy(courseId) {
1267
- return {
1268
- _id: "NAVIGATION_STRATEGY-ELO-default",
1269
- course: courseId,
1270
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1271
- name: "ELO (default)",
1272
- description: "Default ELO-based generator",
1273
- implementingClass: "elo" /* ELO */,
1274
- serializedData: ""
1275
- };
1276
- }
1277
- };
1278
- }
1279
- });
1280
-
1281
- // src/core/navigators/generators/elo.ts
1282
- import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
1283
- var ELONavigator;
1284
- var init_elo = __esm({
1285
- "src/core/navigators/generators/elo.ts"() {
1286
- "use strict";
1287
- init_navigators();
1288
- ELONavigator = class extends ContentNavigator {
1289
- /** Human-readable name for CardGenerator interface */
1290
- name;
1291
- constructor(user, course, strategyData) {
1292
- super(user, course, strategyData);
1293
- this.name = strategyData?.name || "ELO";
1294
- }
1295
- /**
1296
- * Get new cards with suitability scores based on ELO distance.
1297
- *
1298
- * Cards closer to user's ELO get higher scores.
1299
- * Score formula: max(0, 1 - distance / 500)
1300
- *
1301
- * NOTE: This generator only handles NEW cards. Reviews are handled by
1302
- * SRSNavigator. Use CompositeGenerator to combine both.
1303
- *
1304
- * This method supports both the legacy signature (limit only) and the
1305
- * CardGenerator interface signature (limit, context).
1306
- *
1307
- * @param limit - Maximum number of cards to return
1308
- * @param context - Optional GeneratorContext (used when called via Pipeline)
1309
- */
1310
- async getWeightedCards(limit, context) {
1311
- let userGlobalElo;
1312
- if (context?.userElo !== void 0) {
1313
- userGlobalElo = context.userElo;
1314
- } else {
1315
- const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1316
- const userElo = toCourseElo3(courseReg.elo);
1317
- userGlobalElo = userElo.global.score;
1318
- }
1319
- const activeCards = await this.user.getActiveCards();
1320
- const newCards = (await this.course.getCardsCenteredAtELO(
1321
- { limit, elo: "user" },
1322
- (c) => !activeCards.some((ac) => c.cardID === ac.cardID)
1323
- )).map((c) => ({ ...c, status: "new" }));
1324
- const cardIds = newCards.map((c) => c.cardID);
1325
- const cardEloData = await this.course.getCardEloData(cardIds);
1326
- const scored = newCards.map((c, i) => {
1327
- const cardElo = cardEloData[i]?.global?.score ?? 1e3;
1328
- const distance = Math.abs(cardElo - userGlobalElo);
1329
- const score = Math.max(0, 1 - distance / 500);
1330
- return {
1331
- cardId: c.cardID,
1332
- courseId: c.courseID,
1333
- score,
1334
- provenance: [
1335
- {
1336
- strategy: "elo",
1337
- strategyName: this.strategyName || this.name,
1338
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1339
- action: "generated",
1340
- score,
1341
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), new card`
1342
- }
1343
- ]
1344
- };
1345
- });
1346
- scored.sort((a, b) => b.score - a.score);
1347
- return scored.slice(0, limit);
1348
- }
1349
- };
1350
- }
1351
- });
1352
-
1353
- // src/core/navigators/generators/srs.ts
1354
- import moment3 from "moment";
1355
- var SRSNavigator;
1356
- var init_srs = __esm({
1357
- "src/core/navigators/generators/srs.ts"() {
1358
- "use strict";
1359
- init_navigators();
1360
- init_logger();
1361
- SRSNavigator = class extends ContentNavigator {
1362
- /** Human-readable name for CardGenerator interface */
1363
- name;
1364
- constructor(user, course, strategyData) {
1365
- super(user, course, strategyData);
1366
- this.name = strategyData?.name || "SRS";
1367
- }
1368
- /**
1369
- * Get review cards scored by urgency.
1370
- *
1371
- * Score formula combines:
1372
- * - Relative overdueness: hoursOverdue / intervalHours
1373
- * - Interval recency: exponential decay favoring shorter intervals
1374
- *
1375
- * Cards not yet due are excluded (not scored as 0).
1376
- *
1377
- * This method supports both the legacy signature (limit only) and the
1378
- * CardGenerator interface signature (limit, context).
1379
- *
1380
- * @param limit - Maximum number of cards to return
1381
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1382
- */
1383
- async getWeightedCards(limit, _context) {
1384
- if (!this.user || !this.course) {
1385
- throw new Error("SRSNavigator requires user and course to be set");
1386
- }
1387
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1388
- const now = moment3.utc();
1389
- const dueReviews = reviews.filter((r) => now.isAfter(moment3.utc(r.reviewTime)));
1390
- const scored = dueReviews.map((review) => {
1391
- const { score, reason } = this.computeUrgencyScore(review, now);
1392
- return {
1393
- cardId: review.cardId,
1394
- courseId: review.courseId,
1395
- score,
1396
- reviewID: review._id,
1397
- provenance: [
1398
- {
1399
- strategy: "srs",
1400
- strategyName: this.strategyName || this.name,
1401
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1402
- action: "generated",
1403
- score,
1404
- reason
1405
- }
1406
- ]
1407
- };
1408
- });
1409
- logger.debug(`[srsNav] got ${scored.length} weighted cards`);
1410
- return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1411
- }
1412
- /**
1413
- * Compute urgency score for a review card.
1414
- *
1415
- * Two factors:
1416
- * 1. Relative overdueness = hoursOverdue / intervalHours
1417
- * - 2 days overdue on 3-day interval = 0.67 (urgent)
1418
- * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1419
- *
1420
- * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1421
- * - 24h interval → ~1.0 (very recent learning)
1422
- * - 30 days (720h) → ~0.56
1423
- * - 180 days → ~0.30
1424
- *
1425
- * Combined: base 0.5 + weighted average of factors * 0.45
1426
- * Result range: approximately 0.5 to 0.95
1427
- */
1428
- computeUrgencyScore(review, now) {
1429
- const scheduledAt = moment3.utc(review.scheduledAt);
1430
- const due = moment3.utc(review.reviewTime);
1431
- const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1432
- const hoursOverdue = now.diff(due, "hours");
1433
- const relativeOverdue = hoursOverdue / intervalHours;
1434
- const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1435
- const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1436
- const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1437
- const score = Math.min(0.95, 0.5 + urgency * 0.45);
1438
- const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
1439
- return { score, reason };
1440
- }
1441
- };
1442
- }
1443
- });
1444
-
1445
- // src/core/navigators/filters/eloDistance.ts
1446
- function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1447
- const normalizedDistance = distance / halfLife;
1448
- const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1449
- return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1450
- }
1451
- function createEloDistanceFilter(config) {
1452
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1453
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1454
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1455
- return {
1456
- name: "ELO Distance Filter",
1457
- async transform(cards, context) {
1458
- const { course, userElo } = context;
1459
- const cardIds = cards.map((c) => c.cardId);
1460
- const cardElos = await course.getCardEloData(cardIds);
1461
- return cards.map((card, i) => {
1462
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
1463
- const distance = Math.abs(cardElo - userElo);
1464
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1465
- const newScore = card.score * multiplier;
1466
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1467
- return {
1468
- ...card,
1469
- score: newScore,
1470
- provenance: [
1471
- ...card.provenance,
1472
- {
1473
- strategy: "eloDistance",
1474
- strategyName: "ELO Distance Filter",
1475
- strategyId: "ELO_DISTANCE_FILTER",
1476
- action,
1477
- score: newScore,
1478
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
2579
+ const nav = await ContentNavigator.create(user, course, filterStrategy);
2580
+ if ("transform" in nav && typeof nav.transform === "function") {
2581
+ let filter = nav;
2582
+ if (filterStrategy.learnable) {
2583
+ filter = new WeightedFilter(
2584
+ filter,
2585
+ filterStrategy.learnable,
2586
+ filterStrategy.staticWeight,
2587
+ filterStrategy._id
2588
+ );
2589
+ }
2590
+ filters.push(filter);
2591
+ logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
2592
+ } else {
2593
+ warnings.push(
2594
+ `Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
2595
+ );
1479
2596
  }
1480
- ]
2597
+ } catch (e) {
2598
+ warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
2599
+ }
2600
+ }
2601
+ const pipeline = new Pipeline(generator, filters, user, course);
2602
+ logger.debug(
2603
+ `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
2604
+ );
2605
+ return {
2606
+ pipeline,
2607
+ generatorStrategies,
2608
+ filterStrategies: sortedFilterStrategies,
2609
+ warnings
1481
2610
  };
1482
- });
1483
- }
1484
- };
1485
- }
1486
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1487
- var init_eloDistance = __esm({
1488
- "src/core/navigators/filters/eloDistance.ts"() {
1489
- "use strict";
1490
- DEFAULT_HALF_LIFE = 200;
1491
- DEFAULT_MIN_MULTIPLIER = 0.3;
1492
- DEFAULT_MAX_MULTIPLIER = 1;
2611
+ }
2612
+ /**
2613
+ * Creates a default ELO generator strategy.
2614
+ * Used when filters are configured but no generator is specified.
2615
+ */
2616
+ makeDefaultEloStrategy(courseId) {
2617
+ return {
2618
+ _id: "NAVIGATION_STRATEGY-ELO-default",
2619
+ course: courseId,
2620
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
2621
+ name: "ELO (default)",
2622
+ description: "Default ELO-based generator",
2623
+ implementingClass: "elo" /* ELO */,
2624
+ serializedData: ""
2625
+ };
2626
+ }
2627
+ };
1493
2628
  }
1494
2629
  });
1495
2630
 
1496
2631
  // src/core/navigators/defaults.ts
2632
+ var defaults_exports = {};
2633
+ __export(defaults_exports, {
2634
+ createDefaultEloStrategy: () => createDefaultEloStrategy,
2635
+ createDefaultPipeline: () => createDefaultPipeline,
2636
+ createDefaultSrsStrategy: () => createDefaultSrsStrategy
2637
+ });
1497
2638
  function createDefaultEloStrategy(courseId) {
1498
2639
  return {
1499
2640
  _id: "NAVIGATION_STRATEGY-ELO-default",
@@ -1537,12 +2678,310 @@ var init_defaults = __esm({
1537
2678
  }
1538
2679
  });
1539
2680
 
2681
+ // import("./**/*") in src/core/navigators/index.ts
2682
+ var globImport;
2683
+ var init_3 = __esm({
2684
+ 'import("./**/*") in src/core/navigators/index.ts'() {
2685
+ globImport = __glob({
2686
+ "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
2687
+ "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
2688
+ "./defaults.ts": () => Promise.resolve().then(() => (init_defaults(), defaults_exports)),
2689
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
2690
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2691
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2692
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2693
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
2694
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2695
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2696
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
2697
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
2698
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
2699
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
2700
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
2701
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
2702
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
2703
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
2704
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
2705
+ });
2706
+ }
2707
+ });
2708
+
2709
+ // src/core/navigators/index.ts
2710
+ var navigators_exports = {};
2711
+ __export(navigators_exports, {
2712
+ ContentNavigator: () => ContentNavigator,
2713
+ NavigatorRole: () => NavigatorRole,
2714
+ NavigatorRoles: () => NavigatorRoles,
2715
+ Navigators: () => Navigators,
2716
+ getCardOrigin: () => getCardOrigin,
2717
+ getRegisteredNavigator: () => getRegisteredNavigator,
2718
+ getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
2719
+ hasRegisteredNavigator: () => hasRegisteredNavigator,
2720
+ initializeNavigatorRegistry: () => initializeNavigatorRegistry,
2721
+ isFilter: () => isFilter,
2722
+ isGenerator: () => isGenerator,
2723
+ registerNavigator: () => registerNavigator
2724
+ });
2725
+ function registerNavigator(implementingClass, constructor) {
2726
+ navigatorRegistry.set(implementingClass, constructor);
2727
+ logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}`);
2728
+ }
2729
+ function getRegisteredNavigator(implementingClass) {
2730
+ return navigatorRegistry.get(implementingClass);
2731
+ }
2732
+ function hasRegisteredNavigator(implementingClass) {
2733
+ return navigatorRegistry.has(implementingClass);
2734
+ }
2735
+ function getRegisteredNavigatorNames() {
2736
+ return Array.from(navigatorRegistry.keys());
2737
+ }
2738
+ async function initializeNavigatorRegistry() {
2739
+ logger.debug("[NavigatorRegistry] Initializing built-in navigators...");
2740
+ const [eloModule, srsModule] = await Promise.all([
2741
+ Promise.resolve().then(() => (init_elo(), elo_exports)),
2742
+ Promise.resolve().then(() => (init_srs(), srs_exports))
2743
+ ]);
2744
+ registerNavigator("elo", eloModule.default);
2745
+ registerNavigator("srs", srsModule.default);
2746
+ const [
2747
+ hierarchyModule,
2748
+ interferenceModule,
2749
+ relativePriorityModule,
2750
+ userTagPreferenceModule
2751
+ ] = await Promise.all([
2752
+ Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2753
+ Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2754
+ Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2755
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
2756
+ ]);
2757
+ registerNavigator("hierarchyDefinition", hierarchyModule.default);
2758
+ registerNavigator("interferenceMitigator", interferenceModule.default);
2759
+ registerNavigator("relativePriority", relativePriorityModule.default);
2760
+ registerNavigator("userTagPreference", userTagPreferenceModule.default);
2761
+ logger.debug(
2762
+ `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
2763
+ );
2764
+ }
2765
+ function getCardOrigin(card) {
2766
+ if (card.provenance.length === 0) {
2767
+ throw new Error("Card has no provenance - cannot determine origin");
2768
+ }
2769
+ const firstEntry = card.provenance[0];
2770
+ const reason = firstEntry.reason.toLowerCase();
2771
+ if (reason.includes("failed")) {
2772
+ return "failed";
2773
+ }
2774
+ if (reason.includes("review")) {
2775
+ return "review";
2776
+ }
2777
+ return "new";
2778
+ }
2779
+ function isGenerator(impl) {
2780
+ return NavigatorRoles[impl] === "generator" /* GENERATOR */;
2781
+ }
2782
+ function isFilter(impl) {
2783
+ return NavigatorRoles[impl] === "filter" /* FILTER */;
2784
+ }
2785
+ var navigatorRegistry, Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
2786
+ var init_navigators = __esm({
2787
+ "src/core/navigators/index.ts"() {
2788
+ "use strict";
2789
+ init_logger();
2790
+ init_();
2791
+ init_2();
2792
+ init_3();
2793
+ navigatorRegistry = /* @__PURE__ */ new Map();
2794
+ Navigators = /* @__PURE__ */ ((Navigators2) => {
2795
+ Navigators2["ELO"] = "elo";
2796
+ Navigators2["SRS"] = "srs";
2797
+ Navigators2["HIERARCHY"] = "hierarchyDefinition";
2798
+ Navigators2["INTERFERENCE"] = "interferenceMitigator";
2799
+ Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
2800
+ Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
2801
+ return Navigators2;
2802
+ })(Navigators || {});
2803
+ NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
2804
+ NavigatorRole2["GENERATOR"] = "generator";
2805
+ NavigatorRole2["FILTER"] = "filter";
2806
+ return NavigatorRole2;
2807
+ })(NavigatorRole || {});
2808
+ NavigatorRoles = {
2809
+ ["elo" /* ELO */]: "generator" /* GENERATOR */,
2810
+ ["srs" /* SRS */]: "generator" /* GENERATOR */,
2811
+ ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
2812
+ ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
2813
+ ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
2814
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
2815
+ };
2816
+ ContentNavigator = class {
2817
+ /** User interface for this navigation session */
2818
+ user;
2819
+ /** Course interface for this navigation session */
2820
+ course;
2821
+ /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
2822
+ strategyName;
2823
+ /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
2824
+ strategyId;
2825
+ /** Evolutionary weighting configuration */
2826
+ learnable;
2827
+ /** Whether to bypass deviation (manual/static weighting) */
2828
+ staticWeight;
2829
+ /**
2830
+ * Constructor for standard navigators.
2831
+ * Call this from subclass constructors to initialize common fields.
2832
+ *
2833
+ * Note: CompositeGenerator and Pipeline call super() without args, then set
2834
+ * user/course fields directly if needed.
2835
+ */
2836
+ constructor(user, course, strategyData) {
2837
+ this.user = user;
2838
+ this.course = course;
2839
+ if (strategyData) {
2840
+ this.strategyName = strategyData.name;
2841
+ this.strategyId = strategyData._id;
2842
+ this.learnable = strategyData.learnable;
2843
+ this.staticWeight = strategyData.staticWeight;
2844
+ }
2845
+ }
2846
+ // ============================================================================
2847
+ // STRATEGY STATE HELPERS
2848
+ // ============================================================================
2849
+ //
2850
+ // These methods allow strategies to persist their own state (user preferences,
2851
+ // learned patterns, temporal tracking) in the user database.
2852
+ //
2853
+ // ============================================================================
2854
+ /**
2855
+ * Unique key identifying this strategy for state storage.
2856
+ *
2857
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
2858
+ * Override in subclasses if multiple instances of the same strategy type
2859
+ * need separate state storage.
2860
+ */
2861
+ get strategyKey() {
2862
+ return this.constructor.name;
2863
+ }
2864
+ /**
2865
+ * Get this strategy's persisted state for the current course.
2866
+ *
2867
+ * @returns The strategy's data payload, or null if no state exists
2868
+ * @throws Error if user or course is not initialized
2869
+ */
2870
+ async getStrategyState() {
2871
+ if (!this.user || !this.course) {
2872
+ throw new Error(
2873
+ `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2874
+ );
2875
+ }
2876
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
2877
+ }
2878
+ /**
2879
+ * Persist this strategy's state for the current course.
2880
+ *
2881
+ * @param data - The strategy's data payload to store
2882
+ * @throws Error if user or course is not initialized
2883
+ */
2884
+ async putStrategyState(data) {
2885
+ if (!this.user || !this.course) {
2886
+ throw new Error(
2887
+ `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2888
+ );
2889
+ }
2890
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
2891
+ }
2892
+ /**
2893
+ * Factory method to create navigator instances.
2894
+ *
2895
+ * First checks the navigator registry for a pre-registered constructor.
2896
+ * If not found, falls back to dynamic import (for custom navigators).
2897
+ *
2898
+ * For reliable operation in test environments, call initializeNavigatorRegistry()
2899
+ * before using this method.
2900
+ *
2901
+ * @param user - User interface
2902
+ * @param course - Course interface
2903
+ * @param strategyData - Strategy configuration document
2904
+ * @returns the runtime object used to steer a study session.
2905
+ */
2906
+ static async create(user, course, strategyData) {
2907
+ const implementingClass = strategyData.implementingClass;
2908
+ const RegisteredImpl = getRegisteredNavigator(implementingClass);
2909
+ if (RegisteredImpl) {
2910
+ logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);
2911
+ return new RegisteredImpl(user, course, strategyData);
2912
+ }
2913
+ logger.debug(
2914
+ `[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`
2915
+ );
2916
+ let NavigatorImpl;
2917
+ const variations = [".ts", ".js", ""];
2918
+ for (const ext of variations) {
2919
+ try {
2920
+ const module = await globImport_generators(`./generators/${implementingClass}${ext}`);
2921
+ NavigatorImpl = module.default;
2922
+ if (NavigatorImpl) break;
2923
+ } catch (e) {
2924
+ logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);
2925
+ }
2926
+ try {
2927
+ const module = await globImport_filters(`./filters/${implementingClass}${ext}`);
2928
+ NavigatorImpl = module.default;
2929
+ if (NavigatorImpl) break;
2930
+ } catch (e) {
2931
+ logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);
2932
+ }
2933
+ try {
2934
+ const module = await globImport(`./${implementingClass}${ext}`);
2935
+ NavigatorImpl = module.default;
2936
+ if (NavigatorImpl) break;
2937
+ } catch (e) {
2938
+ logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);
2939
+ }
2940
+ if (NavigatorImpl) break;
2941
+ }
2942
+ if (!NavigatorImpl) {
2943
+ throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
2944
+ }
2945
+ return new NavigatorImpl(user, course, strategyData);
2946
+ }
2947
+ /**
2948
+ * Get cards with suitability scores and provenance trails.
2949
+ *
2950
+ * **This is the PRIMARY API for navigation strategies.**
2951
+ *
2952
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
2953
+ * better candidates for presentation. Each card includes a provenance trail
2954
+ * documenting how strategies contributed to the final score.
2955
+ *
2956
+ * ## Implementation Required
2957
+ * All navigation strategies MUST override this method. The base class does
2958
+ * not provide a default implementation.
2959
+ *
2960
+ * ## For Generators
2961
+ * Override this method to generate candidates and compute scores based on
2962
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
2963
+ * initial provenance entry with action='generated'.
2964
+ *
2965
+ * ## For Filters
2966
+ * Filters should implement the CardFilter interface instead and be composed
2967
+ * via Pipeline. Filters do not directly implement getWeightedCards().
2968
+ *
2969
+ * @param limit - Maximum cards to return
2970
+ * @returns Cards sorted by score descending, with provenance trails
2971
+ */
2972
+ async getWeightedCards(_limit) {
2973
+ throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
2974
+ }
2975
+ };
2976
+ }
2977
+ });
2978
+
1540
2979
  // src/impl/couch/courseDB.ts
1541
2980
  import {
1542
2981
  EloToNumber,
1543
2982
  Status,
1544
2983
  blankCourseElo as blankCourseElo2,
1545
- toCourseElo as toCourseElo4
2984
+ toCourseElo as toCourseElo6
1546
2985
  } from "@vue-skuilder/common";
1547
2986
  function randIntWeightedTowardZero(n) {
1548
2987
  return Math.floor(Math.random() * Math.random() * Math.random() * n);
@@ -1699,7 +3138,7 @@ var init_courseDB = __esm({
1699
3138
  docs.rows.forEach((r) => {
1700
3139
  if (isSuccessRow(r)) {
1701
3140
  if (r.doc && r.doc.elo) {
1702
- ret.push(toCourseElo4(r.doc.elo));
3141
+ ret.push(toCourseElo6(r.doc.elo));
1703
3142
  } else {
1704
3143
  logger.warn("no elo data for card: " + r.id);
1705
3144
  ret.push(blankCourseElo2());
@@ -3444,6 +4883,19 @@ Currently logged-in as ${this._username}.`
3444
4883
  };
3445
4884
  await this.localDB.put(doc);
3446
4885
  }
4886
+ async putUserOutcome(record) {
4887
+ try {
4888
+ await this.localDB.put(record);
4889
+ } catch (err) {
4890
+ if (err.status === 409) {
4891
+ const existing = await this.localDB.get(record._id);
4892
+ record._rev = existing._rev;
4893
+ await this.localDB.put(record);
4894
+ } else {
4895
+ throw err;
4896
+ }
4897
+ }
4898
+ }
3447
4899
  async deleteStrategyState(courseId, strategyKey) {
3448
4900
  const docId = buildStrategyStateId(courseId, strategyKey);
3449
4901
  try {
@@ -3486,6 +4938,7 @@ var init_factory = __esm({
3486
4938
  "use strict";
3487
4939
  init_common();
3488
4940
  init_logger();
4941
+ init_navigators();
3489
4942
  NOT_SET = "NOT_SET";
3490
4943
  ENV = {
3491
4944
  COUCHDB_SERVER_PROTOCOL: NOT_SET,
@@ -3742,6 +5195,13 @@ var init_strategyState = __esm({
3742
5195
  }
3743
5196
  });
3744
5197
 
5198
+ // src/core/types/userOutcome.ts
5199
+ var init_userOutcome = __esm({
5200
+ "src/core/types/userOutcome.ts"() {
5201
+ "use strict";
5202
+ }
5203
+ });
5204
+
3745
5205
  // src/core/bulkImport/cardProcessor.ts
3746
5206
  import { Status as Status4 } from "@vue-skuilder/common";
3747
5207
  async function importParsedCards(parsedCards, courseDB, config) {
@@ -3863,7 +5323,7 @@ var init_cardProcessor = __esm({
3863
5323
  });
3864
5324
 
3865
5325
  // src/core/bulkImport/types.ts
3866
- var init_types = __esm({
5326
+ var init_types3 = __esm({
3867
5327
  "src/core/bulkImport/types.ts"() {
3868
5328
  "use strict";
3869
5329
  }
@@ -3874,7 +5334,7 @@ var init_bulkImport = __esm({
3874
5334
  "src/core/bulkImport/index.ts"() {
3875
5335
  "use strict";
3876
5336
  init_cardProcessor();
3877
- init_types();
5337
+ init_types3();
3878
5338
  }
3879
5339
  });
3880
5340
 
@@ -3885,10 +5345,12 @@ var init_core = __esm({
3885
5345
  init_types_legacy();
3886
5346
  init_user();
3887
5347
  init_strategyState();
5348
+ init_userOutcome();
3888
5349
  init_Loggable();
3889
5350
  init_util();
3890
5351
  init_navigators();
3891
5352
  init_bulkImport();
5353
+ init_orchestration();
3892
5354
  }
3893
5355
  });
3894
5356
  init_core();
@@ -3901,19 +5363,37 @@ export {
3901
5363
  NavigatorRole,
3902
5364
  NavigatorRoles,
3903
5365
  Navigators,
5366
+ aggregateOutcomesForGradient,
3904
5367
  areQuestionRecords,
3905
5368
  buildStrategyStateId,
5369
+ computeDeviation,
5370
+ computeEffectiveWeight,
5371
+ computeOutcomeSignal,
5372
+ computeSpread,
5373
+ computeStrategyGradient,
5374
+ createOrchestrationContext,
3906
5375
  docIsDeleted,
3907
5376
  getCardHistoryID,
3908
5377
  getCardOrigin,
5378
+ getDefaultLearnableWeight,
5379
+ getRegisteredNavigator,
5380
+ getRegisteredNavigatorNames,
3909
5381
  getStudySource,
5382
+ hasRegisteredNavigator,
3910
5383
  importParsedCards,
5384
+ initializeNavigatorRegistry,
3911
5385
  isFilter,
3912
5386
  isGenerator,
3913
5387
  isQuestionRecord,
3914
5388
  isReview,
3915
5389
  log,
3916
5390
  parseCardHistoryID,
5391
+ recordUserOutcome,
5392
+ registerNavigator,
5393
+ runPeriodUpdate,
5394
+ scoreAccuracyInZone,
5395
+ updateLearningState,
5396
+ updateStrategyWeight,
3917
5397
  validateProcessorConfig
3918
5398
  };
3919
5399
  //# sourceMappingURL=index.mjs.map