@vue-skuilder/db 0.1.23 → 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 (66) 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 +36 -11
  26. package/dist/index.d.ts +36 -11
  27. package/dist/index.js +2410 -806
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2112 -529
  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 +107 -0
  62. package/src/factory.ts +6 -0
  63. package/src/impl/common/BaseUserDB.ts +16 -0
  64. package/src/study/SessionController.ts +64 -1
  65. package/tests/core/navigators/Pipeline.test.ts +2 -0
  66. package/docs/todo-evolutionary-orchestration.md +0 -310
package/dist/index.mjs CHANGED
@@ -1,5 +1,10 @@
1
1
  var __defProp = Object.defineProperty;
2
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
+ };
3
8
  var __esm = (fn, res) => function __init() {
4
9
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
10
  };
@@ -96,6 +101,8 @@ var init_types_legacy = __esm({
96
101
  DocType3["TAG"] = "TAG";
97
102
  DocType3["NAVIGATION_STRATEGY"] = "NAVIGATION_STRATEGY";
98
103
  DocType3["STRATEGY_STATE"] = "STRATEGY_STATE";
104
+ DocType3["USER_OUTCOME"] = "USER_OUTCOME";
105
+ DocType3["STRATEGY_LEARNING_STATE"] = "STRATEGY_LEARNING_STATE";
99
106
  return DocType3;
100
107
  })(DocType || {});
101
108
  DocTypePrefixes = {
@@ -110,7 +117,9 @@ var init_types_legacy = __esm({
110
117
  ["VIEW" /* VIEW */]: "VIEW",
111
118
  ["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
112
119
  ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
113
- ["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"
114
123
  };
115
124
  }
116
125
  });
@@ -831,199 +840,1626 @@ var init_courseLookupDB = __esm({
831
840
  }
832
841
  });
833
842
 
