@vue-skuilder/db 0.1.18 → 0.1.21

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 (87) hide show
  1. package/CLAUDE.md +2 -2
  2. package/dist/{classroomDB-BgfrVb8d.d.ts → contentSource-BP9hznNV.d.ts} +220 -197
  3. package/dist/{classroomDB-CTOenngH.d.cts → contentSource-DsJadoBU.d.cts} +220 -197
  4. package/dist/core/index.d.cts +80 -6
  5. package/dist/core/index.d.ts +80 -6
  6. package/dist/core/index.js +735 -1560
  7. package/dist/core/index.js.map +1 -1
  8. package/dist/core/index.mjs +708 -1539
  9. package/dist/core/index.mjs.map +1 -1
  10. package/dist/{dataLayerProvider-D6PoCwS6.d.cts → dataLayerProvider-CHYrQ5pB.d.cts} +1 -1
  11. package/dist/{dataLayerProvider-CZxC9GtB.d.ts → dataLayerProvider-MDTxXq2l.d.ts} +1 -1
  12. package/dist/impl/couch/index.d.cts +8 -23
  13. package/dist/impl/couch/index.d.ts +8 -23
  14. package/dist/impl/couch/index.js +723 -1578
  15. package/dist/impl/couch/index.js.map +1 -1
  16. package/dist/impl/couch/index.mjs +692 -1552
  17. package/dist/impl/couch/index.mjs.map +1 -1
  18. package/dist/impl/static/index.d.cts +25 -8
  19. package/dist/impl/static/index.d.ts +25 -8
  20. package/dist/impl/static/index.js +700 -1400
  21. package/dist/impl/static/index.js.map +1 -1
  22. package/dist/impl/static/index.mjs +688 -1393
  23. package/dist/impl/static/index.mjs.map +1 -1
  24. package/dist/{index-D-Fa4Smt.d.cts → index-B_j6u5E4.d.cts} +1 -1
  25. package/dist/{index-CD8BZz2k.d.ts → index-Dj0SEgk3.d.ts} +1 -1
  26. package/dist/index.d.cts +71 -63
  27. package/dist/index.d.ts +71 -63
  28. package/dist/index.js +1162 -1996
  29. package/dist/index.js.map +1 -1
  30. package/dist/index.mjs +1124 -1955
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/pouch/index.js +3 -0
  33. package/dist/pouch/index.js.map +1 -1
  34. package/dist/pouch/index.mjs +3 -0
  35. package/dist/pouch/index.mjs.map +1 -1
  36. package/dist/{types-CzPDLAK6.d.cts → types-Bn0itutr.d.cts} +1 -1
  37. package/dist/{types-CewsN87z.d.ts → types-DQaXnuoc.d.ts} +1 -1
  38. package/dist/{types-legacy-6ettoclI.d.cts → types-legacy-DDY4N-Uq.d.cts} +3 -1
  39. package/dist/{types-legacy-6ettoclI.d.ts → types-legacy-DDY4N-Uq.d.ts} +3 -1
  40. package/dist/util/packer/index.d.cts +3 -3
  41. package/dist/util/packer/index.d.ts +3 -3
  42. package/docs/navigators-architecture.md +115 -17
  43. package/package.json +4 -4
  44. package/src/core/index.ts +1 -0
  45. package/src/core/interfaces/classroomDB.ts +5 -13
  46. package/src/core/interfaces/contentSource.ts +6 -66
  47. package/src/core/interfaces/courseDB.ts +15 -7
  48. package/src/core/interfaces/userDB.ts +32 -0
  49. package/src/core/navigators/Pipeline.ts +136 -52
  50. package/src/core/navigators/PipelineAssembler.ts +1 -1
  51. package/src/core/navigators/defaults.ts +84 -0
  52. package/src/core/navigators/{hierarchyDefinition.ts → filters/hierarchyDefinition.ts} +15 -29
  53. package/src/core/navigators/filters/index.ts +3 -0
  54. package/src/core/navigators/filters/inferredPreferenceStub.ts +107 -0
  55. package/src/core/navigators/{interferenceMitigator.ts → filters/interferenceMitigator.ts} +11 -37
  56. package/src/core/navigators/{relativePriority.ts → filters/relativePriority.ts} +12 -38
  57. package/src/core/navigators/filters/userGoalStub.ts +136 -0
  58. package/src/core/navigators/filters/userTagPreference.ts +217 -0
  59. package/src/core/navigators/{CompositeGenerator.ts → generators/CompositeGenerator.ts} +15 -64
  60. package/src/core/navigators/{elo.ts → generators/elo.ts} +13 -63
  61. package/src/core/navigators/{srs.ts → generators/srs.ts} +11 -40
  62. package/src/core/navigators/generators/types.ts +1 -1
  63. package/src/core/navigators/index.ts +95 -91
  64. package/src/core/types/strategyState.ts +84 -0
  65. package/src/core/types/types-legacy.ts +2 -0
  66. package/src/impl/common/BaseUserDB.ts +74 -7
  67. package/src/impl/couch/adminDB.ts +1 -2
  68. package/src/impl/couch/classroomDB.ts +100 -103
  69. package/src/impl/couch/courseDB.ts +35 -91
  70. package/src/impl/couch/pouchdb-setup.ts +7 -0
  71. package/src/impl/static/StaticDataUnpacker.ts +50 -1
  72. package/src/impl/static/courseDB.ts +87 -37
  73. package/src/study/SessionController.ts +122 -202
  74. package/src/study/SourceMixer.ts +65 -0
  75. package/src/study/TagFilteredContentSource.ts +49 -92
  76. package/src/study/index.ts +1 -0
  77. package/src/study/services/CardHydrationService.ts +165 -81
  78. package/src/util/dataDirectory.ts +1 -1
  79. package/src/util/index.ts +0 -1
  80. package/tests/core/navigators/CompositeGenerator.test.ts +44 -168
  81. package/tests/core/navigators/Pipeline.test.ts +6 -72
  82. package/tests/core/navigators/PipelineAssembler.test.ts +8 -58
  83. package/tests/core/navigators/navigators.test.ts +118 -151
  84. package/docs/todo-pipeline-optimization.md +0 -117
  85. package/docs/todo-strategy-state-storage.md +0 -278
  86. package/src/core/navigators/hardcodedOrder.ts +0 -163
  87. package/src/util/tuiLogger.ts +0 -139
@@ -1,17 +1,7 @@
1
- var __defProp = Object.defineProperty;
2
1
  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
- };
8
2
  var __esm = (fn, res) => function __init() {
9
3
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
4
  };
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
5
 
16
6
  // src/impl/common/SyncStrategy.ts
