@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
@@ -1,7 +1,17 @@
1
+ var __defProp = Object.defineProperty;
1
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __glob = (map) => (path2) => {
4
+ var fn = map[path2];
5
+ if (fn) return fn();
6
+ throw new Error("Module not found in bundle: " + path2);
7
+ };
2
8
  var __esm = (fn, res) => function __init() {
3
9
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
4
10
  };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
5
15
 
6
16
  // src/impl/common/SyncStrategy.ts
7
17
  var init_SyncStrategy = __esm({
@@ -252,7 +262,9 @@ var init_types_legacy = __esm({
252
262
  ["VIEW" /* VIEW */]: "VIEW",
253
263
  ["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
254
264
  ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
255
- ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE"
265
+ ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE",
266
+ ["USER_OUTCOME" /* USER_OUTCOME */]: "USER_OUTCOME",
267
+ ["STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */]: "STRATEGY_LEARNING_STATE"
256
268
  };
257
269
  }
258
270
  });
@@ -593,173 +605,1382 @@ var init_courseLookupDB = __esm({
593
605
  }
594
606
  });
595
607
 
596
- // src/core/navigators/index.ts
597
- function isGenerator(impl) {
598
- return NavigatorRoles[impl] === "generator" /* GENERATOR */;
599
- }
600
- function isFilter(impl) {
601
- return NavigatorRoles[impl] === "filter" /* FILTER */;
602
- }
603
- var NavigatorRoles, ContentNavigator;
604
- var init_navigators = __esm({
605
- "src/core/navigators/index.ts"() {
608
+ // src/core/navigators/generators/CompositeGenerator.ts
609
+ var CompositeGenerator_exports = {};
610
+ __export(CompositeGenerator_exports, {
611
+ AggregationMode: () => AggregationMode,
612
+ default: () => CompositeGenerator
613
+ });
614
+ var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
615
+ var init_CompositeGenerator = __esm({
616
+ "src/core/navigators/generators/CompositeGenerator.ts"() {
606
617
  "use strict";
618
+ init_navigators();
607
619
  init_logger();
608
- NavigatorRoles = {
609
- ["elo" /* ELO */]: "generator" /* GENERATOR */,
610
- ["srs" /* SRS */]: "generator" /* GENERATOR */,
611
- ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
612
- ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
613
- ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
614
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
615
- };
616
- ContentNavigator = class {
617
- /** User interface for this navigation session */
618
- user;
619
- /** Course interface for this navigation session */
620
- course;
621
- /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
622
- strategyName;
623
- /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
624
- strategyId;
625
- /**
626
- * Constructor for standard navigators.
627
- * Call this from subclass constructors to initialize common fields.
628
- *
629
- * Note: CompositeGenerator and Pipeline call super() without args, then set
630
- * user/course fields directly if needed.
631
- */
632
- constructor(user, course, strategyData) {
633
- this.user = user;
634
- this.course = course;
635
- if (strategyData) {
636
- this.strategyName = strategyData.name;
637
- this.strategyId = strategyData._id;
620
+ AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
621
+ AggregationMode2["MAX"] = "max";
622
+ AggregationMode2["AVERAGE"] = "average";
623
+ AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
624
+ return AggregationMode2;
625
+ })(AggregationMode || {});
626
+ DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
627
+ FREQUENCY_BOOST_FACTOR = 0.1;
628
+ CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
629
+ /** Human-readable name for CardGenerator interface */
630
+ name = "Composite Generator";
631
+ generators;
632
+ aggregationMode;
633
+ constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
634
+ super();
635
+ this.generators = generators;
636
+ this.aggregationMode = aggregationMode;
637
+ if (generators.length === 0) {
638
+ throw new Error("CompositeGenerator requires at least one generator");
638
639
  }
640
+ logger.debug(
641
+ `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
642
+ );
639
643
  }
640
- // ============================================================================
641
- // STRATEGY STATE HELPERS
642
- // ============================================================================
643
- //
644
- // These methods allow strategies to persist their own state (user preferences,
645
- // learned patterns, temporal tracking) in the user database.
646
- //
647
- // ============================================================================
648
644
  /**
649
- * Unique key identifying this strategy for state storage.
645
+ * Creates a CompositeGenerator from strategy data.
650
646
  *
651
- * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
652
- * Override in subclasses if multiple instances of the same strategy type
653
- * need separate state storage.
647
+ * This is a convenience factory for use by PipelineAssembler.
654
648
  */
655
- get strategyKey() {
656
- return this.constructor.name;
649
+ static async fromStrategies(user, course, strategies, aggregationMode = DEFAULT_AGGREGATION_MODE) {
650
+ const generators = await Promise.all(
651
+ strategies.map((s) => ContentNavigator.create(user, course, s))
652
+ );
653
+ return new _CompositeGenerator(generators, aggregationMode);
657
654
  }
658
655
  /**
659
- * Get this strategy's persisted state for the current course.
656
+ * Get weighted cards from all generators, merge and deduplicate.
660
657
  *
661
- * @returns The strategy's data payload, or null if no state exists
662
- * @throws Error if user or course is not initialized
658
+ * Cards appearing in multiple generators receive a score boost.
659
+ * Provenance tracks which generators produced each card and how scores were aggregated.
660
+ *
661
+ * This method supports both the legacy signature (limit only) and the
662
+ * CardGenerator interface signature (limit, context).
663
+ *
664
+ * @param limit - Maximum number of cards to return
665
+ * @param context - GeneratorContext passed to child generators (required when called via Pipeline)
663
666
  */
664
- async getStrategyState() {
665
- if (!this.user || !this.course) {
667
+ async getWeightedCards(limit, context) {
668
+ if (!context) {
666
669
  throw new Error(
667
- `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
670
+ "CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly."
668
671
  );
669
672
  }
670
- return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
673
+ const results = await Promise.all(
674
+ this.generators.map((g) => g.getWeightedCards(limit, context))
675
+ );
676
+ const byCardId = /* @__PURE__ */ new Map();
677
+ results.forEach((cards, index) => {
678
+ const gen = this.generators[index];
679
+ let weight = gen.learnable?.weight ?? 1;
680
+ let deviation;
681
+ if (gen.learnable && !gen.staticWeight && context.orchestration) {
682
+ const strategyId = gen.strategyId;
683
+ if (strategyId) {
684
+ weight = context.orchestration.getEffectiveWeight(strategyId, gen.learnable);
685
+ deviation = context.orchestration.getDeviation(strategyId);
686
+ }
687
+ }
688
+ for (const card of cards) {
689
+ if (card.provenance.length > 0) {
690
+ card.provenance[0].effectiveWeight = weight;
691
+ card.provenance[0].deviation = deviation;
692
+ }
693
+ const existing = byCardId.get(card.cardId) || [];
694
+ existing.push({ card, weight });
695
+ byCardId.set(card.cardId, existing);
696
+ }
697
+ });
698
+ const merged = [];
699
+ for (const [, items] of byCardId) {
700
+ const cards = items.map((i) => i.card);
701
+ const aggregatedScore = this.aggregateScores(items);
702
+ const finalScore = Math.min(1, aggregatedScore);
703
+ const mergedProvenance = cards.flatMap((c) => c.provenance);
704
+ const initialScore = cards[0].score;
705
+ const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
706
+ const reason = this.buildAggregationReason(items, finalScore);
707
+ merged.push({
708
+ ...cards[0],
709
+ score: finalScore,
710
+ provenance: [
711
+ ...mergedProvenance,
712
+ {
713
+ strategy: "composite",
714
+ strategyName: "Composite Generator",
715
+ strategyId: "COMPOSITE_GENERATOR",
716
+ action,
717
+ score: finalScore,
718
+ reason
719
+ }
720
+ ]
721
+ });
722
+ }
723
+ return merged.sort((a, b) => b.score - a.score).slice(0, limit);
671
724
  }
672
725
  /**
673
- * Persist this strategy's state for the current course.
674
- *
675
- * @param data - The strategy's data payload to store
676
- * @throws Error if user or course is not initialized
726
+ * Build human-readable reason for score aggregation.
677
727
  */
678
- async putStrategyState(data) {
679
- if (!this.user || !this.course) {
680
- throw new Error(
681
- `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
682
- );
728
+ buildAggregationReason(items, finalScore) {
729
+ const cards = items.map((i) => i.card);
730
+ const count = cards.length;
731
+ const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
732
+ if (count === 1) {
733
+ const weightMsg = Math.abs(items[0].weight - 1) > 1e-3 ? ` (w=${items[0].weight.toFixed(2)})` : "";
734
+ return `Single generator, score ${finalScore.toFixed(2)}${weightMsg}`;
735
+ }
736
+ const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
737
+ switch (this.aggregationMode) {
738
+ case "max" /* MAX */:
739
+ return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
740
+ case "average" /* AVERAGE */:
741
+ return `Weighted Avg of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
742
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
743
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
744
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
745
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
746
+ const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
747
+ return `Frequency boost from ${count} generators (${strategies}): w-avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
748
+ }
749
+ default:
750
+ return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
683
751
  }
684
- return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
685
752
  }
686
753
  /**
687
- * Factory method to create navigator instances dynamically.
688
- *
689
- * @param user - User interface
690
- * @param course - Course interface
691
- * @param strategyData - Strategy configuration document
692
- * @returns the runtime object used to steer a study session.
754
+ * Aggregate scores from multiple generators for the same card.
693
755
  */
694
- static async create(user, course, strategyData) {
695
- const implementingClass = strategyData.implementingClass;
696
- let NavigatorImpl;
697
- const variations = [".ts", ".js", ""];
698
- const dirs = ["filters", "generators"];
699
- for (const ext of variations) {
700
- for (const dir of dirs) {
701
- const loadFrom = `./${dir}/${implementingClass}${ext}`;
702
- try {
703
- const module = await import(loadFrom);
704
- NavigatorImpl = module.default;
705
- break;
706
- } catch (e) {
707
- logger.debug(`Failed to load extension from ${loadFrom}:`, e);
708
- }
756
+ aggregateScores(items) {
757
+ const scores = items.map((i) => i.card.score);
758
+ switch (this.aggregationMode) {
759
+ case "max" /* MAX */:
760
+ return Math.max(...scores);
761
+ case "average" /* AVERAGE */: {
762
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
763
+ if (totalWeight === 0) return 0;
764
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
765
+ return weightedSum / totalWeight;
709
766
  }
767
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
768
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
769
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
770
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
771
+ const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (items.length - 1);
772
+ return avg * frequencyBoost;
773
+ }
774
+ default:
775
+ return scores[0];
710
776
  }
711
- if (!NavigatorImpl) {
712
- throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
713
- }
714
- return new NavigatorImpl(user, course, strategyData);
777
+ }
778
+ };
779
+ }
780
+ });
781
+
782
+ // src/core/navigators/generators/elo.ts
783
+ var elo_exports = {};
784
+ __export(elo_exports, {
785
+ default: () => ELONavigator
786
+ });
787
+ import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
788
+ var ELONavigator;
789
+ var init_elo = __esm({
790
+ "src/core/navigators/generators/elo.ts"() {
791
+ "use strict";
792
+ init_navigators();
793
+ ELONavigator = class extends ContentNavigator {
794
+ /** Human-readable name for CardGenerator interface */
795
+ name;
796
+ constructor(user, course, strategyData) {
797
+ super(user, course, strategyData);
798
+ this.name = strategyData?.name || "ELO";
715
799
  }
716
800
  /**
717
- * Get cards with suitability scores and provenance trails.
718
- *
719
- * **This is the PRIMARY API for navigation strategies.**
720
- *
721
- * Returns cards ranked by suitability score (0-1). Higher scores indicate
722
- * better candidates for presentation. Each card includes a provenance trail
723
- * documenting how strategies contributed to the final score.
801
+ * Get new cards with suitability scores based on ELO distance.
724
802
  *
725
- * ## Implementation Required
726
- * All navigation strategies MUST override this method. The base class does
727
- * not provide a default implementation.
803
+ * Cards closer to user's ELO get higher scores.
804
+ * Score formula: max(0, 1 - distance / 500)
728
805
  *
729
- * ## For Generators
730
- * Override this method to generate candidates and compute scores based on
731
- * your strategy's logic (e.g., ELO proximity, review urgency). Create the
732
- * initial provenance entry with action='generated'.
806
+ * NOTE: This generator only handles NEW cards. Reviews are handled by
807
+ * SRSNavigator. Use CompositeGenerator to combine both.
733
808
  *
734
- * ## For Filters
735
- * Filters should implement the CardFilter interface instead and be composed
736
- * via Pipeline. Filters do not directly implement getWeightedCards().
809
+ * This method supports both the legacy signature (limit only) and the
810
+ * CardGenerator interface signature (limit, context).
737
811
  *
738
- * @param limit - Maximum cards to return
739
- * @returns Cards sorted by score descending, with provenance trails
812
+ * @param limit - Maximum number of cards to return
813
+ * @param context - Optional GeneratorContext (used when called via Pipeline)
740
814
  */
741
- async getWeightedCards(_limit) {
742
- throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
743
- }
744
- };
745
- }
746
- });
747
-
748
- // src/core/navigators/Pipeline.ts
749
- import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
750
- function logPipelineConfig(generator, filters) {
751
- const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
752
- logger.info(
753
- `[Pipeline] Configuration:
754
- Generator: ${generator.name}
755
- Filters:${filterList}`
756
- );
757
- }
758
- function logTagHydration(cards, tagsByCard) {
759
- const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
760
- const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
761
- logger.debug(
762
- `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
815
+ async getWeightedCards(limit, context) {
816
+ let userGlobalElo;
817
+ if (context?.userElo !== void 0) {
818
+ userGlobalElo = context.userElo;
819
+ } else {
820
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
821
+ const userElo = toCourseElo2(courseReg.elo);
822
+ userGlobalElo = userElo.global.score;
823
+ }
824
+ const activeCards = await this.user.getActiveCards();
825
+ const newCards = (await this.course.getCardsCenteredAtELO(
826
+ { limit, elo: "user" },
827
+ (c) => !activeCards.some((ac) => c.cardID === ac.cardID)
828
+ )).map((c) => ({ ...c, status: "new" }));
829
+ const cardIds = newCards.map((c) => c.cardID);
830
+ const cardEloData = await this.course.getCardEloData(cardIds);
831
+ const scored = newCards.map((c, i) => {
832
+ const cardElo = cardEloData[i]?.global?.score ?? 1e3;
833
+ const distance = Math.abs(cardElo - userGlobalElo);
834
+ const score = Math.max(0, 1 - distance / 500);
835
+ return {
836
+ cardId: c.cardID,
837
+ courseId: c.courseID,
838
+ score,
839
+ provenance: [
840
+ {
841
+ strategy: "elo",
842
+ strategyName: this.strategyName || this.name,
843
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
844
+ action: "generated",
845
+ score,
846
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), new card`
847
+ }
848
+ ]
849
+ };
850
+ });
851
+ scored.sort((a, b) => b.score - a.score);
852
+ return scored.slice(0, limit);
853
+ }
854
+ };
855
+ }
856
+ });
857
+
858
+ // src/core/navigators/generators/index.ts
859
+ var generators_exports = {};
860
+ var init_generators = __esm({
861
+ "src/core/navigators/generators/index.ts"() {
862
+ "use strict";
863
+ }
864
+ });
865
+
866
+ // src/core/navigators/generators/srs.ts
867
+ var srs_exports = {};
868
+ __export(srs_exports, {
869
+ default: () => SRSNavigator
870
+ });
871
+ import moment from "moment";
872
+ var SRSNavigator;
873
+ var init_srs = __esm({
874
+ "src/core/navigators/generators/srs.ts"() {
875
+ "use strict";
876
+ init_navigators();
877
+ init_logger();
878
+ SRSNavigator = class extends ContentNavigator {
879
+ /** Human-readable name for CardGenerator interface */
880
+ name;
881
+ constructor(user, course, strategyData) {
882
+ super(user, course, strategyData);
883
+ this.name = strategyData?.name || "SRS";
884
+ }
885
+ /**
886
+ * Get review cards scored by urgency.
887
+ *
888
+ * Score formula combines:
889
+ * - Relative overdueness: hoursOverdue / intervalHours
890
+ * - Interval recency: exponential decay favoring shorter intervals
891
+ *
892
+ * Cards not yet due are excluded (not scored as 0).
893
+ *
894
+ * This method supports both the legacy signature (limit only) and the
895
+ * CardGenerator interface signature (limit, context).
896
+ *
897
+ * @param limit - Maximum number of cards to return
898
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
899
+ */
900
+ async getWeightedCards(limit, _context) {
901
+ if (!this.user || !this.course) {
902
+ throw new Error("SRSNavigator requires user and course to be set");
903
+ }
904
+ const reviews = await this.user.getPendingReviews(this.course.getCourseID());
905
+ const now = moment.utc();
906
+ const dueReviews = reviews.filter((r) => now.isAfter(moment.utc(r.reviewTime)));
907
+ const scored = dueReviews.map((review) => {
908
+ const { score, reason } = this.computeUrgencyScore(review, now);
909
+ return {
910
+ cardId: review.cardId,
911
+ courseId: review.courseId,
912
+ score,
913
+ reviewID: review._id,
914
+ provenance: [
915
+ {
916
+ strategy: "srs",
917
+ strategyName: this.strategyName || this.name,
918
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
919
+ action: "generated",
920
+ score,
921
+ reason
922
+ }
923
+ ]
924
+ };
925
+ });
926
+ logger.debug(`[srsNav] got ${scored.length} weighted cards`);
927
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
928
+ }
929
+ /**
930
+ * Compute urgency score for a review card.
931
+ *
932
+ * Two factors:
933
+ * 1. Relative overdueness = hoursOverdue / intervalHours
934
+ * - 2 days overdue on 3-day interval = 0.67 (urgent)
935
+ * - 2 days overdue on 180-day interval = 0.01 (not urgent)
936
+ *
937
+ * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
938
+ * - 24h interval → ~1.0 (very recent learning)
939
+ * - 30 days (720h) → ~0.56
940
+ * - 180 days → ~0.30
941
+ *
942
+ * Combined: base 0.5 + weighted average of factors * 0.45
943
+ * Result range: approximately 0.5 to 0.95
944
+ */
945
+ computeUrgencyScore(review, now) {
946
+ const scheduledAt = moment.utc(review.scheduledAt);
947
+ const due = moment.utc(review.reviewTime);
948
+ const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
949
+ const hoursOverdue = now.diff(due, "hours");
950
+ const relativeOverdue = hoursOverdue / intervalHours;
951
+ const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
952
+ const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
953
+ const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
954
+ const score = Math.min(0.95, 0.5 + urgency * 0.45);
955
+ const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
956
+ return { score, reason };
957
+ }
958
+ };
959
+ }
960
+ });
961
+
962
+ // src/core/navigators/generators/types.ts
963
+ var types_exports = {};
964
+ var init_types = __esm({
965
+ "src/core/navigators/generators/types.ts"() {
966
+ "use strict";
967
+ }
968
+ });
969
+
970
+ // import("./generators/**/*") in src/core/navigators/index.ts
971
+ var globImport_generators;
972
+ var init_ = __esm({
973
+ 'import("./generators/**/*") in src/core/navigators/index.ts'() {
974
+ globImport_generators = __glob({
975
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
976
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
977
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
978
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
979
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports))
980
+ });
981
+ }
982
+ });
983
+
984
+ // src/core/types/contentNavigationStrategy.ts
985
+ var DEFAULT_LEARNABLE_WEIGHT;
986
+ var init_contentNavigationStrategy = __esm({
987
+ "src/core/types/contentNavigationStrategy.ts"() {
988
+ "use strict";
989
+ DEFAULT_LEARNABLE_WEIGHT = {
990
+ weight: 1,
991
+ confidence: 0.1,
992
+ // Low confidence initially = wide exploration
993
+ sampleSize: 0
994
+ };
995
+ }
996
+ });
997
+
998
+ // src/core/navigators/filters/WeightedFilter.ts
999
+ var WeightedFilter_exports = {};
1000
+ __export(WeightedFilter_exports, {
1001
+ WeightedFilter: () => WeightedFilter
1002
+ });
1003
+ var WeightedFilter;
1004
+ var init_WeightedFilter = __esm({
1005
+ "src/core/navigators/filters/WeightedFilter.ts"() {
1006
+ "use strict";
1007
+ init_contentNavigationStrategy();
1008
+ WeightedFilter = class {
1009
+ name;
1010
+ inner;
1011
+ learnable;
1012
+ staticWeight;
1013
+ strategyId;
1014
+ constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
1015
+ this.inner = inner;
1016
+ this.name = inner.name;
1017
+ this.learnable = learnable;
1018
+ this.staticWeight = staticWeight;
1019
+ this.strategyId = strategyId;
1020
+ }
1021
+ /**
1022
+ * Apply the inner filter, then scale its effect by the configured weight.
1023
+ */
1024
+ async transform(cards, context) {
1025
+ let effectiveWeight = this.learnable.weight;
1026
+ let deviation;
1027
+ if (!this.staticWeight && context.orchestration) {
1028
+ const strategyId = this.strategyId || this.inner.strategyId || this.name;
1029
+ effectiveWeight = context.orchestration.getEffectiveWeight(strategyId, this.learnable);
1030
+ deviation = context.orchestration.getDeviation(strategyId);
1031
+ }
1032
+ if (Math.abs(effectiveWeight - 1) < 1e-3) {
1033
+ return this.inner.transform(cards, context);
1034
+ }
1035
+ const originalScores = /* @__PURE__ */ new Map();
1036
+ for (const card of cards) {
1037
+ originalScores.set(card.cardId, card.score);
1038
+ }
1039
+ const transformedCards = await this.inner.transform(cards, context);
1040
+ return transformedCards.map((card) => {
1041
+ const originalScore = originalScores.get(card.cardId);
1042
+ if (originalScore === void 0 || originalScore === 0 || card.score === 0) {
1043
+ return card;
1044
+ }
1045
+ const rawEffect = card.score / originalScore;
1046
+ if (Math.abs(rawEffect - 1) < 1e-4) {
1047
+ return card;
1048
+ }
1049
+ const weightedEffect = Math.pow(rawEffect, effectiveWeight);
1050
+ const newScore = originalScore * weightedEffect;
1051
+ const lastProvIndex = card.provenance.length - 1;
1052
+ const lastProv = card.provenance[lastProvIndex];
1053
+ if (lastProv) {
1054
+ const updatedProvenance = [...card.provenance];
1055
+ updatedProvenance[lastProvIndex] = {
1056
+ ...lastProv,
1057
+ score: newScore,
1058
+ effectiveWeight,
1059
+ deviation
1060
+ // We can optionally append to the reason, but the structured field is key
1061
+ };
1062
+ return {
1063
+ ...card,
1064
+ score: newScore,
1065
+ provenance: updatedProvenance
1066
+ };
1067
+ }
1068
+ return {
1069
+ ...card,
1070
+ score: newScore
1071
+ };
1072
+ });
1073
+ }
1074
+ };
1075
+ }
1076
+ });
1077
+
1078
+ // src/core/navigators/filters/eloDistance.ts
1079
+ var eloDistance_exports = {};
1080
+ __export(eloDistance_exports, {
1081
+ DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1082
+ DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1083
+ DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1084
+ createEloDistanceFilter: () => createEloDistanceFilter
1085
+ });
1086
+ function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1087
+ const normalizedDistance = distance / halfLife;
1088
+ const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1089
+ return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1090
+ }
1091
+ function createEloDistanceFilter(config) {
1092
+ const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1093
+ const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1094
+ const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1095
+ return {
1096
+ name: "ELO Distance Filter",
1097
+ async transform(cards, context) {
1098
+ const { course, userElo } = context;
1099
+ const cardIds = cards.map((c) => c.cardId);
1100
+ const cardElos = await course.getCardEloData(cardIds);
1101
+ return cards.map((card, i) => {
1102
+ const cardElo = cardElos[i]?.global?.score ?? 1e3;
1103
+ const distance = Math.abs(cardElo - userElo);
1104
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1105
+ const newScore = card.score * multiplier;
1106
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1107
+ return {
1108
+ ...card,
1109
+ score: newScore,
1110
+ provenance: [
1111
+ ...card.provenance,
1112
+ {
1113
+ strategy: "eloDistance",
1114
+ strategyName: "ELO Distance Filter",
1115
+ strategyId: "ELO_DISTANCE_FILTER",
1116
+ action,
1117
+ score: newScore,
1118
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1119
+ }
1120
+ ]
1121
+ };
1122
+ });
1123
+ }
1124
+ };
1125
+ }
1126
+ var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1127
+ var init_eloDistance = __esm({
1128
+ "src/core/navigators/filters/eloDistance.ts"() {
1129
+ "use strict";
1130
+ DEFAULT_HALF_LIFE = 200;
1131
+ DEFAULT_MIN_MULTIPLIER = 0.3;
1132
+ DEFAULT_MAX_MULTIPLIER = 1;
1133
+ }
1134
+ });
1135
+
1136
+ // src/core/navigators/filters/hierarchyDefinition.ts
1137
+ var hierarchyDefinition_exports = {};
1138
+ __export(hierarchyDefinition_exports, {
1139
+ default: () => HierarchyDefinitionNavigator
1140
+ });
1141
+ import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
1142
+ var DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1143
+ var init_hierarchyDefinition = __esm({
1144
+ "src/core/navigators/filters/hierarchyDefinition.ts"() {
1145
+ "use strict";
1146
+ init_navigators();
1147
+ DEFAULT_MIN_COUNT = 3;
1148
+ HierarchyDefinitionNavigator = class extends ContentNavigator {
1149
+ config;
1150
+ /** Human-readable name for CardFilter interface */
1151
+ name;
1152
+ constructor(user, course, strategyData) {
1153
+ super(user, course, strategyData);
1154
+ this.config = this.parseConfig(strategyData.serializedData);
1155
+ this.name = strategyData.name || "Hierarchy Definition";
1156
+ }
1157
+ parseConfig(serializedData) {
1158
+ try {
1159
+ const parsed = JSON.parse(serializedData);
1160
+ return {
1161
+ prerequisites: parsed.prerequisites || {}
1162
+ };
1163
+ } catch {
1164
+ return {
1165
+ prerequisites: {}
1166
+ };
1167
+ }
1168
+ }
1169
+ /**
1170
+ * Check if a specific prerequisite is satisfied
1171
+ */
1172
+ isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1173
+ if (!userTagElo) return false;
1174
+ const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1175
+ if (userTagElo.count < minCount) return false;
1176
+ if (prereq.masteryThreshold?.minElo !== void 0) {
1177
+ return userTagElo.score >= prereq.masteryThreshold.minElo;
1178
+ } else {
1179
+ return userTagElo.score >= userGlobalElo;
1180
+ }
1181
+ }
1182
+ /**
1183
+ * Get the set of tags the user has mastered.
1184
+ * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1185
+ */
1186
+ async getMasteredTags(context) {
1187
+ const mastered = /* @__PURE__ */ new Set();
1188
+ try {
1189
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1190
+ const userElo = toCourseElo3(courseReg.elo);
1191
+ for (const prereqs of Object.values(this.config.prerequisites)) {
1192
+ for (const prereq of prereqs) {
1193
+ const tagElo = userElo.tags[prereq.tag];
1194
+ if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1195
+ mastered.add(prereq.tag);
1196
+ }
1197
+ }
1198
+ }
1199
+ } catch {
1200
+ }
1201
+ return mastered;
1202
+ }
1203
+ /**
1204
+ * Get the set of tags that are unlocked (prerequisites met)
1205
+ */
1206
+ getUnlockedTags(masteredTags) {
1207
+ const unlocked = /* @__PURE__ */ new Set();
1208
+ for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1209
+ const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1210
+ if (allPrereqsMet) {
1211
+ unlocked.add(tagId);
1212
+ }
1213
+ }
1214
+ return unlocked;
1215
+ }
1216
+ /**
1217
+ * Check if a tag has prerequisites defined in config
1218
+ */
1219
+ hasPrerequisites(tagId) {
1220
+ return tagId in this.config.prerequisites;
1221
+ }
1222
+ /**
1223
+ * Check if a card is unlocked and generate reason.
1224
+ */
1225
+ async checkCardUnlock(card, _course, unlockedTags, masteredTags) {
1226
+ try {
1227
+ const cardTags = card.tags ?? [];
1228
+ const lockedTags = cardTags.filter(
1229
+ (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1230
+ );
1231
+ if (lockedTags.length === 0) {
1232
+ const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1233
+ return {
1234
+ isUnlocked: true,
1235
+ reason: `Prerequisites met, tags: ${tagList}`
1236
+ };
1237
+ }
1238
+ const missingPrereqs = lockedTags.flatMap((tag) => {
1239
+ const prereqs = this.config.prerequisites[tag] || [];
1240
+ return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1241
+ });
1242
+ return {
1243
+ isUnlocked: false,
1244
+ reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1245
+ };
1246
+ } catch {
1247
+ return {
1248
+ isUnlocked: true,
1249
+ reason: "Prerequisites check skipped (tag lookup failed)"
1250
+ };
1251
+ }
1252
+ }
1253
+ /**
1254
+ * CardFilter.transform implementation.
1255
+ *
1256
+ * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1257
+ */
1258
+ async transform(cards, context) {
1259
+ const masteredTags = await this.getMasteredTags(context);
1260
+ const unlockedTags = this.getUnlockedTags(masteredTags);
1261
+ const gated = [];
1262
+ for (const card of cards) {
1263
+ const { isUnlocked, reason } = await this.checkCardUnlock(
1264
+ card,
1265
+ context.course,
1266
+ unlockedTags,
1267
+ masteredTags
1268
+ );
1269
+ const finalScore = isUnlocked ? card.score : 0;
1270
+ const action = isUnlocked ? "passed" : "penalized";
1271
+ gated.push({
1272
+ ...card,
1273
+ score: finalScore,
1274
+ provenance: [
1275
+ ...card.provenance,
1276
+ {
1277
+ strategy: "hierarchyDefinition",
1278
+ strategyName: this.strategyName || this.name,
1279
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1280
+ action,
1281
+ score: finalScore,
1282
+ reason
1283
+ }
1284
+ ]
1285
+ });
1286
+ }
1287
+ return gated;
1288
+ }
1289
+ /**
1290
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1291
+ *
1292
+ * Use transform() via Pipeline instead.
1293
+ */
1294
+ async getWeightedCards(_limit) {
1295
+ throw new Error(
1296
+ "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1297
+ );
1298
+ }
1299
+ };
1300
+ }
1301
+ });
1302
+
1303
+ // src/core/navigators/filters/userTagPreference.ts
1304
+ var userTagPreference_exports = {};
1305
+ __export(userTagPreference_exports, {
1306
+ default: () => UserTagPreferenceFilter
1307
+ });
1308
+ var UserTagPreferenceFilter;
1309
+ var init_userTagPreference = __esm({
1310
+ "src/core/navigators/filters/userTagPreference.ts"() {
1311
+ "use strict";
1312
+ init_navigators();
1313
+ UserTagPreferenceFilter = class extends ContentNavigator {
1314
+ _strategyData;
1315
+ /** Human-readable name for CardFilter interface */
1316
+ name;
1317
+ constructor(user, course, strategyData) {
1318
+ super(user, course, strategyData);
1319
+ this._strategyData = strategyData;
1320
+ this.name = strategyData.name || "User Tag Preferences";
1321
+ }
1322
+ /**
1323
+ * Compute multiplier for a card based on its tags and user preferences.
1324
+ * Returns the maximum multiplier among all matching tags, or 1.0 if no matches.
1325
+ */
1326
+ computeMultiplier(cardTags, boostMap) {
1327
+ const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== void 0);
1328
+ if (multipliers.length === 0) {
1329
+ return 1;
1330
+ }
1331
+ return Math.max(...multipliers);
1332
+ }
1333
+ /**
1334
+ * Build human-readable reason for the filter's decision.
1335
+ */
1336
+ buildReason(cardTags, boostMap, multiplier) {
1337
+ const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);
1338
+ if (multiplier === 0) {
1339
+ return `Excluded by user preference: ${matchingTags.join(", ")} (${multiplier}x)`;
1340
+ }
1341
+ if (multiplier < 1) {
1342
+ return `Penalized by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1343
+ }
1344
+ if (multiplier > 1) {
1345
+ return `Boosted by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1346
+ }
1347
+ return "No matching user preferences";
1348
+ }
1349
+ /**
1350
+ * CardFilter.transform implementation.
1351
+ *
1352
+ * Apply user tag preferences:
1353
+ * 1. Read preferences from strategy state
1354
+ * 2. If no preferences, pass through unchanged
1355
+ * 3. For each card:
1356
+ * - Look up tag in boost record
1357
+ * - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)
1358
+ * - If multiple tags match: use max multiplier
1359
+ * - Append provenance with clear reason
1360
+ */
1361
+ async transform(cards, _context) {
1362
+ const prefs = await this.getStrategyState();
1363
+ if (!prefs || Object.keys(prefs.boost).length === 0) {
1364
+ return cards.map((card) => ({
1365
+ ...card,
1366
+ provenance: [
1367
+ ...card.provenance,
1368
+ {
1369
+ strategy: "userTagPreference",
1370
+ strategyName: this.strategyName || this.name,
1371
+ strategyId: this.strategyId || this._strategyData._id,
1372
+ action: "passed",
1373
+ score: card.score,
1374
+ reason: "No user tag preferences configured"
1375
+ }
1376
+ ]
1377
+ }));
1378
+ }
1379
+ const adjusted = await Promise.all(
1380
+ cards.map(async (card) => {
1381
+ const cardTags = card.tags ?? [];
1382
+ const multiplier = this.computeMultiplier(cardTags, prefs.boost);
1383
+ const finalScore = Math.min(1, card.score * multiplier);
1384
+ let action;
1385
+ if (multiplier === 0 || multiplier < 1) {
1386
+ action = "penalized";
1387
+ } else if (multiplier > 1) {
1388
+ action = "boosted";
1389
+ } else {
1390
+ action = "passed";
1391
+ }
1392
+ return {
1393
+ ...card,
1394
+ score: finalScore,
1395
+ provenance: [
1396
+ ...card.provenance,
1397
+ {
1398
+ strategy: "userTagPreference",
1399
+ strategyName: this.strategyName || this.name,
1400
+ strategyId: this.strategyId || this._strategyData._id,
1401
+ action,
1402
+ score: finalScore,
1403
+ reason: this.buildReason(cardTags, prefs.boost, multiplier)
1404
+ }
1405
+ ]
1406
+ };
1407
+ })
1408
+ );
1409
+ return adjusted;
1410
+ }
1411
+ /**
1412
+ * Legacy getWeightedCards - throws as filters should not be used as generators.
1413
+ */
1414
+ async getWeightedCards(_limit) {
1415
+ throw new Error(
1416
+ "UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1417
+ );
1418
+ }
1419
+ };
1420
+ }
1421
+ });
1422
+
1423
+ // src/core/navigators/filters/index.ts
1424
+ var filters_exports = {};
1425
+ __export(filters_exports, {
1426
+ UserTagPreferenceFilter: () => UserTagPreferenceFilter,
1427
+ createEloDistanceFilter: () => createEloDistanceFilter
1428
+ });
1429
+ var init_filters = __esm({
1430
+ "src/core/navigators/filters/index.ts"() {
1431
+ "use strict";
1432
+ init_eloDistance();
1433
+ init_userTagPreference();
1434
+ }
1435
+ });
1436
+
1437
+ // src/core/navigators/filters/inferredPreferenceStub.ts
1438
+ var inferredPreferenceStub_exports = {};
1439
+ __export(inferredPreferenceStub_exports, {
1440
+ INFERRED_PREFERENCE_NAVIGATOR_STUB: () => INFERRED_PREFERENCE_NAVIGATOR_STUB
1441
+ });
1442
+ var INFERRED_PREFERENCE_NAVIGATOR_STUB;
1443
+ var init_inferredPreferenceStub = __esm({
1444
+ "src/core/navigators/filters/inferredPreferenceStub.ts"() {
1445
+ "use strict";
1446
+ INFERRED_PREFERENCE_NAVIGATOR_STUB = true;
1447
+ }
1448
+ });
1449
+
1450
+ // src/core/navigators/filters/interferenceMitigator.ts
1451
+ var interferenceMitigator_exports = {};
1452
+ __export(interferenceMitigator_exports, {
1453
+ default: () => InterferenceMitigatorNavigator
1454
+ });
1455
+ import { toCourseElo as toCourseElo4 } from "@vue-skuilder/common";
1456
+ var DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1457
+ var init_interferenceMitigator = __esm({
1458
+ "src/core/navigators/filters/interferenceMitigator.ts"() {
1459
+ "use strict";
1460
+ init_navigators();
1461
+ DEFAULT_MIN_COUNT2 = 10;
1462
+ DEFAULT_MIN_ELAPSED_DAYS = 3;
1463
+ DEFAULT_INTERFERENCE_DECAY = 0.8;
1464
+ InterferenceMitigatorNavigator = class extends ContentNavigator {
1465
+ config;
1466
+ /** Human-readable name for CardFilter interface */
1467
+ name;
1468
+ /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1469
+ interferenceMap;
1470
+ constructor(user, course, strategyData) {
1471
+ super(user, course, strategyData);
1472
+ this.config = this.parseConfig(strategyData.serializedData);
1473
+ this.interferenceMap = this.buildInterferenceMap();
1474
+ this.name = strategyData.name || "Interference Mitigator";
1475
+ }
1476
+ parseConfig(serializedData) {
1477
+ try {
1478
+ const parsed = JSON.parse(serializedData);
1479
+ let sets = parsed.interferenceSets || [];
1480
+ if (sets.length > 0 && Array.isArray(sets[0])) {
1481
+ sets = sets.map((tags) => ({ tags }));
1482
+ }
1483
+ return {
1484
+ interferenceSets: sets,
1485
+ maturityThreshold: {
1486
+ minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1487
+ minElo: parsed.maturityThreshold?.minElo,
1488
+ minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1489
+ },
1490
+ defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1491
+ };
1492
+ } catch {
1493
+ return {
1494
+ interferenceSets: [],
1495
+ maturityThreshold: {
1496
+ minCount: DEFAULT_MIN_COUNT2,
1497
+ minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1498
+ },
1499
+ defaultDecay: DEFAULT_INTERFERENCE_DECAY
1500
+ };
1501
+ }
1502
+ }
1503
+ /**
1504
+ * Build a map from each tag to its interference partners with decay coefficients.
1505
+ * If tags A, B, C are in an interference group with decay 0.8, then:
1506
+ * - A interferes with B (decay 0.8) and C (decay 0.8)
1507
+ * - B interferes with A (decay 0.8) and C (decay 0.8)
1508
+ * - etc.
1509
+ */
1510
+ buildInterferenceMap() {
1511
+ const map = /* @__PURE__ */ new Map();
1512
+ for (const group of this.config.interferenceSets) {
1513
+ const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
1514
+ for (const tag of group.tags) {
1515
+ if (!map.has(tag)) {
1516
+ map.set(tag, []);
1517
+ }
1518
+ const partners = map.get(tag);
1519
+ for (const other of group.tags) {
1520
+ if (other !== tag) {
1521
+ const existing = partners.find((p) => p.partner === other);
1522
+ if (existing) {
1523
+ existing.decay = Math.max(existing.decay, decay);
1524
+ } else {
1525
+ partners.push({ partner: other, decay });
1526
+ }
1527
+ }
1528
+ }
1529
+ }
1530
+ }
1531
+ return map;
1532
+ }
1533
+ /**
1534
+ * Get the set of tags that are currently immature for this user.
1535
+ * A tag is immature if the user has interacted with it but hasn't
1536
+ * reached the maturity threshold.
1537
+ */
1538
+ async getImmatureTags(context) {
1539
+ const immature = /* @__PURE__ */ new Set();
1540
+ try {
1541
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1542
+ const userElo = toCourseElo4(courseReg.elo);
1543
+ const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
1544
+ const minElo = this.config.maturityThreshold?.minElo;
1545
+ const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
1546
+ const minCountForElapsed = minElapsedDays * 2;
1547
+ for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
1548
+ if (tagElo.count === 0) continue;
1549
+ const belowCount = tagElo.count < minCount;
1550
+ const belowElo = minElo !== void 0 && tagElo.score < minElo;
1551
+ const belowElapsed = tagElo.count < minCountForElapsed;
1552
+ if (belowCount || belowElo || belowElapsed) {
1553
+ immature.add(tagId);
1554
+ }
1555
+ }
1556
+ } catch {
1557
+ }
1558
+ return immature;
1559
+ }
1560
+ /**
1561
+ * Get all tags that interfere with any immature tag, along with their decay coefficients.
1562
+ * These are the tags we want to avoid introducing.
1563
+ */
1564
+ getTagsToAvoid(immatureTags) {
1565
+ const avoid = /* @__PURE__ */ new Map();
1566
+ for (const immatureTag of immatureTags) {
1567
+ const partners = this.interferenceMap.get(immatureTag);
1568
+ if (partners) {
1569
+ for (const { partner, decay } of partners) {
1570
+ if (!immatureTags.has(partner)) {
1571
+ const existing = avoid.get(partner) ?? 0;
1572
+ avoid.set(partner, Math.max(existing, decay));
1573
+ }
1574
+ }
1575
+ }
1576
+ }
1577
+ return avoid;
1578
+ }
1579
+ /**
1580
+ * Compute interference score reduction for a card.
1581
+ * Returns: { multiplier, interfering tags, reason }
1582
+ */
1583
+ computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
1584
+ if (tagsToAvoid.size === 0) {
1585
+ return {
1586
+ multiplier: 1,
1587
+ interferingTags: [],
1588
+ reason: "No interference detected"
1589
+ };
1590
+ }
1591
+ let multiplier = 1;
1592
+ const interferingTags = [];
1593
+ for (const tag of cardTags) {
1594
+ const decay = tagsToAvoid.get(tag);
1595
+ if (decay !== void 0) {
1596
+ interferingTags.push(tag);
1597
+ multiplier *= 1 - decay;
1598
+ }
1599
+ }
1600
+ if (interferingTags.length === 0) {
1601
+ return {
1602
+ multiplier: 1,
1603
+ interferingTags: [],
1604
+ reason: "No interference detected"
1605
+ };
1606
+ }
1607
+ const causingTags = /* @__PURE__ */ new Set();
1608
+ for (const tag of interferingTags) {
1609
+ for (const immatureTag of immatureTags) {
1610
+ const partners = this.interferenceMap.get(immatureTag);
1611
+ if (partners?.some((p) => p.partner === tag)) {
1612
+ causingTags.add(immatureTag);
1613
+ }
1614
+ }
1615
+ }
1616
+ const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
1617
+ return { multiplier, interferingTags, reason };
1618
+ }
1619
+ /**
1620
+ * CardFilter.transform implementation.
1621
+ *
1622
+ * Apply interference-aware scoring. Cards with tags that interfere with
1623
+ * immature learnings get reduced scores.
1624
+ */
1625
+ async transform(cards, context) {
1626
+ const immatureTags = await this.getImmatureTags(context);
1627
+ const tagsToAvoid = this.getTagsToAvoid(immatureTags);
1628
+ const adjusted = [];
1629
+ for (const card of cards) {
1630
+ const cardTags = card.tags ?? [];
1631
+ const { multiplier, reason } = this.computeInterferenceEffect(
1632
+ cardTags,
1633
+ tagsToAvoid,
1634
+ immatureTags
1635
+ );
1636
+ const finalScore = card.score * multiplier;
1637
+ const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
1638
+ adjusted.push({
1639
+ ...card,
1640
+ score: finalScore,
1641
+ provenance: [
1642
+ ...card.provenance,
1643
+ {
1644
+ strategy: "interferenceMitigator",
1645
+ strategyName: this.strategyName || this.name,
1646
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
1647
+ action,
1648
+ score: finalScore,
1649
+ reason
1650
+ }
1651
+ ]
1652
+ });
1653
+ }
1654
+ return adjusted;
1655
+ }
1656
+ /**
1657
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1658
+ *
1659
+ * Use transform() via Pipeline instead.
1660
+ */
1661
+ async getWeightedCards(_limit) {
1662
+ throw new Error(
1663
+ "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1664
+ );
1665
+ }
1666
+ };
1667
+ }
1668
+ });
1669
+
1670
+ // src/core/navigators/filters/relativePriority.ts
1671
+ var relativePriority_exports = {};
1672
+ __export(relativePriority_exports, {
1673
+ default: () => RelativePriorityNavigator
1674
+ });
1675
+ var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
1676
+ var init_relativePriority = __esm({
1677
+ "src/core/navigators/filters/relativePriority.ts"() {
1678
+ "use strict";
1679
+ init_navigators();
1680
+ DEFAULT_PRIORITY = 0.5;
1681
+ DEFAULT_PRIORITY_INFLUENCE = 0.5;
1682
+ DEFAULT_COMBINE_MODE = "max";
1683
+ RelativePriorityNavigator = class extends ContentNavigator {
1684
+ config;
1685
+ /** Human-readable name for CardFilter interface */
1686
+ name;
1687
+ constructor(user, course, strategyData) {
1688
+ super(user, course, strategyData);
1689
+ this.config = this.parseConfig(strategyData.serializedData);
1690
+ this.name = strategyData.name || "Relative Priority";
1691
+ }
1692
+ parseConfig(serializedData) {
1693
+ try {
1694
+ const parsed = JSON.parse(serializedData);
1695
+ return {
1696
+ tagPriorities: parsed.tagPriorities || {},
1697
+ defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
1698
+ combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
1699
+ priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
1700
+ };
1701
+ } catch {
1702
+ return {
1703
+ tagPriorities: {},
1704
+ defaultPriority: DEFAULT_PRIORITY,
1705
+ combineMode: DEFAULT_COMBINE_MODE,
1706
+ priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
1707
+ };
1708
+ }
1709
+ }
1710
+ /**
1711
+ * Look up the priority for a tag.
1712
+ */
1713
+ getTagPriority(tagId) {
1714
+ return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
1715
+ }
1716
+ /**
1717
+ * Compute combined priority for a card based on its tags.
1718
+ */
1719
+ computeCardPriority(cardTags) {
1720
+ if (cardTags.length === 0) {
1721
+ return this.config.defaultPriority ?? DEFAULT_PRIORITY;
1722
+ }
1723
+ const priorities = cardTags.map((tag) => this.getTagPriority(tag));
1724
+ switch (this.config.combineMode) {
1725
+ case "max":
1726
+ return Math.max(...priorities);
1727
+ case "min":
1728
+ return Math.min(...priorities);
1729
+ case "average":
1730
+ return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
1731
+ default:
1732
+ return Math.max(...priorities);
1733
+ }
1734
+ }
1735
+ /**
1736
+ * Compute boost factor based on priority.
1737
+ *
1738
+ * The formula: 1 + (priority - 0.5) * priorityInfluence
1739
+ *
1740
+ * This creates a multiplier centered around 1.0:
1741
+ * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
1742
+ * - Priority 0.5 with any influence → 1.00 (neutral)
1743
+ * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
1744
+ */
1745
+ computeBoostFactor(priority) {
1746
+ const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
1747
+ return 1 + (priority - 0.5) * influence;
1748
+ }
1749
+ /**
1750
+ * Build human-readable reason for priority adjustment.
1751
+ */
1752
+ buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
1753
+ if (cardTags.length === 0) {
1754
+ return `No tags, neutral priority (${priority.toFixed(2)})`;
1755
+ }
1756
+ const tagList = cardTags.slice(0, 3).join(", ");
1757
+ const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
1758
+ if (boostFactor === 1) {
1759
+ return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
1760
+ } else if (boostFactor > 1) {
1761
+ return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1762
+ } else {
1763
+ return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1764
+ }
1765
+ }
1766
+ /**
1767
+ * CardFilter.transform implementation.
1768
+ *
1769
+ * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
1770
+ * cards with low-priority tags get reduced scores.
1771
+ */
1772
+ async transform(cards, _context) {
1773
+ const adjusted = await Promise.all(
1774
+ cards.map(async (card) => {
1775
+ const cardTags = card.tags ?? [];
1776
+ const priority = this.computeCardPriority(cardTags);
1777
+ const boostFactor = this.computeBoostFactor(priority);
1778
+ const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
1779
+ const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
1780
+ const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
1781
+ return {
1782
+ ...card,
1783
+ score: finalScore,
1784
+ provenance: [
1785
+ ...card.provenance,
1786
+ {
1787
+ strategy: "relativePriority",
1788
+ strategyName: this.strategyName || this.name,
1789
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
1790
+ action,
1791
+ score: finalScore,
1792
+ reason
1793
+ }
1794
+ ]
1795
+ };
1796
+ })
1797
+ );
1798
+ return adjusted;
1799
+ }
1800
+ /**
1801
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1802
+ *
1803
+ * Use transform() via Pipeline instead.
1804
+ */
1805
+ async getWeightedCards(_limit) {
1806
+ throw new Error(
1807
+ "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1808
+ );
1809
+ }
1810
+ };
1811
+ }
1812
+ });
1813
+
1814
+ // src/core/navigators/filters/types.ts
1815
+ var types_exports2 = {};
1816
+ var init_types2 = __esm({
1817
+ "src/core/navigators/filters/types.ts"() {
1818
+ "use strict";
1819
+ }
1820
+ });
1821
+
1822
+ // src/core/navigators/filters/userGoalStub.ts
1823
+ var userGoalStub_exports = {};
1824
+ __export(userGoalStub_exports, {
1825
+ USER_GOAL_NAVIGATOR_STUB: () => USER_GOAL_NAVIGATOR_STUB
1826
+ });
1827
+ var USER_GOAL_NAVIGATOR_STUB;
1828
+ var init_userGoalStub = __esm({
1829
+ "src/core/navigators/filters/userGoalStub.ts"() {
1830
+ "use strict";
1831
+ USER_GOAL_NAVIGATOR_STUB = true;
1832
+ }
1833
+ });
1834
+
1835
+ // import("./filters/**/*") in src/core/navigators/index.ts
1836
+ var globImport_filters;
1837
+ var init_2 = __esm({
1838
+ 'import("./filters/**/*") in src/core/navigators/index.ts'() {
1839
+ globImport_filters = __glob({
1840
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
1841
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
1842
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
1843
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
1844
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
1845
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
1846
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
1847
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
1848
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
1849
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
1850
+ });
1851
+ }
1852
+ });
1853
+
1854
+ // src/core/orchestration/gradient.ts
1855
+ var init_gradient = __esm({
1856
+ "src/core/orchestration/gradient.ts"() {
1857
+ "use strict";
1858
+ init_logger();
1859
+ }
1860
+ });
1861
+
1862
+ // src/core/orchestration/learning.ts
1863
+ var init_learning = __esm({
1864
+ "src/core/orchestration/learning.ts"() {
1865
+ "use strict";
1866
+ init_contentNavigationStrategy();
1867
+ init_types_legacy();
1868
+ init_logger();
1869
+ }
1870
+ });
1871
+
1872
+ // src/core/orchestration/signal.ts
1873
+ var init_signal = __esm({
1874
+ "src/core/orchestration/signal.ts"() {
1875
+ "use strict";
1876
+ }
1877
+ });
1878
+
1879
+ // src/core/orchestration/recording.ts
1880
+ var init_recording = __esm({
1881
+ "src/core/orchestration/recording.ts"() {
1882
+ "use strict";
1883
+ init_signal();
1884
+ init_types_legacy();
1885
+ init_logger();
1886
+ }
1887
+ });
1888
+
1889
+ // src/core/orchestration/index.ts
1890
+ function fnv1a(str) {
1891
+ let hash = 2166136261;
1892
+ for (let i = 0; i < str.length; i++) {
1893
+ hash ^= str.charCodeAt(i);
1894
+ hash = Math.imul(hash, 16777619);
1895
+ }
1896
+ return hash >>> 0;
1897
+ }
1898
+ function computeDeviation(userId, strategyId, salt) {
1899
+ const input = `${userId}:${strategyId}:${salt}`;
1900
+ const hash = fnv1a(input);
1901
+ const normalized = hash / 4294967296;
1902
+ return normalized * 2 - 1;
1903
+ }
1904
+ function computeSpread(confidence) {
1905
+ const clampedConfidence = Math.max(0, Math.min(1, confidence));
1906
+ return MAX_SPREAD - clampedConfidence * (MAX_SPREAD - MIN_SPREAD);
1907
+ }
1908
+ function computeEffectiveWeight(learnable, userId, strategyId, salt) {
1909
+ const deviation = computeDeviation(userId, strategyId, salt);
1910
+ const spread = computeSpread(learnable.confidence);
1911
+ const adjustment = deviation * spread * learnable.weight;
1912
+ const effective = learnable.weight + adjustment;
1913
+ return Math.max(MIN_WEIGHT, Math.min(MAX_WEIGHT, effective));
1914
+ }
1915
+ async function createOrchestrationContext(user, course) {
1916
+ let courseConfig;
1917
+ try {
1918
+ courseConfig = await course.getCourseConfig();
1919
+ } catch (e) {
1920
+ logger.error(`[Orchestration] Failed to load course config: ${e}`);
1921
+ courseConfig = {
1922
+ name: "Unknown",
1923
+ description: "",
1924
+ public: false,
1925
+ deleted: false,
1926
+ creator: "",
1927
+ admins: [],
1928
+ moderators: [],
1929
+ dataShapes: [],
1930
+ questionTypes: [],
1931
+ orchestration: { salt: "default" }
1932
+ };
1933
+ }
1934
+ const userId = user.getUsername();
1935
+ const salt = courseConfig.orchestration?.salt || "default_salt";
1936
+ return {
1937
+ user,
1938
+ course,
1939
+ userId,
1940
+ courseConfig,
1941
+ getEffectiveWeight(strategyId, learnable) {
1942
+ return computeEffectiveWeight(learnable, userId, strategyId, salt);
1943
+ },
1944
+ getDeviation(strategyId) {
1945
+ return computeDeviation(userId, strategyId, salt);
1946
+ }
1947
+ };
1948
+ }
1949
+ var MIN_SPREAD, MAX_SPREAD, MIN_WEIGHT, MAX_WEIGHT;
1950
+ var init_orchestration = __esm({
1951
+ "src/core/orchestration/index.ts"() {
1952
+ "use strict";
1953
+ init_logger();
1954
+ init_gradient();
1955
+ init_learning();
1956
+ init_signal();
1957
+ init_recording();
1958
+ MIN_SPREAD = 0.1;
1959
+ MAX_SPREAD = 0.5;
1960
+ MIN_WEIGHT = 0.1;
1961
+ MAX_WEIGHT = 3;
1962
+ }
1963
+ });
1964
+
1965
+ // src/core/navigators/Pipeline.ts
1966
+ var Pipeline_exports = {};
1967
+ __export(Pipeline_exports, {
1968
+ Pipeline: () => Pipeline
1969
+ });
1970
+ import { toCourseElo as toCourseElo5 } from "@vue-skuilder/common";
1971
+ function logPipelineConfig(generator, filters) {
1972
+ const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
1973
+ logger.info(
1974
+ `[Pipeline] Configuration:
1975
+ Generator: ${generator.name}
1976
+ Filters:${filterList}`
1977
+ );
1978
+ }
1979
+ function logTagHydration(cards, tagsByCard) {
1980
+ const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
1981
+ const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
1982
+ logger.debug(
1983
+ `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
763
1984
  );
764
1985
  }
765
1986
  function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores) {
@@ -788,6 +2009,7 @@ var init_Pipeline = __esm({
788
2009
  "use strict";
789
2010
  init_navigators();
790
2011
  init_logger();
2012
+ init_orchestration();
791
2013
  Pipeline = class extends ContentNavigator {
792
2014
  generator;
793
2015
  filters;
@@ -867,194 +2089,93 @@ var init_Pipeline = __esm({
867
2089
  * @returns Cards with tags populated
868
2090
  */
869
2091
  async hydrateTags(cards) {
870
- if (cards.length === 0) {
871
- return cards;
872
- }
873
- const cardIds = cards.map((c) => c.cardId);
874
- const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
875
- logTagHydration(cards, tagsByCard);
876
- return cards.map((card) => ({
877
- ...card,
878
- tags: tagsByCard.get(card.cardId) ?? []
879
- }));
880
- }
881
- /**
882
- * Build shared context for generator and filters.
883
- *
884
- * Called once per getWeightedCards() invocation.
885
- * Contains data that the generator and multiple filters might need.
886
- *
887
- * The context satisfies both GeneratorContext and FilterContext interfaces.
888
- */
889
- async buildContext() {
890
- let userElo = 1e3;
891
- try {
892
- const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
893
- const courseElo = toCourseElo2(courseReg.elo);
894
- userElo = courseElo.global.score;
895
- } catch (e) {
896
- logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
897
- }
898
- return {
899
- user: this.user,
900
- course: this.course,
901
- userElo
902
- };
903
- }
904
- /**
905
- * Get the course ID for this pipeline.
906
- */
907
- getCourseID() {
908
- return this.course.getCourseID();
909
- }
910
- };
911
- }
912
- });
913
-
914
- // src/core/navigators/generators/CompositeGenerator.ts
915
- var DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
916
- var init_CompositeGenerator = __esm({
917
- "src/core/navigators/generators/CompositeGenerator.ts"() {
918
- "use strict";
919
- init_navigators();
920
- init_logger();
921
- DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
922
- FREQUENCY_BOOST_FACTOR = 0.1;
923
- CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
924
- /** Human-readable name for CardGenerator interface */
925
- name = "Composite Generator";
926
- generators;
927
- aggregationMode;
928
- constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
929
- super();
930
- this.generators = generators;
931
- this.aggregationMode = aggregationMode;
932
- if (generators.length === 0) {
933
- throw new Error("CompositeGenerator requires at least one generator");
934
- }
935
- logger.debug(
936
- `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
937
- );
938
- }
939
- /**
940
- * Creates a CompositeGenerator from strategy data.
941
- *
942
- * This is a convenience factory for use by PipelineAssembler.
943
- */
944
- static async fromStrategies(user, course, strategies, aggregationMode = DEFAULT_AGGREGATION_MODE) {
945
- const generators = await Promise.all(
946
- strategies.map((s) => ContentNavigator.create(user, course, s))
947
- );
948
- return new _CompositeGenerator(generators, aggregationMode);
949
- }
950
- /**
951
- * Get weighted cards from all generators, merge and deduplicate.
952
- *
953
- * Cards appearing in multiple generators receive a score boost.
954
- * Provenance tracks which generators produced each card and how scores were aggregated.
955
- *
956
- * This method supports both the legacy signature (limit only) and the
957
- * CardGenerator interface signature (limit, context).
958
- *
959
- * @param limit - Maximum number of cards to return
960
- * @param context - GeneratorContext passed to child generators (required when called via Pipeline)
961
- */
962
- async getWeightedCards(limit, context) {
963
- if (!context) {
964
- throw new Error(
965
- "CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly."
966
- );
967
- }
968
- const results = await Promise.all(
969
- this.generators.map((g) => g.getWeightedCards(limit, context))
970
- );
971
- const byCardId = /* @__PURE__ */ new Map();
972
- for (const cards of results) {
973
- for (const card of cards) {
974
- const existing = byCardId.get(card.cardId) || [];
975
- existing.push(card);
976
- byCardId.set(card.cardId, existing);
977
- }
978
- }
979
- const merged = [];
980
- for (const [, cards] of byCardId) {
981
- const aggregatedScore = this.aggregateScores(cards);
982
- const finalScore = Math.min(1, aggregatedScore);
983
- const mergedProvenance = cards.flatMap((c) => c.provenance);
984
- const initialScore = cards[0].score;
985
- const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
986
- const reason = this.buildAggregationReason(cards, finalScore);
987
- merged.push({
988
- ...cards[0],
989
- score: finalScore,
990
- provenance: [
991
- ...mergedProvenance,
992
- {
993
- strategy: "composite",
994
- strategyName: "Composite Generator",
995
- strategyId: "COMPOSITE_GENERATOR",
996
- action,
997
- score: finalScore,
998
- reason
999
- }
1000
- ]
1001
- });
2092
+ if (cards.length === 0) {
2093
+ return cards;
1002
2094
  }
1003
- return merged.sort((a, b) => b.score - a.score).slice(0, limit);
2095
+ const cardIds = cards.map((c) => c.cardId);
2096
+ const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
2097
+ logTagHydration(cards, tagsByCard);
2098
+ return cards.map((card) => ({
2099
+ ...card,
2100
+ tags: tagsByCard.get(card.cardId) ?? []
2101
+ }));
1004
2102
  }
1005
2103
  /**
1006
- * Build human-readable reason for score aggregation.
2104
+ * Build shared context for generator and filters.
2105
+ *
2106
+ * Called once per getWeightedCards() invocation.
2107
+ * Contains data that the generator and multiple filters might need.
2108
+ *
2109
+ * The context satisfies both GeneratorContext and FilterContext interfaces.
1007
2110
  */
1008
- buildAggregationReason(cards, finalScore) {
1009
- const count = cards.length;
1010
- const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
1011
- if (count === 1) {
1012
- return `Single generator, score ${finalScore.toFixed(2)}`;
1013
- }
1014
- const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
1015
- switch (this.aggregationMode) {
1016
- case "max" /* MAX */:
1017
- return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
1018
- case "average" /* AVERAGE */:
1019
- return `Average of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
1020
- case "frequencyBoost" /* FREQUENCY_BOOST */: {
1021
- const avg = cards.reduce((sum, c) => sum + c.score, 0) / count;
1022
- const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
1023
- return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
1024
- }
1025
- default:
1026
- return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
2111
+ async buildContext() {
2112
+ let userElo = 1e3;
2113
+ try {
2114
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
2115
+ const courseElo = toCourseElo5(courseReg.elo);
2116
+ userElo = courseElo.global.score;
2117
+ } catch (e) {
2118
+ logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
1027
2119
  }
2120
+ const orchestration = await createOrchestrationContext(this.user, this.course);
2121
+ return {
2122
+ user: this.user,
2123
+ course: this.course,
2124
+ userElo,
2125
+ orchestration
2126
+ };
1028
2127
  }
1029
2128
  /**
1030
- * Aggregate scores from multiple generators for the same card.
2129
+ * Get the course ID for this pipeline.
1031
2130
  */
1032
- aggregateScores(cards) {
1033
- const scores = cards.map((c) => c.score);
1034
- switch (this.aggregationMode) {
1035
- case "max" /* MAX */:
1036
- return Math.max(...scores);
1037
- case "average" /* AVERAGE */:
1038
- return scores.reduce((sum, s) => sum + s, 0) / scores.length;
1039
- case "frequencyBoost" /* FREQUENCY_BOOST */: {
1040
- const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
1041
- const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (cards.length - 1);
1042
- return avg * frequencyBoost;
1043
- }
1044
- default:
1045
- return scores[0];
2131
+ getCourseID() {
2132
+ return this.course.getCourseID();
2133
+ }
2134
+ /**
2135
+ * Get orchestration context for outcome recording.
2136
+ */
2137
+ async getOrchestrationContext() {
2138
+ return createOrchestrationContext(this.user, this.course);
2139
+ }
2140
+ /**
2141
+ * Get IDs of all strategies in this pipeline.
2142
+ * Used to record which strategies contributed to an outcome.
2143
+ */
2144
+ getStrategyIds() {
2145
+ const ids = [];
2146
+ const extractId = (obj) => {
2147
+ if (obj.strategyId) return obj.strategyId;
2148
+ return null;
2149
+ };
2150
+ const genId = extractId(this.generator);
2151
+ if (genId) ids.push(genId);
2152
+ if (this.generator.generators && Array.isArray(this.generator.generators)) {
2153
+ this.generator.generators.forEach((g) => {
2154
+ const subId = extractId(g);
2155
+ if (subId) ids.push(subId);
2156
+ });
2157
+ }
2158
+ for (const filter of this.filters) {
2159
+ const fId = extractId(filter);
2160
+ if (fId) ids.push(fId);
1046
2161
  }
2162
+ return [...new Set(ids)];
1047
2163
  }
1048
2164
  };
1049
2165
  }
1050
2166
  });
1051
2167
 
1052
2168
  // src/core/navigators/PipelineAssembler.ts
2169
+ var PipelineAssembler_exports = {};
2170
+ __export(PipelineAssembler_exports, {
2171
+ PipelineAssembler: () => PipelineAssembler
2172
+ });
1053
2173
  var PipelineAssembler;
1054
2174
  var init_PipelineAssembler = __esm({
1055
2175
  "src/core/navigators/PipelineAssembler.ts"() {
1056
2176
  "use strict";
1057
2177
  init_navigators();
2178
+ init_WeightedFilter();
1058
2179
  init_Pipeline();
1059
2180
  init_types_legacy();
1060
2181
  init_logger();
@@ -1129,7 +2250,16 @@ var init_PipelineAssembler = __esm({
1129
2250
  try {
1130
2251
  const nav = await ContentNavigator.create(user, course, filterStrategy);
1131
2252
  if ("transform" in nav && typeof nav.transform === "function") {
1132
- filters.push(nav);
2253
+ let filter = nav;
2254
+ if (filterStrategy.learnable) {
2255
+ filter = new WeightedFilter(
2256
+ filter,
2257
+ filterStrategy.learnable,
2258
+ filterStrategy.staticWeight,
2259
+ filterStrategy._id
2260
+ );
2261
+ }
2262
+ filters.push(filter);
1133
2263
  logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
1134
2264
  } else {
1135
2265
  warnings.push(
@@ -1140,252 +2270,43 @@ var init_PipelineAssembler = __esm({
1140
2270
  warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
1141
2271
  }
1142
2272
  }
1143
- const pipeline = new Pipeline(generator, filters, user, course);
1144
- logger.debug(
1145
- `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
1146
- );
1147
- return {
1148
- pipeline,
1149
- generatorStrategies,
1150
- filterStrategies: sortedFilterStrategies,
1151
- warnings
1152
- };
1153
- }
1154
- /**
1155
- * Creates a default ELO generator strategy.
1156
- * Used when filters are configured but no generator is specified.
1157
- */
1158
- makeDefaultEloStrategy(courseId) {
1159
- return {
1160
- _id: "NAVIGATION_STRATEGY-ELO-default",
1161
- course: courseId,
1162
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1163
- name: "ELO (default)",
1164
- description: "Default ELO-based generator",
1165
- implementingClass: "elo" /* ELO */,
1166
- serializedData: ""
1167
- };
1168
- }
1169
- };
1170
- }
1171
- });
1172
-
1173
- // src/core/navigators/generators/elo.ts
1174
- import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
1175
- var ELONavigator;
1176
- var init_elo = __esm({
1177
- "src/core/navigators/generators/elo.ts"() {
1178
- "use strict";
1179
- init_navigators();
1180
- ELONavigator = class extends ContentNavigator {
1181
- /** Human-readable name for CardGenerator interface */
1182
- name;
1183
- constructor(user, course, strategyData) {
1184
- super(user, course, strategyData);
1185
- this.name = strategyData?.name || "ELO";
1186
- }
1187
- /**
1188
- * Get new cards with suitability scores based on ELO distance.
1189
- *
1190
- * Cards closer to user's ELO get higher scores.
1191
- * Score formula: max(0, 1 - distance / 500)
1192
- *
1193
- * NOTE: This generator only handles NEW cards. Reviews are handled by
1194
- * SRSNavigator. Use CompositeGenerator to combine both.
1195
- *
1196
- * This method supports both the legacy signature (limit only) and the
1197
- * CardGenerator interface signature (limit, context).
1198
- *
1199
- * @param limit - Maximum number of cards to return
1200
- * @param context - Optional GeneratorContext (used when called via Pipeline)
1201
- */
1202
- async getWeightedCards(limit, context) {
1203
- let userGlobalElo;
1204
- if (context?.userElo !== void 0) {
1205
- userGlobalElo = context.userElo;
1206
- } else {
1207
- const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1208
- const userElo = toCourseElo3(courseReg.elo);
1209
- userGlobalElo = userElo.global.score;
1210
- }
1211
- const activeCards = await this.user.getActiveCards();
1212
- const newCards = (await this.course.getCardsCenteredAtELO(
1213
- { limit, elo: "user" },
1214
- (c) => !activeCards.some((ac) => c.cardID === ac.cardID)
1215
- )).map((c) => ({ ...c, status: "new" }));
1216
- const cardIds = newCards.map((c) => c.cardID);
1217
- const cardEloData = await this.course.getCardEloData(cardIds);
1218
- const scored = newCards.map((c, i) => {
1219
- const cardElo = cardEloData[i]?.global?.score ?? 1e3;
1220
- const distance = Math.abs(cardElo - userGlobalElo);
1221
- const score = Math.max(0, 1 - distance / 500);
1222
- return {
1223
- cardId: c.cardID,
1224
- courseId: c.courseID,
1225
- score,
1226
- provenance: [
1227
- {
1228
- strategy: "elo",
1229
- strategyName: this.strategyName || this.name,
1230
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1231
- action: "generated",
1232
- score,
1233
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), new card`
1234
- }
1235
- ]
1236
- };
1237
- });
1238
- scored.sort((a, b) => b.score - a.score);
1239
- return scored.slice(0, limit);
1240
- }
1241
- };
1242
- }
1243
- });
1244
-
1245
- // src/core/navigators/generators/srs.ts
1246
- import moment from "moment";
1247
- var SRSNavigator;
1248
- var init_srs = __esm({
1249
- "src/core/navigators/generators/srs.ts"() {
1250
- "use strict";
1251
- init_navigators();
1252
- init_logger();
1253
- SRSNavigator = class extends ContentNavigator {
1254
- /** Human-readable name for CardGenerator interface */
1255
- name;
1256
- constructor(user, course, strategyData) {
1257
- super(user, course, strategyData);
1258
- this.name = strategyData?.name || "SRS";
1259
- }
1260
- /**
1261
- * Get review cards scored by urgency.
1262
- *
1263
- * Score formula combines:
1264
- * - Relative overdueness: hoursOverdue / intervalHours
1265
- * - Interval recency: exponential decay favoring shorter intervals
1266
- *
1267
- * Cards not yet due are excluded (not scored as 0).
1268
- *
1269
- * This method supports both the legacy signature (limit only) and the
1270
- * CardGenerator interface signature (limit, context).
1271
- *
1272
- * @param limit - Maximum number of cards to return
1273
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1274
- */
1275
- async getWeightedCards(limit, _context) {
1276
- if (!this.user || !this.course) {
1277
- throw new Error("SRSNavigator requires user and course to be set");
1278
- }
1279
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1280
- const now = moment.utc();
1281
- const dueReviews = reviews.filter((r) => now.isAfter(moment.utc(r.reviewTime)));
1282
- const scored = dueReviews.map((review) => {
1283
- const { score, reason } = this.computeUrgencyScore(review, now);
1284
- return {
1285
- cardId: review.cardId,
1286
- courseId: review.courseId,
1287
- score,
1288
- reviewID: review._id,
1289
- provenance: [
1290
- {
1291
- strategy: "srs",
1292
- strategyName: this.strategyName || this.name,
1293
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1294
- action: "generated",
1295
- score,
1296
- reason
1297
- }
1298
- ]
1299
- };
1300
- });
1301
- logger.debug(`[srsNav] got ${scored.length} weighted cards`);
1302
- return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1303
- }
1304
- /**
1305
- * Compute urgency score for a review card.
1306
- *
1307
- * Two factors:
1308
- * 1. Relative overdueness = hoursOverdue / intervalHours
1309
- * - 2 days overdue on 3-day interval = 0.67 (urgent)
1310
- * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1311
- *
1312
- * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1313
- * - 24h interval → ~1.0 (very recent learning)
1314
- * - 30 days (720h) → ~0.56
1315
- * - 180 days → ~0.30
1316
- *
1317
- * Combined: base 0.5 + weighted average of factors * 0.45
1318
- * Result range: approximately 0.5 to 0.95
1319
- */
1320
- computeUrgencyScore(review, now) {
1321
- const scheduledAt = moment.utc(review.scheduledAt);
1322
- const due = moment.utc(review.reviewTime);
1323
- const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1324
- const hoursOverdue = now.diff(due, "hours");
1325
- const relativeOverdue = hoursOverdue / intervalHours;
1326
- const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1327
- const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1328
- const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1329
- const score = Math.min(0.95, 0.5 + urgency * 0.45);
1330
- const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
1331
- return { score, reason };
2273
+ const pipeline = new Pipeline(generator, filters, user, course);
2274
+ logger.debug(
2275
+ `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
2276
+ );
2277
+ return {
2278
+ pipeline,
2279
+ generatorStrategies,
2280
+ filterStrategies: sortedFilterStrategies,
2281
+ warnings
2282
+ };
1332
2283
  }
1333
- };
1334
- }
1335
- });
1336
-
1337
- // src/core/navigators/filters/eloDistance.ts
1338
- function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1339
- const normalizedDistance = distance / halfLife;
1340
- const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1341
- return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1342
- }
1343
- function createEloDistanceFilter(config) {
1344
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1345
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1346
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1347
- return {
1348
- name: "ELO Distance Filter",
1349
- async transform(cards, context) {
1350
- const { course, userElo } = context;
1351
- const cardIds = cards.map((c) => c.cardId);
1352
- const cardElos = await course.getCardEloData(cardIds);
1353
- return cards.map((card, i) => {
1354
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
1355
- const distance = Math.abs(cardElo - userElo);
1356
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1357
- const newScore = card.score * multiplier;
1358
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
2284
+ /**
2285
+ * Creates a default ELO generator strategy.
2286
+ * Used when filters are configured but no generator is specified.
2287
+ */
2288
+ makeDefaultEloStrategy(courseId) {
1359
2289
  return {
1360
- ...card,
1361
- score: newScore,
1362
- provenance: [
1363
- ...card.provenance,
1364
- {
1365
- strategy: "eloDistance",
1366
- strategyName: "ELO Distance Filter",
1367
- strategyId: "ELO_DISTANCE_FILTER",
1368
- action,
1369
- score: newScore,
1370
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1371
- }
1372
- ]
2290
+ _id: "NAVIGATION_STRATEGY-ELO-default",
2291
+ course: courseId,
2292
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
2293
+ name: "ELO (default)",
2294
+ description: "Default ELO-based generator",
2295
+ implementingClass: "elo" /* ELO */,
2296
+ serializedData: ""
1373
2297
  };
1374
- });
1375
- }
1376
- };
1377
- }
1378
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1379
- var init_eloDistance = __esm({
1380
- "src/core/navigators/filters/eloDistance.ts"() {
1381
- "use strict";
1382
- DEFAULT_HALF_LIFE = 200;
1383
- DEFAULT_MIN_MULTIPLIER = 0.3;
1384
- DEFAULT_MAX_MULTIPLIER = 1;
2298
+ }
2299
+ };
1385
2300
  }
1386
2301
  });
1387
2302
 
1388
2303
  // src/core/navigators/defaults.ts
2304
+ var defaults_exports = {};
2305
+ __export(defaults_exports, {
2306
+ createDefaultEloStrategy: () => createDefaultEloStrategy,
2307
+ createDefaultPipeline: () => createDefaultPipeline,
2308
+ createDefaultSrsStrategy: () => createDefaultSrsStrategy
2309
+ });
1389
2310
  function createDefaultEloStrategy(courseId) {
1390
2311
  return {
1391
2312
  _id: "NAVIGATION_STRATEGY-ELO-default",
@@ -1429,12 +2350,310 @@ var init_defaults = __esm({
1429
2350
  }
1430
2351
  });
1431
2352
 
2353
+ // import("./**/*") in src/core/navigators/index.ts
2354
+ var globImport;
2355
+ var init_3 = __esm({
2356
+ 'import("./**/*") in src/core/navigators/index.ts'() {
2357
+ globImport = __glob({
2358
+ "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
2359
+ "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
2360
+ "./defaults.ts": () => Promise.resolve().then(() => (init_defaults(), defaults_exports)),
2361
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
2362
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2363
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2364
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2365
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
2366
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2367
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2368
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
2369
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
2370
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
2371
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
2372
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
2373
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
2374
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
2375
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
2376
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
2377
+ });
2378
+ }
2379
+ });
2380
+
2381
+ // src/core/navigators/index.ts
2382
+ var navigators_exports = {};
2383
+ __export(navigators_exports, {
2384
+ ContentNavigator: () => ContentNavigator,
2385
+ NavigatorRole: () => NavigatorRole,
2386
+ NavigatorRoles: () => NavigatorRoles,
2387
+ Navigators: () => Navigators,
2388
+ getCardOrigin: () => getCardOrigin,
2389
+ getRegisteredNavigator: () => getRegisteredNavigator,
2390
+ getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
2391
+ hasRegisteredNavigator: () => hasRegisteredNavigator,
2392
+ initializeNavigatorRegistry: () => initializeNavigatorRegistry,
2393
+ isFilter: () => isFilter,
2394
+ isGenerator: () => isGenerator,
2395
+ registerNavigator: () => registerNavigator
2396
+ });
2397
+ function registerNavigator(implementingClass, constructor) {
2398
+ navigatorRegistry.set(implementingClass, constructor);
2399
+ logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}`);
2400
+ }
2401
+ function getRegisteredNavigator(implementingClass) {
2402
+ return navigatorRegistry.get(implementingClass);
2403
+ }
2404
+ function hasRegisteredNavigator(implementingClass) {
2405
+ return navigatorRegistry.has(implementingClass);
2406
+ }
2407
+ function getRegisteredNavigatorNames() {
2408
+ return Array.from(navigatorRegistry.keys());
2409
+ }
2410
+ async function initializeNavigatorRegistry() {
2411
+ logger.debug("[NavigatorRegistry] Initializing built-in navigators...");
2412
+ const [eloModule, srsModule] = await Promise.all([
2413
+ Promise.resolve().then(() => (init_elo(), elo_exports)),
2414
+ Promise.resolve().then(() => (init_srs(), srs_exports))
2415
+ ]);
2416
+ registerNavigator("elo", eloModule.default);
2417
+ registerNavigator("srs", srsModule.default);
2418
+ const [
2419
+ hierarchyModule,
2420
+ interferenceModule,
2421
+ relativePriorityModule,
2422
+ userTagPreferenceModule
2423
+ ] = await Promise.all([
2424
+ Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2425
+ Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2426
+ Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2427
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
2428
+ ]);
2429
+ registerNavigator("hierarchyDefinition", hierarchyModule.default);
2430
+ registerNavigator("interferenceMitigator", interferenceModule.default);
2431
+ registerNavigator("relativePriority", relativePriorityModule.default);
2432
+ registerNavigator("userTagPreference", userTagPreferenceModule.default);
2433
+ logger.debug(
2434
+ `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
2435
+ );
2436
+ }
2437
+ function getCardOrigin(card) {
2438
+ if (card.provenance.length === 0) {
2439
+ throw new Error("Card has no provenance - cannot determine origin");
2440
+ }
2441
+ const firstEntry = card.provenance[0];
2442
+ const reason = firstEntry.reason.toLowerCase();
2443
+ if (reason.includes("failed")) {
2444
+ return "failed";
2445
+ }
2446
+ if (reason.includes("review")) {
2447
+ return "review";
2448
+ }
2449
+ return "new";
2450
+ }
2451
+ function isGenerator(impl) {
2452
+ return NavigatorRoles[impl] === "generator" /* GENERATOR */;
2453
+ }
2454
+ function isFilter(impl) {
2455
+ return NavigatorRoles[impl] === "filter" /* FILTER */;
2456
+ }
2457
+ var navigatorRegistry, Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
2458
+ var init_navigators = __esm({
2459
+ "src/core/navigators/index.ts"() {
2460
+ "use strict";
2461
+ init_logger();
2462
+ init_();
2463
+ init_2();
2464
+ init_3();
2465
+ navigatorRegistry = /* @__PURE__ */ new Map();
2466
+ Navigators = /* @__PURE__ */ ((Navigators2) => {
2467
+ Navigators2["ELO"] = "elo";
2468
+ Navigators2["SRS"] = "srs";
2469
+ Navigators2["HIERARCHY"] = "hierarchyDefinition";
2470
+ Navigators2["INTERFERENCE"] = "interferenceMitigator";
2471
+ Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
2472
+ Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
2473
+ return Navigators2;
2474
+ })(Navigators || {});
2475
+ NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
2476
+ NavigatorRole2["GENERATOR"] = "generator";
2477
+ NavigatorRole2["FILTER"] = "filter";
2478
+ return NavigatorRole2;
2479
+ })(NavigatorRole || {});
2480
+ NavigatorRoles = {
2481
+ ["elo" /* ELO */]: "generator" /* GENERATOR */,
2482
+ ["srs" /* SRS */]: "generator" /* GENERATOR */,
2483
+ ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
2484
+ ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
2485
+ ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
2486
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
2487
+ };
2488
+ ContentNavigator = class {
2489
+ /** User interface for this navigation session */
2490
+ user;
2491
+ /** Course interface for this navigation session */
2492
+ course;
2493
+ /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
2494
+ strategyName;
2495
+ /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
2496
+ strategyId;
2497
+ /** Evolutionary weighting configuration */
2498
+ learnable;
2499
+ /** Whether to bypass deviation (manual/static weighting) */
2500
+ staticWeight;
2501
+ /**
2502
+ * Constructor for standard navigators.
2503
+ * Call this from subclass constructors to initialize common fields.
2504
+ *
2505
+ * Note: CompositeGenerator and Pipeline call super() without args, then set
2506
+ * user/course fields directly if needed.
2507
+ */
2508
+ constructor(user, course, strategyData) {
2509
+ this.user = user;
2510
+ this.course = course;
2511
+ if (strategyData) {
2512
+ this.strategyName = strategyData.name;
2513
+ this.strategyId = strategyData._id;
2514
+ this.learnable = strategyData.learnable;
2515
+ this.staticWeight = strategyData.staticWeight;
2516
+ }
2517
+ }
2518
+ // ============================================================================
2519
+ // STRATEGY STATE HELPERS
2520
+ // ============================================================================
2521
+ //
2522
+ // These methods allow strategies to persist their own state (user preferences,
2523
+ // learned patterns, temporal tracking) in the user database.
2524
+ //
2525
+ // ============================================================================
2526
+ /**
2527
+ * Unique key identifying this strategy for state storage.
2528
+ *
2529
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
2530
+ * Override in subclasses if multiple instances of the same strategy type
2531
+ * need separate state storage.
2532
+ */
2533
+ get strategyKey() {
2534
+ return this.constructor.name;
2535
+ }
2536
+ /**
2537
+ * Get this strategy's persisted state for the current course.
2538
+ *
2539
+ * @returns The strategy's data payload, or null if no state exists
2540
+ * @throws Error if user or course is not initialized
2541
+ */
2542
+ async getStrategyState() {
2543
+ if (!this.user || !this.course) {
2544
+ throw new Error(
2545
+ `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2546
+ );
2547
+ }
2548
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
2549
+ }
2550
+ /**
2551
+ * Persist this strategy's state for the current course.
2552
+ *
2553
+ * @param data - The strategy's data payload to store
2554
+ * @throws Error if user or course is not initialized
2555
+ */
2556
+ async putStrategyState(data) {
2557
+ if (!this.user || !this.course) {
2558
+ throw new Error(
2559
+ `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2560
+ );
2561
+ }
2562
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
2563
+ }
2564
+ /**
2565
+ * Factory method to create navigator instances.
2566
+ *
2567
+ * First checks the navigator registry for a pre-registered constructor.
2568
+ * If not found, falls back to dynamic import (for custom navigators).
2569
+ *
2570
+ * For reliable operation in test environments, call initializeNavigatorRegistry()
2571
+ * before using this method.
2572
+ *
2573
+ * @param user - User interface
2574
+ * @param course - Course interface
2575
+ * @param strategyData - Strategy configuration document
2576
+ * @returns the runtime object used to steer a study session.
2577
+ */
2578
+ static async create(user, course, strategyData) {
2579
+ const implementingClass = strategyData.implementingClass;
2580
+ const RegisteredImpl = getRegisteredNavigator(implementingClass);
2581
+ if (RegisteredImpl) {
2582
+ logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);
2583
+ return new RegisteredImpl(user, course, strategyData);
2584
+ }
2585
+ logger.debug(
2586
+ `[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`
2587
+ );
2588
+ let NavigatorImpl;
2589
+ const variations = [".ts", ".js", ""];
2590
+ for (const ext of variations) {
2591
+ try {
2592
+ const module = await globImport_generators(`./generators/${implementingClass}${ext}`);
2593
+ NavigatorImpl = module.default;
2594
+ if (NavigatorImpl) break;
2595
+ } catch (e) {
2596
+ logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);
2597
+ }
2598
+ try {
2599
+ const module = await globImport_filters(`./filters/${implementingClass}${ext}`);
2600
+ NavigatorImpl = module.default;
2601
+ if (NavigatorImpl) break;
2602
+ } catch (e) {
2603
+ logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);
2604
+ }
2605
+ try {
2606
+ const module = await globImport(`./${implementingClass}${ext}`);
2607
+ NavigatorImpl = module.default;
2608
+ if (NavigatorImpl) break;
2609
+ } catch (e) {
2610
+ logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);
2611
+ }
2612
+ if (NavigatorImpl) break;
2613
+ }
2614
+ if (!NavigatorImpl) {
2615
+ throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
2616
+ }
2617
+ return new NavigatorImpl(user, course, strategyData);
2618
+ }
2619
+ /**
2620
+ * Get cards with suitability scores and provenance trails.
2621
+ *
2622
+ * **This is the PRIMARY API for navigation strategies.**
2623
+ *
2624
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
2625
+ * better candidates for presentation. Each card includes a provenance trail
2626
+ * documenting how strategies contributed to the final score.
2627
+ *
2628
+ * ## Implementation Required
2629
+ * All navigation strategies MUST override this method. The base class does
2630
+ * not provide a default implementation.
2631
+ *
2632
+ * ## For Generators
2633
+ * Override this method to generate candidates and compute scores based on
2634
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
2635
+ * initial provenance entry with action='generated'.
2636
+ *
2637
+ * ## For Filters
2638
+ * Filters should implement the CardFilter interface instead and be composed
2639
+ * via Pipeline. Filters do not directly implement getWeightedCards().
2640
+ *
2641
+ * @param limit - Maximum cards to return
2642
+ * @returns Cards sorted by score descending, with provenance trails
2643
+ */
2644
+ async getWeightedCards(_limit) {
2645
+ throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
2646
+ }
2647
+ };
2648
+ }
2649
+ });
2650
+
1432
2651
  // src/impl/couch/courseDB.ts
1433
2652
  import {
1434
2653
  EloToNumber,
1435
2654
  Status,
1436
2655
  blankCourseElo as blankCourseElo2,
1437
- toCourseElo as toCourseElo4
2656
+ toCourseElo as toCourseElo6
1438
2657
  } from "@vue-skuilder/common";
1439
2658
  function randIntWeightedTowardZero(n) {
1440
2659
  return Math.floor(Math.random() * Math.random() * Math.random() * n);
@@ -1678,7 +2897,7 @@ var init_courseDB = __esm({
1678
2897
  docs.rows.forEach((r) => {
1679
2898
  if (isSuccessRow(r)) {
1680
2899
  if (r.doc && r.doc.elo) {
1681
- ret.push(toCourseElo4(r.doc.elo));
2900
+ ret.push(toCourseElo6(r.doc.elo));
1682
2901
  } else {
1683
2902
  logger.warn("no elo data for card: " + r.id);
1684
2903
  ret.push(blankCourseElo2());
@@ -2698,6 +3917,13 @@ var init_strategyState = __esm({
2698
3917
  }
2699
3918
  });
2700
3919
 
3920
+ // src/core/types/userOutcome.ts
3921
+ var init_userOutcome = __esm({
3922
+ "src/core/types/userOutcome.ts"() {
3923
+ "use strict";
3924
+ }
3925
+ });
3926
+
2701
3927
  // src/core/util/index.ts
2702
3928
  function getCardHistoryID(courseID, cardID) {
2703
3929
  return `${DocTypePrefixes["CARDRECORD" /* CARDRECORD */]}-${courseID}-${cardID}`;
@@ -2719,7 +3945,7 @@ var init_cardProcessor = __esm({
2719
3945
  });
2720
3946
 
2721
3947
  // src/core/bulkImport/types.ts
2722
- var init_types = __esm({
3948
+ var init_types3 = __esm({
2723
3949
  "src/core/bulkImport/types.ts"() {
2724
3950
  "use strict";
2725
3951
  }
@@ -2730,7 +3956,7 @@ var init_bulkImport = __esm({
2730
3956
  "src/core/bulkImport/index.ts"() {
2731
3957
  "use strict";
2732
3958
  init_cardProcessor();
2733
- init_types();
3959
+ init_types3();
2734
3960
  }
2735
3961
  });
2736
3962
 
@@ -2742,10 +3968,12 @@ var init_core = __esm({
2742
3968
  init_types_legacy();
2743
3969
  init_user();
2744
3970
  init_strategyState();
3971
+ init_userOutcome();
2745
3972
  init_Loggable();
2746
3973
  init_util();
2747
3974
  init_navigators();
2748
3975
  init_bulkImport();
3976
+ init_orchestration();
2749
3977
  }
2750
3978
  });
2751
3979
 
@@ -3938,6 +5166,19 @@ Currently logged-in as ${this._username}.`
3938
5166
  };
3939
5167
  await this.localDB.put(doc);
3940
5168
  }
5169
+ async putUserOutcome(record) {
5170
+ try {
5171
+ await this.localDB.put(record);
5172
+ } catch (err) {
5173
+ if (err.status === 409) {
5174
+ const existing = await this.localDB.get(record._id);
5175
+ record._rev = existing._rev;
5176
+ await this.localDB.put(record);
5177
+ } else {
5178
+ throw err;
5179
+ }
5180
+ }
5181
+ }
3941
5182
  async deleteStrategyState(courseId, strategyKey) {
3942
5183
  const docId = buildStrategyStateId(courseId, strategyKey);
3943
5184
  try {
@@ -3980,6 +5221,7 @@ var init_factory = __esm({
3980
5221
  "use strict";
3981
5222
  init_common();
3982
5223
  init_logger();
5224
+ init_navigators();
3983
5225
  NOT_SET = "NOT_SET";
3984
5226
  ENV = {
3985
5227
  COUCHDB_SERVER_PROTOCOL: NOT_SET,