834
- // src/core/navigators/index.ts
835
- function getCardOrigin(card) {
836
- if (card.provenance.length === 0) {
837
- throw new Error("Card has no provenance - cannot determine origin");
838
- }
839
- const firstEntry = card.provenance[0];
840
- const reason = firstEntry.reason.toLowerCase();
841
- if (reason.includes("failed")) {
842
- return "failed";
843
- }
844
- if (reason.includes("review")) {
845
- return "review";
846
- }
847
- return "new";
848
- }
849
- function isGenerator(impl) {
850
- return NavigatorRoles[impl] === "generator" /* GENERATOR */;
851
- }
852
- function isFilter(impl) {
853
- return NavigatorRoles[impl] === "filter" /* FILTER */;
854
- }
855
- var Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
856
- var init_navigators = __esm({
857
- "src/core/navigators/index.ts"() {
843
+ // src/core/navigators/generators/CompositeGenerator.ts
844
+ var CompositeGenerator_exports = {};
845
+ __export(CompositeGenerator_exports, {
846
+ AggregationMode: () => AggregationMode,
847
+ default: () => CompositeGenerator
848
+ });
849
+ var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
850
+ var init_CompositeGenerator = __esm({
851
+ "src/core/navigators/generators/CompositeGenerator.ts"() {
858
852
  "use strict";
853
+ init_navigators();
859
854
  init_logger();
860
- Navigators = /* @__PURE__ */ ((Navigators2) => {
861
- Navigators2["ELO"] = "elo";
862
- Navigators2["SRS"] = "srs";
863
- Navigators2["HIERARCHY"] = "hierarchyDefinition";
864
- Navigators2["INTERFERENCE"] = "interferenceMitigator";
865
- Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
866
- Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
867
- return Navigators2;
868
- })(Navigators || {});
869
- NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
870
- NavigatorRole2["GENERATOR"] = "generator";
871
- NavigatorRole2["FILTER"] = "filter";
872
- return NavigatorRole2;
873
- })(NavigatorRole || {});
874
- NavigatorRoles = {
875
- ["elo" /* ELO */]: "generator" /* GENERATOR */,
876
- ["srs" /* SRS */]: "generator" /* GENERATOR */,
877
- ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
878
- ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
879
- ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
880
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
881
- };
882
- ContentNavigator = class {
883
- /** User interface for this navigation session */
884
- user;
885
- /** Course interface for this navigation session */
886
- course;
887
- /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
888
- strategyName;
889
- /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
890
- strategyId;
891
- /**
892
- * Constructor for standard navigators.
893
- * Call this from subclass constructors to initialize common fields.
894
- *
895
- * Note: CompositeGenerator and Pipeline call super() without args, then set
896
- * user/course fields directly if needed.
897
- */
898
- constructor(user, course, strategyData) {
899
- this.user = user;
900
- this.course = course;
901
- if (strategyData) {
902
- this.strategyName = strategyData.name;
903
- this.strategyId = strategyData._id;
855
+ AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
856
+ AggregationMode2["MAX"] = "max";
857
+ AggregationMode2["AVERAGE"] = "average";
858
+ AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
859
+ return AggregationMode2;
860
+ })(AggregationMode || {});
861
+ DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
862
+ FREQUENCY_BOOST_FACTOR = 0.1;
863
+ CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
864
+ /** Human-readable name for CardGenerator interface */
865
+ name = "Composite Generator";
866
+ generators;
867
+ aggregationMode;
868
+ constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
869
+ super();
870
+ this.generators = generators;
871
+ this.aggregationMode = aggregationMode;
872
+ if (generators.length === 0) {
873
+ throw new Error("CompositeGenerator requires at least one generator");
904
874
  }
875
+ logger.debug(
876
+ `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
877
+ );
905
878
  }
906
- // ============================================================================
907
- // STRATEGY STATE HELPERS
908
- // ============================================================================
909
- //
910
- // These methods allow strategies to persist their own state (user preferences,
911
- // learned patterns, temporal tracking) in the user database.
912
- //
913
- // ============================================================================
914
879
  /**
915
- * Unique key identifying this strategy for state storage.
880
+ * Creates a CompositeGenerator from strategy data.
916
881
  *
917
- * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
918
- * Override in subclasses if multiple instances of the same strategy type
919
- * need separate state storage.
882
+ * This is a convenience factory for use by PipelineAssembler.
920
883
  */
921
- get strategyKey() {
922
- return this.constructor.name;
884
+ static async fromStrategies(user, course, strategies, aggregationMode = DEFAULT_AGGREGATION_MODE) {
885
+ const generators = await Promise.all(
886
+ strategies.map((s) => ContentNavigator.create(user, course, s))
887
+ );
888
+ return new _CompositeGenerator(generators, aggregationMode);
923
889
  }
924
890
  /**
925
- * Get this strategy's persisted state for the current course.
891
+ * Get weighted cards from all generators, merge and deduplicate.
926
892
  *
927
- * @returns The strategy's data payload, or null if no state exists
928
- * @throws Error if user or course is not initialized
929
- */
930
- async getStrategyState() {
931
- if (!this.user || !this.course) {
932
- throw new Error(
933
- `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
934
- );
935
- }
936
- return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
937
- }
938
- /**
939
- * Persist this strategy's state for the current course.
893
+ * Cards appearing in multiple generators receive a score boost.
894
+ * Provenance tracks which generators produced each card and how scores were aggregated.
940
895
  *
941
- * @param data - The strategy's data payload to store
942
- * @throws Error if user or course is not initialized
896
+ * This method supports both the legacy signature (limit only) and the
897
+ * CardGenerator interface signature (limit, context).
898
+ *
899
+ * @param limit - Maximum number of cards to return
900
+ * @param context - GeneratorContext passed to child generators (required when called via Pipeline)
943
901
  */
944
- async putStrategyState(data) {
945
- if (!this.user || !this.course) {
902
+ async getWeightedCards(limit, context) {
903
+ if (!context) {
946
904
  throw new Error(
947
- `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
905
+ "CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly."
948
906
  );
949
907
  }
950
- return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
908
+ const results = await Promise.all(
909
+ this.generators.map((g) => g.getWeightedCards(limit, context))
910
+ );
911
+ const byCardId = /* @__PURE__ */ new Map();
912
+ results.forEach((cards, index) => {
913
+ const gen = this.generators[index];
914
+ let weight = gen.learnable?.weight ?? 1;
915
+ let deviation;
916
+ if (gen.learnable && !gen.staticWeight && context.orchestration) {
917
+ const strategyId = gen.strategyId;
918
+ if (strategyId) {
919
+ weight = context.orchestration.getEffectiveWeight(strategyId, gen.learnable);
920
+ deviation = context.orchestration.getDeviation(strategyId);
921
+ }
922
+ }
923
+ for (const card of cards) {
924
+ if (card.provenance.length > 0) {
925
+ card.provenance[0].effectiveWeight = weight;
926
+ card.provenance[0].deviation = deviation;
927
+ }
928
+ const existing = byCardId.get(card.cardId) || [];
929
+ existing.push({ card, weight });
930
+ byCardId.set(card.cardId, existing);
931
+ }
932
+ });
933
+ const merged = [];
934
+ for (const [, items] of byCardId) {
935
+ const cards = items.map((i) => i.card);
936
+ const aggregatedScore = this.aggregateScores(items);
937
+ const finalScore = Math.min(1, aggregatedScore);
938
+ const mergedProvenance = cards.flatMap((c) => c.provenance);
939
+ const initialScore = cards[0].score;
940
+ const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
941
+ const reason = this.buildAggregationReason(items, finalScore);
942
+ merged.push({
943
+ ...cards[0],
944
+ score: finalScore,
945
+ provenance: [
946
+ ...mergedProvenance,
947
+ {
948
+ strategy: "composite",
949
+ strategyName: "Composite Generator",
950
+ strategyId: "COMPOSITE_GENERATOR",
951
+ action,
952
+ score: finalScore,
953
+ reason
954
+ }
955
+ ]
956
+ });
957
+ }
958
+ return merged.sort((a, b) => b.score - a.score).slice(0, limit);
951
959
  }
952
960
  /**
953
- * Factory method to create navigator instances dynamically.
954
- *
955
- * @param user - User interface
956
- * @param course - Course interface
957
- * @param strategyData - Strategy configuration document
958
- * @returns the runtime object used to steer a study session.
961
+ * Build human-readable reason for score aggregation.
959
962
  */
960
- static async create(user, course, strategyData) {
961
- const implementingClass = strategyData.implementingClass;
962
- let NavigatorImpl;
963
- const variations = [".ts", ".js", ""];
964
- const dirs = ["filters", "generators"];
965
- for (const ext of variations) {
966
- for (const dir of dirs) {
967
- const loadFrom = `./${dir}/${implementingClass}${ext}`;
968
- try {
969
- const module = await import(loadFrom);
970
- NavigatorImpl = module.default;
971
- break;
972
- } catch (e) {
973
- logger.debug(`Failed to load extension from ${loadFrom}:`, e);
974
- }
975
- }
963
+ buildAggregationReason(items, finalScore) {
964
+ const cards = items.map((i) => i.card);
965
+ const count = cards.length;
966
+ const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
967
+ if (count === 1) {
968
+ const weightMsg = Math.abs(items[0].weight - 1) > 1e-3 ? ` (w=${items[0].weight.toFixed(2)})` : "";
969
+ return `Single generator, score ${finalScore.toFixed(2)}${weightMsg}`;
976
970
  }
977
- if (!NavigatorImpl) {
978
- throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
971
+ const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
972
+ switch (this.aggregationMode) {
973
+ case "max" /* MAX */:
974
+ return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
975
+ case "average" /* AVERAGE */:
976
+ return `Weighted Avg of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
977
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
978
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
979
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
980
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
981
+ const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
982
+ return `Frequency boost from ${count} generators (${strategies}): w-avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
983
+ }
984
+ default:
985
+ return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
979
986
  }
980
- return new NavigatorImpl(user, course, strategyData);
981
987
  }
982
988
  /**
983
- * Get cards with suitability scores and provenance trails.
984
- *
985
- * **This is the PRIMARY API for navigation strategies.**
986
- *
987
- * Returns cards ranked by suitability score (0-1). Higher scores indicate
988
- * better candidates for presentation. Each card includes a provenance trail
989
- * documenting how strategies contributed to the final score.
990
- *
991
- * ## Implementation Required
992
- * All navigation strategies MUST override this method. The base class does
993
- * not provide a default implementation.
994
- *
995
- * ## For Generators
996
- * Override this method to generate candidates and compute scores based on
997
- * your strategy's logic (e.g., ELO proximity, review urgency). Create the
998
- * initial provenance entry with action='generated'.
999
- *
1000
- * ## For Filters
1001
- * Filters should implement the CardFilter interface instead and be composed
1002
- * via Pipeline. Filters do not directly implement getWeightedCards().
1003
- *
1004
- * @param limit - Maximum cards to return
1005
- * @returns Cards sorted by score descending, with provenance trails
989
+ * Aggregate scores from multiple generators for the same card.
1006
990
  */
1007
- async getWeightedCards(_limit) {
1008
- throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
991
+ aggregateScores(items) {
992
+ const scores = items.map((i) => i.card.score);
993
+ switch (this.aggregationMode) {
994
+ case "max" /* MAX */:
995
+ return Math.max(...scores);
996
+ case "average" /* AVERAGE */: {
997
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
998
+ if (totalWeight === 0) return 0;
999
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
1000
+ return weightedSum / totalWeight;
1001
+ }
1002
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
1003
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
1004
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
1005
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
1006
+ const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (items.length - 1);
1007
+ return avg * frequencyBoost;
1008
+ }
1009
+ default:
1010
+ return scores[0];
1011
+ }
1009
1012
  }
1010
1013
  };
1011
1014
  }
1012
1015
  });
1013
1016
 
1014
- // src/core/navigators/Pipeline.ts
1017
+ // src/core/navigators/generators/elo.ts
1018
+ var elo_exports = {};
1019
+ __export(elo_exports, {
1020
+ default: () => ELONavigator
1021
+ });
1015
1022
  import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
1016
- function logPipelineConfig(generator, filters) {
1017
- const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
1018
- logger.info(
1019
- `[Pipeline] Configuration:
1020
- Generator: ${generator.name}
1021
- Filters:${filterList}`
1022
- );
1023
- }
1024
- function logTagHydration(cards, tagsByCard) {
1025
- const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
1026
- const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
1023
+ var ELONavigator;
1024
+ var init_elo = __esm({
1025
+ "src/core/navigators/generators/elo.ts"() {
1026
+ "use strict";
1027
+ init_navigators();
1028
+ ELONavigator = class extends ContentNavigator {
1029
+ /** Human-readable name for CardGenerator interface */
1030
+ name;
1031
+ constructor(user, course, strategyData) {
1032
+ super(user, course, strategyData);
1033
+ this.name = strategyData?.name || "ELO";
1034
+ }
1035
+ /**
1036
+ * Get new cards with suitability scores based on ELO distance.
1037
+ *
1038
+ * Cards closer to user's ELO get higher scores.
1039
+ * Score formula: max(0, 1 - distance / 500)
1040
+ *
1041
+ * NOTE: This generator only handles NEW cards. Reviews are handled by
1042
+ * SRSNavigator. Use CompositeGenerator to combine both.
1043
+ *
1044
+ * This method supports both the legacy signature (limit only) and the
1045
+ * CardGenerator interface signature (limit, context).
1046
+ *
1047
+ * @param limit - Maximum number of cards to return
1048
+ * @param context - Optional GeneratorContext (used when called via Pipeline)
1049
+ */
1050
+ async getWeightedCards(limit, context) {
1051
+ let userGlobalElo;
1052
+ if (context?.userElo !== void 0) {
1053
+ userGlobalElo = context.userElo;
1054
+ } else {
1055
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1056
+ const userElo = toCourseElo2(courseReg.elo);
1057
+ userGlobalElo = userElo.global.score;
1058
+ }
1059
+ const activeCards = await this.user.getActiveCards();
1060
+ const newCards = (await this.course.getCardsCenteredAtELO(
1061
+ { limit, elo: "user" },
1062
+ (c) => !activeCards.some((ac) => c.cardID === ac.cardID)
1063
+ )).map((c) => ({ ...c, status: "new" }));
1064
+ const cardIds = newCards.map((c) => c.cardID);
1065
+ const cardEloData = await this.course.getCardEloData(cardIds);
1066
+ const scored = newCards.map((c, i) => {
1067
+ const cardElo = cardEloData[i]?.global?.score ?? 1e3;
1068
+ const distance = Math.abs(cardElo - userGlobalElo);
1069
+ const score = Math.max(0, 1 - distance / 500);
1070
+ return {
1071
+ cardId: c.cardID,
1072
+ courseId: c.courseID,
1073
+ score,
1074
+ provenance: [
1075
+ {
1076
+ strategy: "elo",
1077
+ strategyName: this.strategyName || this.name,
1078
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1079
+ action: "generated",
1080
+ score,
1081
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), new card`
1082
+ }
1083
+ ]
1084
+ };
1085
+ });
1086
+ scored.sort((a, b) => b.score - a.score);
1087
+ return scored.slice(0, limit);
1088
+ }
1089
+ };
1090
+ }
1091
+ });
1092
+
1093
+ // src/core/navigators/generators/index.ts
1094
+ var generators_exports = {};
1095
+ var init_generators = __esm({
1096
+ "src/core/navigators/generators/index.ts"() {
1097
+ "use strict";
1098
+ }
1099
+ });
1100
+
1101
+ // src/core/navigators/generators/srs.ts
1102
+ var srs_exports = {};
1103
+ __export(srs_exports, {
1104
+ default: () => SRSNavigator
1105
+ });
1106
+ import moment3 from "moment";
1107
+ var SRSNavigator;
1108
+ var init_srs = __esm({
1109
+ "src/core/navigators/generators/srs.ts"() {
1110
+ "use strict";
1111
+ init_navigators();
1112
+ init_logger();
1113
+ SRSNavigator = class extends ContentNavigator {
1114
+ /** Human-readable name for CardGenerator interface */
1115
+ name;
1116
+ constructor(user, course, strategyData) {
1117
+ super(user, course, strategyData);
1118
+ this.name = strategyData?.name || "SRS";
1119
+ }
1120
+ /**
1121
+ * Get review cards scored by urgency.
1122
+ *
1123
+ * Score formula combines:
1124
+ * - Relative overdueness: hoursOverdue / intervalHours
1125
+ * - Interval recency: exponential decay favoring shorter intervals
1126
+ *
1127
+ * Cards not yet due are excluded (not scored as 0).
1128
+ *
1129
+ * This method supports both the legacy signature (limit only) and the
1130
+ * CardGenerator interface signature (limit, context).
1131
+ *
1132
+ * @param limit - Maximum number of cards to return
1133
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1134
+ */
1135
+ async getWeightedCards(limit, _context) {
1136
+ if (!this.user || !this.course) {
1137
+ throw new Error("SRSNavigator requires user and course to be set");
1138
+ }
1139
+ const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1140
+ const now = moment3.utc();
1141
+ const dueReviews = reviews.filter((r) => now.isAfter(moment3.utc(r.reviewTime)));
1142
+ const scored = dueReviews.map((review) => {
1143
+ const { score, reason } = this.computeUrgencyScore(review, now);
1144
+ return {
1145
+ cardId: review.cardId,
1146
+ courseId: review.courseId,
1147
+ score,
1148
+ reviewID: review._id,
1149
+ provenance: [
1150
+ {
1151
+ strategy: "srs",
1152
+ strategyName: this.strategyName || this.name,
1153
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1154
+ action: "generated",
1155
+ score,
1156
+ reason
1157
+ }
1158
+ ]
1159
+ };
1160
+ });
1161
+ logger.debug(`[srsNav] got ${scored.length} weighted cards`);
1162
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1163
+ }
1164
+ /**
1165
+ * Compute urgency score for a review card.
1166
+ *
1167
+ * Two factors:
1168
+ * 1. Relative overdueness = hoursOverdue / intervalHours
1169
+ * - 2 days overdue on 3-day interval = 0.67 (urgent)
1170
+ * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1171
+ *
1172
+ * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1173
+ * - 24h interval → ~1.0 (very recent learning)
1174
+ * - 30 days (720h) → ~0.56
1175
+ * - 180 days → ~0.30
1176
+ *
1177
+ * Combined: base 0.5 + weighted average of factors * 0.45
1178
+ * Result range: approximately 0.5 to 0.95
1179
+ */
1180
+ computeUrgencyScore(review, now) {
1181
+ const scheduledAt = moment3.utc(review.scheduledAt);
1182
+ const due = moment3.utc(review.reviewTime);
1183
+ const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1184
+ const hoursOverdue = now.diff(due, "hours");
1185
+ const relativeOverdue = hoursOverdue / intervalHours;
1186
+ const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1187
+ const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1188
+ const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1189
+ const score = Math.min(0.95, 0.5 + urgency * 0.45);
1190
+ const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
1191
+ return { score, reason };
1192
+ }
1193
+ };
1194
+ }
1195
+ });
1196
+
1197
+ // src/core/navigators/generators/types.ts
1198
+ var types_exports = {};
1199
+ var init_types = __esm({
1200
+ "src/core/navigators/generators/types.ts"() {
1201
+ "use strict";
1202
+ }
1203
+ });
1204
+
1205
+ // import("./generators/**/*") in src/core/navigators/index.ts
1206
+ var globImport_generators;
1207
+ var init_ = __esm({
1208
+ 'import("./generators/**/*") in src/core/navigators/index.ts'() {
1209
+ globImport_generators = __glob({
1210
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
1211
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
1212
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
1213
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
1214
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports))
1215
+ });
1216
+ }
1217
+ });
1218
+
1219
+ // src/core/types/contentNavigationStrategy.ts
1220
+ var DEFAULT_LEARNABLE_WEIGHT;
1221
+ var init_contentNavigationStrategy = __esm({
1222
+ "src/core/types/contentNavigationStrategy.ts"() {
1223
+ "use strict";
1224
+ DEFAULT_LEARNABLE_WEIGHT = {
1225
+ weight: 1,
1226
+ confidence: 0.1,
1227
+ // Low confidence initially = wide exploration
1228
+ sampleSize: 0
1229
+ };
1230
+ }
1231
+ });
1232
+
1233
+ // src/core/navigators/filters/WeightedFilter.ts
1234
+ var WeightedFilter_exports = {};
1235
+ __export(WeightedFilter_exports, {
1236
+ WeightedFilter: () => WeightedFilter
1237
+ });
1238
+ var WeightedFilter;
1239
+ var init_WeightedFilter = __esm({
1240
+ "src/core/navigators/filters/WeightedFilter.ts"() {
1241
+ "use strict";
1242
+ init_contentNavigationStrategy();
1243
+ WeightedFilter = class {
1244
+ name;
1245
+ inner;
1246
+ learnable;
1247
+ staticWeight;
1248
+ strategyId;
1249
+ constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
1250
+ this.inner = inner;
1251
+ this.name = inner.name;
1252
+ this.learnable = learnable;
1253
+ this.staticWeight = staticWeight;
1254
+ this.strategyId = strategyId;
1255
+ }
1256
+ /**
1257
+ * Apply the inner filter, then scale its effect by the configured weight.
1258
+ */
1259
+ async transform(cards, context) {
1260
+ let effectiveWeight = this.learnable.weight;
1261
+ let deviation;
1262
+ if (!this.staticWeight && context.orchestration) {
1263
+ const strategyId = this.strategyId || this.inner.strategyId || this.name;
1264
+ effectiveWeight = context.orchestration.getEffectiveWeight(strategyId, this.learnable);
1265
+ deviation = context.orchestration.getDeviation(strategyId);
1266
+ }
1267
+ if (Math.abs(effectiveWeight - 1) < 1e-3) {
1268
+ return this.inner.transform(cards, context);
1269
+ }
1270
+ const originalScores = /* @__PURE__ */ new Map();
1271
+ for (const card of cards) {
1272
+ originalScores.set(card.cardId, card.score);
1273
+ }
1274
+ const transformedCards = await this.inner.transform(cards, context);
1275
+ return transformedCards.map((card) => {
1276
+ const originalScore = originalScores.get(card.cardId);
1277
+ if (originalScore === void 0 || originalScore === 0 || card.score === 0) {
1278
+ return card;
1279
+ }
1280
+ const rawEffect = card.score / originalScore;
1281
+ if (Math.abs(rawEffect - 1) < 1e-4) {
1282
+ return card;
1283
+ }
1284
+ const weightedEffect = Math.pow(rawEffect, effectiveWeight);
1285
+ const newScore = originalScore * weightedEffect;
1286
+ const lastProvIndex = card.provenance.length - 1;
1287
+ const lastProv = card.provenance[lastProvIndex];
1288
+ if (lastProv) {
1289
+ const updatedProvenance = [...card.provenance];
1290
+ updatedProvenance[lastProvIndex] = {
1291
+ ...lastProv,
1292
+ score: newScore,
1293
+ effectiveWeight,
1294
+ deviation
1295
+ // We can optionally append to the reason, but the structured field is key
1296
+ };
1297
+ return {
1298
+ ...card,
1299
+ score: newScore,
1300
+ provenance: updatedProvenance
1301
+ };
1302
+ }
1303
+ return {
1304
+ ...card,
1305
+ score: newScore
1306
+ };
1307
+ });
1308
+ }
1309
+ };
1310
+ }
1311
+ });
1312
+
1313
+ // src/core/navigators/filters/eloDistance.ts
1314
+ var eloDistance_exports = {};
1315
+ __export(eloDistance_exports, {
1316
+ DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1317
+ DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1318
+ DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1319
+ createEloDistanceFilter: () => createEloDistanceFilter
1320
+ });
1321
+ function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1322
+ const normalizedDistance = distance / halfLife;
1323
+ const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1324
+ return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1325
+ }
1326
+ function createEloDistanceFilter(config) {
1327
+ const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1328
+ const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1329
+ const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1330
+ return {
1331
+ name: "ELO Distance Filter",
1332
+ async transform(cards, context) {
1333
+ const { course, userElo } = context;
1334
+ const cardIds = cards.map((c) => c.cardId);
1335
+ const cardElos = await course.getCardEloData(cardIds);
1336
+ return cards.map((card, i) => {
1337
+ const cardElo = cardElos[i]?.global?.score ?? 1e3;
1338
+ const distance = Math.abs(cardElo - userElo);
1339
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1340
+ const newScore = card.score * multiplier;
1341
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1342
+ return {
1343
+ ...card,
1344
+ score: newScore,
1345
+ provenance: [
1346
+ ...card.provenance,
1347
+ {
1348
+ strategy: "eloDistance",
1349
+ strategyName: "ELO Distance Filter",
1350
+ strategyId: "ELO_DISTANCE_FILTER",
1351
+ action,
1352
+ score: newScore,
1353
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1354
+ }
1355
+ ]
1356
+ };
1357
+ });
1358
+ }
1359
+ };
1360
+ }
1361
+ var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1362
+ var init_eloDistance = __esm({
1363
+ "src/core/navigators/filters/eloDistance.ts"() {
1364
+ "use strict";
1365
+ DEFAULT_HALF_LIFE = 200;
1366
+ DEFAULT_MIN_MULTIPLIER = 0.3;
1367
+ DEFAULT_MAX_MULTIPLIER = 1;
1368
+ }
1369
+ });
1370
+
1371
+ // src/core/navigators/filters/hierarchyDefinition.ts
1372
+ var hierarchyDefinition_exports = {};
1373
+ __export(hierarchyDefinition_exports, {
1374
+ default: () => HierarchyDefinitionNavigator
1375
+ });
1376
+ import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
1377
+ var DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1378
+ var init_hierarchyDefinition = __esm({
1379
+ "src/core/navigators/filters/hierarchyDefinition.ts"() {
1380
+ "use strict";
1381
+ init_navigators();
1382
+ DEFAULT_MIN_COUNT = 3;
1383
+ HierarchyDefinitionNavigator = class extends ContentNavigator {
1384
+ config;
1385
+ /** Human-readable name for CardFilter interface */
1386
+ name;
1387
+ constructor(user, course, strategyData) {
1388
+ super(user, course, strategyData);
1389
+ this.config = this.parseConfig(strategyData.serializedData);
1390
+ this.name = strategyData.name || "Hierarchy Definition";
1391
+ }
1392
+ parseConfig(serializedData) {
1393
+ try {
1394
+ const parsed = JSON.parse(serializedData);
1395
+ return {
1396
+ prerequisites: parsed.prerequisites || {}
1397
+ };
1398
+ } catch {
1399
+ return {
1400
+ prerequisites: {}
1401
+ };
1402
+ }
1403
+ }
1404
+ /**
1405
+ * Check if a specific prerequisite is satisfied
1406
+ */
1407
+ isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1408
+ if (!userTagElo) return false;
1409
+ const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1410
+ if (userTagElo.count < minCount) return false;
1411
+ if (prereq.masteryThreshold?.minElo !== void 0) {
1412
+ return userTagElo.score >= prereq.masteryThreshold.minElo;
1413
+ } else {
1414
+ return userTagElo.score >= userGlobalElo;
1415
+ }
1416
+ }
1417
+ /**
1418
+ * Get the set of tags the user has mastered.
1419
+ * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1420
+ */
1421
+ async getMasteredTags(context) {
1422
+ const mastered = /* @__PURE__ */ new Set();
1423
+ try {
1424
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1425
+ const userElo = toCourseElo3(courseReg.elo);
1426
+ for (const prereqs of Object.values(this.config.prerequisites)) {
1427
+ for (const prereq of prereqs) {
1428
+ const tagElo = userElo.tags[prereq.tag];
1429
+ if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1430
+ mastered.add(prereq.tag);
1431
+ }
1432
+ }
1433
+ }
1434
+ } catch {
1435
+ }
1436
+ return mastered;
1437
+ }
1438
+ /**
1439
+ * Get the set of tags that are unlocked (prerequisites met)
1440
+ */
1441
+ getUnlockedTags(masteredTags) {
1442
+ const unlocked = /* @__PURE__ */ new Set();
1443
+ for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1444
+ const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1445
+ if (allPrereqsMet) {
1446
+ unlocked.add(tagId);
1447
+ }
1448
+ }
1449
+ return unlocked;
1450
+ }
1451
+ /**
1452
+ * Check if a tag has prerequisites defined in config
1453
+ */
1454
+ hasPrerequisites(tagId) {
1455
+ return tagId in this.config.prerequisites;
1456
+ }
1457
+ /**
1458
+ * Check if a card is unlocked and generate reason.
1459
+ */
1460
+ async checkCardUnlock(card, _course, unlockedTags, masteredTags) {
1461
+ try {
1462
+ const cardTags = card.tags ?? [];
1463
+ const lockedTags = cardTags.filter(
1464
+ (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1465
+ );
1466
+ if (lockedTags.length === 0) {
1467
+ const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1468
+ return {
1469
+ isUnlocked: true,
1470
+ reason: `Prerequisites met, tags: ${tagList}`
1471
+ };
1472
+ }
1473
+ const missingPrereqs = lockedTags.flatMap((tag) => {
1474
+ const prereqs = this.config.prerequisites[tag] || [];
1475
+ return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1476
+ });
1477
+ return {
1478
+ isUnlocked: false,
1479
+ reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1480
+ };
1481
+ } catch {
1482
+ return {
1483
+ isUnlocked: true,
1484
+ reason: "Prerequisites check skipped (tag lookup failed)"
1485
+ };
1486
+ }
1487
+ }
1488
+ /**
1489
+ * CardFilter.transform implementation.
1490
+ *
1491
+ * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1492
+ */
1493
+ async transform(cards, context) {
1494
+ const masteredTags = await this.getMasteredTags(context);
1495
+ const unlockedTags = this.getUnlockedTags(masteredTags);
1496
+ const gated = [];
1497
+ for (const card of cards) {
1498
+ const { isUnlocked, reason } = await this.checkCardUnlock(
1499
+ card,
1500
+ context.course,
1501
+ unlockedTags,
1502
+ masteredTags
1503
+ );
1504
+ const finalScore = isUnlocked ? card.score : 0;
1505
+ const action = isUnlocked ? "passed" : "penalized";
1506
+ gated.push({
1507
+ ...card,
1508
+ score: finalScore,
1509
+ provenance: [
1510
+ ...card.provenance,
1511
+ {
1512
+ strategy: "hierarchyDefinition",
1513
+ strategyName: this.strategyName || this.name,
1514
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1515
+ action,
1516
+ score: finalScore,
1517
+ reason
1518
+ }
1519
+ ]
1520
+ });
1521
+ }
1522
+ return gated;
1523
+ }
1524
+ /**
1525
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1526
+ *
1527
+ * Use transform() via Pipeline instead.
1528
+ */
1529
+ async getWeightedCards(_limit) {
1530
+ throw new Error(
1531
+ "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1532
+ );
1533
+ }
1534
+ };
1535
+ }
1536
+ });
1537
+
1538
+ // src/core/navigators/filters/userTagPreference.ts
1539
+ var userTagPreference_exports = {};
1540
+ __export(userTagPreference_exports, {
1541
+ default: () => UserTagPreferenceFilter
1542
+ });
1543
+ var UserTagPreferenceFilter;
1544
+ var init_userTagPreference = __esm({
1545
+ "src/core/navigators/filters/userTagPreference.ts"() {
1546
+ "use strict";
1547
+ init_navigators();
1548
+ UserTagPreferenceFilter = class extends ContentNavigator {
1549
+ _strategyData;
1550
+ /** Human-readable name for CardFilter interface */
1551
+ name;
1552
+ constructor(user, course, strategyData) {
1553
+ super(user, course, strategyData);
1554
+ this._strategyData = strategyData;
1555
+ this.name = strategyData.name || "User Tag Preferences";
1556
+ }
1557
+ /**
1558
+ * Compute multiplier for a card based on its tags and user preferences.
1559
+ * Returns the maximum multiplier among all matching tags, or 1.0 if no matches.
1560
+ */
1561
+ computeMultiplier(cardTags, boostMap) {
1562
+ const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== void 0);
1563
+ if (multipliers.length === 0) {
1564
+ return 1;
1565
+ }
1566
+ return Math.max(...multipliers);
1567
+ }
1568
+ /**
1569
+ * Build human-readable reason for the filter's decision.
1570
+ */
1571
+ buildReason(cardTags, boostMap, multiplier) {
1572
+ const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);
1573
+ if (multiplier === 0) {
1574
+ return `Excluded by user preference: ${matchingTags.join(", ")} (${multiplier}x)`;
1575
+ }
1576
+ if (multiplier < 1) {
1577
+ return `Penalized by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1578
+ }
1579
+ if (multiplier > 1) {
1580
+ return `Boosted by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1581
+ }
1582
+ return "No matching user preferences";
1583
+ }
1584
+ /**
1585
+ * CardFilter.transform implementation.
1586
+ *
1587
+ * Apply user tag preferences:
1588
+ * 1. Read preferences from strategy state
1589
+ * 2. If no preferences, pass through unchanged
1590
+ * 3. For each card:
1591
+ * - Look up tag in boost record
1592
+ * - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)
1593
+ * - If multiple tags match: use max multiplier
1594
+ * - Append provenance with clear reason
1595
+ */
1596
+ async transform(cards, _context) {
1597
+ const prefs = await this.getStrategyState();
1598
+ if (!prefs || Object.keys(prefs.boost).length === 0) {
1599
+ return cards.map((card) => ({
1600
+ ...card,
1601
+ provenance: [
1602
+ ...card.provenance,
1603
+ {
1604
+ strategy: "userTagPreference",
1605
+ strategyName: this.strategyName || this.name,
1606
+ strategyId: this.strategyId || this._strategyData._id,
1607
+ action: "passed",
1608
+ score: card.score,
1609
+ reason: "No user tag preferences configured"
1610
+ }
1611
+ ]
1612
+ }));
1613
+ }
1614
+ const adjusted = await Promise.all(
1615
+ cards.map(async (card) => {
1616
+ const cardTags = card.tags ?? [];
1617
+ const multiplier = this.computeMultiplier(cardTags, prefs.boost);
1618
+ const finalScore = Math.min(1, card.score * multiplier);
1619
+ let action;
1620
+ if (multiplier === 0 || multiplier < 1) {
1621
+ action = "penalized";
1622
+ } else if (multiplier > 1) {
1623
+ action = "boosted";
1624
+ } else {
1625
+ action = "passed";
1626
+ }
1627
+ return {
1628
+ ...card,
1629
+ score: finalScore,
1630
+ provenance: [
1631
+ ...card.provenance,
1632
+ {
1633
+ strategy: "userTagPreference",
1634
+ strategyName: this.strategyName || this.name,
1635
+ strategyId: this.strategyId || this._strategyData._id,
1636
+ action,
1637
+ score: finalScore,
1638
+ reason: this.buildReason(cardTags, prefs.boost, multiplier)
1639
+ }
1640
+ ]
1641
+ };
1642
+ })
1643
+ );
1644
+ return adjusted;
1645
+ }
1646
+ /**
1647
+ * Legacy getWeightedCards - throws as filters should not be used as generators.
1648
+ */
1649
+ async getWeightedCards(_limit) {
1650
+ throw new Error(
1651
+ "UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1652
+ );
1653
+ }
1654
+ };
1655
+ }
1656
+ });
1657
+
1658
+ // src/core/navigators/filters/index.ts
1659
+ var filters_exports = {};
1660
+ __export(filters_exports, {
1661
+ UserTagPreferenceFilter: () => UserTagPreferenceFilter,
1662
+ createEloDistanceFilter: () => createEloDistanceFilter
1663
+ });
1664
+ var init_filters = __esm({
1665
+ "src/core/navigators/filters/index.ts"() {
1666
+ "use strict";
1667
+ init_eloDistance();
1668
+ init_userTagPreference();
1669
+ }
1670
+ });
1671
+
1672
+ // src/core/navigators/filters/inferredPreferenceStub.ts
1673
+ var inferredPreferenceStub_exports = {};
1674
+ __export(inferredPreferenceStub_exports, {
1675
+ INFERRED_PREFERENCE_NAVIGATOR_STUB: () => INFERRED_PREFERENCE_NAVIGATOR_STUB
1676
+ });
1677
+ var INFERRED_PREFERENCE_NAVIGATOR_STUB;
1678
+ var init_inferredPreferenceStub = __esm({
1679
+ "src/core/navigators/filters/inferredPreferenceStub.ts"() {
1680
+ "use strict";
1681
+ INFERRED_PREFERENCE_NAVIGATOR_STUB = true;
1682
+ }
1683
+ });
1684
+
1685
+ // src/core/navigators/filters/interferenceMitigator.ts
1686
+ var interferenceMitigator_exports = {};
1687
+ __export(interferenceMitigator_exports, {
1688
+ default: () => InterferenceMitigatorNavigator
1689
+ });
1690
+ import { toCourseElo as toCourseElo4 } from "@vue-skuilder/common";
1691
+ var DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1692
+ var init_interferenceMitigator = __esm({
1693
+ "src/core/navigators/filters/interferenceMitigator.ts"() {
1694
+ "use strict";
1695
+ init_navigators();
1696
+ DEFAULT_MIN_COUNT2 = 10;
1697
+ DEFAULT_MIN_ELAPSED_DAYS = 3;
1698
+ DEFAULT_INTERFERENCE_DECAY = 0.8;
1699
+ InterferenceMitigatorNavigator = class extends ContentNavigator {
1700
+ config;
1701
+ /** Human-readable name for CardFilter interface */
1702
+ name;
1703
+ /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1704
+ interferenceMap;
1705
+ constructor(user, course, strategyData) {
1706
+ super(user, course, strategyData);
1707
+ this.config = this.parseConfig(strategyData.serializedData);
1708
+ this.interferenceMap = this.buildInterferenceMap();
1709
+ this.name = strategyData.name || "Interference Mitigator";
1710
+ }
1711
+ parseConfig(serializedData) {
1712
+ try {
1713
+ const parsed = JSON.parse(serializedData);
1714
+ let sets = parsed.interferenceSets || [];
1715
+ if (sets.length > 0 && Array.isArray(sets[0])) {
1716
+ sets = sets.map((tags) => ({ tags }));
1717
+ }
1718
+ return {
1719
+ interferenceSets: sets,
1720
+ maturityThreshold: {
1721
+ minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1722
+ minElo: parsed.maturityThreshold?.minElo,
1723
+ minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1724
+ },
1725
+ defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1726
+ };
1727
+ } catch {
1728
+ return {
1729
+ interferenceSets: [],
1730
+ maturityThreshold: {
1731
+ minCount: DEFAULT_MIN_COUNT2,
1732
+ minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1733
+ },
1734
+ defaultDecay: DEFAULT_INTERFERENCE_DECAY
1735
+ };
1736
+ }
1737
+ }
1738
+ /**
1739
+ * Build a map from each tag to its interference partners with decay coefficients.
1740
+ * If tags A, B, C are in an interference group with decay 0.8, then:
1741
+ * - A interferes with B (decay 0.8) and C (decay 0.8)
1742
+ * - B interferes with A (decay 0.8) and C (decay 0.8)
1743
+ * - etc.
1744
+ */
1745
+ buildInterferenceMap() {
1746
+ const map = /* @__PURE__ */ new Map();
1747
+ for (const group of this.config.interferenceSets) {
1748
+ const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
1749
+ for (const tag of group.tags) {
1750
+ if (!map.has(tag)) {
1751
+ map.set(tag, []);
1752
+ }
1753
+ const partners = map.get(tag);
1754
+ for (const other of group.tags) {
1755
+ if (other !== tag) {
1756
+ const existing = partners.find((p) => p.partner === other);
1757
+ if (existing) {
1758
+ existing.decay = Math.max(existing.decay, decay);
1759
+ } else {
1760
+ partners.push({ partner: other, decay });
1761
+ }
1762
+ }
1763
+ }
1764
+ }
1765
+ }
1766
+ return map;
1767
+ }
1768
+ /**
1769
+ * Get the set of tags that are currently immature for this user.
1770
+ * A tag is immature if the user has interacted with it but hasn't
1771
+ * reached the maturity threshold.
1772
+ */
1773
+ async getImmatureTags(context) {
1774
+ const immature = /* @__PURE__ */ new Set();
1775
+ try {
1776
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1777
+ const userElo = toCourseElo4(courseReg.elo);
1778
+ const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
1779
+ const minElo = this.config.maturityThreshold?.minElo;
1780
+ const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
1781
+ const minCountForElapsed = minElapsedDays * 2;
1782
+ for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
1783
+ if (tagElo.count === 0) continue;
1784
+ const belowCount = tagElo.count < minCount;
1785
+ const belowElo = minElo !== void 0 && tagElo.score < minElo;
1786
+ const belowElapsed = tagElo.count < minCountForElapsed;
1787
+ if (belowCount || belowElo || belowElapsed) {
1788
+ immature.add(tagId);
1789
+ }
1790
+ }
1791
+ } catch {
1792
+ }
1793
+ return immature;
1794
+ }
1795
+ /**
1796
+ * Get all tags that interfere with any immature tag, along with their decay coefficients.
1797
+ * These are the tags we want to avoid introducing.
1798
+ */
1799
+ getTagsToAvoid(immatureTags) {
1800
+ const avoid = /* @__PURE__ */ new Map();
1801
+ for (const immatureTag of immatureTags) {
1802
+ const partners = this.interferenceMap.get(immatureTag);
1803
+ if (partners) {
1804
+ for (const { partner, decay } of partners) {
1805
+ if (!immatureTags.has(partner)) {
1806
+ const existing = avoid.get(partner) ?? 0;
1807
+ avoid.set(partner, Math.max(existing, decay));
1808
+ }
1809
+ }
1810
+ }
1811
+ }
1812
+ return avoid;
1813
+ }
1814
+ /**
1815
+ * Compute interference score reduction for a card.
1816
+ * Returns: { multiplier, interfering tags, reason }
1817
+ */
1818
+ computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
1819
+ if (tagsToAvoid.size === 0) {
1820
+ return {
1821
+ multiplier: 1,
1822
+ interferingTags: [],
1823
+ reason: "No interference detected"
1824
+ };
1825
+ }
1826
+ let multiplier = 1;
1827
+ const interferingTags = [];
1828
+ for (const tag of cardTags) {
1829
+ const decay = tagsToAvoid.get(tag);
1830
+ if (decay !== void 0) {
1831
+ interferingTags.push(tag);
1832
+ multiplier *= 1 - decay;
1833
+ }
1834
+ }
1835
+ if (interferingTags.length === 0) {
1836
+ return {
1837
+ multiplier: 1,
1838
+ interferingTags: [],
1839
+ reason: "No interference detected"
1840
+ };
1841
+ }
1842
+ const causingTags = /* @__PURE__ */ new Set();
1843
+ for (const tag of interferingTags) {
1844
+ for (const immatureTag of immatureTags) {
1845
+ const partners = this.interferenceMap.get(immatureTag);
1846
+ if (partners?.some((p) => p.partner === tag)) {
1847
+ causingTags.add(immatureTag);
1848
+ }
1849
+ }
1850
+ }
1851
+ const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
1852
+ return { multiplier, interferingTags, reason };
1853
+ }
1854
+ /**
1855
+ * CardFilter.transform implementation.
1856
+ *
1857
+ * Apply interference-aware scoring. Cards with tags that interfere with
1858
+ * immature learnings get reduced scores.
1859
+ */
1860
+ async transform(cards, context) {
1861
+ const immatureTags = await this.getImmatureTags(context);
1862
+ const tagsToAvoid = this.getTagsToAvoid(immatureTags);
1863
+ const adjusted = [];
1864
+ for (const card of cards) {
1865
+ const cardTags = card.tags ?? [];
1866
+ const { multiplier, reason } = this.computeInterferenceEffect(
1867
+ cardTags,
1868
+ tagsToAvoid,
1869
+ immatureTags
1870
+ );
1871
+ const finalScore = card.score * multiplier;
1872
+ const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
1873
+ adjusted.push({
1874
+ ...card,
1875
+ score: finalScore,
1876
+ provenance: [
1877
+ ...card.provenance,
1878
+ {
1879
+ strategy: "interferenceMitigator",
1880
+ strategyName: this.strategyName || this.name,
1881
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
1882
+ action,
1883
+ score: finalScore,
1884
+ reason
1885
+ }
1886
+ ]
1887
+ });
1888
+ }
1889
+ return adjusted;
1890
+ }
1891
+ /**
1892
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1893
+ *
1894
+ * Use transform() via Pipeline instead.
1895
+ */
1896
+ async getWeightedCards(_limit) {
1897
+ throw new Error(
1898
+ "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1899
+ );
1900
+ }
1901
+ };
1902
+ }
1903
+ });
1904
+
1905
+ // src/core/navigators/filters/relativePriority.ts
1906
+ var relativePriority_exports = {};
1907
+ __export(relativePriority_exports, {
1908
+ default: () => RelativePriorityNavigator
1909
+ });
1910
+ var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
1911
+ var init_relativePriority = __esm({
1912
+ "src/core/navigators/filters/relativePriority.ts"() {
1913
+ "use strict";
1914
+ init_navigators();
1915
+ DEFAULT_PRIORITY = 0.5;
1916
+ DEFAULT_PRIORITY_INFLUENCE = 0.5;
1917
+ DEFAULT_COMBINE_MODE = "max";
1918
+ RelativePriorityNavigator = class extends ContentNavigator {
1919
+ config;
1920
+ /** Human-readable name for CardFilter interface */
1921
+ name;
1922
+ constructor(user, course, strategyData) {
1923
+ super(user, course, strategyData);
1924
+ this.config = this.parseConfig(strategyData.serializedData);
1925
+ this.name = strategyData.name || "Relative Priority";
1926
+ }
1927
+ parseConfig(serializedData) {
1928
+ try {
1929
+ const parsed = JSON.parse(serializedData);
1930
+ return {
1931
+ tagPriorities: parsed.tagPriorities || {},
1932
+ defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
1933
+ combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
1934
+ priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
1935
+ };
1936
+ } catch {
1937
+ return {
1938
+ tagPriorities: {},
1939
+ defaultPriority: DEFAULT_PRIORITY,
1940
+ combineMode: DEFAULT_COMBINE_MODE,
1941
+ priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
1942
+ };
1943
+ }
1944
+ }
1945
+ /**
1946
+ * Look up the priority for a tag.
1947
+ */
1948
+ getTagPriority(tagId) {
1949
+ return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
1950
+ }
1951
+ /**
1952
+ * Compute combined priority for a card based on its tags.
1953
+ */
1954
+ computeCardPriority(cardTags) {
1955
+ if (cardTags.length === 0) {
1956
+ return this.config.defaultPriority ?? DEFAULT_PRIORITY;
1957
+ }
1958
+ const priorities = cardTags.map((tag) => this.getTagPriority(tag));
1959
+ switch (this.config.combineMode) {
1960
+ case "max":
1961
+ return Math.max(...priorities);
1962
+ case "min":
1963
+ return Math.min(...priorities);
1964
+ case "average":
1965
+ return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
1966
+ default:
1967
+ return Math.max(...priorities);
1968
+ }
1969
+ }
1970
+ /**
1971
+ * Compute boost factor based on priority.
1972
+ *
1973
+ * The formula: 1 + (priority - 0.5) * priorityInfluence
1974
+ *
1975
+ * This creates a multiplier centered around 1.0:
1976
+ * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
1977
+ * - Priority 0.5 with any influence → 1.00 (neutral)
1978
+ * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
1979
+ */
1980
+ computeBoostFactor(priority) {
1981
+ const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
1982
+ return 1 + (priority - 0.5) * influence;
1983
+ }
1984
+ /**
1985
+ * Build human-readable reason for priority adjustment.
1986
+ */
1987
+ buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
1988
+ if (cardTags.length === 0) {
1989
+ return `No tags, neutral priority (${priority.toFixed(2)})`;
1990
+ }
1991
+ const tagList = cardTags.slice(0, 3).join(", ");
1992
+ const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
1993
+ if (boostFactor === 1) {
1994
+ return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
1995
+ } else if (boostFactor > 1) {
1996
+ return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1997
+ } else {
1998
+ return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1999
+ }
2000
+ }
2001
+ /**
2002
+ * CardFilter.transform implementation.
2003
+ *
2004
+ * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
2005
+ * cards with low-priority tags get reduced scores.
2006
+ */
2007
+ async transform(cards, _context) {
2008
+ const adjusted = await Promise.all(
2009
+ cards.map(async (card) => {
2010
+ const cardTags = card.tags ?? [];
2011
+ const priority = this.computeCardPriority(cardTags);
2012
+ const boostFactor = this.computeBoostFactor(priority);
2013
+ const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
2014
+ const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
2015
+ const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
2016
+ return {
2017
+ ...card,
2018
+ score: finalScore,
2019
+ provenance: [
2020
+ ...card.provenance,
2021
+ {
2022
+ strategy: "relativePriority",
2023
+ strategyName: this.strategyName || this.name,
2024
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
2025
+ action,
2026
+ score: finalScore,
2027
+ reason
2028
+ }
2029
+ ]
2030
+ };
2031
+ })
2032
+ );
2033
+ return adjusted;
2034
+ }
2035
+ /**
2036
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
2037
+ *
2038
+ * Use transform() via Pipeline instead.
2039
+ */
2040
+ async getWeightedCards(_limit) {
2041
+ throw new Error(
2042
+ "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
2043
+ );
2044
+ }
2045
+ };
2046
+ }
2047
+ });
2048
+
2049
+ // src/core/navigators/filters/types.ts
2050
+ var types_exports2 = {};
2051
+ var init_types2 = __esm({
2052
+ "src/core/navigators/filters/types.ts"() {
2053
+ "use strict";
2054
+ }
2055
+ });
2056
+
2057
+ // src/core/navigators/filters/userGoalStub.ts
2058
+ var userGoalStub_exports = {};
2059
+ __export(userGoalStub_exports, {
2060
+ USER_GOAL_NAVIGATOR_STUB: () => USER_GOAL_NAVIGATOR_STUB
2061
+ });
2062
+ var USER_GOAL_NAVIGATOR_STUB;
2063
+ var init_userGoalStub = __esm({
2064
+ "src/core/navigators/filters/userGoalStub.ts"() {
2065
+ "use strict";
2066
+ USER_GOAL_NAVIGATOR_STUB = true;
2067
+ }
2068
+ });
2069
+
2070
+ // import("./filters/**/*") in src/core/navigators/index.ts
2071
+ var globImport_filters;
2072
+ var init_2 = __esm({
2073
+ 'import("./filters/**/*") in src/core/navigators/index.ts'() {
2074
+ globImport_filters = __glob({
2075
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
2076
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2077
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2078
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2079
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
2080
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2081
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2082
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
2083
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
2084
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
2085
+ });
2086
+ }
2087
+ });
2088
+
2089
+ // src/core/orchestration/gradient.ts
2090
+ function aggregateOutcomesForGradient(outcomes, strategyId) {
2091
+ const observations = [];
2092
+ for (const outcome of outcomes) {
2093
+ const deviation = outcome.deviations[strategyId];
2094
+ if (deviation === void 0) {
2095
+ continue;
2096
+ }
2097
+ observations.push({
2098
+ deviation,
2099
+ outcomeValue: outcome.outcomeValue,
2100
+ weight: 1
2101
+ });
2102
+ }
2103
+ logger.debug(
2104
+ `[Orchestration] Aggregated ${observations.length} observations for strategy ${strategyId}`
2105
+ );
2106
+ return observations;
2107
+ }
2108
+ function computeStrategyGradient(observations) {
2109
+ const n = observations.length;
2110
+ if (n < 3) {
2111
+ logger.debug(`[Orchestration] Insufficient observations for gradient (${n} < 3)`);
2112
+ return null;
2113
+ }
2114
+ let sumX = 0;
2115
+ let sumY = 0;
2116
+ let sumW = 0;
2117
+ for (const obs of observations) {
2118
+ const w = obs.weight ?? 1;
2119
+ sumX += obs.deviation * w;
2120
+ sumY += obs.outcomeValue * w;
2121
+ sumW += w;
2122
+ }
2123
+ const meanX = sumX / sumW;
2124
+ const meanY = sumY / sumW;
2125
+ let numerator = 0;
2126
+ let denominator = 0;
2127
+ let ssTotal = 0;
2128
+ for (const obs of observations) {
2129
+ const w = obs.weight ?? 1;
2130
+ const dx = obs.deviation - meanX;
2131
+ const dy = obs.outcomeValue - meanY;
2132
+ numerator += w * dx * dy;
2133
+ denominator += w * dx * dx;
2134
+ ssTotal += w * dy * dy;
2135
+ }
2136
+ if (denominator < 1e-10) {
2137
+ logger.debug(`[Orchestration] No variance in deviations, cannot compute gradient`);
2138
+ return {
2139
+ gradient: 0,
2140
+ intercept: meanY,
2141
+ rSquared: 0,
2142
+ sampleSize: n
2143
+ };
2144
+ }
2145
+ const gradient = numerator / denominator;
2146
+ const intercept = meanY - gradient * meanX;
2147
+ let ssResidual = 0;
2148
+ for (const obs of observations) {
2149
+ const w = obs.weight ?? 1;
2150
+ const predicted = gradient * obs.deviation + intercept;
2151
+ const residual = obs.outcomeValue - predicted;
2152
+ ssResidual += w * residual * residual;
2153
+ }
2154
+ const rSquared = ssTotal > 1e-10 ? 1 - ssResidual / ssTotal : 0;
2155
+ logger.debug(
2156
+ `[Orchestration] Computed gradient: ${gradient.toFixed(4)}, intercept: ${intercept.toFixed(4)}, R\xB2: ${rSquared.toFixed(4)}, n=${n}`
2157
+ );
2158
+ return {
2159
+ gradient,
2160
+ intercept,
2161
+ rSquared: Math.max(0, Math.min(1, rSquared)),
2162
+ // Clamp to [0,1]
2163
+ sampleSize: n
2164
+ };
2165
+ }
2166
+ var init_gradient = __esm({
2167
+ "src/core/orchestration/gradient.ts"() {
2168
+ "use strict";
2169
+ init_logger();
2170
+ }
2171
+ });
2172
+
2173
+ // src/core/orchestration/learning.ts
2174
+ function updateStrategyWeight(current, gradient) {
2175
+ if (gradient.sampleSize < MIN_OBSERVATIONS_FOR_UPDATE) {
2176
+ logger.debug(
2177
+ `[Orchestration] Insufficient samples (${gradient.sampleSize} < ${MIN_OBSERVATIONS_FOR_UPDATE}), keeping current weight`
2178
+ );
2179
+ return {
2180
+ ...current,
2181
+ sampleSize: current.sampleSize + gradient.sampleSize
2182
+ };
2183
+ }
2184
+ const isReliable = gradient.rSquared >= MIN_R_SQUARED_FOR_GRADIENT;
2185
+ const isFlat = Math.abs(gradient.gradient) < FLAT_GRADIENT_THRESHOLD;
2186
+ let newWeight = current.weight;
2187
+ let newConfidence = current.confidence;
2188
+ if (!isReliable || isFlat) {
2189
+ const confidenceGain = 0.05 * (1 - current.confidence);
2190
+ newConfidence = Math.min(1, current.confidence + confidenceGain);
2191
+ logger.debug(
2192
+ `[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)}`
2193
+ );
2194
+ } else {
2195
+ let delta = gradient.gradient * LEARNING_RATE;
2196
+ delta = Math.max(-MAX_WEIGHT_DELTA, Math.min(MAX_WEIGHT_DELTA, delta));
2197
+ newWeight = current.weight + delta;
2198
+ newWeight = Math.max(0.1, Math.min(3, newWeight));
2199
+ const confidenceGain = 0.02 * (1 - current.confidence);
2200
+ newConfidence = Math.min(1, current.confidence + confidenceGain);
2201
+ logger.debug(
2202
+ `[Orchestration] Adjusting weight: ${current.weight.toFixed(3)} \u2192 ${newWeight.toFixed(3)} (gradient=${gradient.gradient.toFixed(4)}, delta=${delta.toFixed(4)})`
2203
+ );
2204
+ }
2205
+ return {
2206
+ weight: newWeight,
2207
+ confidence: newConfidence,
2208
+ sampleSize: current.sampleSize + gradient.sampleSize
2209
+ };
2210
+ }
2211
+ function updateLearningState(courseId, strategyId, currentWeight, gradient, existing) {
2212
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2213
+ const id = `STRATEGY_LEARNING_STATE::${courseId}::${strategyId}`;
2214
+ const historyEntry = {
2215
+ timestamp: now,
2216
+ weight: currentWeight.weight,
2217
+ confidence: currentWeight.confidence,
2218
+ gradient: gradient.gradient
2219
+ };
2220
+ let history = existing?.history ?? [];
2221
+ history = [...history, historyEntry];
2222
+ if (history.length > MAX_HISTORY_LENGTH) {
2223
+ history = history.slice(history.length - MAX_HISTORY_LENGTH);
2224
+ }
2225
+ const state = {
2226
+ _id: id,
2227
+ _rev: existing?._rev,
2228
+ docType: "STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */,
2229
+ courseId,
2230
+ strategyId,
2231
+ currentWeight,
2232
+ regression: {
2233
+ gradient: gradient.gradient,
2234
+ intercept: gradient.intercept,
2235
+ rSquared: gradient.rSquared,
2236
+ sampleSize: gradient.sampleSize,
2237
+ computedAt: now
2238
+ },
2239
+ history,
2240
+ updatedAt: now
2241
+ };
2242
+ return state;
2243
+ }
2244
+ function runPeriodUpdate(input) {
2245
+ const { courseId, strategyId, currentWeight, gradient, existingState } = input;
2246
+ logger.info(
2247
+ `[Orchestration] Running period update for strategy ${strategyId} (${gradient.sampleSize} observations)`
2248
+ );
2249
+ const newWeight = updateStrategyWeight(currentWeight, gradient);
2250
+ const updated = newWeight.weight !== currentWeight.weight;
2251
+ const learningState = updateLearningState(
2252
+ courseId,
2253
+ strategyId,
2254
+ newWeight,
2255
+ gradient,
2256
+ existingState
2257
+ );
2258
+ logger.info(
2259
+ `[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)}`
2260
+ );
2261
+ return {
2262
+ strategyId,
2263
+ previousWeight: currentWeight,
2264
+ newWeight,
2265
+ gradient,
2266
+ learningState,
2267
+ updated
2268
+ };
2269
+ }
2270
+ function getDefaultLearnableWeight() {
2271
+ return { ...DEFAULT_LEARNABLE_WEIGHT };
2272
+ }
2273
+ var MIN_OBSERVATIONS_FOR_UPDATE, LEARNING_RATE, MAX_WEIGHT_DELTA, MIN_R_SQUARED_FOR_GRADIENT, FLAT_GRADIENT_THRESHOLD, MAX_HISTORY_LENGTH;
2274
+ var init_learning = __esm({
2275
+ "src/core/orchestration/learning.ts"() {
2276
+ "use strict";
2277
+ init_contentNavigationStrategy();
2278
+ init_types_legacy();
2279
+ init_logger();
2280
+ MIN_OBSERVATIONS_FOR_UPDATE = 10;
2281
+ LEARNING_RATE = 0.1;
2282
+ MAX_WEIGHT_DELTA = 0.3;
2283
+ MIN_R_SQUARED_FOR_GRADIENT = 0.05;
2284
+ FLAT_GRADIENT_THRESHOLD = 0.02;
2285
+ MAX_HISTORY_LENGTH = 100;
2286
+ }
2287
+ });
2288
+
2289
+ // src/core/orchestration/signal.ts
2290
+ function computeOutcomeSignal(records, config = {}) {
2291
+ if (!records || records.length === 0) {
2292
+ return null;
2293
+ }
2294
+ const target = config.targetAccuracy ?? 0.85;
2295
+ const tolerance = config.tolerance ?? 0.05;
2296
+ let correct = 0;
2297
+ for (const r of records) {
2298
+ if (r.isCorrect) correct++;
2299
+ }
2300
+ const accuracy = correct / records.length;
2301
+ return scoreAccuracyInZone(accuracy, target, tolerance);
2302
+ }
2303
+ function scoreAccuracyInZone(accuracy, target, tolerance) {
2304
+ const dist = Math.abs(accuracy - target);
2305
+ if (dist <= tolerance) {
2306
+ return 1;
2307
+ }
2308
+ const excess = dist - tolerance;
2309
+ const slope = 2.5;
2310
+ return Math.max(0, 1 - excess * slope);
2311
+ }
2312
+ var init_signal = __esm({
2313
+ "src/core/orchestration/signal.ts"() {
2314
+ "use strict";
2315
+ }
2316
+ });
2317
+
2318
+ // src/core/orchestration/recording.ts
2319
+ async function recordUserOutcome(context, periodStart, periodEnd, records, activeStrategyIds, eloStart = 0, eloEnd = 0, config) {
2320
+ const { user, course, userId } = context;
2321
+ const courseId = course.getCourseID();
2322
+ const outcomeValue = computeOutcomeSignal(records, config);
2323
+ if (outcomeValue === null) {
2324
+ logger.debug(
2325
+ `[Orchestration] No outcome signal computed for ${userId} (insufficient data). Skipping record.`
2326
+ );
2327
+ return;
2328
+ }
2329
+ const deviations = {};
2330
+ for (const strategyId of activeStrategyIds) {
2331
+ deviations[strategyId] = context.getDeviation(strategyId);
2332
+ }
2333
+ const id = `USER_OUTCOME::${courseId}::${userId}::${periodEnd}`;
2334
+ const record = {
2335
+ _id: id,
2336
+ docType: "USER_OUTCOME" /* USER_OUTCOME */,
2337
+ courseId,
2338
+ userId,
2339
+ periodStart,
2340
+ periodEnd,
2341
+ outcomeValue,
2342
+ deviations,
2343
+ metadata: {
2344
+ sessionsCount: 1,
2345
+ // Assumes recording is triggered per-session currently
2346
+ cardsSeen: records.length,
2347
+ eloStart,
2348
+ eloEnd,
2349
+ signalType: "accuracy_in_zone"
2350
+ }
2351
+ };
2352
+ try {
2353
+ await user.putUserOutcome(record);
2354
+ logger.debug(
2355
+ `[Orchestration] Recorded outcome ${outcomeValue.toFixed(3)} for ${userId} (doc: ${id})`
2356
+ );
2357
+ } catch (e) {
2358
+ logger.error(`[Orchestration] Failed to record outcome: ${e}`);
2359
+ }
2360
+ }
2361
+ var init_recording = __esm({
2362
+ "src/core/orchestration/recording.ts"() {
2363
+ "use strict";
2364
+ init_signal();
2365
+ init_types_legacy();
2366
+ init_logger();
2367
+ }
2368
+ });
2369
+
2370
+ // src/core/orchestration/index.ts
2371
+ function fnv1a(str) {
2372
+ let hash = 2166136261;
2373
+ for (let i = 0; i < str.length; i++) {
2374
+ hash ^= str.charCodeAt(i);
2375
+ hash = Math.imul(hash, 16777619);
2376
+ }
2377
+ return hash >>> 0;
2378
+ }
2379
+ function computeDeviation(userId, strategyId, salt) {
2380
+ const input = `${userId}:${strategyId}:${salt}`;
2381
+ const hash = fnv1a(input);
2382
+ const normalized = hash / 4294967296;
2383
+ return normalized * 2 - 1;
2384
+ }
2385
+ function computeSpread(confidence) {
2386
+ const clampedConfidence = Math.max(0, Math.min(1, confidence));
2387
+ return MAX_SPREAD - clampedConfidence * (MAX_SPREAD - MIN_SPREAD);
2388
+ }
2389
+ function computeEffectiveWeight(learnable, userId, strategyId, salt) {
2390
+ const deviation = computeDeviation(userId, strategyId, salt);
2391
+ const spread = computeSpread(learnable.confidence);
2392
+ const adjustment = deviation * spread * learnable.weight;
2393
+ const effective = learnable.weight + adjustment;
2394
+ return Math.max(MIN_WEIGHT, Math.min(MAX_WEIGHT, effective));
2395
+ }
2396
+ async function createOrchestrationContext(user, course) {
2397
+ let courseConfig;
2398
+ try {
2399
+ courseConfig = await course.getCourseConfig();
2400
+ } catch (e) {
2401
+ logger.error(`[Orchestration] Failed to load course config: ${e}`);
2402
+ courseConfig = {
2403
+ name: "Unknown",
2404
+ description: "",
2405
+ public: false,
2406
+ deleted: false,
2407
+ creator: "",
2408
+ admins: [],
2409
+ moderators: [],
2410
+ dataShapes: [],
2411
+ questionTypes: [],
2412
+ orchestration: { salt: "default" }
2413
+ };
2414
+ }
2415
+ const userId = user.getUsername();
2416
+ const salt = courseConfig.orchestration?.salt || "default_salt";
2417
+ return {
2418
+ user,
2419
+ course,
2420
+ userId,
2421
+ courseConfig,
2422
+ getEffectiveWeight(strategyId, learnable) {
2423
+ return computeEffectiveWeight(learnable, userId, strategyId, salt);
2424
+ },
2425
+ getDeviation(strategyId) {
2426
+ return computeDeviation(userId, strategyId, salt);
2427
+ }
2428
+ };
2429
+ }
2430
+ var MIN_SPREAD, MAX_SPREAD, MIN_WEIGHT, MAX_WEIGHT;
2431
+ var init_orchestration = __esm({
2432
+ "src/core/orchestration/index.ts"() {
2433
+ "use strict";
2434
+ init_logger();
2435
+ init_gradient();
2436
+ init_learning();
2437
+ init_signal();
2438
+ init_recording();
2439
+ MIN_SPREAD = 0.1;
2440
+ MAX_SPREAD = 0.5;
2441
+ MIN_WEIGHT = 0.1;
2442
+ MAX_WEIGHT = 3;
2443
+ }
2444
+ });
2445
+
2446
+ // src/core/navigators/Pipeline.ts
2447
+ var Pipeline_exports = {};
2448
+ __export(Pipeline_exports, {
2449
+ Pipeline: () => Pipeline
2450
+ });
2451
+ import { toCourseElo as toCourseElo5 } from "@vue-skuilder/common";
2452
+ function logPipelineConfig(generator, filters) {
2453
+ const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
2454
+ logger.info(
2455
+ `[Pipeline] Configuration:
2456
+ Generator: ${generator.name}
2457
+ Filters:${filterList}`
2458
+ );
2459
+ }
2460
+ function logTagHydration(cards, tagsByCard) {
2461
+ const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
2462
+ const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
1027
2463
  logger.debug(
1028
2464
  `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
1029
2465
  );
@@ -1054,6 +2490,7 @@ var init_Pipeline = __esm({
1054
2490
  "use strict";
1055
2491
  init_navigators();
1056
2492
  init_logger();
2493
+ init_orchestration();
1057
2494
  Pipeline = class extends ContentNavigator {
1058
2495
  generator;
1059
2496
  filters;
@@ -1156,171 +2593,70 @@ var init_Pipeline = __esm({
1156
2593
  let userElo = 1e3;
1157
2594
  try {
1158
2595
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1159
- const courseElo = toCourseElo2(courseReg.elo);
2596
+ const courseElo = toCourseElo5(courseReg.elo);
1160
2597
  userElo = courseElo.global.score;
1161
2598
  } catch (e) {
1162
2599
  logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
1163
2600
  }
2601
+ const orchestration = await createOrchestrationContext(this.user, this.course);
1164
2602
  return {
1165
2603
  user: this.user,
1166
2604
  course: this.course,
1167
- userElo
2605
+ userElo,
2606
+ orchestration
1168
2607
  };
1169
2608
  }
1170
2609
  /**
1171
2610
  * Get the course ID for this pipeline.
1172
2611
  */
1173
- getCourseID() {
1174
- return this.course.getCourseID();
1175
- }
1176
- };
1177
- }
1178
- });
1179
-
1180
- // src/core/navigators/generators/CompositeGenerator.ts
1181
- var DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
1182
- var init_CompositeGenerator = __esm({
1183
- "src/core/navigators/generators/CompositeGenerator.ts"() {
1184
- "use strict";
1185
- init_navigators();
1186
- init_logger();
1187
- DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
1188
- FREQUENCY_BOOST_FACTOR = 0.1;
1189
- CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
1190
- /** Human-readable name for CardGenerator interface */
1191
- name = "Composite Generator";
1192
- generators;
1193
- aggregationMode;
1194
- constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
1195
- super();
1196
- this.generators = generators;
1197
- this.aggregationMode = aggregationMode;
1198
- if (generators.length === 0) {
1199
- throw new Error("CompositeGenerator requires at least one generator");
1200
- }
1201
- logger.debug(
1202
- `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
1203
- );
1204
- }
1205
- /**
1206
- * Creates a CompositeGenerator from strategy data.
1207
- *
1208
- * This is a convenience factory for use by PipelineAssembler.
1209
- */
1210
- static async fromStrategies(user, course, strategies, aggregationMode = DEFAULT_AGGREGATION_MODE) {
1211
- const generators = await Promise.all(
1212
- strategies.map((s) => ContentNavigator.create(user, course, s))
1213
- );
1214
- return new _CompositeGenerator(generators, aggregationMode);
1215
- }
1216
- /**
1217
- * Get weighted cards from all generators, merge and deduplicate.
1218
- *
1219
- * Cards appearing in multiple generators receive a score boost.
1220
- * Provenance tracks which generators produced each card and how scores were aggregated.
1221
- *
1222
- * This method supports both the legacy signature (limit only) and the
1223
- * CardGenerator interface signature (limit, context).
1224
- *
1225
- * @param limit - Maximum number of cards to return
1226
- * @param context - GeneratorContext passed to child generators (required when called via Pipeline)
1227
- */
1228
- async getWeightedCards(limit, context) {
1229
- if (!context) {
1230
- throw new Error(
1231
- "CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly."
1232
- );
1233
- }
1234
- const results = await Promise.all(
1235
- this.generators.map((g) => g.getWeightedCards(limit, context))
1236
- );
1237
- const byCardId = /* @__PURE__ */ new Map();
1238
- for (const cards of results) {
1239
- for (const card of cards) {
1240
- const existing = byCardId.get(card.cardId) || [];
1241
- existing.push(card);
1242
- byCardId.set(card.cardId, existing);
1243
- }
1244
- }
1245
- const merged = [];
1246
- for (const [, cards] of byCardId) {
1247
- const aggregatedScore = this.aggregateScores(cards);
1248
- const finalScore = Math.min(1, aggregatedScore);
1249
- const mergedProvenance = cards.flatMap((c) => c.provenance);
1250
- const initialScore = cards[0].score;
1251
- const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
1252
- const reason = this.buildAggregationReason(cards, finalScore);
1253
- merged.push({
1254
- ...cards[0],
1255
- score: finalScore,
1256
- provenance: [
1257
- ...mergedProvenance,
1258
- {
1259
- strategy: "composite",
1260
- strategyName: "Composite Generator",
1261
- strategyId: "COMPOSITE_GENERATOR",
1262
- action,
1263
- score: finalScore,
1264
- reason
1265
- }
1266
- ]
1267
- });
1268
- }
1269
- return merged.sort((a, b) => b.score - a.score).slice(0, limit);
2612
+ getCourseID() {
2613
+ return this.course.getCourseID();
1270
2614
  }
1271
2615
  /**
1272
- * Build human-readable reason for score aggregation.
2616
+ * Get orchestration context for outcome recording.
1273
2617
  */
1274
- buildAggregationReason(cards, finalScore) {
1275
- const count = cards.length;
1276
- const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
1277
- if (count === 1) {
1278
- return `Single generator, score ${finalScore.toFixed(2)}`;
1279
- }
1280
- const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
1281
- switch (this.aggregationMode) {
1282
- case "max" /* MAX */:
1283
- return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
1284
- case "average" /* AVERAGE */:
1285
- return `Average of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
1286
- case "frequencyBoost" /* FREQUENCY_BOOST */: {
1287
- const avg = cards.reduce((sum, c) => sum + c.score, 0) / count;
1288
- const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
1289
- return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
1290
- }
1291
- default:
1292
- return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
1293
- }
2618
+ async getOrchestrationContext() {
2619
+ return createOrchestrationContext(this.user, this.course);
1294
2620
  }
1295
2621
  /**
1296
- * Aggregate scores from multiple generators for the same card.
2622
+ * Get IDs of all strategies in this pipeline.
2623
+ * Used to record which strategies contributed to an outcome.
1297
2624
  */
1298
- aggregateScores(cards) {
1299
- const scores = cards.map((c) => c.score);
1300
- switch (this.aggregationMode) {
1301
- case "max" /* MAX */:
1302
- return Math.max(...scores);
1303
- case "average" /* AVERAGE */:
1304
- return scores.reduce((sum, s) => sum + s, 0) / scores.length;
1305
- case "frequencyBoost" /* FREQUENCY_BOOST */: {
1306
- const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
1307
- const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (cards.length - 1);
1308
- return avg * frequencyBoost;
1309
- }
1310
- default:
1311
- return scores[0];
2625
+ getStrategyIds() {
2626
+ const ids = [];
2627
+ const extractId = (obj) => {
2628
+ if (obj.strategyId) return obj.strategyId;
2629
+ return null;
2630
+ };
2631
+ const genId = extractId(this.generator);
2632
+ if (genId) ids.push(genId);
2633
+ if (this.generator.generators && Array.isArray(this.generator.generators)) {
2634
+ this.generator.generators.forEach((g) => {
2635
+ const subId = extractId(g);
2636
+ if (subId) ids.push(subId);
2637
+ });
2638
+ }
2639
+ for (const filter of this.filters) {
2640
+ const fId = extractId(filter);
2641
+ if (fId) ids.push(fId);
1312
2642
  }
2643
+ return [...new Set(ids)];
1313
2644
  }
1314
2645
  };
1315
2646
  }
1316
2647
  });
1317
2648
 
1318
2649
  // src/core/navigators/PipelineAssembler.ts
2650
+ var PipelineAssembler_exports = {};
2651
+ __export(PipelineAssembler_exports, {
2652
+ PipelineAssembler: () => PipelineAssembler
2653
+ });
1319
2654
  var PipelineAssembler;
1320
2655
  var init_PipelineAssembler = __esm({
1321
2656
  "src/core/navigators/PipelineAssembler.ts"() {
1322
2657
  "use strict";
1323
2658
  init_navigators();
2659
+ init_WeightedFilter();
1324
2660
  init_Pipeline();
1325
2661
  init_types_legacy();
1326
2662
  init_logger();
@@ -1395,7 +2731,16 @@ var init_PipelineAssembler = __esm({
1395
2731
  try {
1396
2732
  const nav = await ContentNavigator.create(user, course, filterStrategy);
1397
2733
  if ("transform" in nav && typeof nav.transform === "function") {
1398
- filters.push(nav);
2734
+ let filter = nav;
2735
+ if (filterStrategy.learnable) {
2736
+ filter = new WeightedFilter(
2737
+ filter,
2738
+ filterStrategy.learnable,
2739
+ filterStrategy.staticWeight,
2740
+ filterStrategy._id
2741
+ );
2742
+ }
2743
+ filters.push(filter);
1399
2744
  logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
1400
2745
  } else {
1401
2746
  warnings.push(
@@ -1428,230 +2773,21 @@ var init_PipelineAssembler = __esm({
1428
2773
  docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1429
2774
  name: "ELO (default)",
1430
2775
  description: "Default ELO-based generator",
1431
- implementingClass: "elo" /* ELO */,
1432
- serializedData: ""
1433
- };
1434
- }
1435
- };
1436
- }
1437
- });
1438
-
1439
- // src/core/navigators/generators/elo.ts
1440
- import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
1441
- var ELONavigator;
1442
- var init_elo = __esm({
1443
- "src/core/navigators/generators/elo.ts"() {
1444
- "use strict";
1445
- init_navigators();
1446
- ELONavigator = class extends ContentNavigator {
1447
- /** Human-readable name for CardGenerator interface */
1448
- name;
1449
- constructor(user, course, strategyData) {
1450
- super(user, course, strategyData);
1451
- this.name = strategyData?.name || "ELO";
1452
- }
1453
- /**
1454
- * Get new cards with suitability scores based on ELO distance.
1455
- *
1456
- * Cards closer to user's ELO get higher scores.
1457
- * Score formula: max(0, 1 - distance / 500)
1458
- *
1459
- * NOTE: This generator only handles NEW cards. Reviews are handled by
1460
- * SRSNavigator. Use CompositeGenerator to combine both.
1461
- *
1462
- * This method supports both the legacy signature (limit only) and the
1463
- * CardGenerator interface signature (limit, context).
1464
- *
1465
- * @param limit - Maximum number of cards to return
1466
- * @param context - Optional GeneratorContext (used when called via Pipeline)
1467
- */
1468
- async getWeightedCards(limit, context) {
1469
- let userGlobalElo;
1470
- if (context?.userElo !== void 0) {
1471
- userGlobalElo = context.userElo;
1472
- } else {
1473
- const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1474
- const userElo = toCourseElo3(courseReg.elo);
1475
- userGlobalElo = userElo.global.score;
1476
- }
1477
- const activeCards = await this.user.getActiveCards();
1478
- const newCards = (await this.course.getCardsCenteredAtELO(
1479
- { limit, elo: "user" },
1480
- (c) => !activeCards.some((ac) => c.cardID === ac.cardID)
1481
- )).map((c) => ({ ...c, status: "new" }));
1482
- const cardIds = newCards.map((c) => c.cardID);
1483
- const cardEloData = await this.course.getCardEloData(cardIds);
1484
- const scored = newCards.map((c, i) => {
1485
- const cardElo = cardEloData[i]?.global?.score ?? 1e3;
1486
- const distance = Math.abs(cardElo - userGlobalElo);
1487
- const score = Math.max(0, 1 - distance / 500);
1488
- return {
1489
- cardId: c.cardID,
1490
- courseId: c.courseID,
1491
- score,
1492
- provenance: [
1493
- {
1494
- strategy: "elo",
1495
- strategyName: this.strategyName || this.name,
1496
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1497
- action: "generated",
1498
- score,
1499
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), new card`
1500
- }
1501
- ]
1502
- };
1503
- });
1504
- scored.sort((a, b) => b.score - a.score);
1505
- return scored.slice(0, limit);
1506
- }
1507
- };
1508
- }
1509
- });
1510
-
1511
- // src/core/navigators/generators/srs.ts
1512
- import moment3 from "moment";
1513
- var SRSNavigator;
1514
- var init_srs = __esm({
1515
- "src/core/navigators/generators/srs.ts"() {
1516
- "use strict";
1517
- init_navigators();
1518
- init_logger();
1519
- SRSNavigator = class extends ContentNavigator {
1520
- /** Human-readable name for CardGenerator interface */
1521
- name;
1522
- constructor(user, course, strategyData) {
1523
- super(user, course, strategyData);
1524
- this.name = strategyData?.name || "SRS";
1525
- }
1526
- /**
1527
- * Get review cards scored by urgency.
1528
- *
1529
- * Score formula combines:
1530
- * - Relative overdueness: hoursOverdue / intervalHours
1531
- * - Interval recency: exponential decay favoring shorter intervals
1532
- *
1533
- * Cards not yet due are excluded (not scored as 0).
1534
- *
1535
- * This method supports both the legacy signature (limit only) and the
1536
- * CardGenerator interface signature (limit, context).
1537
- *
1538
- * @param limit - Maximum number of cards to return
1539
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1540
- */
1541
- async getWeightedCards(limit, _context) {
1542
- if (!this.user || !this.course) {
1543
- throw new Error("SRSNavigator requires user and course to be set");
1544
- }
1545
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1546
- const now = moment3.utc();
1547
- const dueReviews = reviews.filter((r) => now.isAfter(moment3.utc(r.reviewTime)));
1548
- const scored = dueReviews.map((review) => {
1549
- const { score, reason } = this.computeUrgencyScore(review, now);
1550
- return {
1551
- cardId: review.cardId,
1552
- courseId: review.courseId,
1553
- score,
1554
- reviewID: review._id,
1555
- provenance: [
1556
- {
1557
- strategy: "srs",
1558
- strategyName: this.strategyName || this.name,
1559
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1560
- action: "generated",
1561
- score,
1562
- reason
1563
- }
1564
- ]
1565
- };
1566
- });
1567
- logger.debug(`[srsNav] got ${scored.length} weighted cards`);
1568
- return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1569
- }
1570
- /**
1571
- * Compute urgency score for a review card.
1572
- *
1573
- * Two factors:
1574
- * 1. Relative overdueness = hoursOverdue / intervalHours
1575
- * - 2 days overdue on 3-day interval = 0.67 (urgent)
1576
- * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1577
- *
1578
- * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1579
- * - 24h interval → ~1.0 (very recent learning)
1580
- * - 30 days (720h) → ~0.56
1581
- * - 180 days → ~0.30
1582
- *
1583
- * Combined: base 0.5 + weighted average of factors * 0.45
1584
- * Result range: approximately 0.5 to 0.95
1585
- */
1586
- computeUrgencyScore(review, now) {
1587
- const scheduledAt = moment3.utc(review.scheduledAt);
1588
- const due = moment3.utc(review.reviewTime);
1589
- const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1590
- const hoursOverdue = now.diff(due, "hours");
1591
- const relativeOverdue = hoursOverdue / intervalHours;
1592
- const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1593
- const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1594
- const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1595
- const score = Math.min(0.95, 0.5 + urgency * 0.45);
1596
- const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
1597
- return { score, reason };
1598
- }
1599
- };
1600
- }
1601
- });
1602
-
1603
- // src/core/navigators/filters/eloDistance.ts
1604
- function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1605
- const normalizedDistance = distance / halfLife;
1606
- const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1607
- return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1608
- }
1609
- function createEloDistanceFilter(config) {
1610
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1611
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1612
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1613
- return {
1614
- name: "ELO Distance Filter",
1615
- async transform(cards, context) {
1616
- const { course, userElo } = context;
1617
- const cardIds = cards.map((c) => c.cardId);
1618
- const cardElos = await course.getCardEloData(cardIds);
1619
- return cards.map((card, i) => {
1620
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
1621
- const distance = Math.abs(cardElo - userElo);
1622
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1623
- const newScore = card.score * multiplier;
1624
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1625
- return {
1626
- ...card,
1627
- score: newScore,
1628
- provenance: [
1629
- ...card.provenance,
1630
- {
1631
- strategy: "eloDistance",
1632
- strategyName: "ELO Distance Filter",
1633
- strategyId: "ELO_DISTANCE_FILTER",
1634
- action,
1635
- score: newScore,
1636
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1637
- }
1638
- ]
1639
- };
1640
- });
1641
- }
1642
- };
1643
- }
1644
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1645
- var init_eloDistance = __esm({
1646
- "src/core/navigators/filters/eloDistance.ts"() {
1647
- "use strict";
1648
- DEFAULT_HALF_LIFE = 200;
1649
- DEFAULT_MIN_MULTIPLIER = 0.3;
1650
- DEFAULT_MAX_MULTIPLIER = 1;
2776
+ implementingClass: "elo" /* ELO */,
2777
+ serializedData: ""
2778
+ };
2779
+ }
2780
+ };
1651
2781
  }