17
7
  var init_SyncStrategy = __esm({
@@ -89,6 +79,9 @@ var init_pouchdb_setup = __esm({
89
79
  "use strict";
90
80
  PouchDB.plugin(PouchDBFind);
91
81
  PouchDB.plugin(PouchDBAuth);
82
+ if (typeof PouchDB.debug !== "undefined") {
83
+ PouchDB.debug.disable();
84
+ }
92
85
  PouchDB.defaults({
93
86
  // ajax: {
94
87
  // timeout: 60000,
@@ -258,7 +251,8 @@ var init_types_legacy = __esm({
258
251
  ["QUESTION" /* QUESTIONTYPE */]: "QUESTION",
259
252
  ["VIEW" /* VIEW */]: "VIEW",
260
253
  ["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
261
- ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY"
254
+ ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
255
+ ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE"
262
256
  };
263
257
  }
264
258
  });
@@ -599,24 +593,331 @@ var init_courseLookupDB = __esm({
599
593
  }
600
594
  });
601
595
 
602
- // src/core/navigators/CompositeGenerator.ts
603
- var CompositeGenerator_exports = {};
604
- __export(CompositeGenerator_exports, {
605
- AggregationMode: () => AggregationMode,
606
- default: () => CompositeGenerator
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"() {
606
+ "use strict";
607
+ 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;
638
+ }
639
+ }
640
+ // ============================================================================
641
+ // STRATEGY STATE HELPERS
642
+ // ============================================================================
643
+ //
644
+ // These methods allow strategies to persist their own state (user preferences,
645
+ // learned patterns, temporal tracking) in the user database.
646
+ //
647
+ // ============================================================================
648
+ /**
649
+ * Unique key identifying this strategy for state storage.
650
+ *
651
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
652
+ * Override in subclasses if multiple instances of the same strategy type
653
+ * need separate state storage.
654
+ */
655
+ get strategyKey() {
656
+ return this.constructor.name;
657
+ }
658
+ /**
659
+ * Get this strategy's persisted state for the current course.
660
+ *
661
+ * @returns The strategy's data payload, or null if no state exists
662
+ * @throws Error if user or course is not initialized
663
+ */
664
+ async getStrategyState() {
665
+ if (!this.user || !this.course) {
666
+ throw new Error(
667
+ `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
668
+ );
669
+ }
670
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
671
+ }
672
+ /**
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
677
+ */
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
+ );
683
+ }
684
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
685
+ }
686
+ /**
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.
693
+ */
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
+ }
709
+ }
710
+ }
711
+ if (!NavigatorImpl) {
712
+ throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
713
+ }
714
+ return new NavigatorImpl(user, course, strategyData);
715
+ }
716
+ /**
717
+ * Get cards with suitability scores and provenance trails.
718
+ *
719
+ * **This is the PRIMARY API for navigation strategies.**
720
+ *
721
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
722
+ * better candidates for presentation. Each card includes a provenance trail
723
+ * documenting how strategies contributed to the final score.
724
+ *
725
+ * ## Implementation Required
726
+ * All navigation strategies MUST override this method. The base class does
727
+ * not provide a default implementation.
728
+ *
729
+ * ## For Generators
730
+ * Override this method to generate candidates and compute scores based on
731
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
732
+ * initial provenance entry with action='generated'.
733
+ *
734
+ * ## For Filters
735
+ * Filters should implement the CardFilter interface instead and be composed
736
+ * via Pipeline. Filters do not directly implement getWeightedCards().
737
+ *
738
+ * @param limit - Maximum cards to return
739
+ * @returns Cards sorted by score descending, with provenance trails
740
+ */
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`
763
+ );
764
+ }
765
+ function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores) {
766
+ const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
767
+ logger.info(
768
+ `[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})`
769
+ );
770
+ }
771
+ function logCardProvenance(cards, maxCards = 3) {
772
+ const cardsToLog = cards.slice(0, maxCards);
773
+ logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
774
+ for (const card of cardsToLog) {
775
+ logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
776
+ for (const entry of card.provenance) {
777
+ const scoreChange = entry.score.toFixed(3);
778
+ const action = entry.action.padEnd(9);
779
+ logger.debug(
780
+ `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
781
+ );
782
+ }
783
+ }
784
+ }
785
+ var Pipeline;
786
+ var init_Pipeline = __esm({
787
+ "src/core/navigators/Pipeline.ts"() {
788
+ "use strict";
789
+ init_navigators();
790
+ init_logger();
791
+ Pipeline = class extends ContentNavigator {
792
+ generator;
793
+ filters;
794
+ /**
795
+ * Create a new pipeline.
796
+ *
797
+ * @param generator - The generator (or CompositeGenerator) that produces candidates
798
+ * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
799
+ * @param user - User database interface
800
+ * @param course - Course database interface
801
+ */
802
+ constructor(generator, filters, user, course) {
803
+ super();
804
+ this.generator = generator;
805
+ this.filters = filters;
806
+ this.user = user;
807
+ this.course = course;
808
+ course.getCourseConfig().then((cfg) => {
809
+ logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);
810
+ }).catch((e) => {
811
+ logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);
812
+ });
813
+ logPipelineConfig(generator, filters);
814
+ }
815
+ /**
816
+ * Get weighted cards by running generator and applying filters.
817
+ *
818
+ * 1. Build shared context (user ELO, etc.)
819
+ * 2. Get candidates from generator (passing context)
820
+ * 3. Batch hydrate tags for all candidates
821
+ * 4. Apply each filter sequentially
822
+ * 5. Remove zero-score cards
823
+ * 6. Sort by score descending
824
+ * 7. Return top N
825
+ *
826
+ * @param limit - Maximum number of cards to return
827
+ * @returns Cards sorted by score descending
828
+ */
829
+ async getWeightedCards(limit) {
830
+ const context = await this.buildContext();
831
+ const overFetchMultiplier = 2 + this.filters.length * 0.5;
832
+ const fetchLimit = Math.ceil(limit * overFetchMultiplier);
833
+ logger.debug(
834
+ `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
835
+ );
836
+ let cards = await this.generator.getWeightedCards(fetchLimit, context);
837
+ const generatedCount = cards.length;
838
+ logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
839
+ cards = await this.hydrateTags(cards);
840
+ for (const filter of this.filters) {
841
+ const beforeCount = cards.length;
842
+ cards = await filter.transform(cards, context);
843
+ logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeCount} \u2192 ${cards.length} cards`);
844
+ }
845
+ cards = cards.filter((c) => c.score > 0);
846
+ cards.sort((a, b) => b.score - a.score);
847
+ const result = cards.slice(0, limit);
848
+ const topScores = result.slice(0, 3).map((c) => c.score);
849
+ logExecutionSummary(
850
+ this.generator.name,
851
+ generatedCount,
852
+ this.filters.length,
853
+ result.length,
854
+ topScores
855
+ );
856
+ logCardProvenance(result, 3);
857
+ return result;
858
+ }
859
+ /**
860
+ * Batch hydrate tags for all cards.
861
+ *
862
+ * Fetches tags for all cards in a single database query and attaches them
863
+ * to the WeightedCard objects. Filters can then use card.tags instead of
864
+ * making individual getAppliedTags() calls.
865
+ *
866
+ * @param cards - Cards to hydrate
867
+ * @returns Cards with tags populated
868
+ */
869
+ async hydrateTags(cards) {
870
+ if (cards.length === 0) {
871
+ return cards;
872
+ }
873
+ const cardIds = cards.map((c) => c.cardId);
874
+ const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
875
+ logTagHydration(cards, tagsByCard);
876
+ return cards.map((card) => ({
877
+ ...card,
878
+ tags: tagsByCard.get(card.cardId) ?? []
879
+ }));
880
+ }
881
+ /**
882
+ * Build shared context for generator and filters.
883
+ *
884
+ * Called once per getWeightedCards() invocation.
885
+ * Contains data that the generator and multiple filters might need.
886
+ *
887
+ * The context satisfies both GeneratorContext and FilterContext interfaces.
888
+ */
889
+ async buildContext() {
890
+ let userElo = 1e3;
891
+ try {
892
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
893
+ const courseElo = toCourseElo2(courseReg.elo);
894
+ userElo = courseElo.global.score;
895
+ } catch (e) {
896
+ logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
897
+ }
898
+ return {
899
+ user: this.user,
900
+ course: this.course,
901
+ userElo
902
+ };
903
+ }
904
+ /**
905
+ * Get the course ID for this pipeline.
906
+ */
907
+ getCourseID() {
908
+ return this.course.getCourseID();
909
+ }
910
+ };
911
+ }
607
912
  });
608
- var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
913
+
914
+ // src/core/navigators/generators/CompositeGenerator.ts
915
+ var DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
609
916
  var init_CompositeGenerator = __esm({
610
- "src/core/navigators/CompositeGenerator.ts"() {
917
+ "src/core/navigators/generators/CompositeGenerator.ts"() {
611
918
  "use strict";
612
919
  init_navigators();
613
920
  init_logger();
614
- AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
615
- AggregationMode2["MAX"] = "max";
616
- AggregationMode2["AVERAGE"] = "average";
617
- AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
618
- return AggregationMode2;
619
- })(AggregationMode || {});
620
921
  DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
621
922
  FREQUENCY_BOOST_FACTOR = 0.1;
622
923
  CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
@@ -656,9 +957,14 @@ var init_CompositeGenerator = __esm({
656
957
  * CardGenerator interface signature (limit, context).
657
958
  *
658
959
  * @param limit - Maximum number of cards to return
659
- * @param context - Optional GeneratorContext passed to child generators
960
+ * @param context - GeneratorContext passed to child generators (required when called via Pipeline)
660
961
  */
661
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
+ }
662
968
  const results = await Promise.all(
663
969
  this.generators.map((g) => g.getWeightedCards(limit, context))
664
970
  );
@@ -739,193 +1045,21 @@ var init_CompositeGenerator = __esm({
739
1045
  return scores[0];
740
1046
  }
741
1047
  }
742
- /**
743
- * Get new cards from all generators, merged and deduplicated.
744
- */
745
- async getNewCards(n) {
746
- const legacyGenerators = this.generators.filter(
747
- (g) => g instanceof ContentNavigator
748
- );
749
- const results = await Promise.all(legacyGenerators.map((g) => g.getNewCards(n)));
750
- const seen = /* @__PURE__ */ new Set();
751
- const merged = [];
752
- for (const cards of results) {
753
- for (const card of cards) {
754
- if (!seen.has(card.cardID)) {
755
- seen.add(card.cardID);
756
- merged.push(card);
757
- }
758
- }
759
- }
760
- return n ? merged.slice(0, n) : merged;
761
- }
762
- /**
763
- * Get pending reviews from all generators, merged and deduplicated.
764
- */
765
- async getPendingReviews() {
766
- const legacyGenerators = this.generators.filter(
767
- (g) => g instanceof ContentNavigator
768
- );
769
- const results = await Promise.all(legacyGenerators.map((g) => g.getPendingReviews()));
770
- const seen = /* @__PURE__ */ new Set();
771
- const merged = [];
772
- for (const reviews of results) {
773
- for (const review of reviews) {
774
- if (!seen.has(review.cardID)) {
775
- seen.add(review.cardID);
776
- merged.push(review);
777
- }
778
- }
779
- }
780
- return merged;
781
- }
782
1048
  };
783
1049
  }
784
1050
  });
785
1051
 
786
- // src/core/navigators/Pipeline.ts
787
- var Pipeline_exports = {};
788
- __export(Pipeline_exports, {
789
- Pipeline: () => Pipeline
790
- });
791
- import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
792
- var Pipeline;
793
- var init_Pipeline = __esm({
794
- "src/core/navigators/Pipeline.ts"() {
1052
+ // src/core/navigators/PipelineAssembler.ts
1053
+ var PipelineAssembler;
1054
+ var init_PipelineAssembler = __esm({
1055
+ "src/core/navigators/PipelineAssembler.ts"() {
795
1056
  "use strict";
796
1057
  init_navigators();
1058
+ init_Pipeline();
1059
+ init_types_legacy();
797
1060
  init_logger();
798
- Pipeline = class extends ContentNavigator {
799
- generator;
800
- filters;
801
- /**
802
- * Create a new pipeline.
803
- *
804
- * @param generator - The generator (or CompositeGenerator) that produces candidates
805
- * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
806
- * @param user - User database interface
807
- * @param course - Course database interface
808
- */
809
- constructor(generator, filters, user, course) {
810
- super();
811
- this.generator = generator;
812
- this.filters = filters;
813
- this.user = user;
814
- this.course = course;
815
- logger.debug(
816
- `[Pipeline] Created with generator '${generator.name}' and ${filters.length} filters: ${filters.map((f) => f.name).join(", ")}`
817
- );
818
- }
819
- /**
820
- * Get weighted cards by running generator and applying filters.
821
- *
822
- * 1. Build shared context (user ELO, etc.)
823
- * 2. Get candidates from generator (passing context)
824
- * 3. Apply each filter sequentially
825
- * 4. Remove zero-score cards
826
- * 5. Sort by score descending
827
- * 6. Return top N
828
- *
829
- * @param limit - Maximum number of cards to return
830
- * @returns Cards sorted by score descending
831
- */
832
- async getWeightedCards(limit) {
833
- const context = await this.buildContext();
834
- const overFetchMultiplier = 2 + this.filters.length * 0.5;
835
- const fetchLimit = Math.ceil(limit * overFetchMultiplier);
836
- logger.debug(
837
- `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
838
- );
839
- let cards = await this.generator.getWeightedCards(fetchLimit, context);
840
- logger.debug(`[Pipeline] Generator returned ${cards.length} candidates`);
841
- for (const filter of this.filters) {
842
- const beforeCount = cards.length;
843
- cards = await filter.transform(cards, context);
844
- logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeCount} \u2192 ${cards.length} cards`);
845
- }
846
- cards = cards.filter((c) => c.score > 0);
847
- cards.sort((a, b) => b.score - a.score);
848
- const result = cards.slice(0, limit);
849
- logger.debug(
850
- `[Pipeline] Returning ${result.length} cards (top scores: ${result.slice(0, 3).map((c) => c.score.toFixed(2)).join(", ")}...)`
851
- );
852
- return result;
853
- }
854
- /**
855
- * Build shared context for generator and filters.
856
- *
857
- * Called once per getWeightedCards() invocation.
858
- * Contains data that the generator and multiple filters might need.
859
- *
860
- * The context satisfies both GeneratorContext and FilterContext interfaces.
861
- */
862
- async buildContext() {
863
- let userElo = 1e3;
864
- try {
865
- const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
866
- const courseElo = toCourseElo2(courseReg.elo);
867
- userElo = courseElo.global.score;
868
- } catch (e) {
869
- logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
870
- }
871
- return {
872
- user: this.user,
873
- course: this.course,
874
- userElo
875
- };
876
- }
877
- // ===========================================================================
878
- // Legacy StudyContentSource methods
879
- // ===========================================================================
880
- //
881
- // These delegate to the generator for backward compatibility.
882
- // Eventually SessionController will use getWeightedCards() exclusively.
883
- //
884
- /**
885
- * Get new cards via legacy API.
886
- * Delegates to the generator if it supports the legacy interface.
887
- */
888
- async getNewCards(n) {
889
- if ("getNewCards" in this.generator && typeof this.generator.getNewCards === "function") {
890
- return this.generator.getNewCards(n);
891
- }
892
- return [];
893
- }
894
- /**
895
- * Get pending reviews via legacy API.
896
- * Delegates to the generator if it supports the legacy interface.
897
- */
898
- async getPendingReviews() {
899
- if ("getPendingReviews" in this.generator && typeof this.generator.getPendingReviews === "function") {
900
- return this.generator.getPendingReviews();
901
- }
902
- return [];
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/PipelineAssembler.ts
915
- var PipelineAssembler_exports = {};
916
- __export(PipelineAssembler_exports, {
917
- PipelineAssembler: () => PipelineAssembler
918
- });
919
- var PipelineAssembler;
920
- var init_PipelineAssembler = __esm({
921
- "src/core/navigators/PipelineAssembler.ts"() {
922
- "use strict";
923
- init_navigators();
924
- init_Pipeline();
925
- init_types_legacy();
926
- init_logger();
927
- init_CompositeGenerator();
928
- PipelineAssembler = class {
1061
+ init_CompositeGenerator();
1062
+ PipelineAssembler = class {
929
1063
  /**
930
1064
  * Assembles a navigation pipeline from strategy documents.
931
1065
  *
@@ -1036,15 +1170,11 @@ var init_PipelineAssembler = __esm({
1036
1170
  }
1037
1171
  });
1038
1172
 
1039
- // src/core/navigators/elo.ts
1040
- var elo_exports = {};
1041
- __export(elo_exports, {
1042
- default: () => ELONavigator
1043
- });
1173
+ // src/core/navigators/generators/elo.ts
1044
1174
  import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
1045
1175
  var ELONavigator;
1046
1176
  var init_elo = __esm({
1047
- "src/core/navigators/elo.ts"() {
1177
+ "src/core/navigators/generators/elo.ts"() {
1048
1178
  "use strict";
1049
1179
  init_navigators();
1050
1180
  ELONavigator = class extends ContentNavigator {
@@ -1054,50 +1184,6 @@ var init_elo = __esm({
1054
1184
  super(user, course, strategyData);
1055
1185
  this.name = strategyData?.name || "ELO";
1056
1186
  }
1057
- async getPendingReviews() {
1058
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1059
- const elo = await this.course.getCardEloData(reviews.map((r) => r.cardId));
1060
- const ratedReviews = reviews.map((r, i) => {
1061
- const ratedR = {
1062
- ...r,
1063
- ...elo[i]
1064
- };
1065
- return ratedR;
1066
- });
1067
- ratedReviews.sort((a, b) => {
1068
- return a.global.score - b.global.score;
1069
- });
1070
- return ratedReviews.map((r) => {
1071
- return {
1072
- ...r,
1073
- contentSourceType: "course",
1074
- contentSourceID: this.course.getCourseID(),
1075
- cardID: r.cardId,
1076
- courseID: r.courseId,
1077
- qualifiedID: `${r.courseId}-${r.cardId}`,
1078
- reviewID: r._id,
1079
- status: "review"
1080
- };
1081
- });
1082
- }
1083
- async getNewCards(limit = 99) {
1084
- const activeCards = await this.user.getActiveCards();
1085
- return (await this.course.getCardsCenteredAtELO(
1086
- { limit, elo: "user" },
1087
- (c) => {
1088
- if (activeCards.some((ac) => c.cardID === ac.cardID)) {
1089
- return false;
1090
- } else {
1091
- return true;
1092
- }
1093
- }
1094
- )).map((c) => {
1095
- return {
1096
- ...c,
1097
- status: "new"
1098
- };
1099
- });
1100
- }
1101
1187
  /**
1102
1188
  * Get new cards with suitability scores based on ELO distance.
1103
1189
  *
@@ -1122,7 +1208,11 @@ var init_elo = __esm({
1122
1208
  const userElo = toCourseElo3(courseReg.elo);
1123
1209
  userGlobalElo = userElo.global.score;
1124
1210
  }
1125
- const newCards = await this.getNewCards(limit);
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" }));
1126
1216
  const cardIds = newCards.map((c) => c.cardID);
1127
1217
  const cardEloData = await this.course.getCardEloData(cardIds);
1128
1218
  const scored = newCards.map((c, i) => {
@@ -1152,160 +1242,29 @@ var init_elo = __esm({
1152
1242
  }
1153
1243
  });
1154
1244
 
1155
- // src/core/navigators/filters/eloDistance.ts
1156
- var eloDistance_exports = {};
1157
- __export(eloDistance_exports, {
1158
- DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1159
- DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1160
- DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1161
- createEloDistanceFilter: () => createEloDistanceFilter
1162
- });
1163
- function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1164
- const normalizedDistance = distance / halfLife;
1165
- const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1166
- return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1167
- }
1168
- function createEloDistanceFilter(config) {
1169
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1170
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1171
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1172
- return {
1173
- name: "ELO Distance Filter",
1174
- async transform(cards, context) {
1175
- const { course, userElo } = context;
1176
- const cardIds = cards.map((c) => c.cardId);
1177
- const cardElos = await course.getCardEloData(cardIds);
1178
- return cards.map((card, i) => {
1179
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
1180
- const distance = Math.abs(cardElo - userElo);
1181
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1182
- const newScore = card.score * multiplier;
1183
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1184
- return {
1185
- ...card,
1186
- score: newScore,
1187
- provenance: [
1188
- ...card.provenance,
1189
- {
1190
- strategy: "eloDistance",
1191
- strategyName: "ELO Distance Filter",
1192
- strategyId: "ELO_DISTANCE_FILTER",
1193
- action,
1194
- score: newScore,
1195
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1196
- }
1197
- ]
1198
- };
1199
- });
1200
- }
1201
- };
1202
- }
1203
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1204
- var init_eloDistance = __esm({
1205
- "src/core/navigators/filters/eloDistance.ts"() {
1206
- "use strict";
1207
- DEFAULT_HALF_LIFE = 200;
1208
- DEFAULT_MIN_MULTIPLIER = 0.3;
1209
- DEFAULT_MAX_MULTIPLIER = 1;
1210
- }
1211
- });
1212
-
1213
- // src/core/navigators/filters/index.ts
1214
- var filters_exports = {};
1215
- __export(filters_exports, {
1216
- createEloDistanceFilter: () => createEloDistanceFilter
1217
- });
1218
- var init_filters = __esm({
1219
- "src/core/navigators/filters/index.ts"() {
1220
- "use strict";
1221
- init_eloDistance();
1222
- }
1223
- });
1224
-
1225
- // src/core/navigators/filters/types.ts
1226
- var types_exports = {};
1227
- var init_types = __esm({
1228
- "src/core/navigators/filters/types.ts"() {
1229
- "use strict";
1230
- }
1231
- });
1232
-
1233
- // src/core/navigators/generators/index.ts
1234
- var generators_exports = {};
1235
- var init_generators = __esm({
1236
- "src/core/navigators/generators/index.ts"() {
1237
- "use strict";
1238
- }
1239
- });
1240
-
1241
- // src/core/navigators/generators/types.ts
1242
- var types_exports2 = {};
1243
- var init_types2 = __esm({
1244
- "src/core/navigators/generators/types.ts"() {
1245
- "use strict";
1246
- }
1247
- });
1248
-
1249
- // src/core/navigators/hardcodedOrder.ts
1250
- var hardcodedOrder_exports = {};
1251
- __export(hardcodedOrder_exports, {
1252
- default: () => HardcodedOrderNavigator
1253
- });
1254
- var HardcodedOrderNavigator;
1255
- var init_hardcodedOrder = __esm({
1256
- "src/core/navigators/hardcodedOrder.ts"() {
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"() {
1257
1250
  "use strict";
1258
1251
  init_navigators();
1259
1252
  init_logger();
1260
- HardcodedOrderNavigator = class extends ContentNavigator {
1253
+ SRSNavigator = class extends ContentNavigator {
1261
1254
  /** Human-readable name for CardGenerator interface */
1262
1255
  name;
1263
- orderedCardIds = [];
1264
1256
  constructor(user, course, strategyData) {
1265
1257
  super(user, course, strategyData);
1266
- this.name = strategyData.name || "Hardcoded Order";
1267
- if (strategyData.serializedData) {
1268
- try {
1269
- this.orderedCardIds = JSON.parse(strategyData.serializedData);
1270
- } catch (e) {
1271
- logger.error("Failed to parse serializedData for HardcodedOrderNavigator", e);
1272
- }
1273
- }
1274
- }
1275
- async getPendingReviews() {
1276
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1277
- return reviews.map((r) => {
1278
- return {
1279
- ...r,
1280
- contentSourceType: "course",
1281
- contentSourceID: this.course.getCourseID(),
1282
- cardID: r.cardId,
1283
- courseID: r.courseId,
1284
- reviewID: r._id,
1285
- status: "review"
1286
- };
1287
- });
1288
- }
1289
- async getNewCards(limit = 99) {
1290
- const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
1291
- const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
1292
- const cardsToReturn = newCardIds.slice(0, limit);
1293
- return cardsToReturn.map((cardId) => {
1294
- return {
1295
- cardID: cardId,
1296
- courseID: this.course.getCourseID(),
1297
- contentSourceType: "course",
1298
- contentSourceID: this.course.getCourseID(),
1299
- status: "new"
1300
- };
1301
- });
1258
+ this.name = strategyData?.name || "SRS";
1302
1259
  }
1303
1260
  /**
1304
- * Get cards in hardcoded order with scores based on position.
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
1305
1266
  *
1306
- * Earlier cards in the sequence get higher scores.
1307
- * Score formula: 1.0 - (position / totalCards) * 0.5
1308
- * This ensures scores range from 1.0 (first card) to 0.5+ (last card).
1267
+ * Cards not yet due are excluded (not scored as 0).
1309
1268
  *
1310
1269
  * This method supports both the legacy signature (limit only) and the
1311
1270
  * CardGenerator interface signature (limit, context).
@@ -1314,692 +1273,33 @@ var init_hardcodedOrder = __esm({
1314
1273
  * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1315
1274
  */
1316
1275
  async getWeightedCards(limit, _context) {
1317
- const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
1318
- const reviews = await this.getPendingReviews();
1319
- const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
1320
- const totalCards = newCardIds.length;
1321
- const scoredNew = newCardIds.slice(0, limit).map((cardId, index) => {
1322
- const position = index + 1;
1323
- const score = Math.max(0.5, 1 - index / totalCards * 0.5);
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);
1324
1284
  return {
1325
- cardId,
1326
- courseId: this.course.getCourseID(),
1285
+ cardId: review.cardId,
1286
+ courseId: review.courseId,
1327
1287
  score,
1288
+ reviewID: review._id,
1328
1289
  provenance: [
1329
1290
  {
1330
- strategy: "hardcodedOrder",
1291
+ strategy: "srs",
1331
1292
  strategyName: this.strategyName || this.name,
1332
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1293
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1333
1294
  action: "generated",
1334
1295
  score,
1335
- reason: `Position ${position} of ${totalCards} in fixed sequence, new card`
1296
+ reason
1336
1297
  }
1337
1298
  ]
1338
1299
  };
1339
1300
  });
1340
- const scoredReviews = reviews.map((r) => ({
1341
- cardId: r.cardID,
1342
- courseId: r.courseID,
1343
- score: 1,
1344
- provenance: [
1345
- {
1346
- strategy: "hardcodedOrder",
1347
- strategyName: this.strategyName || this.name,
1348
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1349
- action: "generated",
1350
- score: 1,
1351
- reason: "Scheduled review, highest priority"
1352
- }
1353
- ]
1354
- }));
1355
- const all = [...scoredReviews, ...scoredNew];
1356
- all.sort((a, b) => b.score - a.score);
1357
- return all.slice(0, limit);
1358
- }
1359
- };
1360
- }
1361
- });
1362
-
1363
- // src/core/navigators/hierarchyDefinition.ts
1364
- var hierarchyDefinition_exports = {};
1365
- __export(hierarchyDefinition_exports, {
1366
- default: () => HierarchyDefinitionNavigator
1367
- });
1368
- import { toCourseElo as toCourseElo4 } from "@vue-skuilder/common";
1369
- var DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1370
- var init_hierarchyDefinition = __esm({
1371
- "src/core/navigators/hierarchyDefinition.ts"() {
1372
- "use strict";
1373
- init_navigators();
1374
- DEFAULT_MIN_COUNT = 3;
1375
- HierarchyDefinitionNavigator = class extends ContentNavigator {
1376
- config;
1377
- _strategyData;
1378
- /** Human-readable name for CardFilter interface */
1379
- name;
1380
- constructor(user, course, _strategyData) {
1381
- super(user, course, _strategyData);
1382
- this._strategyData = _strategyData;
1383
- this.config = this.parseConfig(_strategyData.serializedData);
1384
- this.name = _strategyData.name || "Hierarchy Definition";
1385
- }
1386
- parseConfig(serializedData) {
1387
- try {
1388
- const parsed = JSON.parse(serializedData);
1389
- return {
1390
- prerequisites: parsed.prerequisites || {}
1391
- };
1392
- } catch {
1393
- return {
1394
- prerequisites: {}
1395
- };
1396
- }
1397
- }
1398
- /**
1399
- * Check if a specific prerequisite is satisfied
1400
- */
1401
- isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1402
- if (!userTagElo) return false;
1403
- const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1404
- if (userTagElo.count < minCount) return false;
1405
- if (prereq.masteryThreshold?.minElo !== void 0) {
1406
- return userTagElo.score >= prereq.masteryThreshold.minElo;
1407
- } else {
1408
- return userTagElo.score >= userGlobalElo;
1409
- }
1410
- }
1411
- /**
1412
- * Get the set of tags the user has mastered.
1413
- * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1414
- */
1415
- async getMasteredTags(context) {
1416
- const mastered = /* @__PURE__ */ new Set();
1417
- try {
1418
- const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1419
- const userElo = toCourseElo4(courseReg.elo);
1420
- for (const prereqs of Object.values(this.config.prerequisites)) {
1421
- for (const prereq of prereqs) {
1422
- const tagElo = userElo.tags[prereq.tag];
1423
- if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1424
- mastered.add(prereq.tag);
1425
- }
1426
- }
1427
- }
1428
- } catch {
1429
- }
1430
- return mastered;
1431
- }
1432
- /**
1433
- * Get the set of tags that are unlocked (prerequisites met)
1434
- */
1435
- getUnlockedTags(masteredTags) {
1436
- const unlocked = /* @__PURE__ */ new Set();
1437
- for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1438
- const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1439
- if (allPrereqsMet) {
1440
- unlocked.add(tagId);
1441
- }
1442
- }
1443
- return unlocked;
1444
- }
1445
- /**
1446
- * Check if a tag has prerequisites defined in config
1447
- */
1448
- hasPrerequisites(tagId) {
1449
- return tagId in this.config.prerequisites;
1450
- }
1451
- /**
1452
- * Check if a card is unlocked and generate reason.
1453
- */
1454
- async checkCardUnlock(cardId, course, unlockedTags, masteredTags) {
1455
- try {
1456
- const tagResponse = await course.getAppliedTags(cardId);
1457
- const cardTags = tagResponse.rows.map((row) => row.value?.name || row.key);
1458
- const lockedTags = cardTags.filter(
1459
- (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1460
- );
1461
- if (lockedTags.length === 0) {
1462
- const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1463
- return {
1464
- isUnlocked: true,
1465
- reason: `Prerequisites met, tags: ${tagList}`
1466
- };
1467
- }
1468
- const missingPrereqs = lockedTags.flatMap((tag) => {
1469
- const prereqs = this.config.prerequisites[tag] || [];
1470
- return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1471
- });
1472
- return {
1473
- isUnlocked: false,
1474
- reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1475
- };
1476
- } catch {
1477
- return {
1478
- isUnlocked: true,
1479
- reason: "Prerequisites check skipped (tag lookup failed)"
1480
- };
1481
- }
1482
- }
1483
- /**
1484
- * CardFilter.transform implementation.
1485
- *
1486
- * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1487
- */
1488
- async transform(cards, context) {
1489
- const masteredTags = await this.getMasteredTags(context);
1490
- const unlockedTags = this.getUnlockedTags(masteredTags);
1491
- const gated = [];
1492
- for (const card of cards) {
1493
- const { isUnlocked, reason } = await this.checkCardUnlock(
1494
- card.cardId,
1495
- context.course,
1496
- unlockedTags,
1497
- masteredTags
1498
- );
1499
- const finalScore = isUnlocked ? card.score : 0;
1500
- const action = isUnlocked ? "passed" : "penalized";
1501
- gated.push({
1502
- ...card,
1503
- score: finalScore,
1504
- provenance: [
1505
- ...card.provenance,
1506
- {
1507
- strategy: "hierarchyDefinition",
1508
- strategyName: this.strategyName || this.name,
1509
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1510
- action,
1511
- score: finalScore,
1512
- reason
1513
- }
1514
- ]
1515
- });
1516
- }
1517
- return gated;
1518
- }
1519
- /**
1520
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
1521
- *
1522
- * Use transform() via Pipeline instead.
1523
- */
1524
- async getWeightedCards(_limit) {
1525
- throw new Error(
1526
- "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1527
- );
1528
- }
1529
- // Legacy methods - stub implementations since filters don't generate cards
1530
- async getNewCards(_n) {
1531
- return [];
1532
- }
1533
- async getPendingReviews() {
1534
- return [];
1535
- }
1536
- };
1537
- }
1538
- });
1539
-
1540
- // src/core/navigators/interferenceMitigator.ts
1541
- var interferenceMitigator_exports = {};
1542
- __export(interferenceMitigator_exports, {
1543
- default: () => InterferenceMitigatorNavigator
1544
- });
1545
- import { toCourseElo as toCourseElo5 } from "@vue-skuilder/common";
1546
- var DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1547
- var init_interferenceMitigator = __esm({
1548
- "src/core/navigators/interferenceMitigator.ts"() {
1549
- "use strict";
1550
- init_navigators();
1551
- DEFAULT_MIN_COUNT2 = 10;
1552
- DEFAULT_MIN_ELAPSED_DAYS = 3;
1553
- DEFAULT_INTERFERENCE_DECAY = 0.8;
1554
- InterferenceMitigatorNavigator = class extends ContentNavigator {
1555
- config;
1556
- _strategyData;
1557
- /** Human-readable name for CardFilter interface */
1558
- name;
1559
- /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1560
- interferenceMap;
1561
- constructor(user, course, _strategyData) {
1562
- super(user, course, _strategyData);
1563
- this._strategyData = _strategyData;
1564
- this.config = this.parseConfig(_strategyData.serializedData);
1565
- this.interferenceMap = this.buildInterferenceMap();
1566
- this.name = _strategyData.name || "Interference Mitigator";
1567
- }
1568
- parseConfig(serializedData) {
1569
- try {
1570
- const parsed = JSON.parse(serializedData);
1571
- let sets = parsed.interferenceSets || [];
1572
- if (sets.length > 0 && Array.isArray(sets[0])) {
1573
- sets = sets.map((tags) => ({ tags }));
1574
- }
1575
- return {
1576
- interferenceSets: sets,
1577
- maturityThreshold: {
1578
- minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1579
- minElo: parsed.maturityThreshold?.minElo,
1580
- minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1581
- },
1582
- defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1583
- };
1584
- } catch {
1585
- return {
1586
- interferenceSets: [],
1587
- maturityThreshold: {
1588
- minCount: DEFAULT_MIN_COUNT2,
1589
- minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1590
- },
1591
- defaultDecay: DEFAULT_INTERFERENCE_DECAY
1592
- };
1593
- }
1594
- }
1595
- /**
1596
- * Build a map from each tag to its interference partners with decay coefficients.
1597
- * If tags A, B, C are in an interference group with decay 0.8, then:
1598
- * - A interferes with B (decay 0.8) and C (decay 0.8)
1599
- * - B interferes with A (decay 0.8) and C (decay 0.8)
1600
- * - etc.
1601
- */
1602
- buildInterferenceMap() {
1603
- const map = /* @__PURE__ */ new Map();
1604
- for (const group of this.config.interferenceSets) {
1605
- const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
1606
- for (const tag of group.tags) {
1607
- if (!map.has(tag)) {
1608
- map.set(tag, []);
1609
- }
1610
- const partners = map.get(tag);
1611
- for (const other of group.tags) {
1612
- if (other !== tag) {
1613
- const existing = partners.find((p) => p.partner === other);
1614
- if (existing) {
1615
- existing.decay = Math.max(existing.decay, decay);
1616
- } else {
1617
- partners.push({ partner: other, decay });
1618
- }
1619
- }
1620
- }
1621
- }
1622
- }
1623
- return map;
1624
- }
1625
- /**
1626
- * Get the set of tags that are currently immature for this user.
1627
- * A tag is immature if the user has interacted with it but hasn't
1628
- * reached the maturity threshold.
1629
- */
1630
- async getImmatureTags(context) {
1631
- const immature = /* @__PURE__ */ new Set();
1632
- try {
1633
- const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1634
- const userElo = toCourseElo5(courseReg.elo);
1635
- const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
1636
- const minElo = this.config.maturityThreshold?.minElo;
1637
- const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
1638
- const minCountForElapsed = minElapsedDays * 2;
1639
- for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
1640
- if (tagElo.count === 0) continue;
1641
- const belowCount = tagElo.count < minCount;
1642
- const belowElo = minElo !== void 0 && tagElo.score < minElo;
1643
- const belowElapsed = tagElo.count < minCountForElapsed;
1644
- if (belowCount || belowElo || belowElapsed) {
1645
- immature.add(tagId);
1646
- }
1647
- }
1648
- } catch {
1649
- }
1650
- return immature;
1651
- }
1652
- /**
1653
- * Get all tags that interfere with any immature tag, along with their decay coefficients.
1654
- * These are the tags we want to avoid introducing.
1655
- */
1656
- getTagsToAvoid(immatureTags) {
1657
- const avoid = /* @__PURE__ */ new Map();
1658
- for (const immatureTag of immatureTags) {
1659
- const partners = this.interferenceMap.get(immatureTag);
1660
- if (partners) {
1661
- for (const { partner, decay } of partners) {
1662
- if (!immatureTags.has(partner)) {
1663
- const existing = avoid.get(partner) ?? 0;
1664
- avoid.set(partner, Math.max(existing, decay));
1665
- }
1666
- }
1667
- }
1668
- }
1669
- return avoid;
1670
- }
1671
- /**
1672
- * Get tags for a single card
1673
- */
1674
- async getCardTags(cardId, course) {
1675
- try {
1676
- const tagResponse = await course.getAppliedTags(cardId);
1677
- return tagResponse.rows.map((row) => row.value?.name || row.key).filter(Boolean);
1678
- } catch {
1679
- return [];
1680
- }
1681
- }
1682
- /**
1683
- * Compute interference score reduction for a card.
1684
- * Returns: { multiplier, interfering tags, reason }
1685
- */
1686
- computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
1687
- if (tagsToAvoid.size === 0) {
1688
- return {
1689
- multiplier: 1,
1690
- interferingTags: [],
1691
- reason: "No interference detected"
1692
- };
1693
- }
1694
- let multiplier = 1;
1695
- const interferingTags = [];
1696
- for (const tag of cardTags) {
1697
- const decay = tagsToAvoid.get(tag);
1698
- if (decay !== void 0) {
1699
- interferingTags.push(tag);
1700
- multiplier *= 1 - decay;
1701
- }
1702
- }
1703
- if (interferingTags.length === 0) {
1704
- return {
1705
- multiplier: 1,
1706
- interferingTags: [],
1707
- reason: "No interference detected"
1708
- };
1709
- }
1710
- const causingTags = /* @__PURE__ */ new Set();
1711
- for (const tag of interferingTags) {
1712
- for (const immatureTag of immatureTags) {
1713
- const partners = this.interferenceMap.get(immatureTag);
1714
- if (partners?.some((p) => p.partner === tag)) {
1715
- causingTags.add(immatureTag);
1716
- }
1717
- }
1718
- }
1719
- const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
1720
- return { multiplier, interferingTags, reason };
1721
- }
1722
- /**
1723
- * CardFilter.transform implementation.
1724
- *
1725
- * Apply interference-aware scoring. Cards with tags that interfere with
1726
- * immature learnings get reduced scores.
1727
- */
1728
- async transform(cards, context) {
1729
- const immatureTags = await this.getImmatureTags(context);
1730
- const tagsToAvoid = this.getTagsToAvoid(immatureTags);
1731
- const adjusted = [];
1732
- for (const card of cards) {
1733
- const cardTags = await this.getCardTags(card.cardId, context.course);
1734
- const { multiplier, reason } = this.computeInterferenceEffect(
1735
- cardTags,
1736
- tagsToAvoid,
1737
- immatureTags
1738
- );
1739
- const finalScore = card.score * multiplier;
1740
- const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
1741
- adjusted.push({
1742
- ...card,
1743
- score: finalScore,
1744
- provenance: [
1745
- ...card.provenance,
1746
- {
1747
- strategy: "interferenceMitigator",
1748
- strategyName: this.strategyName || this.name,
1749
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
1750
- action,
1751
- score: finalScore,
1752
- reason
1753
- }
1754
- ]
1755
- });
1756
- }
1757
- return adjusted;
1758
- }
1759
- /**
1760
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
1761
- *
1762
- * Use transform() via Pipeline instead.
1763
- */
1764
- async getWeightedCards(_limit) {
1765
- throw new Error(
1766
- "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1767
- );
1768
- }
1769
- // Legacy methods - stub implementations since filters don't generate cards
1770
- async getNewCards(_n) {
1771
- return [];
1772
- }
1773
- async getPendingReviews() {
1774
- return [];
1775
- }
1776
- };
1777
- }
1778
- });
1779
-
1780
- // src/core/navigators/relativePriority.ts
1781
- var relativePriority_exports = {};
1782
- __export(relativePriority_exports, {
1783
- default: () => RelativePriorityNavigator
1784
- });
1785
- var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
1786
- var init_relativePriority = __esm({
1787
- "src/core/navigators/relativePriority.ts"() {
1788
- "use strict";
1789
- init_navigators();
1790
- DEFAULT_PRIORITY = 0.5;
1791
- DEFAULT_PRIORITY_INFLUENCE = 0.5;
1792
- DEFAULT_COMBINE_MODE = "max";
1793
- RelativePriorityNavigator = class extends ContentNavigator {
1794
- config;
1795
- _strategyData;
1796
- /** Human-readable name for CardFilter interface */
1797
- name;
1798
- constructor(user, course, _strategyData) {
1799
- super(user, course, _strategyData);
1800
- this._strategyData = _strategyData;
1801
- this.config = this.parseConfig(_strategyData.serializedData);
1802
- this.name = _strategyData.name || "Relative Priority";
1803
- }
1804
- parseConfig(serializedData) {
1805
- try {
1806
- const parsed = JSON.parse(serializedData);
1807
- return {
1808
- tagPriorities: parsed.tagPriorities || {},
1809
- defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
1810
- combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
1811
- priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
1812
- };
1813
- } catch {
1814
- return {
1815
- tagPriorities: {},
1816
- defaultPriority: DEFAULT_PRIORITY,
1817
- combineMode: DEFAULT_COMBINE_MODE,
1818
- priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
1819
- };
1820
- }
1821
- }
1822
- /**
1823
- * Look up the priority for a tag.
1824
- */
1825
- getTagPriority(tagId) {
1826
- return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
1827
- }
1828
- /**
1829
- * Compute combined priority for a card based on its tags.
1830
- */
1831
- computeCardPriority(cardTags) {
1832
- if (cardTags.length === 0) {
1833
- return this.config.defaultPriority ?? DEFAULT_PRIORITY;
1834
- }
1835
- const priorities = cardTags.map((tag) => this.getTagPriority(tag));
1836
- switch (this.config.combineMode) {
1837
- case "max":
1838
- return Math.max(...priorities);
1839
- case "min":
1840
- return Math.min(...priorities);
1841
- case "average":
1842
- return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
1843
- default:
1844
- return Math.max(...priorities);
1845
- }
1846
- }
1847
- /**
1848
- * Compute boost factor based on priority.
1849
- *
1850
- * The formula: 1 + (priority - 0.5) * priorityInfluence
1851
- *
1852
- * This creates a multiplier centered around 1.0:
1853
- * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
1854
- * - Priority 0.5 with any influence → 1.00 (neutral)
1855
- * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
1856
- */
1857
- computeBoostFactor(priority) {
1858
- const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
1859
- return 1 + (priority - 0.5) * influence;
1860
- }
1861
- /**
1862
- * Build human-readable reason for priority adjustment.
1863
- */
1864
- buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
1865
- if (cardTags.length === 0) {
1866
- return `No tags, neutral priority (${priority.toFixed(2)})`;
1867
- }
1868
- const tagList = cardTags.slice(0, 3).join(", ");
1869
- const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
1870
- if (boostFactor === 1) {
1871
- return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
1872
- } else if (boostFactor > 1) {
1873
- return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1874
- } else {
1875
- return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1876
- }
1877
- }
1878
- /**
1879
- * Get tags for a single card.
1880
- */
1881
- async getCardTags(cardId, course) {
1882
- try {
1883
- const tagResponse = await course.getAppliedTags(cardId);
1884
- return tagResponse.rows.map((r) => r.doc?.name).filter((x) => !!x);
1885
- } catch {
1886
- return [];
1887
- }
1888
- }
1889
- /**
1890
- * CardFilter.transform implementation.
1891
- *
1892
- * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
1893
- * cards with low-priority tags get reduced scores.
1894
- */
1895
- async transform(cards, context) {
1896
- const adjusted = await Promise.all(
1897
- cards.map(async (card) => {
1898
- const cardTags = await this.getCardTags(card.cardId, context.course);
1899
- const priority = this.computeCardPriority(cardTags);
1900
- const boostFactor = this.computeBoostFactor(priority);
1901
- const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
1902
- const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
1903
- const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
1904
- return {
1905
- ...card,
1906
- score: finalScore,
1907
- provenance: [
1908
- ...card.provenance,
1909
- {
1910
- strategy: "relativePriority",
1911
- strategyName: this.strategyName || this.name,
1912
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
1913
- action,
1914
- score: finalScore,
1915
- reason
1916
- }
1917
- ]
1918
- };
1919
- })
1920
- );
1921
- return adjusted;
1922
- }
1923
- /**
1924
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
1925
- *
1926
- * Use transform() via Pipeline instead.
1927
- */
1928
- async getWeightedCards(_limit) {
1929
- throw new Error(
1930
- "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1931
- );
1932
- }
1933
- // Legacy methods - stub implementations since filters don't generate cards
1934
- async getNewCards(_n) {
1935
- return [];
1936
- }
1937
- async getPendingReviews() {
1938
- return [];
1939
- }
1940
- };
1941
- }
1942
- });
1943
-
1944
- // src/core/navigators/srs.ts
1945
- var srs_exports = {};
1946
- __export(srs_exports, {
1947
- default: () => SRSNavigator
1948
- });
1949
- import moment from "moment";
1950
- var SRSNavigator;
1951
- var init_srs = __esm({
1952
- "src/core/navigators/srs.ts"() {
1953
- "use strict";
1954
- init_navigators();
1955
- SRSNavigator = class extends ContentNavigator {
1956
- /** Human-readable name for CardGenerator interface */
1957
- name;
1958
- constructor(user, course, strategyData) {
1959
- super(user, course, strategyData);
1960
- this.name = strategyData?.name || "SRS";
1961
- }
1962
- /**
1963
- * Get review cards scored by urgency.
1964
- *
1965
- * Score formula combines:
1966
- * - Relative overdueness: hoursOverdue / intervalHours
1967
- * - Interval recency: exponential decay favoring shorter intervals
1968
- *
1969
- * Cards not yet due are excluded (not scored as 0).
1970
- *
1971
- * This method supports both the legacy signature (limit only) and the
1972
- * CardGenerator interface signature (limit, context).
1973
- *
1974
- * @param limit - Maximum number of cards to return
1975
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1976
- */
1977
- async getWeightedCards(limit, _context) {
1978
- if (!this.user || !this.course) {
1979
- throw new Error("SRSNavigator requires user and course to be set");
1980
- }
1981
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1982
- const now = moment.utc();
1983
- const dueReviews = reviews.filter((r) => now.isAfter(moment.utc(r.reviewTime)));
1984
- const scored = dueReviews.map((review) => {
1985
- const { score, reason } = this.computeUrgencyScore(review, now);
1986
- return {
1987
- cardId: review.cardId,
1988
- courseId: review.courseId,
1989
- score,
1990
- provenance: [
1991
- {
1992
- strategy: "srs",
1993
- strategyName: this.strategyName || this.name,
1994
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1995
- action: "generated",
1996
- score,
1997
- reason
1998
- }
1999
- ]
2000
- };
2001
- });
2002
- return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1301
+ logger.debug(`[srsNav] got ${scored.length} weighted cards`);
1302
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
2003
1303
  }
2004
1304
  /**
2005
1305
  * Compute urgency score for a review card.
@@ -2030,235 +1330,102 @@ var init_srs = __esm({
2030
1330
  const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
2031
1331
  return { score, reason };
2032
1332
  }
2033
- /**
2034
- * Get pending reviews in legacy format.
2035
- *
2036
- * Returns all pending reviews for the course, enriched with session item fields.
2037
- */
2038
- async getPendingReviews() {
2039
- if (!this.user || !this.course) {
2040
- throw new Error("SRSNavigator requires user and course to be set");
2041
- }
2042
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
2043
- return reviews.map((r) => ({
2044
- ...r,
2045
- contentSourceType: "course",
2046
- contentSourceID: this.course.getCourseID(),
2047
- cardID: r.cardId,
2048
- courseID: r.courseId,
2049
- qualifiedID: `${r.courseId}-${r.cardId}`,
2050
- reviewID: r._id,
2051
- status: "review"
2052
- }));
2053
- }
2054
- /**
2055
- * SRS does not generate new cards.
2056
- * Use ELONavigator or another generator for new cards.
2057
- */
2058
- async getNewCards(_n) {
2059
- return [];
2060
- }
2061
1333
  };
2062
1334
  }
2063
1335
  });
2064
1336
 
2065
- // import("./**/*") in src/core/navigators/index.ts
2066
- var globImport;
2067
- var init_ = __esm({
2068
- 'import("./**/*") in src/core/navigators/index.ts'() {
2069
- globImport = __glob({
2070
- "./CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
2071
- "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
2072
- "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
2073
- "./elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
2074
- "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2075
- "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2076
- "./filters/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
2077
- "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
2078
- "./generators/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
2079
- "./hardcodedOrder.ts": () => Promise.resolve().then(() => (init_hardcodedOrder(), hardcodedOrder_exports)),
2080
- "./hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2081
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
2082
- "./interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2083
- "./relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2084
- "./srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports))
2085
- });
2086
- }
2087
- });
2088
-
2089
- // src/core/navigators/index.ts
2090
- var navigators_exports = {};
2091
- __export(navigators_exports, {
2092
- ContentNavigator: () => ContentNavigator,
2093
- NavigatorRole: () => NavigatorRole,
2094
- NavigatorRoles: () => NavigatorRoles,
2095
- Navigators: () => Navigators,
2096
- getCardOrigin: () => getCardOrigin,
2097
- isFilter: () => isFilter,
2098
- isGenerator: () => isGenerator
2099
- });
2100
- function getCardOrigin(card) {
2101
- if (card.provenance.length === 0) {
2102
- throw new Error("Card has no provenance - cannot determine origin");
2103
- }
2104
- const firstEntry = card.provenance[0];
2105
- const reason = firstEntry.reason.toLowerCase();
2106
- if (reason.includes("failed")) {
2107
- return "failed";
2108
- }
2109
- if (reason.includes("review")) {
2110
- return "review";
2111
- }
2112
- return "new";
2113
- }
2114
- function isGenerator(impl) {
2115
- return NavigatorRoles[impl] === "generator" /* GENERATOR */;
2116
- }
2117
- function isFilter(impl) {
2118
- return NavigatorRoles[impl] === "filter" /* FILTER */;
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;
2119
1342
  }
2120
- var Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
2121
- var init_navigators = __esm({
2122
- "src/core/navigators/index.ts"() {
2123
- "use strict";
2124
- init_logger();
2125
- init_();
2126
- Navigators = /* @__PURE__ */ ((Navigators2) => {
2127
- Navigators2["ELO"] = "elo";
2128
- Navigators2["SRS"] = "srs";
2129
- Navigators2["HARDCODED"] = "hardcodedOrder";
2130
- Navigators2["HIERARCHY"] = "hierarchyDefinition";
2131
- Navigators2["INTERFERENCE"] = "interferenceMitigator";
2132
- Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
2133
- return Navigators2;
2134
- })(Navigators || {});
2135
- NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
2136
- NavigatorRole2["GENERATOR"] = "generator";
2137
- NavigatorRole2["FILTER"] = "filter";
2138
- return NavigatorRole2;
2139
- })(NavigatorRole || {});
2140
- NavigatorRoles = {
2141
- ["elo" /* ELO */]: "generator" /* GENERATOR */,
2142
- ["srs" /* SRS */]: "generator" /* GENERATOR */,
2143
- ["hardcodedOrder" /* HARDCODED */]: "generator" /* GENERATOR */,
2144
- ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
2145
- ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
2146
- ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */
2147
- };
2148
- ContentNavigator = class {
2149
- /** User interface for this navigation session */
2150
- user;
2151
- /** Course interface for this navigation session */
2152
- course;
2153
- /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
2154
- strategyName;
2155
- /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
2156
- strategyId;
2157
- /**
2158
- * Constructor for standard navigators.
2159
- * Call this from subclass constructors to initialize common fields.
2160
- *
2161
- * Note: CompositeGenerator doesn't use this pattern and should call super() without args.
2162
- */
2163
- constructor(user, course, strategyData) {
2164
- if (user && course && strategyData) {
2165
- this.user = user;
2166
- this.course = course;
2167
- this.strategyName = strategyData.name;
2168
- this.strategyId = strategyData._id;
2169
- }
2170
- }
2171
- /**
2172
- * Factory method to create navigator instances dynamically.
2173
- *
2174
- * @param user - User interface
2175
- * @param course - Course interface
2176
- * @param strategyData - Strategy configuration document
2177
- * @returns the runtime object used to steer a study session.
2178
- */
2179
- static async create(user, course, strategyData) {
2180
- const implementingClass = strategyData.implementingClass;
2181
- let NavigatorImpl;
2182
- const variations = [".ts", ".js", ""];
2183
- for (const ext of variations) {
2184
- try {
2185
- const module = await globImport(`./${implementingClass}${ext}`);
2186
- NavigatorImpl = module.default;
2187
- break;
2188
- } catch (e) {
2189
- logger.debug(`Failed to load with extension ${ext}:`, e);
2190
- }
2191
- }
2192
- if (!NavigatorImpl) {
2193
- throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
2194
- }
2195
- return new NavigatorImpl(user, course, strategyData);
2196
- }
2197
- /**
2198
- * Get cards with suitability scores and provenance trails.
2199
- *
2200
- * **This is the PRIMARY API for navigation strategies.**
2201
- *
2202
- * Returns cards ranked by suitability score (0-1). Higher scores indicate
2203
- * better candidates for presentation. Each card includes a provenance trail
2204
- * documenting how strategies contributed to the final score.
2205
- *
2206
- * ## For Generators
2207
- * Override this method to generate candidates and compute scores based on
2208
- * your strategy's logic (e.g., ELO proximity, review urgency). Create the
2209
- * initial provenance entry with action='generated'.
2210
- *
2211
- * ## Default Implementation
2212
- * The base class provides a backward-compatible default that:
2213
- * 1. Calls legacy getNewCards() and getPendingReviews()
2214
- * 2. Assigns score=1.0 to all cards
2215
- * 3. Creates minimal provenance from legacy methods
2216
- * 4. Returns combined results up to limit
2217
- *
2218
- * This allows existing strategies to work without modification while
2219
- * new strategies can override with proper scoring and provenance.
2220
- *
2221
- * @param limit - Maximum cards to return
2222
- * @returns Cards sorted by score descending, with provenance trails
2223
- */
2224
- async getWeightedCards(limit) {
2225
- const newCards = await this.getNewCards(limit);
2226
- const reviews = await this.getPendingReviews();
2227
- const weighted = [
2228
- ...newCards.map((c) => ({
2229
- cardId: c.cardID,
2230
- courseId: c.courseID,
2231
- score: 1,
2232
- provenance: [
2233
- {
2234
- strategy: "legacy",
2235
- strategyName: this.strategyName || "Legacy API",
2236
- strategyId: this.strategyId || "legacy-fallback",
2237
- action: "generated",
2238
- score: 1,
2239
- reason: "Generated via legacy getNewCards(), new card"
2240
- }
2241
- ]
2242
- })),
2243
- ...reviews.map((r) => ({
2244
- cardId: r.cardID,
2245
- courseId: r.courseID,
2246
- score: 1,
2247
- provenance: [
2248
- {
2249
- strategy: "legacy",
2250
- strategyName: this.strategyName || "Legacy API",
2251
- strategyId: this.strategyId || "legacy-fallback",
2252
- action: "generated",
2253
- score: 1,
2254
- reason: "Generated via legacy getPendingReviews(), review"
2255
- }
2256
- ]
2257
- }))
2258
- ];
2259
- return weighted.slice(0, limit);
2260
- }
2261
- };
1343
+ function createEloDistanceFilter(config) {
1344
+ const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1345
+ const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1346
+ const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1347
+ return {
1348
+ name: "ELO Distance Filter",
1349
+ async transform(cards, context) {
1350
+ const { course, userElo } = context;
1351
+ const cardIds = cards.map((c) => c.cardId);
1352
+ const cardElos = await course.getCardEloData(cardIds);
1353
+ return cards.map((card, i) => {
1354
+ const cardElo = cardElos[i]?.global?.score ?? 1e3;
1355
+ const distance = Math.abs(cardElo - userElo);
1356
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1357
+ const newScore = card.score * multiplier;
1358
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1359
+ return {
1360
+ ...card,
1361
+ score: newScore,
1362
+ provenance: [
1363
+ ...card.provenance,
1364
+ {
1365
+ strategy: "eloDistance",
1366
+ strategyName: "ELO Distance Filter",
1367
+ strategyId: "ELO_DISTANCE_FILTER",
1368
+ action,
1369
+ score: newScore,
1370
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1371
+ }
1372
+ ]
1373
+ };
1374
+ });
1375
+ }
1376
+ };
1377
+ }
1378
+ var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1379
+ var init_eloDistance = __esm({
1380
+ "src/core/navigators/filters/eloDistance.ts"() {
1381
+ "use strict";
1382
+ DEFAULT_HALF_LIFE = 200;
1383
+ DEFAULT_MIN_MULTIPLIER = 0.3;
1384
+ DEFAULT_MAX_MULTIPLIER = 1;
1385
+ }
1386
+ });
1387
+
1388
+ // src/core/navigators/defaults.ts
1389
+ function createDefaultEloStrategy(courseId) {
1390
+ return {
1391
+ _id: "NAVIGATION_STRATEGY-ELO-default",
1392
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1393
+ name: "ELO (default)",
1394
+ description: "Default ELO-based navigation strategy for new cards",
1395
+ implementingClass: "elo" /* ELO */,
1396
+ course: courseId,
1397
+ serializedData: ""
1398
+ };
1399
+ }
1400
+ function createDefaultSrsStrategy(courseId) {
1401
+ return {
1402
+ _id: "NAVIGATION_STRATEGY-SRS-default",
1403
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1404
+ name: "SRS (default)",
1405
+ description: "Default SRS-based navigation strategy for reviews",
1406
+ implementingClass: "srs" /* SRS */,
1407
+ course: courseId,
1408
+ serializedData: ""
1409
+ };
1410
+ }
1411
+ function createDefaultPipeline(user, course) {
1412
+ const courseId = course.getCourseID();
1413
+ const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
1414
+ const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
1415
+ const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
1416
+ const eloDistanceFilter = createEloDistanceFilter();
1417
+ return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
1418
+ }
1419
+ var init_defaults = __esm({
1420
+ "src/core/navigators/defaults.ts"() {
1421
+ "use strict";
1422
+ init_navigators();
1423
+ init_Pipeline();
1424
+ init_CompositeGenerator();
1425
+ init_elo();
1426
+ init_srs();
1427
+ init_eloDistance();
1428
+ init_types_legacy();
2262
1429
  }
2263
1430
  });
2264
1431
 
@@ -2267,7 +1434,7 @@ import {
2267
1434
  EloToNumber,
2268
1435
  Status,
2269
1436
  blankCourseElo as blankCourseElo2,
2270
- toCourseElo as toCourseElo6
1437
+ toCourseElo as toCourseElo4
2271
1438
  } from "@vue-skuilder/common";
2272
1439
  function randIntWeightedTowardZero(n) {
2273
1440
  return Math.floor(Math.random() * Math.random() * Math.random() * n);
@@ -2398,12 +1565,8 @@ var init_courseDB = __esm({
2398
1565
  init_courseAPI();
2399
1566
  init_courseLookupDB();
2400
1567
  init_navigators();
2401
- init_Pipeline();
2402
1568
  init_PipelineAssembler();
2403
- init_CompositeGenerator();
2404
- init_elo();
2405
- init_srs();
2406
- init_eloDistance();
1569
+ init_defaults();
2407
1570
  CoursesDB = class {
2408
1571
  _courseIDs;
2409
1572
  constructor(courseIDs) {
@@ -2515,7 +1678,7 @@ var init_courseDB = __esm({
2515
1678
  docs.rows.forEach((r) => {
2516
1679
  if (isSuccessRow(r)) {
2517
1680
  if (r.doc && r.doc.elo) {
2518
- ret.push(toCourseElo6(r.doc.elo));
1681
+ ret.push(toCourseElo4(r.doc.elo));
2519
1682
  } else {
2520
1683
  logger.warn("no elo data for card: " + r.id);
2521
1684
  ret.push(blankCourseElo2());
@@ -2584,15 +1747,6 @@ var init_courseDB = __esm({
2584
1747
  ret[r.id] = r.doc.id_displayable_data;
2585
1748
  }
2586
1749
  });
2587
- await Promise.all(
2588
- cards.rows.map((r) => {
2589
- return async () => {
2590
- if (isSuccessRow(r)) {
2591
- ret[r.id] = r.doc.id_displayable_data;
2592
- }
2593
- };
2594
- })
2595
- );
2596
1750
  return ret;
2597
1751
  }
2598
1752
  async getCardsByELO(elo, cardLimit) {
@@ -2677,6 +1831,28 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
2677
1831
  throw new Error(`Failed to find tags for card ${this.id}-${cardId}`);
2678
1832
  }
2679
1833
  }
1834
+ async getAppliedTagsBatch(cardIds) {
1835
+ if (cardIds.length === 0) {
1836
+ return /* @__PURE__ */ new Map();
1837
+ }
1838
+ const db = getCourseDB2(this.id);
1839
+ const result = await db.query("getTags", {
1840
+ keys: cardIds,
1841
+ include_docs: false
1842
+ });
1843
+ const tagsByCard = /* @__PURE__ */ new Map();
1844
+ for (const cardId of cardIds) {
1845
+ tagsByCard.set(cardId, []);
1846
+ }
1847
+ for (const row of result.rows) {
1848
+ const cardId = row.key;
1849
+ const tagName = row.value?.name;
1850
+ if (tagName && tagsByCard.has(cardId)) {
1851
+ tagsByCard.get(cardId).push(tagName);
1852
+ }
1853
+ }
1854
+ return tagsByCard;
1855
+ }
2680
1856
  async addTagToCard(cardId, tagId, updateELO) {
2681
1857
  return await addTagToCard(
2682
1858
  this.id,
@@ -2804,7 +1980,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
2804
1980
  logger.debug(
2805
1981
  "[courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])"
2806
1982
  );
2807
- return this.createDefaultPipeline(user);
1983
+ return createDefaultPipeline(user, this);
2808
1984
  }
2809
1985
  const assembler = new PipelineAssembler();
2810
1986
  const { pipeline, generatorStrategies, filterStrategies, warnings } = await assembler.assemble({
@@ -2817,7 +1993,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
2817
1993
  }
2818
1994
  if (!pipeline) {
2819
1995
  logger.debug("[courseDB] Pipeline assembly failed, using default pipeline");
2820
- return this.createDefaultPipeline(user);
1996
+ return createDefaultPipeline(user, this);
2821
1997
  }
2822
1998
  logger.debug(
2823
1999
  `[courseDB] Using assembled pipeline with ${generatorStrategies.length} generator(s) and ${filterStrategies.length} filter(s)`
@@ -2828,69 +2004,12 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
2828
2004
  throw e;
2829
2005
  }
2830
2006
  }
2831
- makeDefaultEloStrategy() {
2832
- return {
2833
- _id: "NAVIGATION_STRATEGY-ELO-default",
2834
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
2835
- name: "ELO (default)",
2836
- description: "Default ELO-based navigation strategy for new cards",
2837
- implementingClass: "elo" /* ELO */,
2838
- course: this.id,
2839
- serializedData: ""
2840
- };
2841
- }
2842
- makeDefaultSrsStrategy() {
2843
- return {
2844
- _id: "NAVIGATION_STRATEGY-SRS-default",
2845
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
2846
- name: "SRS (default)",
2847
- description: "Default SRS-based navigation strategy for reviews",
2848
- implementingClass: "srs" /* SRS */,
2849
- course: this.id,
2850
- serializedData: ""
2851
- };
2852
- }
2853
- /**
2854
- * Creates the default navigation pipeline for courses with no configured strategies.
2855
- *
2856
- * Default: Pipeline(Composite(ELO, SRS), [eloDistanceFilter])
2857
- * - ELO generator: scores new cards by skill proximity
2858
- * - SRS generator: scores reviews by overdueness and interval recency
2859
- * - ELO distance filter: penalizes cards far from user's current level
2860
- */
2861
- createDefaultPipeline(user) {
2862
- const eloNavigator = new ELONavigator(user, this, this.makeDefaultEloStrategy());
2863
- const srsNavigator = new SRSNavigator(user, this, this.makeDefaultSrsStrategy());
2864
- const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
2865
- const eloDistanceFilter = createEloDistanceFilter();
2866
- return new Pipeline(compositeGenerator, [eloDistanceFilter], user, this);
2867
- }
2868
2007
  ////////////////////////////////////
2869
2008
  // END NavigationStrategyManager implementation
2870
2009
  ////////////////////////////////////
2871
2010
  ////////////////////////////////////
2872
2011
  // StudyContentSource implementation
2873
2012
  ////////////////////////////////////
2874
- async getNewCards(limit = 99) {
2875
- const u = await this._getCurrentUser();
2876
- try {
2877
- const navigator = await this.createNavigator(u);
2878
- return navigator.getNewCards(limit);
2879
- } catch (e) {
2880
- logger.error(`[courseDB] Error in getNewCards: ${e}`);
2881
- throw e;
2882
- }
2883
- }
2884
- async getPendingReviews() {
2885
- const u = await this._getCurrentUser();
2886
- try {
2887
- const navigator = await this.createNavigator(u);
2888
- return navigator.getPendingReviews();
2889
- } catch (e) {
2890
- logger.error(`[courseDB] Error in getPendingReviews: ${e}`);
2891
- throw e;
2892
- }
2893
- }
2894
2013
  /**
2895
2014
  * Get cards with suitability scores for presentation.
2896
2015
  *
@@ -3141,79 +2260,27 @@ var init_classroomDB2 = __esm({
3141
2260
  setChangeFcn(f) {
3142
2261
  void this.userMessages.on("change", f);
3143
2262
  }
3144
- async getPendingReviews() {
3145
- const u = this._user;
3146
- return (await u.getPendingReviews()).filter((r) => r.scheduledFor === "classroom" && r.schedulingAgentId === this._id).map((r) => {
3147
- return {
3148
- ...r,
3149
- qualifiedID: `${r.courseId}-${r.cardId}`,
3150
- courseID: r.courseId,
3151
- cardID: r.cardId,
3152
- contentSourceType: "classroom",
3153
- contentSourceID: this._id,
3154
- reviewID: r._id,
3155
- status: "review"
3156
- };
3157
- });
3158
- }
3159
- async getNewCards() {
3160
- const activeCards = await this._user.getActiveCards();
3161
- const now = moment2.utc();
3162
- const assigned = await this.getAssignedContent();
3163
- const due = assigned.filter((c) => now.isAfter(moment2.utc(c.activeOn, REVIEW_TIME_FORMAT)));
3164
- logger.info(`Due content: ${JSON.stringify(due)}`);
3165
- let ret = [];
3166
- for (let i = 0; i < due.length; i++) {
3167
- const content = due[i];
3168
- if (content.type === "course") {
3169
- const db = new CourseDB(content.courseID, async () => this._user);
3170
- ret = ret.concat(await db.getNewCards());
3171
- } else if (content.type === "tag") {
3172
- const tagDoc = await getTag(content.courseID, content.tagID);
3173
- ret = ret.concat(
3174
- tagDoc.taggedCards.map((c) => {
3175
- return {
3176
- courseID: content.courseID,
3177
- cardID: c,
3178
- qualifiedID: `${content.courseID}-${c}`,
3179
- contentSourceType: "classroom",
3180
- contentSourceID: this._id,
3181
- status: "new"
3182
- };
3183
- })
3184
- );
3185
- } else if (content.type === "card") {
3186
- ret.push(await getCourseDB2(content.courseID).get(content.cardID));
3187
- }
3188
- }
3189
- logger.info(
3190
- `New Cards from classroom ${this._cfg.name}: ${ret.map((c) => `${c.courseID}-${c.cardID}`)}`
3191
- );
3192
- return ret.filter((c) => {
3193
- if (activeCards.some((ac) => c.cardID === ac.cardID)) {
3194
- return false;
3195
- } else {
3196
- return true;
3197
- }
3198
- });
3199
- }
3200
2263
  /**
3201
2264
  * Get cards with suitability scores for presentation.
3202
2265
  *
3203
- * This implementation wraps the legacy getNewCards/getPendingReviews methods,
3204
- * assigning score=1.0 to all cards. StudentClassroomDB does not currently
3205
- * support pluggable navigation strategies.
2266
+ * Gathers new cards from assigned content (courses, tags, cards) and
2267
+ * pending reviews scheduled for this classroom. Assigns score=1.0 to all.
3206
2268
  *
3207
2269
  * @param limit - Maximum number of cards to return
3208
2270
  * @returns Cards sorted by score descending (all scores = 1.0)
3209
2271
  */
3210
2272
  async getWeightedCards(limit) {
3211
- const [newCards, reviews] = await Promise.all([this.getNewCards(), this.getPendingReviews()]);
3212
- const weighted = [
3213
- ...newCards.map((c) => ({
3214
- cardId: c.cardID,
3215
- courseId: c.courseID,
2273
+ const weighted = [];
2274
+ const allUserReviews = await this._user.getPendingReviews();
2275
+ const classroomReviews = allUserReviews.filter(
2276
+ (r) => r.scheduledFor === "classroom" && r.schedulingAgentId === this._id
2277
+ );
2278
+ for (const r of classroomReviews) {
2279
+ weighted.push({
2280
+ cardId: r.cardId,
2281
+ courseId: r.courseId,
3216
2282
  score: 1,
2283
+ reviewID: r._id,
3217
2284
  provenance: [
3218
2285
  {
3219
2286
  strategy: "classroom",
@@ -3221,27 +2288,84 @@ var init_classroomDB2 = __esm({
3221
2288
  strategyId: "CLASSROOM",
3222
2289
  action: "generated",
3223
2290
  score: 1,
3224
- reason: "Classroom legacy getNewCards(), new card"
2291
+ reason: "Classroom scheduled review"
3225
2292
  }
3226
2293
  ]
3227
- })),
3228
- ...reviews.map((r) => ({
3229
- cardId: r.cardID,
3230
- courseId: r.courseID,
3231
- score: 1,
3232
- provenance: [
3233
- {
3234
- strategy: "classroom",
3235
- strategyName: "Classroom",
3236
- strategyId: "CLASSROOM",
3237
- action: "generated",
3238
- score: 1,
3239
- reason: "Classroom legacy getPendingReviews(), review"
2294
+ });
2295
+ }
2296
+ const activeCards = await this._user.getActiveCards();
2297
+ const activeCardIds = new Set(activeCards.map((ac) => ac.cardID));
2298
+ const now = moment2.utc();
2299
+ const assigned = await this.getAssignedContent();
2300
+ const due = assigned.filter((c) => now.isAfter(moment2.utc(c.activeOn, REVIEW_TIME_FORMAT)));
2301
+ logger.info(`[StudentClassroomDB] Due content: ${JSON.stringify(due)}`);
2302
+ for (const content of due) {
2303
+ if (content.type === "course") {
2304
+ const db = new CourseDB(content.courseID, async () => this._user);
2305
+ const courseCards = await db.getWeightedCards(limit);
2306
+ for (const card of courseCards) {
2307
+ if (!activeCardIds.has(card.cardId)) {
2308
+ weighted.push({
2309
+ ...card,
2310
+ provenance: [
2311
+ ...card.provenance,
2312
+ {
2313
+ strategy: "classroom",
2314
+ strategyName: "Classroom",
2315
+ strategyId: "CLASSROOM",
2316
+ action: "passed",
2317
+ score: card.score,
2318
+ reason: `Assigned via classroom from course ${content.courseID}`
2319
+ }
2320
+ ]
2321
+ });
3240
2322
  }
3241
- ]
3242
- }))
3243
- ];
3244
- return weighted.slice(0, limit);
2323
+ }
2324
+ } else if (content.type === "tag") {
2325
+ const tagDoc = await getTag(content.courseID, content.tagID);
2326
+ for (const cardId of tagDoc.taggedCards) {
2327
+ if (!activeCardIds.has(cardId)) {
2328
+ weighted.push({
2329
+ cardId,
2330
+ courseId: content.courseID,
2331
+ score: 1,
2332
+ provenance: [
2333
+ {
2334
+ strategy: "classroom",
2335
+ strategyName: "Classroom",
2336
+ strategyId: "CLASSROOM",
2337
+ action: "generated",
2338
+ score: 1,
2339
+ reason: `Classroom assigned tag: ${content.tagID}, new card`
2340
+ }
2341
+ ]
2342
+ });
2343
+ }
2344
+ }
2345
+ } else if (content.type === "card") {
2346
+ if (!activeCardIds.has(content.cardID)) {
2347
+ weighted.push({
2348
+ cardId: content.cardID,
2349
+ courseId: content.courseID,
2350
+ score: 1,
2351
+ provenance: [
2352
+ {
2353
+ strategy: "classroom",
2354
+ strategyName: "Classroom",
2355
+ strategyId: "CLASSROOM",
2356
+ action: "generated",
2357
+ score: 1,
2358
+ reason: "Classroom assigned card, new card"
2359
+ }
2360
+ ]
2361
+ });
2362
+ }
2363
+ }
2364
+ }
2365
+ logger.info(
2366
+ `[StudentClassroomDB] New cards from classroom ${this._cfg.name}: ${weighted.length} total (reviews + new)`
2367
+ );
2368
+ return weighted.sort((a, b) => b.score - a.score).slice(0, limit);
3245
2369
  }
3246
2370
  };
3247
2371
  TeacherClassroomDB = class _TeacherClassroomDB extends ClassroomDBBase {
@@ -3409,108 +2533,71 @@ var init_TagFilteredContentSource = __esm({
3409
2533
  return finalCardIds;
3410
2534
  }
3411
2535
  /**
3412
- * Gets new cards that match the tag filter and are not already active for the user.
2536
+ * Get cards with suitability scores for presentation.
2537
+ *
2538
+ * Filters cards by tag inclusion/exclusion and assigns score=1.0 to all.
2539
+ * TagFilteredContentSource does not currently support pluggable navigation
2540
+ * strategies - it returns flat-scored candidates.
2541
+ *
2542
+ * @param limit - Maximum number of cards to return
2543
+ * @returns Cards sorted by score descending (all scores = 1.0)
3413
2544
  */
3414
- async getNewCards(limit) {
2545
+ async getWeightedCards(limit) {
3415
2546
  if (!hasActiveFilter(this.filter)) {
3416
- logger.warn("[TagFilteredContentSource] getNewCards called with no active filter");
2547
+ logger.warn("[TagFilteredContentSource] getWeightedCards called with no active filter");
3417
2548
  return [];
3418
2549
  }
3419
2550
  const eligibleCardIds = await this.resolveFilteredCardIds();
3420
2551
  const activeCards = await this.user.getActiveCards();
3421
2552
  const activeCardIds = new Set(activeCards.map((c) => c.cardID));
3422
- const newItems = [];
2553
+ const newCardWeighted = [];
3423
2554
  for (const cardId of eligibleCardIds) {
3424
2555
  if (!activeCardIds.has(cardId)) {
3425
- newItems.push({
3426
- courseID: this.courseId,
3427
- cardID: cardId,
3428
- contentSourceType: "course",
3429
- contentSourceID: this.courseId,
3430
- status: "new"
2556
+ newCardWeighted.push({
2557
+ cardId,
2558
+ courseId: this.courseId,
2559
+ score: 1,
2560
+ provenance: [
2561
+ {
2562
+ strategy: "tagFilter",
2563
+ strategyName: "Tag Filter",
2564
+ strategyId: "TAG_FILTER",
2565
+ action: "generated",
2566
+ score: 1,
2567
+ reason: `Tag-filtered new card (tags: ${this.filter.include.join(", ")})`
2568
+ }
2569
+ ]
3431
2570
  });
3432
2571
  }
3433
- if (limit !== void 0 && newItems.length >= limit) {
2572
+ if (newCardWeighted.length >= limit) {
3434
2573
  break;
3435
2574
  }
3436
2575
  }
3437
- logger.info(`[TagFilteredContentSource] Found ${newItems.length} new cards matching filter`);
3438
- return newItems;
3439
- }
3440
- /**
3441
- * Gets pending reviews, filtered to only include cards that match the tag filter.
3442
- */
3443
- async getPendingReviews() {
3444
- if (!hasActiveFilter(this.filter)) {
3445
- logger.warn("[TagFilteredContentSource] getPendingReviews called with no active filter");
3446
- return [];
3447
- }
3448
- const eligibleCardIds = await this.resolveFilteredCardIds();
2576
+ logger.info(
2577
+ `[TagFilteredContentSource] Found ${newCardWeighted.length} new cards matching filter`
2578
+ );
3449
2579
  const allReviews = await this.user.getPendingReviews(this.courseId);
3450
- const filteredReviews = allReviews.filter((review) => {
3451
- return eligibleCardIds.has(review.cardId);
3452
- });
2580
+ const filteredReviews = allReviews.filter((review) => eligibleCardIds.has(review.cardId));
3453
2581
  logger.info(
3454
2582
  `[TagFilteredContentSource] Found ${filteredReviews.length} pending reviews matching filter (of ${allReviews.length} total)`
3455
2583
  );
3456
- return filteredReviews.map((r) => ({
3457
- ...r,
3458
- courseID: r.courseId,
3459
- cardID: r.cardId,
3460
- contentSourceType: "course",
3461
- contentSourceID: this.courseId,
2584
+ const reviewWeighted = filteredReviews.map((r) => ({
2585
+ cardId: r.cardId,
2586
+ courseId: r.courseId,
2587
+ score: 1,
3462
2588
  reviewID: r._id,
3463
- status: "review"
2589
+ provenance: [
2590
+ {
2591
+ strategy: "tagFilter",
2592
+ strategyName: "Tag Filter",
2593
+ strategyId: "TAG_FILTER",
2594
+ action: "generated",
2595
+ score: 1,
2596
+ reason: `Tag-filtered review (tags: ${this.filter.include.join(", ")})`
2597
+ }
2598
+ ]
3464
2599
  }));
3465
- }
3466
- /**
3467
- * Get cards with suitability scores for presentation.
3468
- *
3469
- * This implementation wraps the legacy getNewCards/getPendingReviews methods,
3470
- * assigning score=1.0 to all cards. TagFilteredContentSource does not currently
3471
- * support pluggable navigation strategies - it returns flat-scored candidates.
3472
- *
3473
- * @param limit - Maximum number of cards to return
3474
- * @returns Cards sorted by score descending (all scores = 1.0)
3475
- */
3476
- async getWeightedCards(limit) {
3477
- const [newCards, reviews] = await Promise.all([
3478
- this.getNewCards(limit),
3479
- this.getPendingReviews()
3480
- ]);
3481
- const weighted = [
3482
- ...reviews.map((r) => ({
3483
- cardId: r.cardID,
3484
- courseId: r.courseID,
3485
- score: 1,
3486
- provenance: [
3487
- {
3488
- strategy: "tagFilter",
3489
- strategyName: "Tag Filter",
3490
- strategyId: "TAG_FILTER",
3491
- action: "generated",
3492
- score: 1,
3493
- reason: `Tag-filtered review (tags: ${this.filter.include.join(", ")})`
3494
- }
3495
- ]
3496
- })),
3497
- ...newCards.map((c) => ({
3498
- cardId: c.cardID,
3499
- courseId: c.courseID,
3500
- score: 1,
3501
- provenance: [
3502
- {
3503
- strategy: "tagFilter",
3504
- strategyName: "Tag Filter",
3505
- strategyId: "TAG_FILTER",
3506
- action: "generated",
3507
- score: 1,
3508
- reason: `Tag-filtered new card (tags: ${this.filter.include.join(", ")})`
3509
- }
3510
- ]
3511
- }))
3512
- ];
3513
- return weighted.slice(0, limit);
2600
+ return [...reviewWeighted, ...newCardWeighted].slice(0, limit);
3514
2601
  }
3515
2602
  /**
3516
2603
  * Clears the cached resolved card IDs.
@@ -3601,6 +2688,16 @@ var init_user = __esm({
3601
2688
  }
3602
2689
  });
3603
2690
 
2691
+ // src/core/types/strategyState.ts
2692
+ function buildStrategyStateId(courseId, strategyKey) {
2693
+ return `STRATEGY_STATE::${courseId}::${strategyKey}`;
2694
+ }
2695
+ var init_strategyState = __esm({
2696
+ "src/core/types/strategyState.ts"() {
2697
+ "use strict";
2698
+ }
2699
+ });
2700
+
3604
2701
  // src/core/util/index.ts
3605
2702
  function getCardHistoryID(courseID, cardID) {
3606
2703
  return `${DocTypePrefixes["CARDRECORD" /* CARDRECORD */]}-${courseID}-${cardID}`;
@@ -3622,7 +2719,7 @@ var init_cardProcessor = __esm({
3622
2719
  });
3623
2720
 
3624
2721
  // src/core/bulkImport/types.ts
3625
- var init_types3 = __esm({
2722
+ var init_types = __esm({
3626
2723
  "src/core/bulkImport/types.ts"() {
3627
2724
  "use strict";
3628
2725
  }
@@ -3633,7 +2730,7 @@ var init_bulkImport = __esm({
3633
2730
  "src/core/bulkImport/index.ts"() {
3634
2731
  "use strict";
3635
2732
  init_cardProcessor();
3636
- init_types3();
2733
+ init_types();
3637
2734
  }
3638
2735
  });
3639
2736
 
@@ -3644,6 +2741,7 @@ var init_core = __esm({
3644
2741
  init_interfaces();
3645
2742
  init_types_legacy();
3646
2743
  init_user();
2744
+ init_strategyState();
3647
2745
  init_Loggable();
3648
2746
  init_util();
3649
2747
  init_navigators();
@@ -3651,14 +2749,6 @@ var init_core = __esm({
3651
2749
  }
3652
2750
  });
3653
2751
 
3654
- // src/util/tuiLogger.ts
3655
- var init_tuiLogger = __esm({
3656
- "src/util/tuiLogger.ts"() {
3657
- "use strict";
3658
- init_dataDirectory();
3659
- }
3660
- });
3661
-
3662
2752
  // src/util/dataDirectory.ts
3663
2753
  import * as path from "path";
3664
2754
  import * as os from "os";
@@ -3675,7 +2765,7 @@ function getDbPath(dbName) {
3675
2765
  var init_dataDirectory = __esm({
3676
2766
  "src/util/dataDirectory.ts"() {
3677
2767
  "use strict";
3678
- init_tuiLogger();
2768
+ init_logger();
3679
2769
  init_factory();
3680
2770
  }
3681
2771
  });
@@ -3832,7 +2922,9 @@ import moment5 from "moment";
3832
2922
  function accomodateGuest() {
3833
2923
  logger.log("[funnel] accomodateGuest() called");
3834
2924
  if (typeof localStorage === "undefined") {
3835
- logger.log("[funnel] localStorage not available (Node.js environment), returning default guest");
2925
+ logger.log(
2926
+ "[funnel] localStorage not available (Node.js environment), returning default guest"
2927
+ );
3836
2928
  return {
3837
2929
  username: GuestUsername + "nodejs-test",
3838
2930
  firstVisit: true
@@ -4810,6 +3902,55 @@ Currently logged-in as ${this._username}.`
4810
3902
  async updateUserElo(courseId, elo) {
4811
3903
  return updateUserElo(this._username, courseId, elo);
4812
3904
  }
3905
+ async getStrategyState(courseId, strategyKey) {
3906
+ const docId = buildStrategyStateId(courseId, strategyKey);
3907
+ try {
3908
+ const doc = await this.localDB.get(docId);
3909
+ return doc.data;
3910
+ } catch (e) {
3911
+ const err = e;
3912
+ if (err.status === 404) {
3913
+ return null;
3914
+ }
3915
+ throw e;
3916
+ }
3917
+ }
3918
+ async putStrategyState(courseId, strategyKey, data) {
3919
+ const docId = buildStrategyStateId(courseId, strategyKey);
3920
+ let existingRev;
3921
+ try {
3922
+ const existing = await this.localDB.get(docId);
3923
+ existingRev = existing._rev;
3924
+ } catch (e) {
3925
+ const err = e;
3926
+ if (err.status !== 404) {
3927
+ throw e;
3928
+ }
3929
+ }
3930
+ const doc = {
3931
+ _id: docId,
3932
+ _rev: existingRev,
3933
+ docType: "STRATEGY_STATE" /* STRATEGY_STATE */,
3934
+ courseId,
3935
+ strategyKey,
3936
+ data,
3937
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
3938
+ };
3939
+ await this.localDB.put(doc);
3940
+ }
3941
+ async deleteStrategyState(courseId, strategyKey) {
3942
+ const docId = buildStrategyStateId(courseId, strategyKey);
3943
+ try {
3944
+ const doc = await this.localDB.get(docId);
3945
+ await this.localDB.remove(doc);
3946
+ } catch (e) {
3947
+ const err = e;
3948
+ if (err.status === 404) {
3949
+ return;
3950
+ }
3951
+ throw e;
3952
+ }
3953
+ }
4813
3954
  };
4814
3955
  userCoursesDoc = "CourseRegistrations";
4815
3956
  userClassroomsDoc = "ClassroomRegistrations";
@@ -4910,8 +4051,7 @@ var init_adminDB2 = __esm({
4910
4051
  }
4911
4052
  }
4912
4053
  }
4913
- const dbs = await Promise.all(promisedCRDbs);
4914
- return dbs.map((db) => {
4054
+ return promisedCRDbs.map((db) => {
4915
4055
  return {
4916
4056
  ...db.getConfig(),
4917
4057
  _id: db._id