1652
2782
  });
1653
2783
 
1654
2784
  // src/core/navigators/defaults.ts
2785
+ var defaults_exports = {};
2786
+ __export(defaults_exports, {
2787
+ createDefaultEloStrategy: () => createDefaultEloStrategy,
2788
+ createDefaultPipeline: () => createDefaultPipeline,
2789
+ createDefaultSrsStrategy: () => createDefaultSrsStrategy
2790
+ });
1655
2791
  function createDefaultEloStrategy(courseId) {
1656
2792
  return {
1657
2793
  _id: "NAVIGATION_STRATEGY-ELO-default",
@@ -1695,12 +2831,310 @@ var init_defaults = __esm({
1695
2831
  }
1696
2832
  });
1697
2833
 
2834
+ // import("./**/*") in src/core/navigators/index.ts
2835
+ var globImport;
2836
+ var init_3 = __esm({
2837
+ 'import("./**/*") in src/core/navigators/index.ts'() {
2838
+ globImport = __glob({
2839
+ "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
2840
+ "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
2841
+ "./defaults.ts": () => Promise.resolve().then(() => (init_defaults(), defaults_exports)),
2842
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
2843
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2844
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2845
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2846
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
2847
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2848
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2849
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
2850
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
2851
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
2852
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
2853
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
2854
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
2855
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
2856
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
2857
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
2858
+ });
2859
+ }
2860
+ });
2861
+
2862
+ // src/core/navigators/index.ts
2863
+ var navigators_exports = {};
2864
+ __export(navigators_exports, {
2865
+ ContentNavigator: () => ContentNavigator,
2866
+ NavigatorRole: () => NavigatorRole,
2867
+ NavigatorRoles: () => NavigatorRoles,
2868
+ Navigators: () => Navigators,
2869
+ getCardOrigin: () => getCardOrigin,
2870
+ getRegisteredNavigator: () => getRegisteredNavigator,
2871
+ getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
2872
+ hasRegisteredNavigator: () => hasRegisteredNavigator,
2873
+ initializeNavigatorRegistry: () => initializeNavigatorRegistry,
2874
+ isFilter: () => isFilter,
2875
+ isGenerator: () => isGenerator,
2876
+ registerNavigator: () => registerNavigator
2877
+ });
2878
+ function registerNavigator(implementingClass, constructor) {
2879
+ navigatorRegistry.set(implementingClass, constructor);
2880
+ logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}`);
2881
+ }
2882
+ function getRegisteredNavigator(implementingClass) {
2883
+ return navigatorRegistry.get(implementingClass);
2884
+ }
2885
+ function hasRegisteredNavigator(implementingClass) {
2886
+ return navigatorRegistry.has(implementingClass);
2887
+ }
2888
+ function getRegisteredNavigatorNames() {
2889
+ return Array.from(navigatorRegistry.keys());
2890
+ }
2891
+ async function initializeNavigatorRegistry() {
2892
+ logger.debug("[NavigatorRegistry] Initializing built-in navigators...");
2893
+ const [eloModule, srsModule] = await Promise.all([
2894
+ Promise.resolve().then(() => (init_elo(), elo_exports)),
2895
+ Promise.resolve().then(() => (init_srs(), srs_exports))
2896
+ ]);
2897
+ registerNavigator("elo", eloModule.default);
2898
+ registerNavigator("srs", srsModule.default);
2899
+ const [
2900
+ hierarchyModule,
2901
+ interferenceModule,
2902
+ relativePriorityModule,
2903
+ userTagPreferenceModule
2904
+ ] = await Promise.all([
2905
+ Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2906
+ Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2907
+ Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2908
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
2909
+ ]);
2910
+ registerNavigator("hierarchyDefinition", hierarchyModule.default);
2911
+ registerNavigator("interferenceMitigator", interferenceModule.default);
2912
+ registerNavigator("relativePriority", relativePriorityModule.default);
2913
+ registerNavigator("userTagPreference", userTagPreferenceModule.default);
2914
+ logger.debug(
2915
+ `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
2916
+ );
2917
+ }
2918
+ function getCardOrigin(card) {
2919
+ if (card.provenance.length === 0) {
2920
+ throw new Error("Card has no provenance - cannot determine origin");
2921
+ }
2922
+ const firstEntry = card.provenance[0];
2923
+ const reason = firstEntry.reason.toLowerCase();
2924
+ if (reason.includes("failed")) {
2925
+ return "failed";
2926
+ }
2927
+ if (reason.includes("review")) {
2928
+ return "review";
2929
+ }
2930
+ return "new";
2931
+ }
2932
+ function isGenerator(impl) {
2933
+ return NavigatorRoles[impl] === "generator" /* GENERATOR */;
2934
+ }
2935
+ function isFilter(impl) {
2936
+ return NavigatorRoles[impl] === "filter" /* FILTER */;
2937
+ }
2938
+ var navigatorRegistry, Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
2939
+ var init_navigators = __esm({
2940
+ "src/core/navigators/index.ts"() {
2941
+ "use strict";
2942
+ init_logger();
2943
+ init_();
2944
+ init_2();
2945
+ init_3();
2946
+ navigatorRegistry = /* @__PURE__ */ new Map();
2947
+ Navigators = /* @__PURE__ */ ((Navigators2) => {
2948
+ Navigators2["ELO"] = "elo";
2949
+ Navigators2["SRS"] = "srs";
2950
+ Navigators2["HIERARCHY"] = "hierarchyDefinition";
2951
+ Navigators2["INTERFERENCE"] = "interferenceMitigator";
2952
+ Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
2953
+ Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
2954
+ return Navigators2;
2955
+ })(Navigators || {});
2956
+ NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
2957
+ NavigatorRole2["GENERATOR"] = "generator";
2958
+ NavigatorRole2["FILTER"] = "filter";
2959
+ return NavigatorRole2;
2960
+ })(NavigatorRole || {});
2961
+ NavigatorRoles = {
2962
+ ["elo" /* ELO */]: "generator" /* GENERATOR */,
2963
+ ["srs" /* SRS */]: "generator" /* GENERATOR */,
2964
+ ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
2965
+ ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
2966
+ ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
2967
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
2968
+ };
2969
+ ContentNavigator = class {
2970
+ /** User interface for this navigation session */
2971
+ user;
2972
+ /** Course interface for this navigation session */
2973
+ course;
2974
+ /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
2975
+ strategyName;
2976
+ /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
2977
+ strategyId;
2978
+ /** Evolutionary weighting configuration */
2979
+ learnable;
2980
+ /** Whether to bypass deviation (manual/static weighting) */
2981
+ staticWeight;
2982
+ /**
2983
+ * Constructor for standard navigators.
2984
+ * Call this from subclass constructors to initialize common fields.
2985
+ *
2986
+ * Note: CompositeGenerator and Pipeline call super() without args, then set
2987
+ * user/course fields directly if needed.
2988
+ */
2989
+ constructor(user, course, strategyData) {
2990
+ this.user = user;
2991
+ this.course = course;
2992
+ if (strategyData) {
2993
+ this.strategyName = strategyData.name;
2994
+ this.strategyId = strategyData._id;
2995
+ this.learnable = strategyData.learnable;
2996
+ this.staticWeight = strategyData.staticWeight;
2997
+ }
2998
+ }
2999
+ // ============================================================================
3000
+ // STRATEGY STATE HELPERS
3001
+ // ============================================================================
3002
+ //
3003
+ // These methods allow strategies to persist their own state (user preferences,
3004
+ // learned patterns, temporal tracking) in the user database.
3005
+ //
3006
+ // ============================================================================
3007
+ /**
3008
+ * Unique key identifying this strategy for state storage.
3009
+ *
3010
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
3011
+ * Override in subclasses if multiple instances of the same strategy type
3012
+ * need separate state storage.
3013
+ */
3014
+ get strategyKey() {
3015
+ return this.constructor.name;
3016
+ }
3017
+ /**
3018
+ * Get this strategy's persisted state for the current course.
3019
+ *
3020
+ * @returns The strategy's data payload, or null if no state exists
3021
+ * @throws Error if user or course is not initialized
3022
+ */
3023
+ async getStrategyState() {
3024
+ if (!this.user || !this.course) {
3025
+ throw new Error(
3026
+ `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
3027
+ );
3028
+ }
3029
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
3030
+ }
3031
+ /**
3032
+ * Persist this strategy's state for the current course.
3033
+ *
3034
+ * @param data - The strategy's data payload to store
3035
+ * @throws Error if user or course is not initialized
3036
+ */
3037
+ async putStrategyState(data) {
3038
+ if (!this.user || !this.course) {
3039
+ throw new Error(
3040
+ `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
3041
+ );
3042
+ }
3043
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
3044
+ }
3045
+ /**
3046
+ * Factory method to create navigator instances.
3047
+ *
3048
+ * First checks the navigator registry for a pre-registered constructor.
3049
+ * If not found, falls back to dynamic import (for custom navigators).
3050
+ *
3051
+ * For reliable operation in test environments, call initializeNavigatorRegistry()
3052
+ * before using this method.
3053
+ *
3054
+ * @param user - User interface
3055
+ * @param course - Course interface
3056
+ * @param strategyData - Strategy configuration document
3057
+ * @returns the runtime object used to steer a study session.
3058
+ */
3059
+ static async create(user, course, strategyData) {
3060
+ const implementingClass = strategyData.implementingClass;
3061
+ const RegisteredImpl = getRegisteredNavigator(implementingClass);
3062
+ if (RegisteredImpl) {
3063
+ logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);
3064
+ return new RegisteredImpl(user, course, strategyData);
3065
+ }
3066
+ logger.debug(
3067
+ `[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`
3068
+ );
3069
+ let NavigatorImpl;
3070
+ const variations = [".ts", ".js", ""];
3071
+ for (const ext of variations) {
3072
+ try {
3073
+ const module = await globImport_generators(`./generators/${implementingClass}${ext}`);
3074
+ NavigatorImpl = module.default;
3075
+ if (NavigatorImpl) break;
3076
+ } catch (e) {
3077
+ logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);
3078
+ }
3079
+ try {
3080
+ const module = await globImport_filters(`./filters/${implementingClass}${ext}`);
3081
+ NavigatorImpl = module.default;
3082
+ if (NavigatorImpl) break;
3083
+ } catch (e) {
3084
+ logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);
3085
+ }
3086
+ try {
3087
+ const module = await globImport(`./${implementingClass}${ext}`);
3088
+ NavigatorImpl = module.default;
3089
+ if (NavigatorImpl) break;
3090
+ } catch (e) {
3091
+ logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);
3092
+ }
3093
+ if (NavigatorImpl) break;
3094
+ }
3095
+ if (!NavigatorImpl) {
3096
+ throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
3097
+ }
3098
+ return new NavigatorImpl(user, course, strategyData);
3099
+ }
3100
+ /**
3101
+ * Get cards with suitability scores and provenance trails.
3102
+ *
3103
+ * **This is the PRIMARY API for navigation strategies.**
3104
+ *
3105
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
3106
+ * better candidates for presentation. Each card includes a provenance trail
3107
+ * documenting how strategies contributed to the final score.
3108
+ *
3109
+ * ## Implementation Required
3110
+ * All navigation strategies MUST override this method. The base class does
3111
+ * not provide a default implementation.
3112
+ *
3113
+ * ## For Generators
3114
+ * Override this method to generate candidates and compute scores based on
3115
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
3116
+ * initial provenance entry with action='generated'.
3117
+ *
3118
+ * ## For Filters
3119
+ * Filters should implement the CardFilter interface instead and be composed
3120
+ * via Pipeline. Filters do not directly implement getWeightedCards().
3121
+ *
3122
+ * @param limit - Maximum cards to return
3123
+ * @returns Cards sorted by score descending, with provenance trails
3124
+ */
3125
+ async getWeightedCards(_limit) {
3126
+ throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
3127
+ }
3128
+ };
3129
+ }
3130
+ });
3131
+
1698
3132
  // src/impl/couch/courseDB.ts
1699
3133
  import {
1700
3134
  EloToNumber,
1701
3135
  Status,
1702
3136
  blankCourseElo as blankCourseElo2,
1703
- toCourseElo as toCourseElo4
3137
+ toCourseElo as toCourseElo6
1704
3138
  } from "@vue-skuilder/common";
1705
3139
  function randIntWeightedTowardZero(n) {
1706
3140
  return Math.floor(Math.random() * Math.random() * Math.random() * n);
@@ -1902,7 +3336,7 @@ var init_courseDB = __esm({
1902
3336
  docs.rows.forEach((r) => {
1903
3337
  if (isSuccessRow(r)) {
1904
3338
  if (r.doc && r.doc.elo) {
1905
- ret.push(toCourseElo4(r.doc.elo));
3339
+ ret.push(toCourseElo6(r.doc.elo));
1906
3340
  } else {
1907
3341
  logger.warn("no elo data for card: " + r.id);
1908
3342
  ret.push(blankCourseElo2());
@@ -4115,6 +5549,19 @@ Currently logged-in as ${this._username}.`
4115
5549
  };
4116
5550
  await this.localDB.put(doc);
4117
5551
  }
5552
+ async putUserOutcome(record) {
5553
+ try {
5554
+ await this.localDB.put(record);
5555
+ } catch (err) {
5556
+ if (err.status === 409) {
5557
+ const existing = await this.localDB.get(record._id);
5558
+ record._rev = existing._rev;
5559
+ await this.localDB.put(record);
5560
+ } else {
5561
+ throw err;
5562
+ }
5563
+ }
5564
+ }
4118
5565
  async deleteStrategyState(courseId, strategyKey) {
4119
5566
  const docId = buildStrategyStateId(courseId, strategyKey);
4120
5567
  try {
@@ -5242,6 +6689,7 @@ async function initializeDataLayer(config) {
5242
6689
  logger.warn("Data layer already initialized. Returning existing instance.");
5243
6690
  return dataLayerInstance;
5244
6691
  }
6692
+ await initializeNavigatorRegistry();
5245
6693
  if (config.options.localStoragePrefix) {
5246
6694
  ENV.LOCAL_STORAGE_PREFIX = config.options.localStoragePrefix;
5247
6695
  }
@@ -5296,6 +6744,7 @@ var init_factory = __esm({
5296
6744
  "use strict";
5297
6745
  init_common();
5298
6746
  init_logger();
6747
+ init_navigators();
5299
6748
  NOT_SET = "NOT_SET";
5300
6749
  ENV = {
5301
6750
  COUCHDB_SERVER_PROTOCOL: NOT_SET,
@@ -5552,6 +7001,13 @@ var init_strategyState = __esm({
5552
7001
  }
5553
7002
  });
5554
7003
 
7004
+ // src/core/types/userOutcome.ts
7005
+ var init_userOutcome = __esm({
7006
+ "src/core/types/userOutcome.ts"() {
7007
+ "use strict";
7008
+ }
7009
+ });
7010
+
5555
7011
  // src/core/bulkImport/cardProcessor.ts
5556
7012
  import { Status as Status5 } from "@vue-skuilder/common";
5557
7013
  async function importParsedCards(parsedCards, courseDB, config) {
@@ -5673,7 +7129,7 @@ var init_cardProcessor = __esm({
5673
7129
  });
5674
7130
 
5675
7131
  // src/core/bulkImport/types.ts
5676
- var init_types = __esm({
7132
+ var init_types3 = __esm({
5677
7133
  "src/core/bulkImport/types.ts"() {
5678
7134
  "use strict";
5679
7135
  }
@@ -5684,7 +7140,7 @@ var init_bulkImport = __esm({
5684
7140
  "src/core/bulkImport/index.ts"() {
5685
7141
  "use strict";
5686
7142
  init_cardProcessor();
5687
- init_types();
7143
+ init_types3();
5688
7144
  }
5689
7145
  });
5690
7146
 
@@ -5696,10 +7152,12 @@ var init_core = __esm({
5696
7152
  init_types_legacy();
5697
7153
  init_user();
5698
7154
  init_strategyState();
7155
+ init_userOutcome();
5699
7156
  init_Loggable();
5700
7157
  init_util();
5701
7158
  init_navigators();
5702
7159
  init_bulkImport();
7160
+ init_orchestration();
5703
7161
  }
5704
7162
  });
5705
7163
 
@@ -5846,6 +7304,66 @@ function registerQuestionType(question, courseConfig) {
5846
7304
  logger.info(`Registered QuestionType: ${namespacedQuestionName}`);
5847
7305
  return true;
5848
7306
  }
7307
+ function removeDataShape(dataShapeName, courseConfig) {
7308
+ const index = courseConfig.dataShapes.findIndex((ds) => ds.name === dataShapeName);
7309
+ if (index === -1) {
7310
+ logger.info(`DataShape '${dataShapeName}' not found in course config`);
7311
+ return false;
7312
+ }
7313
+ courseConfig.dataShapes.splice(index, 1);
7314
+ courseConfig.questionTypes.forEach((qt) => {
7315
+ const dsIndex = qt.dataShapeList.indexOf(dataShapeName);
7316
+ if (dsIndex !== -1) {
7317
+ qt.dataShapeList.splice(dsIndex, 1);
7318
+ }
7319
+ });
7320
+ logger.info(`Removed DataShape: ${dataShapeName}`);
7321
+ return true;
7322
+ }
7323
+ function removeQuestionType(questionTypeName, courseConfig) {
7324
+ const index = courseConfig.questionTypes.findIndex((qt) => qt.name === questionTypeName);
7325
+ if (index === -1) {
7326
+ logger.info(`QuestionType '${questionTypeName}' not found in course config`);
7327
+ return false;
7328
+ }
7329
+ courseConfig.questionTypes.splice(index, 1);
7330
+ courseConfig.dataShapes.forEach((ds) => {
7331
+ const qtIndex = ds.questionTypes.indexOf(questionTypeName);
7332
+ if (qtIndex !== -1) {
7333
+ ds.questionTypes.splice(qtIndex, 1);
7334
+ }
7335
+ });
7336
+ logger.info(`Removed QuestionType: ${questionTypeName}`);
7337
+ return true;
7338
+ }
7339
+ async function removeCustomQuestionTypes(dataShapeNames, questionTypeNames, courseConfig, courseDB) {
7340
+ try {
7341
+ logger.info("Beginning custom question removal");
7342
+ logger.info(`Removing ${dataShapeNames.length} data shapes and ${questionTypeNames.length} question types`);
7343
+ let removedCount = 0;
7344
+ for (const qtName of questionTypeNames) {
7345
+ if (removeQuestionType(qtName, courseConfig)) {
7346
+ removedCount++;
7347
+ }
7348
+ }
7349
+ for (const dsName of dataShapeNames) {
7350
+ if (removeDataShape(dsName, courseConfig)) {
7351
+ removedCount++;
7352
+ }
7353
+ }
7354
+ logger.info("Updating course configuration...");
7355
+ const updateResult = await courseDB.updateCourseConfig(courseConfig);
7356
+ if (!updateResult.ok) {
7357
+ throw new Error(`Failed to update course config: ${JSON.stringify(updateResult)}`);
7358
+ }
7359
+ logger.info(`Custom question removal complete: ${removedCount} items removed`);
7360
+ return { success: true, removedCount };
7361
+ } catch (error) {
7362
+ const errorMessage = error instanceof Error ? error.message : String(error);
7363
+ logger.error(`Custom question removal failed: ${errorMessage}`);
7364
+ return { success: false, removedCount: 0, errorMessage };
7365
+ }
7366
+ }
5849
7367
  async function registerSeedData(question, courseDB, username) {
5850
7368
  if (question.questionClass.seedData && Array.isArray(question.questionClass.seedData)) {
5851
7369
  logger.info(`Registering seed data for question: ${question.name}`);
@@ -6063,7 +7581,7 @@ var SrsService = class {
6063
7581
 
6064
7582
  // src/study/services/EloService.ts
6065
7583
  init_logger();
6066
- import { adjustCourseScores, toCourseElo as toCourseElo5 } from "@vue-skuilder/common";
7584
+ import { adjustCourseScores, toCourseElo as toCourseElo7 } from "@vue-skuilder/common";
6067
7585
  var EloService = class {
6068
7586
  dataLayer;
6069
7587
  user;
@@ -6085,7 +7603,7 @@ var EloService = class {
6085
7603
  logger.warn(`k value interpretation not currently implemented`);
6086
7604
  }
6087
7605
  const courseDB = this.dataLayer.getCourseDB(currentCard.card.course_id);
6088
- const userElo = toCourseElo5(userCourseRegDoc.courses.find((c) => c.courseID === course_id).elo);
7606
+ const userElo = toCourseElo7(userCourseRegDoc.courses.find((c) => c.courseID === course_id).elo);
6089
7607
  const cardElo = (await courseDB.getCardEloData([currentCard.card.card_id]))[0];
6090
7608
  if (cardElo && userElo) {
6091
7609
  const eloUpdate = adjustCourseScores(userElo, cardElo, userScore);
@@ -6294,7 +7812,7 @@ init_logger();
6294
7812
  import {
6295
7813
  displayableDataToViewData,
6296
7814
  isCourseElo,
6297
- toCourseElo as toCourseElo6
7815
+ toCourseElo as toCourseElo8
6298
7816
  } from "@vue-skuilder/common";
6299
7817
  function parseAudioURIs(data) {
6300
7818
  if (typeof data !== "string") return [];
@@ -6430,7 +7948,7 @@ var CardHydrationService = class {
6430
7948
  const courseDB = this.getCourseDB(item.courseID);
6431
7949
  const cardData = await courseDB.getCourseDoc(item.cardID);
6432
7950
  if (!isCourseElo(cardData.elo)) {
6433
- cardData.elo = toCourseElo6(cardData.elo);
7951
+ cardData.elo = toCourseElo8(cardData.elo);
6434
7952
  }
6435
7953
  const view = this.getViewComponent(cardData.id_view);
6436
7954
  const dataDocs = await Promise.all(
@@ -6515,6 +8033,7 @@ var ItemQueue = class {
6515
8033
 
6516
8034
  // src/study/SessionController.ts
6517
8035
  init_couch();
8036
+ init_recording();
6518
8037
 
6519
8038
  // src/util/index.ts
6520
8039
  init_Loggable();
@@ -8362,6 +9881,49 @@ var SessionController = class extends Loggable {
8362
9881
  this.failedQ.dequeue((queueItem) => queueItem.cardID);
8363
9882
  }
8364
9883
  }
9884
+ /**
9885
+ * End the session and record learning outcomes.
9886
+ *
9887
+ * This method aggregates all responses from the session and records a
9888
+ * UserOutcomeRecord if evolutionary orchestration is enabled.
9889
+ */
9890
+ async endSession() {
9891
+ if (!this._sessionRecord || this._sessionRecord.length === 0) {
9892
+ return;
9893
+ }
9894
+ const questionRecords = this._sessionRecord.flatMap((r) => r.records).filter((r) => r.userAnswer !== void 0);
9895
+ if (questionRecords.length === 0) {
9896
+ return;
9897
+ }
9898
+ let orchestrationContext = null;
9899
+ const strategies = [];
9900
+ for (const source of this.sources) {
9901
+ if (source.getOrchestrationContext) {
9902
+ try {
9903
+ orchestrationContext = await source.getOrchestrationContext();
9904
+ if (source.getStrategyIds) {
9905
+ strategies.push(...source.getStrategyIds());
9906
+ }
9907
+ } catch (e) {
9908
+ logger.warn(`[SessionController] Failed to get orchestration context: ${e}`);
9909
+ }
9910
+ if (orchestrationContext) break;
9911
+ }
9912
+ }
9913
+ if (!orchestrationContext) {
9914
+ logger.debug("[SessionController] No orchestration context available, skipping outcome recording");
9915
+ return;
9916
+ }
9917
+ const periodEnd = (/* @__PURE__ */ new Date()).toISOString();
9918
+ const periodStart = new Date(this.startTime).toISOString();
9919
+ await recordUserOutcome(
9920
+ orchestrationContext,
9921
+ periodStart,
9922
+ periodEnd,
9923
+ questionRecords,
9924
+ strategies
9925
+ );
9926
+ }
8365
9927
  };
8366
9928
 
8367
9929
  // src/study/index.ts
@@ -8388,8 +9950,15 @@ export {
8388
9950
  StaticToCouchDBMigrator,
8389
9951
  TagFilteredContentSource,
8390
9952
  _resetDataLayer,
9953
+ aggregateOutcomesForGradient,
8391
9954
  areQuestionRecords,
8392
9955
  buildStrategyStateId,
9956
+ computeDeviation,
9957
+ computeEffectiveWeight,
9958
+ computeOutcomeSignal,
9959
+ computeSpread,
9960
+ computeStrategyGradient,
9961
+ createOrchestrationContext,
8393
9962
  docIsDeleted,
8394
9963
  ensureAppDataDirectory,
8395
9964
  getAppDataDirectory,
@@ -8397,10 +9966,15 @@ export {
8397
9966
  getCardOrigin,
8398
9967
  getDataLayer,
8399
9968
  getDbPath,
9969
+ getDefaultLearnableWeight,
9970
+ getRegisteredNavigator,
9971
+ getRegisteredNavigatorNames,
8400
9972
  getStudySource,
9973
+ hasRegisteredNavigator,
8401
9974
  importParsedCards,
8402
9975
  initializeDataDirectory,
8403
9976
  initializeDataLayer,
9977
+ initializeNavigatorRegistry,
8404
9978
  isDataShapeRegistered,
8405
9979
  isDataShapeSchemaAvailable,
8406
9980
  isFilter,
@@ -8412,11 +9986,20 @@ export {
8412
9986
  newInterval,
8413
9987
  parseCardHistoryID,
8414
9988
  processCustomQuestionsData,
9989
+ recordUserOutcome,
8415
9990
  registerBlanksCard,
8416
9991
  registerCustomQuestionTypes,
8417
9992
  registerDataShape,
9993
+ registerNavigator,
8418
9994
  registerQuestionType,
8419
9995
  registerSeedData,
9996
+ removeCustomQuestionTypes,
9997
+ removeDataShape,
9998
+ removeQuestionType,
9999
+ runPeriodUpdate,
10000
+ scoreAccuracyInZone,
10001
+ updateLearningState,
10002
+ updateStrategyWeight,
8420
10003
  validateMigration,
8421
10004
  validateProcessorConfig,
8422
10005
  validateStaticCourse