@vue-skuilder/db 0.1.17 → 0.1.20

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 (92) hide show
  1. package/dist/{userDB-BqwxtJ_7.d.mts → classroomDB-CZdMBiTU.d.ts} +427 -104
  2. package/dist/{userDB-DNa0XPtn.d.ts → classroomDB-PxDZTky3.d.cts} +427 -104
  3. package/dist/core/index.d.cts +304 -0
  4. package/dist/core/index.d.ts +237 -25
  5. package/dist/core/index.js +2246 -118
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +2235 -114
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-VlngD19_.d.mts → dataLayerProvider-D0MoZMjH.d.cts} +1 -1
  10. package/dist/{dataLayerProvider-BV5iZqt_.d.ts → dataLayerProvider-D8o6ZnKW.d.ts} +1 -1
  11. package/dist/impl/couch/{index.d.mts → index.d.cts} +47 -5
  12. package/dist/impl/couch/index.d.ts +46 -4
  13. package/dist/impl/couch/index.js +2250 -134
  14. package/dist/impl/couch/index.js.map +1 -1
  15. package/dist/impl/couch/index.mjs +2212 -97
  16. package/dist/impl/couch/index.mjs.map +1 -1
  17. package/dist/impl/static/{index.d.mts → index.d.cts} +6 -6
  18. package/dist/impl/static/index.d.ts +5 -5
  19. package/dist/impl/static/index.js +1950 -143
  20. package/dist/impl/static/index.js.map +1 -1
  21. package/dist/impl/static/index.mjs +1922 -117
  22. package/dist/impl/static/index.mjs.map +1 -1
  23. package/dist/{index-Bmll7Xse.d.mts → index-B_j6u5E4.d.cts} +1 -1
  24. package/dist/{index-CD8BZz2k.d.ts → index-Dj0SEgk3.d.ts} +1 -1
  25. package/dist/{index.d.mts → index.d.cts} +97 -13
  26. package/dist/index.d.ts +96 -12
  27. package/dist/index.js +2439 -180
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +2386 -135
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/pouch/index.js +3 -3
  32. package/dist/{types-Dbp5DaRR.d.mts → types-Bn0itutr.d.cts} +1 -1
  33. package/dist/{types-CewsN87z.d.ts → types-DQaXnuoc.d.ts} +1 -1
  34. package/dist/{types-legacy-6ettoclI.d.ts → types-legacy-DDY4N-Uq.d.cts} +3 -1
  35. package/dist/{types-legacy-6ettoclI.d.mts → types-legacy-DDY4N-Uq.d.ts} +3 -1
  36. package/dist/util/packer/{index.d.mts → index.d.cts} +3 -3
  37. package/dist/util/packer/index.d.ts +3 -3
  38. package/dist/util/packer/index.js.map +1 -1
  39. package/dist/util/packer/index.mjs.map +1 -1
  40. package/docs/brainstorm-navigation-paradigm.md +369 -0
  41. package/docs/navigators-architecture.md +370 -0
  42. package/docs/todo-evolutionary-orchestration.md +310 -0
  43. package/docs/todo-nominal-tag-types.md +121 -0
  44. package/docs/todo-strategy-authoring.md +401 -0
  45. package/eslint.config.mjs +1 -1
  46. package/package.json +9 -4
  47. package/src/core/index.ts +1 -0
  48. package/src/core/interfaces/contentSource.ts +88 -4
  49. package/src/core/interfaces/courseDB.ts +13 -0
  50. package/src/core/interfaces/navigationStrategyManager.ts +0 -5
  51. package/src/core/interfaces/userDB.ts +32 -0
  52. package/src/core/navigators/CompositeGenerator.ts +268 -0
  53. package/src/core/navigators/Pipeline.ts +318 -0
  54. package/src/core/navigators/PipelineAssembler.ts +194 -0
  55. package/src/core/navigators/elo.ts +104 -15
  56. package/src/core/navigators/filters/eloDistance.ts +132 -0
  57. package/src/core/navigators/filters/index.ts +9 -0
  58. package/src/core/navigators/filters/types.ts +115 -0
  59. package/src/core/navigators/filters/userTagPreference.ts +232 -0
  60. package/src/core/navigators/generators/index.ts +2 -0
  61. package/src/core/navigators/generators/types.ts +107 -0
  62. package/src/core/navigators/hardcodedOrder.ts +111 -12
  63. package/src/core/navigators/hierarchyDefinition.ts +266 -0
  64. package/src/core/navigators/index.ts +404 -3
  65. package/src/core/navigators/inferredPreference.ts +107 -0
  66. package/src/core/navigators/interferenceMitigator.ts +355 -0
  67. package/src/core/navigators/relativePriority.ts +255 -0
  68. package/src/core/navigators/srs.ts +195 -0
  69. package/src/core/navigators/userGoal.ts +136 -0
  70. package/src/core/types/strategyState.ts +84 -0
  71. package/src/core/types/types-legacy.ts +2 -0
  72. package/src/impl/common/BaseUserDB.ts +74 -7
  73. package/src/impl/couch/adminDB.ts +1 -2
  74. package/src/impl/couch/classroomDB.ts +51 -0
  75. package/src/impl/couch/courseDB.ts +147 -49
  76. package/src/impl/static/courseDB.ts +11 -4
  77. package/src/study/SessionController.ts +149 -1
  78. package/src/study/TagFilteredContentSource.ts +255 -0
  79. package/src/study/index.ts +1 -0
  80. package/src/util/dataDirectory.test.ts +51 -22
  81. package/src/util/logger.ts +0 -1
  82. package/tests/core/navigators/CompositeGenerator.test.ts +455 -0
  83. package/tests/core/navigators/Pipeline.test.ts +406 -0
  84. package/tests/core/navigators/PipelineAssembler.test.ts +351 -0
  85. package/tests/core/navigators/SRSNavigator.test.ts +344 -0
  86. package/tests/core/navigators/eloDistanceFilter.test.ts +192 -0
  87. package/tests/core/navigators/navigators.test.ts +710 -0
  88. package/tsconfig.json +1 -1
  89. package/vitest.config.ts +29 -0
  90. package/dist/core/index.d.mts +0 -92
  91. /package/dist/{SyncStrategy-CyATpyLQ.d.mts → SyncStrategy-CyATpyLQ.d.cts} +0 -0
  92. /package/dist/pouch/{index.d.mts → index.d.cts} +0 -0
@@ -122,6 +122,7 @@ var init_types_legacy = __esm({
122
122
  DocType2["SCHEDULED_CARD"] = "SCHEDULED_CARD";
123
123
  DocType2["TAG"] = "TAG";
124
124
  DocType2["NAVIGATION_STRATEGY"] = "NAVIGATION_STRATEGY";
125
+ DocType2["STRATEGY_STATE"] = "STRATEGY_STATE";
125
126
  return DocType2;
126
127
  })(DocType || {});
127
128
  DocTypePrefixes = {
@@ -135,7 +136,8 @@ var init_types_legacy = __esm({
135
136
  ["QUESTION" /* QUESTIONTYPE */]: "QUESTION",
136
137
  ["VIEW" /* VIEW */]: "VIEW",
137
138
  ["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
138
- ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY"
139
+ ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
140
+ ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE"
139
141
  };
140
142
  }
141
143
  });
@@ -181,9 +183,9 @@ var import_pouchdb, import_pouchdb_find, import_pouchdb_authentication, pouchdb_
181
183
  var init_pouchdb_setup = __esm({
182
184
  "src/impl/couch/pouchdb-setup.ts"() {
183
185
  "use strict";
184
- import_pouchdb = __toESM(require("pouchdb"));
185
- import_pouchdb_find = __toESM(require("pouchdb-find"));
186
- import_pouchdb_authentication = __toESM(require("@nilock2/pouchdb-authentication"));
186
+ import_pouchdb = __toESM(require("pouchdb"), 1);
187
+ import_pouchdb_find = __toESM(require("pouchdb-find"), 1);
188
+ import_pouchdb_authentication = __toESM(require("@nilock2/pouchdb-authentication"), 1);
187
189
  import_pouchdb.default.plugin(import_pouchdb_find.default);
188
190
  import_pouchdb.default.plugin(import_pouchdb_authentication.default);
189
191
  import_pouchdb.default.defaults({
@@ -218,8 +220,8 @@ var path, os;
218
220
  var init_dataDirectory = __esm({
219
221
  "src/util/dataDirectory.ts"() {
220
222
  "use strict";
221
- path = __toESM(require("path"));
222
- os = __toESM(require("os"));
223
+ path = __toESM(require("path"), 1);
224
+ os = __toESM(require("os"), 1);
223
225
  init_tuiLogger();
224
226
  init_factory();
225
227
  }
@@ -279,7 +281,7 @@ var import_moment, REVIEW_TIME_FORMAT, log2;
279
281
  var init_userDBHelpers = __esm({
280
282
  "src/impl/common/userDBHelpers.ts"() {
281
283
  "use strict";
282
- import_moment = __toESM(require("moment"));
284
+ import_moment = __toESM(require("moment"), 1);
283
285
  init_core();
284
286
  init_logger();
285
287
  init_pouchdb_setup();
@@ -435,7 +437,7 @@ var import_moment2, UsrCrsData;
435
437
  var init_user_course_relDB = __esm({
436
438
  "src/impl/couch/user-course-relDB.ts"() {
437
439
  "use strict";
438
- import_moment2 = __toESM(require("moment"));
440
+ import_moment2 = __toESM(require("moment"), 1);
439
441
  init_logger();
440
442
  UsrCrsData = class {
441
443
  user;
@@ -709,23 +711,518 @@ var init_courseLookupDB = __esm({
709
711
  }
710
712
  });
711
713
 
714
+ // src/core/navigators/CompositeGenerator.ts
715
+ var CompositeGenerator_exports = {};
716
+ __export(CompositeGenerator_exports, {
717
+ AggregationMode: () => AggregationMode,
718
+ default: () => CompositeGenerator
719
+ });
720
+ var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
721
+ var init_CompositeGenerator = __esm({
722
+ "src/core/navigators/CompositeGenerator.ts"() {
723
+ "use strict";
724
+ init_navigators();
725
+ init_logger();
726
+ AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
727
+ AggregationMode2["MAX"] = "max";
728
+ AggregationMode2["AVERAGE"] = "average";
729
+ AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
730
+ return AggregationMode2;
731
+ })(AggregationMode || {});
732
+ DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
733
+ FREQUENCY_BOOST_FACTOR = 0.1;
734
+ CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
735
+ /** Human-readable name for CardGenerator interface */
736
+ name = "Composite Generator";
737
+ generators;
738
+ aggregationMode;
739
+ constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
740
+ super();
741
+ this.generators = generators;
742
+ this.aggregationMode = aggregationMode;
743
+ if (generators.length === 0) {
744
+ throw new Error("CompositeGenerator requires at least one generator");
745
+ }
746
+ logger.debug(
747
+ `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
748
+ );
749
+ }
750
+ /**
751
+ * Creates a CompositeGenerator from strategy data.
752
+ *
753
+ * This is a convenience factory for use by PipelineAssembler.
754
+ */
755
+ static async fromStrategies(user, course, strategies, aggregationMode = DEFAULT_AGGREGATION_MODE) {
756
+ const generators = await Promise.all(
757
+ strategies.map((s) => ContentNavigator.create(user, course, s))
758
+ );
759
+ return new _CompositeGenerator(generators, aggregationMode);
760
+ }
761
+ /**
762
+ * Get weighted cards from all generators, merge and deduplicate.
763
+ *
764
+ * Cards appearing in multiple generators receive a score boost.
765
+ * Provenance tracks which generators produced each card and how scores were aggregated.
766
+ *
767
+ * This method supports both the legacy signature (limit only) and the
768
+ * CardGenerator interface signature (limit, context).
769
+ *
770
+ * @param limit - Maximum number of cards to return
771
+ * @param context - Optional GeneratorContext passed to child generators
772
+ */
773
+ async getWeightedCards(limit, context) {
774
+ const results = await Promise.all(
775
+ this.generators.map((g) => g.getWeightedCards(limit, context))
776
+ );
777
+ const byCardId = /* @__PURE__ */ new Map();
778
+ for (const cards of results) {
779
+ for (const card of cards) {
780
+ const existing = byCardId.get(card.cardId) || [];
781
+ existing.push(card);
782
+ byCardId.set(card.cardId, existing);
783
+ }
784
+ }
785
+ const merged = [];
786
+ for (const [, cards] of byCardId) {
787
+ const aggregatedScore = this.aggregateScores(cards);
788
+ const finalScore = Math.min(1, aggregatedScore);
789
+ const mergedProvenance = cards.flatMap((c) => c.provenance);
790
+ const initialScore = cards[0].score;
791
+ const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
792
+ const reason = this.buildAggregationReason(cards, finalScore);
793
+ merged.push({
794
+ ...cards[0],
795
+ score: finalScore,
796
+ provenance: [
797
+ ...mergedProvenance,
798
+ {
799
+ strategy: "composite",
800
+ strategyName: "Composite Generator",
801
+ strategyId: "COMPOSITE_GENERATOR",
802
+ action,
803
+ score: finalScore,
804
+ reason
805
+ }
806
+ ]
807
+ });
808
+ }
809
+ return merged.sort((a, b) => b.score - a.score).slice(0, limit);
810
+ }
811
+ /**
812
+ * Build human-readable reason for score aggregation.
813
+ */
814
+ buildAggregationReason(cards, finalScore) {
815
+ const count = cards.length;
816
+ const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
817
+ if (count === 1) {
818
+ return `Single generator, score ${finalScore.toFixed(2)}`;
819
+ }
820
+ const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
821
+ switch (this.aggregationMode) {
822
+ case "max" /* MAX */:
823
+ return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
824
+ case "average" /* AVERAGE */:
825
+ return `Average of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
826
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
827
+ const avg = cards.reduce((sum, c) => sum + c.score, 0) / count;
828
+ const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
829
+ return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
830
+ }
831
+ default:
832
+ return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
833
+ }
834
+ }
835
+ /**
836
+ * Aggregate scores from multiple generators for the same card.
837
+ */
838
+ aggregateScores(cards) {
839
+ const scores = cards.map((c) => c.score);
840
+ switch (this.aggregationMode) {
841
+ case "max" /* MAX */:
842
+ return Math.max(...scores);
843
+ case "average" /* AVERAGE */:
844
+ return scores.reduce((sum, s) => sum + s, 0) / scores.length;
845
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
846
+ const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
847
+ const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (cards.length - 1);
848
+ return avg * frequencyBoost;
849
+ }
850
+ default:
851
+ return scores[0];
852
+ }
853
+ }
854
+ /**
855
+ * Get new cards from all generators, merged and deduplicated.
856
+ */
857
+ async getNewCards(n) {
858
+ const legacyGenerators = this.generators.filter(
859
+ (g) => g instanceof ContentNavigator
860
+ );
861
+ const results = await Promise.all(legacyGenerators.map((g) => g.getNewCards(n)));
862
+ const seen = /* @__PURE__ */ new Set();
863
+ const merged = [];
864
+ for (const cards of results) {
865
+ for (const card of cards) {
866
+ if (!seen.has(card.cardID)) {
867
+ seen.add(card.cardID);
868
+ merged.push(card);
869
+ }
870
+ }
871
+ }
872
+ return n ? merged.slice(0, n) : merged;
873
+ }
874
+ /**
875
+ * Get pending reviews from all generators, merged and deduplicated.
876
+ */
877
+ async getPendingReviews() {
878
+ const legacyGenerators = this.generators.filter(
879
+ (g) => g instanceof ContentNavigator
880
+ );
881
+ const results = await Promise.all(legacyGenerators.map((g) => g.getPendingReviews()));
882
+ const seen = /* @__PURE__ */ new Set();
883
+ const merged = [];
884
+ for (const reviews of results) {
885
+ for (const review of reviews) {
886
+ if (!seen.has(review.cardID)) {
887
+ seen.add(review.cardID);
888
+ merged.push(review);
889
+ }
890
+ }
891
+ }
892
+ return merged;
893
+ }
894
+ };
895
+ }
896
+ });
897
+
898
+ // src/core/navigators/Pipeline.ts
899
+ var Pipeline_exports = {};
900
+ __export(Pipeline_exports, {
901
+ Pipeline: () => Pipeline
902
+ });
903
+ function logPipelineConfig(generator, filters) {
904
+ const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
905
+ logger.info(
906
+ `[Pipeline] Configuration:
907
+ Generator: ${generator.name}
908
+ Filters:${filterList}`
909
+ );
910
+ }
911
+ function logTagHydration(cards, tagsByCard) {
912
+ const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
913
+ const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
914
+ logger.debug(
915
+ `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
916
+ );
917
+ }
918
+ function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores) {
919
+ const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
920
+ logger.info(
921
+ `[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})`
922
+ );
923
+ }
924
+ function logCardProvenance(cards, maxCards = 3) {
925
+ const cardsToLog = cards.slice(0, maxCards);
926
+ logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
927
+ for (const card of cardsToLog) {
928
+ logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
929
+ for (const entry of card.provenance) {
930
+ const scoreChange = entry.score.toFixed(3);
931
+ const action = entry.action.padEnd(9);
932
+ logger.debug(
933
+ `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
934
+ );
935
+ }
936
+ }
937
+ }
938
+ var import_common5, Pipeline;
939
+ var init_Pipeline = __esm({
940
+ "src/core/navigators/Pipeline.ts"() {
941
+ "use strict";
942
+ import_common5 = require("@vue-skuilder/common");
943
+ init_navigators();
944
+ init_logger();
945
+ Pipeline = class extends ContentNavigator {
946
+ generator;
947
+ filters;
948
+ /**
949
+ * Create a new pipeline.
950
+ *
951
+ * @param generator - The generator (or CompositeGenerator) that produces candidates
952
+ * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
953
+ * @param user - User database interface
954
+ * @param course - Course database interface
955
+ */
956
+ constructor(generator, filters, user, course) {
957
+ super();
958
+ this.generator = generator;
959
+ this.filters = filters;
960
+ this.user = user;
961
+ this.course = course;
962
+ logPipelineConfig(generator, filters);
963
+ }
964
+ /**
965
+ * Get weighted cards by running generator and applying filters.
966
+ *
967
+ * 1. Build shared context (user ELO, etc.)
968
+ * 2. Get candidates from generator (passing context)
969
+ * 3. Batch hydrate tags for all candidates
970
+ * 4. Apply each filter sequentially
971
+ * 5. Remove zero-score cards
972
+ * 6. Sort by score descending
973
+ * 7. Return top N
974
+ *
975
+ * @param limit - Maximum number of cards to return
976
+ * @returns Cards sorted by score descending
977
+ */
978
+ async getWeightedCards(limit) {
979
+ const context = await this.buildContext();
980
+ const overFetchMultiplier = 2 + this.filters.length * 0.5;
981
+ const fetchLimit = Math.ceil(limit * overFetchMultiplier);
982
+ logger.debug(
983
+ `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
984
+ );
985
+ let cards = await this.generator.getWeightedCards(fetchLimit, context);
986
+ const generatedCount = cards.length;
987
+ logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
988
+ cards = await this.hydrateTags(cards);
989
+ for (const filter of this.filters) {
990
+ const beforeCount = cards.length;
991
+ cards = await filter.transform(cards, context);
992
+ logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeCount} \u2192 ${cards.length} cards`);
993
+ }
994
+ cards = cards.filter((c) => c.score > 0);
995
+ cards.sort((a, b) => b.score - a.score);
996
+ const result = cards.slice(0, limit);
997
+ const topScores = result.slice(0, 3).map((c) => c.score);
998
+ logExecutionSummary(this.generator.name, generatedCount, this.filters.length, result.length, topScores);
999
+ logCardProvenance(result, 3);
1000
+ return result;
1001
+ }
1002
+ /**
1003
+ * Batch hydrate tags for all cards.
1004
+ *
1005
+ * Fetches tags for all cards in a single database query and attaches them
1006
+ * to the WeightedCard objects. Filters can then use card.tags instead of
1007
+ * making individual getAppliedTags() calls.
1008
+ *
1009
+ * @param cards - Cards to hydrate
1010
+ * @returns Cards with tags populated
1011
+ */
1012
+ async hydrateTags(cards) {
1013
+ if (cards.length === 0) {
1014
+ return cards;
1015
+ }
1016
+ const cardIds = cards.map((c) => c.cardId);
1017
+ const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
1018
+ logTagHydration(cards, tagsByCard);
1019
+ return cards.map((card) => ({
1020
+ ...card,
1021
+ tags: tagsByCard.get(card.cardId) ?? []
1022
+ }));
1023
+ }
1024
+ /**
1025
+ * Build shared context for generator and filters.
1026
+ *
1027
+ * Called once per getWeightedCards() invocation.
1028
+ * Contains data that the generator and multiple filters might need.
1029
+ *
1030
+ * The context satisfies both GeneratorContext and FilterContext interfaces.
1031
+ */
1032
+ async buildContext() {
1033
+ let userElo = 1e3;
1034
+ try {
1035
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1036
+ const courseElo = (0, import_common5.toCourseElo)(courseReg.elo);
1037
+ userElo = courseElo.global.score;
1038
+ } catch (e) {
1039
+ logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
1040
+ }
1041
+ return {
1042
+ user: this.user,
1043
+ course: this.course,
1044
+ userElo
1045
+ };
1046
+ }
1047
+ // ===========================================================================
1048
+ // Legacy StudyContentSource methods
1049
+ // ===========================================================================
1050
+ //
1051
+ // These delegate to the generator for backward compatibility.
1052
+ // Eventually SessionController will use getWeightedCards() exclusively.
1053
+ //
1054
+ /**
1055
+ * Get new cards via legacy API.
1056
+ * Delegates to the generator if it supports the legacy interface.
1057
+ */
1058
+ async getNewCards(n) {
1059
+ if ("getNewCards" in this.generator && typeof this.generator.getNewCards === "function") {
1060
+ return this.generator.getNewCards(n);
1061
+ }
1062
+ return [];
1063
+ }
1064
+ /**
1065
+ * Get pending reviews via legacy API.
1066
+ * Delegates to the generator if it supports the legacy interface.
1067
+ */
1068
+ async getPendingReviews() {
1069
+ if ("getPendingReviews" in this.generator && typeof this.generator.getPendingReviews === "function") {
1070
+ return this.generator.getPendingReviews();
1071
+ }
1072
+ return [];
1073
+ }
1074
+ /**
1075
+ * Get the course ID for this pipeline.
1076
+ */
1077
+ getCourseID() {
1078
+ return this.course.getCourseID();
1079
+ }
1080
+ };
1081
+ }
1082
+ });
1083
+
1084
+ // src/core/navigators/PipelineAssembler.ts
1085
+ var PipelineAssembler_exports = {};
1086
+ __export(PipelineAssembler_exports, {
1087
+ PipelineAssembler: () => PipelineAssembler
1088
+ });
1089
+ var PipelineAssembler;
1090
+ var init_PipelineAssembler = __esm({
1091
+ "src/core/navigators/PipelineAssembler.ts"() {
1092
+ "use strict";
1093
+ init_navigators();
1094
+ init_Pipeline();
1095
+ init_types_legacy();
1096
+ init_logger();
1097
+ init_CompositeGenerator();
1098
+ PipelineAssembler = class {
1099
+ /**
1100
+ * Assembles a navigation pipeline from strategy documents.
1101
+ *
1102
+ * 1. Separates into generators and filters by role
1103
+ * 2. Validates at least one generator exists (or creates default ELO)
1104
+ * 3. Instantiates generators - wraps multiple in CompositeGenerator
1105
+ * 4. Instantiates filters
1106
+ * 5. Returns Pipeline(generator, filters)
1107
+ *
1108
+ * @param input - Strategy documents plus user/course interfaces
1109
+ * @returns Assembled pipeline and any warnings
1110
+ */
1111
+ async assemble(input) {
1112
+ const { strategies, user, course } = input;
1113
+ const warnings = [];
1114
+ if (strategies.length === 0) {
1115
+ return {
1116
+ pipeline: null,
1117
+ generatorStrategies: [],
1118
+ filterStrategies: [],
1119
+ warnings
1120
+ };
1121
+ }
1122
+ const generatorStrategies = [];
1123
+ const filterStrategies = [];
1124
+ for (const s of strategies) {
1125
+ if (isGenerator(s.implementingClass)) {
1126
+ generatorStrategies.push(s);
1127
+ } else if (isFilter(s.implementingClass)) {
1128
+ filterStrategies.push(s);
1129
+ } else {
1130
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
1131
+ }
1132
+ }
1133
+ if (generatorStrategies.length === 0) {
1134
+ if (filterStrategies.length > 0) {
1135
+ logger.debug(
1136
+ "[PipelineAssembler] No generator found, using default ELO with configured filters"
1137
+ );
1138
+ generatorStrategies.push(this.makeDefaultEloStrategy(course.getCourseID()));
1139
+ } else {
1140
+ warnings.push("No generator strategy found");
1141
+ return {
1142
+ pipeline: null,
1143
+ generatorStrategies: [],
1144
+ filterStrategies: [],
1145
+ warnings
1146
+ };
1147
+ }
1148
+ }
1149
+ let generator;
1150
+ if (generatorStrategies.length === 1) {
1151
+ const nav = await ContentNavigator.create(user, course, generatorStrategies[0]);
1152
+ generator = nav;
1153
+ logger.debug(`[PipelineAssembler] Using single generator: ${generatorStrategies[0].name}`);
1154
+ } else {
1155
+ logger.debug(
1156
+ `[PipelineAssembler] Using CompositeGenerator for ${generatorStrategies.length} generators: ${generatorStrategies.map((g) => g.name).join(", ")}`
1157
+ );
1158
+ generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
1159
+ }
1160
+ const filters = [];
1161
+ const sortedFilterStrategies = [...filterStrategies].sort(
1162
+ (a, b) => a.name.localeCompare(b.name)
1163
+ );
1164
+ for (const filterStrategy of sortedFilterStrategies) {
1165
+ try {
1166
+ const nav = await ContentNavigator.create(user, course, filterStrategy);
1167
+ if ("transform" in nav && typeof nav.transform === "function") {
1168
+ filters.push(nav);
1169
+ logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
1170
+ } else {
1171
+ warnings.push(
1172
+ `Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
1173
+ );
1174
+ }
1175
+ } catch (e) {
1176
+ warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
1177
+ }
1178
+ }
1179
+ const pipeline = new Pipeline(generator, filters, user, course);
1180
+ logger.debug(
1181
+ `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
1182
+ );
1183
+ return {
1184
+ pipeline,
1185
+ generatorStrategies,
1186
+ filterStrategies: sortedFilterStrategies,
1187
+ warnings
1188
+ };
1189
+ }
1190
+ /**
1191
+ * Creates a default ELO generator strategy.
1192
+ * Used when filters are configured but no generator is specified.
1193
+ */
1194
+ makeDefaultEloStrategy(courseId) {
1195
+ return {
1196
+ _id: "NAVIGATION_STRATEGY-ELO-default",
1197
+ course: courseId,
1198
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1199
+ name: "ELO (default)",
1200
+ description: "Default ELO-based generator",
1201
+ implementingClass: "elo" /* ELO */,
1202
+ serializedData: ""
1203
+ };
1204
+ }
1205
+ };
1206
+ }
1207
+ });
1208
+
712
1209
  // src/core/navigators/elo.ts
713
1210
  var elo_exports = {};
714
1211
  __export(elo_exports, {
715
1212
  default: () => ELONavigator
716
1213
  });
717
- var ELONavigator;
1214
+ var import_common6, ELONavigator;
718
1215
  var init_elo = __esm({
719
1216
  "src/core/navigators/elo.ts"() {
720
1217
  "use strict";
721
1218
  init_navigators();
1219
+ import_common6 = require("@vue-skuilder/common");
722
1220
  ELONavigator = class extends ContentNavigator {
723
- user;
724
- course;
725
- constructor(user, course) {
726
- super();
727
- this.user = user;
728
- this.course = course;
1221
+ /** Human-readable name for CardGenerator interface */
1222
+ name;
1223
+ constructor(user, course, strategyData) {
1224
+ super(user, course, strategyData);
1225
+ this.name = strategyData?.name || "ELO";
729
1226
  }
730
1227
  async getPendingReviews() {
731
1228
  const reviews = await this.user.getPendingReviews(this.course.getCourseID());
@@ -771,10 +1268,283 @@ var init_elo = __esm({
771
1268
  };
772
1269
  });
773
1270
  }
1271
+ /**
1272
+ * Get new cards with suitability scores based on ELO distance.
1273
+ *
1274
+ * Cards closer to user's ELO get higher scores.
1275
+ * Score formula: max(0, 1 - distance / 500)
1276
+ *
1277
+ * NOTE: This generator only handles NEW cards. Reviews are handled by
1278
+ * SRSNavigator. Use CompositeGenerator to combine both.
1279
+ *
1280
+ * This method supports both the legacy signature (limit only) and the
1281
+ * CardGenerator interface signature (limit, context).
1282
+ *
1283
+ * @param limit - Maximum number of cards to return
1284
+ * @param context - Optional GeneratorContext (used when called via Pipeline)
1285
+ */
1286
+ async getWeightedCards(limit, context) {
1287
+ let userGlobalElo;
1288
+ if (context?.userElo !== void 0) {
1289
+ userGlobalElo = context.userElo;
1290
+ } else {
1291
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1292
+ const userElo = (0, import_common6.toCourseElo)(courseReg.elo);
1293
+ userGlobalElo = userElo.global.score;
1294
+ }
1295
+ const newCards = await this.getNewCards(limit);
1296
+ const cardIds = newCards.map((c) => c.cardID);
1297
+ const cardEloData = await this.course.getCardEloData(cardIds);
1298
+ const scored = newCards.map((c, i) => {
1299
+ const cardElo = cardEloData[i]?.global?.score ?? 1e3;
1300
+ const distance = Math.abs(cardElo - userGlobalElo);
1301
+ const score = Math.max(0, 1 - distance / 500);
1302
+ return {
1303
+ cardId: c.cardID,
1304
+ courseId: c.courseID,
1305
+ score,
1306
+ provenance: [
1307
+ {
1308
+ strategy: "elo",
1309
+ strategyName: this.strategyName || this.name,
1310
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1311
+ action: "generated",
1312
+ score,
1313
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), new card`
1314
+ }
1315
+ ]
1316
+ };
1317
+ });
1318
+ scored.sort((a, b) => b.score - a.score);
1319
+ return scored.slice(0, limit);
1320
+ }
774
1321
  };
775
1322
  }
776
1323
  });
777
1324
 
1325
+ // src/core/navigators/filters/eloDistance.ts
1326
+ var eloDistance_exports = {};
1327
+ __export(eloDistance_exports, {
1328
+ DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1329
+ DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1330
+ DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1331
+ createEloDistanceFilter: () => createEloDistanceFilter
1332
+ });
1333
+ function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1334
+ const normalizedDistance = distance / halfLife;
1335
+ const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1336
+ return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1337
+ }
1338
+ function createEloDistanceFilter(config) {
1339
+ const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1340
+ const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1341
+ const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1342
+ return {
1343
+ name: "ELO Distance Filter",
1344
+ async transform(cards, context) {
1345
+ const { course, userElo } = context;
1346
+ const cardIds = cards.map((c) => c.cardId);
1347
+ const cardElos = await course.getCardEloData(cardIds);
1348
+ return cards.map((card, i) => {
1349
+ const cardElo = cardElos[i]?.global?.score ?? 1e3;
1350
+ const distance = Math.abs(cardElo - userElo);
1351
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1352
+ const newScore = card.score * multiplier;
1353
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1354
+ return {
1355
+ ...card,
1356
+ score: newScore,
1357
+ provenance: [
1358
+ ...card.provenance,
1359
+ {
1360
+ strategy: "eloDistance",
1361
+ strategyName: "ELO Distance Filter",
1362
+ strategyId: "ELO_DISTANCE_FILTER",
1363
+ action,
1364
+ score: newScore,
1365
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1366
+ }
1367
+ ]
1368
+ };
1369
+ });
1370
+ }
1371
+ };
1372
+ }
1373
+ var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1374
+ var init_eloDistance = __esm({
1375
+ "src/core/navigators/filters/eloDistance.ts"() {
1376
+ "use strict";
1377
+ DEFAULT_HALF_LIFE = 200;
1378
+ DEFAULT_MIN_MULTIPLIER = 0.3;
1379
+ DEFAULT_MAX_MULTIPLIER = 1;
1380
+ }
1381
+ });
1382
+
1383
+ // src/core/navigators/filters/userTagPreference.ts
1384
+ var userTagPreference_exports = {};
1385
+ __export(userTagPreference_exports, {
1386
+ default: () => UserTagPreferenceFilter
1387
+ });
1388
+ var UserTagPreferenceFilter;
1389
+ var init_userTagPreference = __esm({
1390
+ "src/core/navigators/filters/userTagPreference.ts"() {
1391
+ "use strict";
1392
+ init_navigators();
1393
+ UserTagPreferenceFilter = class extends ContentNavigator {
1394
+ _strategyData;
1395
+ /** Human-readable name for CardFilter interface */
1396
+ name;
1397
+ constructor(user, course, strategyData) {
1398
+ super(user, course, strategyData);
1399
+ this._strategyData = strategyData;
1400
+ this.name = strategyData.name || "User Tag Preferences";
1401
+ }
1402
+ /**
1403
+ * Compute multiplier for a card based on its tags and user preferences.
1404
+ * Returns the maximum multiplier among all matching tags, or 1.0 if no matches.
1405
+ */
1406
+ computeMultiplier(cardTags, boostMap) {
1407
+ const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== void 0);
1408
+ if (multipliers.length === 0) {
1409
+ return 1;
1410
+ }
1411
+ return Math.max(...multipliers);
1412
+ }
1413
+ /**
1414
+ * Build human-readable reason for the filter's decision.
1415
+ */
1416
+ buildReason(cardTags, boostMap, multiplier) {
1417
+ const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);
1418
+ if (multiplier === 0) {
1419
+ return `Excluded by user preference: ${matchingTags.join(", ")} (${multiplier}x)`;
1420
+ }
1421
+ if (multiplier < 1) {
1422
+ return `Penalized by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1423
+ }
1424
+ if (multiplier > 1) {
1425
+ return `Boosted by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1426
+ }
1427
+ return "No matching user preferences";
1428
+ }
1429
+ /**
1430
+ * CardFilter.transform implementation.
1431
+ *
1432
+ * Apply user tag preferences:
1433
+ * 1. Read preferences from strategy state
1434
+ * 2. If no preferences, pass through unchanged
1435
+ * 3. For each card:
1436
+ * - Look up tag in boost record
1437
+ * - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)
1438
+ * - If multiple tags match: use max multiplier
1439
+ * - Append provenance with clear reason
1440
+ */
1441
+ async transform(cards, _context) {
1442
+ const prefs = await this.getStrategyState();
1443
+ if (!prefs || Object.keys(prefs.boost).length === 0) {
1444
+ return cards.map((card) => ({
1445
+ ...card,
1446
+ provenance: [
1447
+ ...card.provenance,
1448
+ {
1449
+ strategy: "userTagPreference",
1450
+ strategyName: this.strategyName || this.name,
1451
+ strategyId: this.strategyId || this._strategyData._id,
1452
+ action: "passed",
1453
+ score: card.score,
1454
+ reason: "No user tag preferences configured"
1455
+ }
1456
+ ]
1457
+ }));
1458
+ }
1459
+ const adjusted = await Promise.all(
1460
+ cards.map(async (card) => {
1461
+ const cardTags = card.tags ?? [];
1462
+ const multiplier = this.computeMultiplier(cardTags, prefs.boost);
1463
+ const finalScore = Math.min(1, card.score * multiplier);
1464
+ let action;
1465
+ if (multiplier === 0 || multiplier < 1) {
1466
+ action = "penalized";
1467
+ } else if (multiplier > 1) {
1468
+ action = "boosted";
1469
+ } else {
1470
+ action = "passed";
1471
+ }
1472
+ return {
1473
+ ...card,
1474
+ score: finalScore,
1475
+ provenance: [
1476
+ ...card.provenance,
1477
+ {
1478
+ strategy: "userTagPreference",
1479
+ strategyName: this.strategyName || this.name,
1480
+ strategyId: this.strategyId || this._strategyData._id,
1481
+ action,
1482
+ score: finalScore,
1483
+ reason: this.buildReason(cardTags, prefs.boost, multiplier)
1484
+ }
1485
+ ]
1486
+ };
1487
+ })
1488
+ );
1489
+ return adjusted;
1490
+ }
1491
+ /**
1492
+ * Legacy getWeightedCards - throws as filters should not be used as generators.
1493
+ */
1494
+ async getWeightedCards(_limit) {
1495
+ throw new Error(
1496
+ "UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1497
+ );
1498
+ }
1499
+ // Legacy methods - stub implementations since filters don't generate cards
1500
+ async getNewCards(_n) {
1501
+ return [];
1502
+ }
1503
+ async getPendingReviews() {
1504
+ return [];
1505
+ }
1506
+ };
1507
+ }
1508
+ });
1509
+
1510
+ // src/core/navigators/filters/index.ts
1511
+ var filters_exports = {};
1512
+ __export(filters_exports, {
1513
+ UserTagPreferenceFilter: () => UserTagPreferenceFilter,
1514
+ createEloDistanceFilter: () => createEloDistanceFilter
1515
+ });
1516
+ var init_filters = __esm({
1517
+ "src/core/navigators/filters/index.ts"() {
1518
+ "use strict";
1519
+ init_eloDistance();
1520
+ init_userTagPreference();
1521
+ }
1522
+ });
1523
+
1524
+ // src/core/navigators/filters/types.ts
1525
+ var types_exports = {};
1526
+ var init_types = __esm({
1527
+ "src/core/navigators/filters/types.ts"() {
1528
+ "use strict";
1529
+ }
1530
+ });
1531
+
1532
+ // src/core/navigators/generators/index.ts
1533
+ var generators_exports = {};
1534
+ var init_generators = __esm({
1535
+ "src/core/navigators/generators/index.ts"() {
1536
+ "use strict";
1537
+ }
1538
+ });
1539
+
1540
+ // src/core/navigators/generators/types.ts
1541
+ var types_exports2 = {};
1542
+ var init_types2 = __esm({
1543
+ "src/core/navigators/generators/types.ts"() {
1544
+ "use strict";
1545
+ }
1546
+ });
1547
+
778
1548
  // src/core/navigators/hardcodedOrder.ts
779
1549
  var hardcodedOrder_exports = {};
780
1550
  __export(hardcodedOrder_exports, {
@@ -787,13 +1557,12 @@ var init_hardcodedOrder = __esm({
787
1557
  init_navigators();
788
1558
  init_logger();
789
1559
  HardcodedOrderNavigator = class extends ContentNavigator {
1560
+ /** Human-readable name for CardGenerator interface */
1561
+ name;
790
1562
  orderedCardIds = [];
791
- user;
792
- course;
793
1563
  constructor(user, course, strategyData) {
794
- super();
795
- this.user = user;
796
- this.course = course;
1564
+ super(user, course, strategyData);
1565
+ this.name = strategyData.name || "Hardcoded Order";
797
1566
  if (strategyData.serializedData) {
798
1567
  try {
799
1568
  this.orderedCardIds = JSON.parse(strategyData.serializedData);
@@ -816,34 +1585,808 @@ var init_hardcodedOrder = __esm({
816
1585
  };
817
1586
  });
818
1587
  }
819
- async getNewCards(limit = 99) {
820
- const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
821
- const newCardIds = this.orderedCardIds.filter(
822
- (cardId) => !activeCardIds.includes(cardId)
823
- );
824
- const cardsToReturn = newCardIds.slice(0, limit);
825
- return cardsToReturn.map((cardId) => {
1588
+ async getNewCards(limit = 99) {
1589
+ const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
1590
+ const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
1591
+ const cardsToReturn = newCardIds.slice(0, limit);
1592
+ return cardsToReturn.map((cardId) => {
1593
+ return {
1594
+ cardID: cardId,
1595
+ courseID: this.course.getCourseID(),
1596
+ contentSourceType: "course",
1597
+ contentSourceID: this.course.getCourseID(),
1598
+ status: "new"
1599
+ };
1600
+ });
1601
+ }
1602
+ /**
1603
+ * Get cards in hardcoded order with scores based on position.
1604
+ *
1605
+ * Earlier cards in the sequence get higher scores.
1606
+ * Score formula: 1.0 - (position / totalCards) * 0.5
1607
+ * This ensures scores range from 1.0 (first card) to 0.5+ (last card).
1608
+ *
1609
+ * This method supports both the legacy signature (limit only) and the
1610
+ * CardGenerator interface signature (limit, context).
1611
+ *
1612
+ * @param limit - Maximum number of cards to return
1613
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1614
+ */
1615
+ async getWeightedCards(limit, _context) {
1616
+ const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
1617
+ const reviews = await this.getPendingReviews();
1618
+ const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
1619
+ const totalCards = newCardIds.length;
1620
+ const scoredNew = newCardIds.slice(0, limit).map((cardId, index) => {
1621
+ const position = index + 1;
1622
+ const score = Math.max(0.5, 1 - index / totalCards * 0.5);
1623
+ return {
1624
+ cardId,
1625
+ courseId: this.course.getCourseID(),
1626
+ score,
1627
+ provenance: [
1628
+ {
1629
+ strategy: "hardcodedOrder",
1630
+ strategyName: this.strategyName || this.name,
1631
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1632
+ action: "generated",
1633
+ score,
1634
+ reason: `Position ${position} of ${totalCards} in fixed sequence, new card`
1635
+ }
1636
+ ]
1637
+ };
1638
+ });
1639
+ const scoredReviews = reviews.map((r) => ({
1640
+ cardId: r.cardID,
1641
+ courseId: r.courseID,
1642
+ score: 1,
1643
+ provenance: [
1644
+ {
1645
+ strategy: "hardcodedOrder",
1646
+ strategyName: this.strategyName || this.name,
1647
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1648
+ action: "generated",
1649
+ score: 1,
1650
+ reason: "Scheduled review, highest priority"
1651
+ }
1652
+ ]
1653
+ }));
1654
+ const all = [...scoredReviews, ...scoredNew];
1655
+ all.sort((a, b) => b.score - a.score);
1656
+ return all.slice(0, limit);
1657
+ }
1658
+ };
1659
+ }
1660
+ });
1661
+
1662
+ // src/core/navigators/hierarchyDefinition.ts
1663
+ var hierarchyDefinition_exports = {};
1664
+ __export(hierarchyDefinition_exports, {
1665
+ default: () => HierarchyDefinitionNavigator
1666
+ });
1667
+ var import_common7, DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1668
+ var init_hierarchyDefinition = __esm({
1669
+ "src/core/navigators/hierarchyDefinition.ts"() {
1670
+ "use strict";
1671
+ init_navigators();
1672
+ import_common7 = require("@vue-skuilder/common");
1673
+ DEFAULT_MIN_COUNT = 3;
1674
+ HierarchyDefinitionNavigator = class extends ContentNavigator {
1675
+ config;
1676
+ _strategyData;
1677
+ /** Human-readable name for CardFilter interface */
1678
+ name;
1679
+ constructor(user, course, _strategyData) {
1680
+ super(user, course, _strategyData);
1681
+ this._strategyData = _strategyData;
1682
+ this.config = this.parseConfig(_strategyData.serializedData);
1683
+ this.name = _strategyData.name || "Hierarchy Definition";
1684
+ }
1685
+ parseConfig(serializedData) {
1686
+ try {
1687
+ const parsed = JSON.parse(serializedData);
1688
+ return {
1689
+ prerequisites: parsed.prerequisites || {}
1690
+ };
1691
+ } catch {
1692
+ return {
1693
+ prerequisites: {}
1694
+ };
1695
+ }
1696
+ }
1697
+ /**
1698
+ * Check if a specific prerequisite is satisfied
1699
+ */
1700
+ isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1701
+ if (!userTagElo) return false;
1702
+ const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1703
+ if (userTagElo.count < minCount) return false;
1704
+ if (prereq.masteryThreshold?.minElo !== void 0) {
1705
+ return userTagElo.score >= prereq.masteryThreshold.minElo;
1706
+ } else {
1707
+ return userTagElo.score >= userGlobalElo;
1708
+ }
1709
+ }
1710
+ /**
1711
+ * Get the set of tags the user has mastered.
1712
+ * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1713
+ */
1714
+ async getMasteredTags(context) {
1715
+ const mastered = /* @__PURE__ */ new Set();
1716
+ try {
1717
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1718
+ const userElo = (0, import_common7.toCourseElo)(courseReg.elo);
1719
+ for (const prereqs of Object.values(this.config.prerequisites)) {
1720
+ for (const prereq of prereqs) {
1721
+ const tagElo = userElo.tags[prereq.tag];
1722
+ if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1723
+ mastered.add(prereq.tag);
1724
+ }
1725
+ }
1726
+ }
1727
+ } catch {
1728
+ }
1729
+ return mastered;
1730
+ }
1731
+ /**
1732
+ * Get the set of tags that are unlocked (prerequisites met)
1733
+ */
1734
+ getUnlockedTags(masteredTags) {
1735
+ const unlocked = /* @__PURE__ */ new Set();
1736
+ for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1737
+ const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1738
+ if (allPrereqsMet) {
1739
+ unlocked.add(tagId);
1740
+ }
1741
+ }
1742
+ return unlocked;
1743
+ }
1744
+ /**
1745
+ * Check if a tag has prerequisites defined in config
1746
+ */
1747
+ hasPrerequisites(tagId) {
1748
+ return tagId in this.config.prerequisites;
1749
+ }
1750
+ /**
1751
+ * Check if a card is unlocked and generate reason.
1752
+ */
1753
+ async checkCardUnlock(card, course, unlockedTags, masteredTags) {
1754
+ try {
1755
+ const cardTags = card.tags ?? [];
1756
+ const lockedTags = cardTags.filter(
1757
+ (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1758
+ );
1759
+ if (lockedTags.length === 0) {
1760
+ const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1761
+ return {
1762
+ isUnlocked: true,
1763
+ reason: `Prerequisites met, tags: ${tagList}`
1764
+ };
1765
+ }
1766
+ const missingPrereqs = lockedTags.flatMap((tag) => {
1767
+ const prereqs = this.config.prerequisites[tag] || [];
1768
+ return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1769
+ });
1770
+ return {
1771
+ isUnlocked: false,
1772
+ reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1773
+ };
1774
+ } catch {
1775
+ return {
1776
+ isUnlocked: true,
1777
+ reason: "Prerequisites check skipped (tag lookup failed)"
1778
+ };
1779
+ }
1780
+ }
1781
+ /**
1782
+ * CardFilter.transform implementation.
1783
+ *
1784
+ * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1785
+ */
1786
+ async transform(cards, context) {
1787
+ const masteredTags = await this.getMasteredTags(context);
1788
+ const unlockedTags = this.getUnlockedTags(masteredTags);
1789
+ const gated = [];
1790
+ for (const card of cards) {
1791
+ const { isUnlocked, reason } = await this.checkCardUnlock(
1792
+ card,
1793
+ context.course,
1794
+ unlockedTags,
1795
+ masteredTags
1796
+ );
1797
+ const finalScore = isUnlocked ? card.score : 0;
1798
+ const action = isUnlocked ? "passed" : "penalized";
1799
+ gated.push({
1800
+ ...card,
1801
+ score: finalScore,
1802
+ provenance: [
1803
+ ...card.provenance,
1804
+ {
1805
+ strategy: "hierarchyDefinition",
1806
+ strategyName: this.strategyName || this.name,
1807
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1808
+ action,
1809
+ score: finalScore,
1810
+ reason
1811
+ }
1812
+ ]
1813
+ });
1814
+ }
1815
+ return gated;
1816
+ }
1817
+ /**
1818
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1819
+ *
1820
+ * Use transform() via Pipeline instead.
1821
+ */
1822
+ async getWeightedCards(_limit) {
1823
+ throw new Error(
1824
+ "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1825
+ );
1826
+ }
1827
+ // Legacy methods - stub implementations since filters don't generate cards
1828
+ async getNewCards(_n) {
1829
+ return [];
1830
+ }
1831
+ async getPendingReviews() {
1832
+ return [];
1833
+ }
1834
+ };
1835
+ }
1836
+ });
1837
+
1838
+ // src/core/navigators/inferredPreference.ts
1839
+ var inferredPreference_exports = {};
1840
+ __export(inferredPreference_exports, {
1841
+ INFERRED_PREFERENCE_NAVIGATOR_STUB: () => INFERRED_PREFERENCE_NAVIGATOR_STUB
1842
+ });
1843
+ var INFERRED_PREFERENCE_NAVIGATOR_STUB;
1844
+ var init_inferredPreference = __esm({
1845
+ "src/core/navigators/inferredPreference.ts"() {
1846
+ "use strict";
1847
+ INFERRED_PREFERENCE_NAVIGATOR_STUB = true;
1848
+ }
1849
+ });
1850
+
1851
+ // src/core/navigators/interferenceMitigator.ts
1852
+ var interferenceMitigator_exports = {};
1853
+ __export(interferenceMitigator_exports, {
1854
+ default: () => InterferenceMitigatorNavigator
1855
+ });
1856
+ var import_common8, DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1857
+ var init_interferenceMitigator = __esm({
1858
+ "src/core/navigators/interferenceMitigator.ts"() {
1859
+ "use strict";
1860
+ init_navigators();
1861
+ import_common8 = require("@vue-skuilder/common");
1862
+ DEFAULT_MIN_COUNT2 = 10;
1863
+ DEFAULT_MIN_ELAPSED_DAYS = 3;
1864
+ DEFAULT_INTERFERENCE_DECAY = 0.8;
1865
+ InterferenceMitigatorNavigator = class extends ContentNavigator {
1866
+ config;
1867
+ _strategyData;
1868
+ /** Human-readable name for CardFilter interface */
1869
+ name;
1870
+ /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1871
+ interferenceMap;
1872
+ constructor(user, course, _strategyData) {
1873
+ super(user, course, _strategyData);
1874
+ this._strategyData = _strategyData;
1875
+ this.config = this.parseConfig(_strategyData.serializedData);
1876
+ this.interferenceMap = this.buildInterferenceMap();
1877
+ this.name = _strategyData.name || "Interference Mitigator";
1878
+ }
1879
+ parseConfig(serializedData) {
1880
+ try {
1881
+ const parsed = JSON.parse(serializedData);
1882
+ let sets = parsed.interferenceSets || [];
1883
+ if (sets.length > 0 && Array.isArray(sets[0])) {
1884
+ sets = sets.map((tags) => ({ tags }));
1885
+ }
1886
+ return {
1887
+ interferenceSets: sets,
1888
+ maturityThreshold: {
1889
+ minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1890
+ minElo: parsed.maturityThreshold?.minElo,
1891
+ minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1892
+ },
1893
+ defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1894
+ };
1895
+ } catch {
1896
+ return {
1897
+ interferenceSets: [],
1898
+ maturityThreshold: {
1899
+ minCount: DEFAULT_MIN_COUNT2,
1900
+ minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1901
+ },
1902
+ defaultDecay: DEFAULT_INTERFERENCE_DECAY
1903
+ };
1904
+ }
1905
+ }
1906
+ /**
1907
+ * Build a map from each tag to its interference partners with decay coefficients.
1908
+ * If tags A, B, C are in an interference group with decay 0.8, then:
1909
+ * - A interferes with B (decay 0.8) and C (decay 0.8)
1910
+ * - B interferes with A (decay 0.8) and C (decay 0.8)
1911
+ * - etc.
1912
+ */
1913
+ buildInterferenceMap() {
1914
+ const map = /* @__PURE__ */ new Map();
1915
+ for (const group of this.config.interferenceSets) {
1916
+ const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
1917
+ for (const tag of group.tags) {
1918
+ if (!map.has(tag)) {
1919
+ map.set(tag, []);
1920
+ }
1921
+ const partners = map.get(tag);
1922
+ for (const other of group.tags) {
1923
+ if (other !== tag) {
1924
+ const existing = partners.find((p) => p.partner === other);
1925
+ if (existing) {
1926
+ existing.decay = Math.max(existing.decay, decay);
1927
+ } else {
1928
+ partners.push({ partner: other, decay });
1929
+ }
1930
+ }
1931
+ }
1932
+ }
1933
+ }
1934
+ return map;
1935
+ }
1936
+ /**
1937
+ * Get the set of tags that are currently immature for this user.
1938
+ * A tag is immature if the user has interacted with it but hasn't
1939
+ * reached the maturity threshold.
1940
+ */
1941
+ async getImmatureTags(context) {
1942
+ const immature = /* @__PURE__ */ new Set();
1943
+ try {
1944
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1945
+ const userElo = (0, import_common8.toCourseElo)(courseReg.elo);
1946
+ const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
1947
+ const minElo = this.config.maturityThreshold?.minElo;
1948
+ const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
1949
+ const minCountForElapsed = minElapsedDays * 2;
1950
+ for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
1951
+ if (tagElo.count === 0) continue;
1952
+ const belowCount = tagElo.count < minCount;
1953
+ const belowElo = minElo !== void 0 && tagElo.score < minElo;
1954
+ const belowElapsed = tagElo.count < minCountForElapsed;
1955
+ if (belowCount || belowElo || belowElapsed) {
1956
+ immature.add(tagId);
1957
+ }
1958
+ }
1959
+ } catch {
1960
+ }
1961
+ return immature;
1962
+ }
1963
+ /**
1964
+ * Get all tags that interfere with any immature tag, along with their decay coefficients.
1965
+ * These are the tags we want to avoid introducing.
1966
+ */
1967
+ getTagsToAvoid(immatureTags) {
1968
+ const avoid = /* @__PURE__ */ new Map();
1969
+ for (const immatureTag of immatureTags) {
1970
+ const partners = this.interferenceMap.get(immatureTag);
1971
+ if (partners) {
1972
+ for (const { partner, decay } of partners) {
1973
+ if (!immatureTags.has(partner)) {
1974
+ const existing = avoid.get(partner) ?? 0;
1975
+ avoid.set(partner, Math.max(existing, decay));
1976
+ }
1977
+ }
1978
+ }
1979
+ }
1980
+ return avoid;
1981
+ }
1982
+ /**
1983
+ * Compute interference score reduction for a card.
1984
+ * Returns: { multiplier, interfering tags, reason }
1985
+ */
1986
+ computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
1987
+ if (tagsToAvoid.size === 0) {
1988
+ return {
1989
+ multiplier: 1,
1990
+ interferingTags: [],
1991
+ reason: "No interference detected"
1992
+ };
1993
+ }
1994
+ let multiplier = 1;
1995
+ const interferingTags = [];
1996
+ for (const tag of cardTags) {
1997
+ const decay = tagsToAvoid.get(tag);
1998
+ if (decay !== void 0) {
1999
+ interferingTags.push(tag);
2000
+ multiplier *= 1 - decay;
2001
+ }
2002
+ }
2003
+ if (interferingTags.length === 0) {
2004
+ return {
2005
+ multiplier: 1,
2006
+ interferingTags: [],
2007
+ reason: "No interference detected"
2008
+ };
2009
+ }
2010
+ const causingTags = /* @__PURE__ */ new Set();
2011
+ for (const tag of interferingTags) {
2012
+ for (const immatureTag of immatureTags) {
2013
+ const partners = this.interferenceMap.get(immatureTag);
2014
+ if (partners?.some((p) => p.partner === tag)) {
2015
+ causingTags.add(immatureTag);
2016
+ }
2017
+ }
2018
+ }
2019
+ const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
2020
+ return { multiplier, interferingTags, reason };
2021
+ }
2022
+ /**
2023
+ * CardFilter.transform implementation.
2024
+ *
2025
+ * Apply interference-aware scoring. Cards with tags that interfere with
2026
+ * immature learnings get reduced scores.
2027
+ */
2028
+ async transform(cards, context) {
2029
+ const immatureTags = await this.getImmatureTags(context);
2030
+ const tagsToAvoid = this.getTagsToAvoid(immatureTags);
2031
+ const adjusted = [];
2032
+ for (const card of cards) {
2033
+ const cardTags = card.tags ?? [];
2034
+ const { multiplier, reason } = this.computeInterferenceEffect(
2035
+ cardTags,
2036
+ tagsToAvoid,
2037
+ immatureTags
2038
+ );
2039
+ const finalScore = card.score * multiplier;
2040
+ const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
2041
+ adjusted.push({
2042
+ ...card,
2043
+ score: finalScore,
2044
+ provenance: [
2045
+ ...card.provenance,
2046
+ {
2047
+ strategy: "interferenceMitigator",
2048
+ strategyName: this.strategyName || this.name,
2049
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
2050
+ action,
2051
+ score: finalScore,
2052
+ reason
2053
+ }
2054
+ ]
2055
+ });
2056
+ }
2057
+ return adjusted;
2058
+ }
2059
+ /**
2060
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
2061
+ *
2062
+ * Use transform() via Pipeline instead.
2063
+ */
2064
+ async getWeightedCards(_limit) {
2065
+ throw new Error(
2066
+ "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
2067
+ );
2068
+ }
2069
+ // Legacy methods - stub implementations since filters don't generate cards
2070
+ async getNewCards(_n) {
2071
+ return [];
2072
+ }
2073
+ async getPendingReviews() {
2074
+ return [];
2075
+ }
2076
+ };
2077
+ }
2078
+ });
2079
+
2080
+ // src/core/navigators/relativePriority.ts
2081
+ var relativePriority_exports = {};
2082
+ __export(relativePriority_exports, {
2083
+ default: () => RelativePriorityNavigator
2084
+ });
2085
+ var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
2086
+ var init_relativePriority = __esm({
2087
+ "src/core/navigators/relativePriority.ts"() {
2088
+ "use strict";
2089
+ init_navigators();
2090
+ DEFAULT_PRIORITY = 0.5;
2091
+ DEFAULT_PRIORITY_INFLUENCE = 0.5;
2092
+ DEFAULT_COMBINE_MODE = "max";
2093
+ RelativePriorityNavigator = class extends ContentNavigator {
2094
+ config;
2095
+ _strategyData;
2096
+ /** Human-readable name for CardFilter interface */
2097
+ name;
2098
+ constructor(user, course, _strategyData) {
2099
+ super(user, course, _strategyData);
2100
+ this._strategyData = _strategyData;
2101
+ this.config = this.parseConfig(_strategyData.serializedData);
2102
+ this.name = _strategyData.name || "Relative Priority";
2103
+ }
2104
+ parseConfig(serializedData) {
2105
+ try {
2106
+ const parsed = JSON.parse(serializedData);
2107
+ return {
2108
+ tagPriorities: parsed.tagPriorities || {},
2109
+ defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
2110
+ combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
2111
+ priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
2112
+ };
2113
+ } catch {
2114
+ return {
2115
+ tagPriorities: {},
2116
+ defaultPriority: DEFAULT_PRIORITY,
2117
+ combineMode: DEFAULT_COMBINE_MODE,
2118
+ priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
2119
+ };
2120
+ }
2121
+ }
2122
+ /**
2123
+ * Look up the priority for a tag.
2124
+ */
2125
+ getTagPriority(tagId) {
2126
+ return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
2127
+ }
2128
+ /**
2129
+ * Compute combined priority for a card based on its tags.
2130
+ */
2131
+ computeCardPriority(cardTags) {
2132
+ if (cardTags.length === 0) {
2133
+ return this.config.defaultPriority ?? DEFAULT_PRIORITY;
2134
+ }
2135
+ const priorities = cardTags.map((tag) => this.getTagPriority(tag));
2136
+ switch (this.config.combineMode) {
2137
+ case "max":
2138
+ return Math.max(...priorities);
2139
+ case "min":
2140
+ return Math.min(...priorities);
2141
+ case "average":
2142
+ return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
2143
+ default:
2144
+ return Math.max(...priorities);
2145
+ }
2146
+ }
2147
+ /**
2148
+ * Compute boost factor based on priority.
2149
+ *
2150
+ * The formula: 1 + (priority - 0.5) * priorityInfluence
2151
+ *
2152
+ * This creates a multiplier centered around 1.0:
2153
+ * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
2154
+ * - Priority 0.5 with any influence → 1.00 (neutral)
2155
+ * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
2156
+ */
2157
+ computeBoostFactor(priority) {
2158
+ const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
2159
+ return 1 + (priority - 0.5) * influence;
2160
+ }
2161
+ /**
2162
+ * Build human-readable reason for priority adjustment.
2163
+ */
2164
+ buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
2165
+ if (cardTags.length === 0) {
2166
+ return `No tags, neutral priority (${priority.toFixed(2)})`;
2167
+ }
2168
+ const tagList = cardTags.slice(0, 3).join(", ");
2169
+ const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
2170
+ if (boostFactor === 1) {
2171
+ return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
2172
+ } else if (boostFactor > 1) {
2173
+ return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
2174
+ } else {
2175
+ return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
2176
+ }
2177
+ }
2178
+ /**
2179
+ * CardFilter.transform implementation.
2180
+ *
2181
+ * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
2182
+ * cards with low-priority tags get reduced scores.
2183
+ */
2184
+ async transform(cards, _context) {
2185
+ const adjusted = await Promise.all(
2186
+ cards.map(async (card) => {
2187
+ const cardTags = card.tags ?? [];
2188
+ const priority = this.computeCardPriority(cardTags);
2189
+ const boostFactor = this.computeBoostFactor(priority);
2190
+ const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
2191
+ const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
2192
+ const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
2193
+ return {
2194
+ ...card,
2195
+ score: finalScore,
2196
+ provenance: [
2197
+ ...card.provenance,
2198
+ {
2199
+ strategy: "relativePriority",
2200
+ strategyName: this.strategyName || this.name,
2201
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
2202
+ action,
2203
+ score: finalScore,
2204
+ reason
2205
+ }
2206
+ ]
2207
+ };
2208
+ })
2209
+ );
2210
+ return adjusted;
2211
+ }
2212
+ /**
2213
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
2214
+ *
2215
+ * Use transform() via Pipeline instead.
2216
+ */
2217
+ async getWeightedCards(_limit) {
2218
+ throw new Error(
2219
+ "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
2220
+ );
2221
+ }
2222
+ // Legacy methods - stub implementations since filters don't generate cards
2223
+ async getNewCards(_n) {
2224
+ return [];
2225
+ }
2226
+ async getPendingReviews() {
2227
+ return [];
2228
+ }
2229
+ };
2230
+ }
2231
+ });
2232
+
2233
+ // src/core/navigators/srs.ts
2234
+ var srs_exports = {};
2235
+ __export(srs_exports, {
2236
+ default: () => SRSNavigator
2237
+ });
2238
+ var import_moment3, SRSNavigator;
2239
+ var init_srs = __esm({
2240
+ "src/core/navigators/srs.ts"() {
2241
+ "use strict";
2242
+ import_moment3 = __toESM(require("moment"), 1);
2243
+ init_navigators();
2244
+ SRSNavigator = class extends ContentNavigator {
2245
+ /** Human-readable name for CardGenerator interface */
2246
+ name;
2247
+ constructor(user, course, strategyData) {
2248
+ super(user, course, strategyData);
2249
+ this.name = strategyData?.name || "SRS";
2250
+ }
2251
+ /**
2252
+ * Get review cards scored by urgency.
2253
+ *
2254
+ * Score formula combines:
2255
+ * - Relative overdueness: hoursOverdue / intervalHours
2256
+ * - Interval recency: exponential decay favoring shorter intervals
2257
+ *
2258
+ * Cards not yet due are excluded (not scored as 0).
2259
+ *
2260
+ * This method supports both the legacy signature (limit only) and the
2261
+ * CardGenerator interface signature (limit, context).
2262
+ *
2263
+ * @param limit - Maximum number of cards to return
2264
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
2265
+ */
2266
+ async getWeightedCards(limit, _context) {
2267
+ if (!this.user || !this.course) {
2268
+ throw new Error("SRSNavigator requires user and course to be set");
2269
+ }
2270
+ const reviews = await this.user.getPendingReviews(this.course.getCourseID());
2271
+ const now = import_moment3.default.utc();
2272
+ const dueReviews = reviews.filter((r) => now.isAfter(import_moment3.default.utc(r.reviewTime)));
2273
+ const scored = dueReviews.map((review) => {
2274
+ const { score, reason } = this.computeUrgencyScore(review, now);
826
2275
  return {
827
- cardID: cardId,
828
- courseID: this.course.getCourseID(),
829
- contentSourceType: "course",
830
- contentSourceID: this.course.getCourseID(),
831
- status: "new"
2276
+ cardId: review.cardId,
2277
+ courseId: review.courseId,
2278
+ score,
2279
+ provenance: [
2280
+ {
2281
+ strategy: "srs",
2282
+ strategyName: this.strategyName || this.name,
2283
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
2284
+ action: "generated",
2285
+ score,
2286
+ reason
2287
+ }
2288
+ ]
832
2289
  };
833
2290
  });
2291
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
2292
+ }
2293
+ /**
2294
+ * Compute urgency score for a review card.
2295
+ *
2296
+ * Two factors:
2297
+ * 1. Relative overdueness = hoursOverdue / intervalHours
2298
+ * - 2 days overdue on 3-day interval = 0.67 (urgent)
2299
+ * - 2 days overdue on 180-day interval = 0.01 (not urgent)
2300
+ *
2301
+ * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
2302
+ * - 24h interval → ~1.0 (very recent learning)
2303
+ * - 30 days (720h) → ~0.56
2304
+ * - 180 days → ~0.30
2305
+ *
2306
+ * Combined: base 0.5 + weighted average of factors * 0.45
2307
+ * Result range: approximately 0.5 to 0.95
2308
+ */
2309
+ computeUrgencyScore(review, now) {
2310
+ const scheduledAt = import_moment3.default.utc(review.scheduledAt);
2311
+ const due = import_moment3.default.utc(review.reviewTime);
2312
+ const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
2313
+ const hoursOverdue = now.diff(due, "hours");
2314
+ const relativeOverdue = hoursOverdue / intervalHours;
2315
+ const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
2316
+ const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
2317
+ const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
2318
+ const score = Math.min(0.95, 0.5 + urgency * 0.45);
2319
+ const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
2320
+ return { score, reason };
2321
+ }
2322
+ /**
2323
+ * Get pending reviews in legacy format.
2324
+ *
2325
+ * Returns all pending reviews for the course, enriched with session item fields.
2326
+ */
2327
+ async getPendingReviews() {
2328
+ if (!this.user || !this.course) {
2329
+ throw new Error("SRSNavigator requires user and course to be set");
2330
+ }
2331
+ const reviews = await this.user.getPendingReviews(this.course.getCourseID());
2332
+ return reviews.map((r) => ({
2333
+ ...r,
2334
+ contentSourceType: "course",
2335
+ contentSourceID: this.course.getCourseID(),
2336
+ cardID: r.cardId,
2337
+ courseID: r.courseId,
2338
+ qualifiedID: `${r.courseId}-${r.cardId}`,
2339
+ reviewID: r._id,
2340
+ status: "review"
2341
+ }));
2342
+ }
2343
+ /**
2344
+ * SRS does not generate new cards.
2345
+ * Use ELONavigator or another generator for new cards.
2346
+ */
2347
+ async getNewCards(_n) {
2348
+ return [];
834
2349
  }
835
2350
  };
836
2351
  }
837
2352
  });
838
2353
 
2354
+ // src/core/navigators/userGoal.ts
2355
+ var userGoal_exports = {};
2356
+ __export(userGoal_exports, {
2357
+ USER_GOAL_NAVIGATOR_STUB: () => USER_GOAL_NAVIGATOR_STUB
2358
+ });
2359
+ var USER_GOAL_NAVIGATOR_STUB;
2360
+ var init_userGoal = __esm({
2361
+ "src/core/navigators/userGoal.ts"() {
2362
+ "use strict";
2363
+ USER_GOAL_NAVIGATOR_STUB = true;
2364
+ }
2365
+ });
2366
+
839
2367
  // import("./**/*") in src/core/navigators/index.ts
840
2368
  var globImport;
841
2369
  var init_ = __esm({
842
2370
  'import("./**/*") in src/core/navigators/index.ts'() {
843
2371
  globImport = __glob({
2372
+ "./CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
2373
+ "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
2374
+ "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
844
2375
  "./elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
2376
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2377
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2378
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
2379
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
2380
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
2381
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
845
2382
  "./hardcodedOrder.ts": () => Promise.resolve().then(() => (init_hardcodedOrder(), hardcodedOrder_exports)),
846
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
2383
+ "./hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2384
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
2385
+ "./inferredPreference.ts": () => Promise.resolve().then(() => (init_inferredPreference(), inferredPreference_exports)),
2386
+ "./interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2387
+ "./relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2388
+ "./srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
2389
+ "./userGoal.ts": () => Promise.resolve().then(() => (init_userGoal(), userGoal_exports))
847
2390
  });
848
2391
  }
849
2392
  });
@@ -852,9 +2395,34 @@ var init_ = __esm({
852
2395
  var navigators_exports = {};
853
2396
  __export(navigators_exports, {
854
2397
  ContentNavigator: () => ContentNavigator,
855
- Navigators: () => Navigators
2398
+ NavigatorRole: () => NavigatorRole,
2399
+ NavigatorRoles: () => NavigatorRoles,
2400
+ Navigators: () => Navigators,
2401
+ getCardOrigin: () => getCardOrigin,
2402
+ isFilter: () => isFilter,
2403
+ isGenerator: () => isGenerator
856
2404
  });
857
- var Navigators, ContentNavigator;
2405
+ function getCardOrigin(card) {
2406
+ if (card.provenance.length === 0) {
2407
+ throw new Error("Card has no provenance - cannot determine origin");
2408
+ }
2409
+ const firstEntry = card.provenance[0];
2410
+ const reason = firstEntry.reason.toLowerCase();
2411
+ if (reason.includes("failed")) {
2412
+ return "failed";
2413
+ }
2414
+ if (reason.includes("review")) {
2415
+ return "review";
2416
+ }
2417
+ return "new";
2418
+ }
2419
+ function isGenerator(impl) {
2420
+ return NavigatorRoles[impl] === "generator" /* GENERATOR */;
2421
+ }
2422
+ function isFilter(impl) {
2423
+ return NavigatorRoles[impl] === "filter" /* FILTER */;
2424
+ }
2425
+ var Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
858
2426
  var init_navigators = __esm({
859
2427
  "src/core/navigators/index.ts"() {
860
2428
  "use strict";
@@ -862,14 +2430,103 @@ var init_navigators = __esm({
862
2430
  init_();
863
2431
  Navigators = /* @__PURE__ */ ((Navigators2) => {
864
2432
  Navigators2["ELO"] = "elo";
2433
+ Navigators2["SRS"] = "srs";
865
2434
  Navigators2["HARDCODED"] = "hardcodedOrder";
2435
+ Navigators2["HIERARCHY"] = "hierarchyDefinition";
2436
+ Navigators2["INTERFERENCE"] = "interferenceMitigator";
2437
+ Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
2438
+ Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
866
2439
  return Navigators2;
867
2440
  })(Navigators || {});
2441
+ NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
2442
+ NavigatorRole2["GENERATOR"] = "generator";
2443
+ NavigatorRole2["FILTER"] = "filter";
2444
+ return NavigatorRole2;
2445
+ })(NavigatorRole || {});
2446
+ NavigatorRoles = {
2447
+ ["elo" /* ELO */]: "generator" /* GENERATOR */,
2448
+ ["srs" /* SRS */]: "generator" /* GENERATOR */,
2449
+ ["hardcodedOrder" /* HARDCODED */]: "generator" /* GENERATOR */,
2450
+ ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
2451
+ ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
2452
+ ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
2453
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
2454
+ };
868
2455
  ContentNavigator = class {
2456
+ /** User interface for this navigation session */
2457
+ user;
2458
+ /** Course interface for this navigation session */
2459
+ course;
2460
+ /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
2461
+ strategyName;
2462
+ /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
2463
+ strategyId;
2464
+ /**
2465
+ * Constructor for standard navigators.
2466
+ * Call this from subclass constructors to initialize common fields.
2467
+ *
2468
+ * Note: CompositeGenerator doesn't use this pattern and should call super() without args.
2469
+ */
2470
+ constructor(user, course, strategyData) {
2471
+ if (user && course && strategyData) {
2472
+ this.user = user;
2473
+ this.course = course;
2474
+ this.strategyName = strategyData.name;
2475
+ this.strategyId = strategyData._id;
2476
+ }
2477
+ }
2478
+ // ============================================================================
2479
+ // STRATEGY STATE HELPERS
2480
+ // ============================================================================
2481
+ //
2482
+ // These methods allow strategies to persist their own state (user preferences,
2483
+ // learned patterns, temporal tracking) in the user database.
2484
+ //
2485
+ // ============================================================================
2486
+ /**
2487
+ * Unique key identifying this strategy for state storage.
2488
+ *
2489
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
2490
+ * Override in subclasses if multiple instances of the same strategy type
2491
+ * need separate state storage.
2492
+ */
2493
+ get strategyKey() {
2494
+ return this.constructor.name;
2495
+ }
2496
+ /**
2497
+ * Get this strategy's persisted state for the current course.
2498
+ *
2499
+ * @returns The strategy's data payload, or null if no state exists
2500
+ * @throws Error if user or course is not initialized
2501
+ */
2502
+ async getStrategyState() {
2503
+ if (!this.user || !this.course) {
2504
+ throw new Error(
2505
+ `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2506
+ );
2507
+ }
2508
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
2509
+ }
2510
+ /**
2511
+ * Persist this strategy's state for the current course.
2512
+ *
2513
+ * @param data - The strategy's data payload to store
2514
+ * @throws Error if user or course is not initialized
2515
+ */
2516
+ async putStrategyState(data) {
2517
+ if (!this.user || !this.course) {
2518
+ throw new Error(
2519
+ `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2520
+ );
2521
+ }
2522
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
2523
+ }
869
2524
  /**
2525
+ * Factory method to create navigator instances dynamically.
870
2526
  *
871
- * @param user
872
- * @param strategyData
2527
+ * @param user - User interface
2528
+ * @param course - Course interface
2529
+ * @param strategyData - Strategy configuration document
873
2530
  * @returns the runtime object used to steer a study session.
874
2531
  */
875
2532
  static async create(user, course, strategyData) {
@@ -890,6 +2547,70 @@ var init_navigators = __esm({
890
2547
  }
891
2548
  return new NavigatorImpl(user, course, strategyData);
892
2549
  }
2550
+ /**
2551
+ * Get cards with suitability scores and provenance trails.
2552
+ *
2553
+ * **This is the PRIMARY API for navigation strategies.**
2554
+ *
2555
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
2556
+ * better candidates for presentation. Each card includes a provenance trail
2557
+ * documenting how strategies contributed to the final score.
2558
+ *
2559
+ * ## For Generators
2560
+ * Override this method to generate candidates and compute scores based on
2561
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
2562
+ * initial provenance entry with action='generated'.
2563
+ *
2564
+ * ## Default Implementation
2565
+ * The base class provides a backward-compatible default that:
2566
+ * 1. Calls legacy getNewCards() and getPendingReviews()
2567
+ * 2. Assigns score=1.0 to all cards
2568
+ * 3. Creates minimal provenance from legacy methods
2569
+ * 4. Returns combined results up to limit
2570
+ *
2571
+ * This allows existing strategies to work without modification while
2572
+ * new strategies can override with proper scoring and provenance.
2573
+ *
2574
+ * @param limit - Maximum cards to return
2575
+ * @returns Cards sorted by score descending, with provenance trails
2576
+ */
2577
+ async getWeightedCards(limit) {
2578
+ const newCards = await this.getNewCards(limit);
2579
+ const reviews = await this.getPendingReviews();
2580
+ const weighted = [
2581
+ ...newCards.map((c) => ({
2582
+ cardId: c.cardID,
2583
+ courseId: c.courseID,
2584
+ score: 1,
2585
+ provenance: [
2586
+ {
2587
+ strategy: "legacy",
2588
+ strategyName: this.strategyName || "Legacy API",
2589
+ strategyId: this.strategyId || "legacy-fallback",
2590
+ action: "generated",
2591
+ score: 1,
2592
+ reason: "Generated via legacy getNewCards(), new card"
2593
+ }
2594
+ ]
2595
+ })),
2596
+ ...reviews.map((r) => ({
2597
+ cardId: r.cardID,
2598
+ courseId: r.courseID,
2599
+ score: 1,
2600
+ provenance: [
2601
+ {
2602
+ strategy: "legacy",
2603
+ strategyName: this.strategyName || "Legacy API",
2604
+ strategyId: this.strategyId || "legacy-fallback",
2605
+ action: "generated",
2606
+ score: 1,
2607
+ reason: "Generated via legacy getPendingReviews(), review"
2608
+ }
2609
+ ]
2610
+ }))
2611
+ ];
2612
+ return weighted.slice(0, limit);
2613
+ }
893
2614
  };
894
2615
  }
895
2616
  });
@@ -970,11 +2691,11 @@ ${JSON.stringify(config)}
970
2691
  function isSuccessRow(row) {
971
2692
  return "doc" in row && row.doc !== null && row.doc !== void 0;
972
2693
  }
973
- var import_common5, CourseDB;
2694
+ var import_common9, CourseDB;
974
2695
  var init_courseDB = __esm({
975
2696
  "src/impl/couch/courseDB.ts"() {
976
2697
  "use strict";
977
- import_common5 = require("@vue-skuilder/common");
2698
+ import_common9 = require("@vue-skuilder/common");
978
2699
  init_couch();
979
2700
  init_updateQueue();
980
2701
  init_types_legacy();
@@ -983,6 +2704,12 @@ var init_courseDB = __esm({
983
2704
  init_courseAPI();
984
2705
  init_courseLookupDB();
985
2706
  init_navigators();
2707
+ init_Pipeline();
2708
+ init_PipelineAssembler();
2709
+ init_CompositeGenerator();
2710
+ init_elo();
2711
+ init_srs();
2712
+ init_eloDistance();
986
2713
  CourseDB = class {
987
2714
  // private log(msg: string): void {
988
2715
  // log(`CourseLog: ${this.id}\n ${msg}`);
@@ -1049,14 +2776,14 @@ var init_courseDB = __esm({
1049
2776
  docs.rows.forEach((r) => {
1050
2777
  if (isSuccessRow(r)) {
1051
2778
  if (r.doc && r.doc.elo) {
1052
- ret.push((0, import_common5.toCourseElo)(r.doc.elo));
2779
+ ret.push((0, import_common9.toCourseElo)(r.doc.elo));
1053
2780
  } else {
1054
2781
  logger.warn("no elo data for card: " + r.id);
1055
- ret.push((0, import_common5.blankCourseElo)());
2782
+ ret.push((0, import_common9.blankCourseElo)());
1056
2783
  }
1057
2784
  } else {
1058
2785
  logger.warn("no elo data for card: " + JSON.stringify(r));
1059
- ret.push((0, import_common5.blankCourseElo)());
2786
+ ret.push((0, import_common9.blankCourseElo)());
1060
2787
  }
1061
2788
  });
1062
2789
  return ret;
@@ -1118,15 +2845,6 @@ var init_courseDB = __esm({
1118
2845
  ret[r.id] = r.doc.id_displayable_data;
1119
2846
  }
1120
2847
  });
1121
- await Promise.all(
1122
- cards.rows.map((r) => {
1123
- return async () => {
1124
- if (isSuccessRow(r)) {
1125
- ret[r.id] = r.doc.id_displayable_data;
1126
- }
1127
- };
1128
- })
1129
- );
1130
2848
  return ret;
1131
2849
  }
1132
2850
  async getCardsByELO(elo, cardLimit) {
@@ -1211,6 +2929,28 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1211
2929
  throw new Error(`Failed to find tags for card ${this.id}-${cardId}`);
1212
2930
  }
1213
2931
  }
2932
+ async getAppliedTagsBatch(cardIds) {
2933
+ if (cardIds.length === 0) {
2934
+ return /* @__PURE__ */ new Map();
2935
+ }
2936
+ const db = getCourseDB2(this.id);
2937
+ const result = await db.query("getTags", {
2938
+ keys: cardIds,
2939
+ include_docs: false
2940
+ });
2941
+ const tagsByCard = /* @__PURE__ */ new Map();
2942
+ for (const cardId of cardIds) {
2943
+ tagsByCard.set(cardId, []);
2944
+ }
2945
+ for (const row of result.rows) {
2946
+ const cardId = row.key;
2947
+ const tagName = row.value?.name;
2948
+ if (tagName && tagsByCard.has(cardId)) {
2949
+ tagsByCard.get(cardId).push(tagName);
2950
+ }
2951
+ }
2952
+ return tagsByCard;
2953
+ }
1214
2954
  async addTagToCard(cardId, tagId, updateELO) {
1215
2955
  return await addTagToCard(
1216
2956
  this.id,
@@ -1238,7 +2978,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1238
2978
  async getCourseTagStubs() {
1239
2979
  return getCourseTagStubs(this.id);
1240
2980
  }
1241
- async addNote(codeCourse, shape, data, author, tags, uploads, elo = (0, import_common5.blankCourseElo)()) {
2981
+ async addNote(codeCourse, shape, data, author, tags, uploads, elo = (0, import_common9.blankCourseElo)()) {
1242
2982
  try {
1243
2983
  const resp = await addNote55(this.id, codeCourse, shape, data, author, tags, uploads, elo);
1244
2984
  if (resp.ok) {
@@ -1247,19 +2987,19 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1247
2987
  `[courseDB.addNote] Note added but card creation failed: ${resp.cardCreationError}`
1248
2988
  );
1249
2989
  return {
1250
- status: import_common5.Status.error,
2990
+ status: import_common9.Status.error,
1251
2991
  message: `Note was added but no cards were created: ${resp.cardCreationError}`,
1252
2992
  id: resp.id
1253
2993
  };
1254
2994
  }
1255
2995
  return {
1256
- status: import_common5.Status.ok,
2996
+ status: import_common9.Status.ok,
1257
2997
  message: "",
1258
2998
  id: resp.id
1259
2999
  };
1260
3000
  } else {
1261
3001
  return {
1262
- status: import_common5.Status.error,
3002
+ status: import_common9.Status.error,
1263
3003
  message: "Unexpected error adding note"
1264
3004
  };
1265
3005
  }
@@ -1271,7 +3011,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1271
3011
  message: ${err.message}`
1272
3012
  );
1273
3013
  return {
1274
- status: import_common5.Status.error,
3014
+ status: import_common9.Status.error,
1275
3015
  message: `Error adding note to course. ${e.reason || err.message}`
1276
3016
  };
1277
3017
  }
@@ -1322,42 +3062,82 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1322
3062
  logger.debug(JSON.stringify(data));
1323
3063
  return Promise.resolve();
1324
3064
  }
1325
- async surfaceNavigationStrategy() {
3065
+ /**
3066
+ * Creates an instantiated navigator for this course.
3067
+ *
3068
+ * Handles multiple generators by wrapping them in CompositeGenerator.
3069
+ * This is the preferred method for getting a ready-to-use navigator.
3070
+ *
3071
+ * @param user - User database interface
3072
+ * @returns Instantiated ContentNavigator ready for use
3073
+ */
3074
+ async createNavigator(user) {
1326
3075
  try {
1327
- const config = await this.getCourseConfig();
1328
- if (config.defaultNavigationStrategyId) {
1329
- try {
1330
- const strategy = await this.getNavigationStrategy(config.defaultNavigationStrategyId);
1331
- if (strategy) {
1332
- logger.debug(`Surfacing strategy ${strategy.name} from course config`);
1333
- return strategy;
1334
- }
1335
- } catch (e) {
1336
- logger.warn(
1337
- // @ts-expect-error tmp: defaultNavigationStrategyId property does not yet exist
1338
- `Failed to load strategy '${config.defaultNavigationStrategyId}' specified in course config. Falling back to ELO.`,
1339
- e
1340
- );
1341
- }
3076
+ const allStrategies = await this.getAllNavigationStrategies();
3077
+ if (allStrategies.length === 0) {
3078
+ logger.debug(
3079
+ "[courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])"
3080
+ );
3081
+ return this.createDefaultPipeline(user);
1342
3082
  }
1343
- } catch (e) {
1344
- logger.warn(
1345
- "Could not retrieve course config to determine navigation strategy. Falling back to ELO.",
1346
- e
3083
+ const assembler = new PipelineAssembler();
3084
+ const { pipeline, generatorStrategies, filterStrategies, warnings } = await assembler.assemble({
3085
+ strategies: allStrategies,
3086
+ user,
3087
+ course: this
3088
+ });
3089
+ for (const warning of warnings) {
3090
+ logger.warn(`[PipelineAssembler] ${warning}`);
3091
+ }
3092
+ if (!pipeline) {
3093
+ logger.debug("[courseDB] Pipeline assembly failed, using default pipeline");
3094
+ return this.createDefaultPipeline(user);
3095
+ }
3096
+ logger.debug(
3097
+ `[courseDB] Using assembled pipeline with ${generatorStrategies.length} generator(s) and ${filterStrategies.length} filter(s)`
1347
3098
  );
3099
+ return pipeline;
3100
+ } catch (e) {
3101
+ logger.error(`[courseDB] Error creating navigator: ${e}`);
3102
+ throw e;
1348
3103
  }
1349
- logger.warn(`Returning hard-coded default ELO navigator`);
1350
- const ret = {
1351
- _id: "NAVIGATION_STRATEGY-ELO",
3104
+ }
3105
+ makeDefaultEloStrategy() {
3106
+ return {
3107
+ _id: "NAVIGATION_STRATEGY-ELO-default",
1352
3108
  docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1353
- name: "ELO",
1354
- description: "ELO-based navigation strategy",
3109
+ name: "ELO (default)",
3110
+ description: "Default ELO-based navigation strategy for new cards",
1355
3111
  implementingClass: "elo" /* ELO */,
1356
3112
  course: this.id,
1357
3113
  serializedData: ""
1358
- // serde is a noop for ELO navigator.
1359
3114
  };
1360
- return Promise.resolve(ret);
3115
+ }
3116
+ makeDefaultSrsStrategy() {
3117
+ return {
3118
+ _id: "NAVIGATION_STRATEGY-SRS-default",
3119
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
3120
+ name: "SRS (default)",
3121
+ description: "Default SRS-based navigation strategy for reviews",
3122
+ implementingClass: "srs" /* SRS */,
3123
+ course: this.id,
3124
+ serializedData: ""
3125
+ };
3126
+ }
3127
+ /**
3128
+ * Creates the default navigation pipeline for courses with no configured strategies.
3129
+ *
3130
+ * Default: Pipeline(Composite(ELO, SRS), [eloDistanceFilter])
3131
+ * - ELO generator: scores new cards by skill proximity
3132
+ * - SRS generator: scores reviews by overdueness and interval recency
3133
+ * - ELO distance filter: penalizes cards far from user's current level
3134
+ */
3135
+ createDefaultPipeline(user) {
3136
+ const eloNavigator = new ELONavigator(user, this, this.makeDefaultEloStrategy());
3137
+ const srsNavigator = new SRSNavigator(user, this, this.makeDefaultSrsStrategy());
3138
+ const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
3139
+ const eloDistanceFilter = createEloDistanceFilter();
3140
+ return new Pipeline(compositeGenerator, [eloDistanceFilter], user, this);
1361
3141
  }
1362
3142
  ////////////////////////////////////
1363
3143
  // END NavigationStrategyManager implementation
@@ -1368,22 +3148,39 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1368
3148
  async getNewCards(limit = 99) {
1369
3149
  const u = await this._getCurrentUser();
1370
3150
  try {
1371
- const strategy = await this.surfaceNavigationStrategy();
1372
- const navigator = await ContentNavigator.create(u, this, strategy);
3151
+ const navigator = await this.createNavigator(u);
1373
3152
  return navigator.getNewCards(limit);
1374
3153
  } catch (e) {
1375
- logger.error(`[courseDB] Error surfacing a NavigationStrategy: ${e}`);
3154
+ logger.error(`[courseDB] Error in getNewCards: ${e}`);
1376
3155
  throw e;
1377
3156
  }
1378
3157
  }
1379
3158
  async getPendingReviews() {
1380
3159
  const u = await this._getCurrentUser();
1381
3160
  try {
1382
- const strategy = await this.surfaceNavigationStrategy();
1383
- const navigator = await ContentNavigator.create(u, this, strategy);
3161
+ const navigator = await this.createNavigator(u);
1384
3162
  return navigator.getPendingReviews();
1385
3163
  } catch (e) {
1386
- logger.error(`[courseDB] Error surfacing a NavigationStrategy: ${e}`);
3164
+ logger.error(`[courseDB] Error in getPendingReviews: ${e}`);
3165
+ throw e;
3166
+ }
3167
+ }
3168
+ /**
3169
+ * Get cards with suitability scores for presentation.
3170
+ *
3171
+ * This is the PRIMARY API for content sources going forward. Delegates to the
3172
+ * course's configured NavigationStrategy to get scored candidates.
3173
+ *
3174
+ * @param limit - Maximum number of cards to return
3175
+ * @returns Cards sorted by score descending
3176
+ */
3177
+ async getWeightedCards(limit) {
3178
+ const u = await this._getCurrentUser();
3179
+ try {
3180
+ const navigator = await this.createNavigator(u);
3181
+ return navigator.getWeightedCards(limit);
3182
+ } catch (e) {
3183
+ logger.error(`[courseDB] Error getting weighted cards: ${e}`);
1387
3184
  throw e;
1388
3185
  }
1389
3186
  }
@@ -1399,7 +3196,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1399
3196
  const courseDoc = (await u.getCourseRegistrationsDoc()).courses.find((c) => {
1400
3197
  return c.courseID === this.id;
1401
3198
  });
1402
- targetElo = (0, import_common5.EloToNumber)(courseDoc.elo);
3199
+ targetElo = (0, import_common9.EloToNumber)(courseDoc.elo);
1403
3200
  } catch {
1404
3201
  targetElo = 1e3;
1405
3202
  }
@@ -1523,13 +3320,13 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1523
3320
  });
1524
3321
 
1525
3322
  // src/impl/couch/classroomDB.ts
1526
- var import_moment3, CLASSROOM_CONFIG, ClassroomDBBase, StudentClassroomDB;
3323
+ var import_moment4, CLASSROOM_CONFIG, ClassroomDBBase, StudentClassroomDB;
1527
3324
  var init_classroomDB2 = __esm({
1528
3325
  "src/impl/couch/classroomDB.ts"() {
1529
3326
  "use strict";
1530
3327
  init_factory();
1531
3328
  init_logger();
1532
- import_moment3 = __toESM(require("moment"));
3329
+ import_moment4 = __toESM(require("moment"), 1);
1533
3330
  init_pouchdb_setup();
1534
3331
  init_couch();
1535
3332
  init_courseDB();
@@ -1623,9 +3420,9 @@ var init_classroomDB2 = __esm({
1623
3420
  }
1624
3421
  async getNewCards() {
1625
3422
  const activeCards = await this._user.getActiveCards();
1626
- const now = import_moment3.default.utc();
3423
+ const now = import_moment4.default.utc();
1627
3424
  const assigned = await this.getAssignedContent();
1628
- const due = assigned.filter((c) => now.isAfter(import_moment3.default.utc(c.activeOn, REVIEW_TIME_FORMAT2)));
3425
+ const due = assigned.filter((c) => now.isAfter(import_moment4.default.utc(c.activeOn, REVIEW_TIME_FORMAT2)));
1629
3426
  logger.info(`Due content: ${JSON.stringify(due)}`);
1630
3427
  let ret = [];
1631
3428
  for (let i = 0; i < due.length; i++) {
@@ -1662,6 +3459,52 @@ var init_classroomDB2 = __esm({
1662
3459
  }
1663
3460
  });
1664
3461
  }
3462
+ /**
3463
+ * Get cards with suitability scores for presentation.
3464
+ *
3465
+ * This implementation wraps the legacy getNewCards/getPendingReviews methods,
3466
+ * assigning score=1.0 to all cards. StudentClassroomDB does not currently
3467
+ * support pluggable navigation strategies.
3468
+ *
3469
+ * @param limit - Maximum number of cards to return
3470
+ * @returns Cards sorted by score descending (all scores = 1.0)
3471
+ */
3472
+ async getWeightedCards(limit) {
3473
+ const [newCards, reviews] = await Promise.all([this.getNewCards(), this.getPendingReviews()]);
3474
+ const weighted = [
3475
+ ...newCards.map((c) => ({
3476
+ cardId: c.cardID,
3477
+ courseId: c.courseID,
3478
+ score: 1,
3479
+ provenance: [
3480
+ {
3481
+ strategy: "classroom",
3482
+ strategyName: "Classroom",
3483
+ strategyId: "CLASSROOM",
3484
+ action: "generated",
3485
+ score: 1,
3486
+ reason: "Classroom legacy getNewCards(), new card"
3487
+ }
3488
+ ]
3489
+ })),
3490
+ ...reviews.map((r) => ({
3491
+ cardId: r.cardID,
3492
+ courseId: r.courseID,
3493
+ score: 1,
3494
+ provenance: [
3495
+ {
3496
+ strategy: "classroom",
3497
+ strategyName: "Classroom",
3498
+ strategyId: "CLASSROOM",
3499
+ action: "generated",
3500
+ score: 1,
3501
+ reason: "Classroom legacy getPendingReviews(), review"
3502
+ }
3503
+ ]
3504
+ }))
3505
+ ];
3506
+ return weighted.slice(0, limit);
3507
+ }
1665
3508
  };
1666
3509
  }
1667
3510
  });
@@ -1686,19 +3529,19 @@ var init_auth = __esm({
1686
3529
  "use strict";
1687
3530
  init_factory();
1688
3531
  init_logger();
1689
- import_cross_fetch = __toESM(require("cross-fetch"));
3532
+ import_cross_fetch = __toESM(require("cross-fetch"), 1);
1690
3533
  }
1691
3534
  });
1692
3535
 
1693
3536
  // src/impl/couch/CouchDBSyncStrategy.ts
1694
- var import_common6;
3537
+ var import_common10;
1695
3538
  var init_CouchDBSyncStrategy = __esm({
1696
3539
  "src/impl/couch/CouchDBSyncStrategy.ts"() {
1697
3540
  "use strict";
1698
3541
  init_factory();
1699
3542
  init_types_legacy();
1700
3543
  init_logger();
1701
- import_common6 = require("@vue-skuilder/common");
3544
+ import_common10 = require("@vue-skuilder/common");
1702
3545
  init_common();
1703
3546
  init_pouchdb_setup();
1704
3547
  init_couch();
@@ -1758,17 +3601,17 @@ function getStartAndEndKeys2(key) {
1758
3601
  endkey: key + "\uFFF0"
1759
3602
  };
1760
3603
  }
1761
- var import_cross_fetch2, import_moment4, import_process, isBrowser, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, REVIEW_TIME_FORMAT2;
3604
+ var import_cross_fetch2, import_moment5, import_process, isBrowser, GUEST_LOCAL_DB, localUserDB, pouchDBincludeCredentialsConfig, REVIEW_TIME_FORMAT2;
1762
3605
  var init_couch = __esm({
1763
3606
  "src/impl/couch/index.ts"() {
1764
3607
  "use strict";
1765
3608
  init_factory();
1766
3609
  init_types_legacy();
1767
- import_cross_fetch2 = __toESM(require("cross-fetch"));
1768
- import_moment4 = __toESM(require("moment"));
3610
+ import_cross_fetch2 = __toESM(require("cross-fetch"), 1);
3611
+ import_moment5 = __toESM(require("moment"), 1);
1769
3612
  init_logger();
1770
3613
  init_pouchdb_setup();
1771
- import_process = __toESM(require("process"));
3614
+ import_process = __toESM(require("process"), 1);
1772
3615
  init_contentSource();
1773
3616
  init_adminDB2();
1774
3617
  init_classroomDB2();
@@ -1884,14 +3727,14 @@ async function dropUserFromClassroom(user, classID) {
1884
3727
  async function getUserClassrooms(user) {
1885
3728
  return getOrCreateClassroomRegistrationsDoc(user);
1886
3729
  }
1887
- var import_common8, import_moment5, log3, BaseUser, userCoursesDoc, userClassroomsDoc;
3730
+ var import_common12, import_moment6, log3, BaseUser, userCoursesDoc, userClassroomsDoc;
1888
3731
  var init_BaseUserDB = __esm({
1889
3732
  "src/impl/common/BaseUserDB.ts"() {
1890
3733
  "use strict";
1891
3734
  init_core();
1892
3735
  init_util();
1893
- import_common8 = require("@vue-skuilder/common");
1894
- import_moment5 = __toESM(require("moment"));
3736
+ import_common12 = require("@vue-skuilder/common");
3737
+ import_moment6 = __toESM(require("moment"), 1);
1895
3738
  init_types_legacy();
1896
3739
  init_logger();
1897
3740
  init_userDBHelpers();
@@ -1940,7 +3783,7 @@ Currently logged-in as ${this._username}.`
1940
3783
  );
1941
3784
  }
1942
3785
  const result = await this.syncStrategy.createAccount(username, password);
1943
- if (result.status === import_common8.Status.ok) {
3786
+ if (result.status === import_common12.Status.ok) {
1944
3787
  log3(`Account created successfully, updating username to ${username}`);
1945
3788
  this._username = username;
1946
3789
  try {
@@ -1982,7 +3825,7 @@ Currently logged-in as ${this._username}.`
1982
3825
  async resetUserData() {
1983
3826
  if (this.syncStrategy.canAuthenticate()) {
1984
3827
  return {
1985
- status: import_common8.Status.error,
3828
+ status: import_common12.Status.error,
1986
3829
  error: "Reset user data is only available for local-only mode. Use logout instead for remote sync."
1987
3830
  };
1988
3831
  }
@@ -2001,11 +3844,11 @@ Currently logged-in as ${this._username}.`
2001
3844
  await localDB.bulkDocs(docsToDelete);
2002
3845
  }
2003
3846
  await this.init();
2004
- return { status: import_common8.Status.ok };
3847
+ return { status: import_common12.Status.ok };
2005
3848
  } catch (error) {
2006
3849
  logger.error("Failed to reset user data:", error);
2007
3850
  return {
2008
- status: import_common8.Status.error,
3851
+ status: import_common12.Status.error,
2009
3852
  error: error instanceof Error ? error.message : "Unknown error during reset"
2010
3853
  };
2011
3854
  }
@@ -2152,7 +3995,7 @@ Currently logged-in as ${this._username}.`
2152
3995
  );
2153
3996
  return reviews.rows.filter((r) => {
2154
3997
  if (r.id.startsWith(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */])) {
2155
- const date = import_moment5.default.utc(
3998
+ const date = import_moment6.default.utc(
2156
3999
  r.id.substr(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */].length),
2157
4000
  REVIEW_TIME_FORMAT
2158
4001
  );
@@ -2165,11 +4008,11 @@ Currently logged-in as ${this._username}.`
2165
4008
  }).map((r) => r.doc);
2166
4009
  }
2167
4010
  async getReviewsForcast(daysCount) {
2168
- const time = import_moment5.default.utc().add(daysCount, "days");
4011
+ const time = import_moment6.default.utc().add(daysCount, "days");
2169
4012
  return this.getReviewstoDate(time);
2170
4013
  }
2171
4014
  async getPendingReviews(course_id) {
2172
- const now = import_moment5.default.utc();
4015
+ const now = import_moment6.default.utc();
2173
4016
  return this.getReviewstoDate(now, course_id);
2174
4017
  }
2175
4018
  async getScheduledReviewCount(course_id) {
@@ -2456,7 +4299,7 @@ Currently logged-in as ${this._username}.`
2456
4299
  */
2457
4300
  async putCardRecord(record) {
2458
4301
  const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
2459
- record.timeStamp = import_moment5.default.utc(record.timeStamp).toString();
4302
+ record.timeStamp = import_moment6.default.utc(record.timeStamp).toString();
2460
4303
  try {
2461
4304
  const cardHistory = await this.update(
2462
4305
  cardHistoryID,
@@ -2472,7 +4315,7 @@ Currently logged-in as ${this._username}.`
2472
4315
  const ret = {
2473
4316
  ...record2
2474
4317
  };
2475
- ret.timeStamp = import_moment5.default.utc(record2.timeStamp);
4318
+ ret.timeStamp = import_moment6.default.utc(record2.timeStamp);
2476
4319
  return ret;
2477
4320
  });
2478
4321
  return cardHistory;
@@ -2696,6 +4539,55 @@ Currently logged-in as ${this._username}.`
2696
4539
  async updateUserElo(courseId, elo) {
2697
4540
  return updateUserElo(this._username, courseId, elo);
2698
4541
  }
4542
+ async getStrategyState(courseId, strategyKey) {
4543
+ const docId = buildStrategyStateId(courseId, strategyKey);
4544
+ try {
4545
+ const doc = await this.localDB.get(docId);
4546
+ return doc.data;
4547
+ } catch (e) {
4548
+ const err = e;
4549
+ if (err.status === 404) {
4550
+ return null;
4551
+ }
4552
+ throw e;
4553
+ }
4554
+ }
4555
+ async putStrategyState(courseId, strategyKey, data) {
4556
+ const docId = buildStrategyStateId(courseId, strategyKey);
4557
+ let existingRev;
4558
+ try {
4559
+ const existing = await this.localDB.get(docId);
4560
+ existingRev = existing._rev;
4561
+ } catch (e) {
4562
+ const err = e;
4563
+ if (err.status !== 404) {
4564
+ throw e;
4565
+ }
4566
+ }
4567
+ const doc = {
4568
+ _id: docId,
4569
+ _rev: existingRev,
4570
+ docType: "STRATEGY_STATE" /* STRATEGY_STATE */,
4571
+ courseId,
4572
+ strategyKey,
4573
+ data,
4574
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
4575
+ };
4576
+ await this.localDB.put(doc);
4577
+ }
4578
+ async deleteStrategyState(courseId, strategyKey) {
4579
+ const docId = buildStrategyStateId(courseId, strategyKey);
4580
+ try {
4581
+ const doc = await this.localDB.get(docId);
4582
+ await this.localDB.remove(doc);
4583
+ } catch (e) {
4584
+ const err = e;
4585
+ if (err.status === 404) {
4586
+ return;
4587
+ }
4588
+ throw e;
4589
+ }
4590
+ }
2699
4591
  };
2700
4592
  userCoursesDoc = "CourseRegistrations";
2701
4593
  userClassroomsDoc = "ClassroomRegistrations";
@@ -2735,6 +4627,213 @@ var init_factory = __esm({
2735
4627
  }
2736
4628
  });
2737
4629
 
4630
+ // src/study/TagFilteredContentSource.ts
4631
+ var import_common14, TagFilteredContentSource;
4632
+ var init_TagFilteredContentSource = __esm({
4633
+ "src/study/TagFilteredContentSource.ts"() {
4634
+ "use strict";
4635
+ import_common14 = require("@vue-skuilder/common");
4636
+ init_courseDB();
4637
+ init_logger();
4638
+ TagFilteredContentSource = class {
4639
+ courseId;
4640
+ filter;
4641
+ user;
4642
+ // Cache resolved card IDs to avoid repeated lookups within a session
4643
+ resolvedCardIds = null;
4644
+ constructor(courseId, filter, user) {
4645
+ this.courseId = courseId;
4646
+ this.filter = filter;
4647
+ this.user = user;
4648
+ logger.info(
4649
+ `[TagFilteredContentSource] Created for course "${courseId}" with filter:`,
4650
+ JSON.stringify(filter)
4651
+ );
4652
+ }
4653
+ /**
4654
+ * Resolves the TagFilter to a set of eligible card IDs.
4655
+ *
4656
+ * - Cards in `include` tags are OR'd together (card needs at least one)
4657
+ * - Cards in `exclude` tags are removed from the result
4658
+ */
4659
+ async resolveFilteredCardIds() {
4660
+ if (this.resolvedCardIds !== null) {
4661
+ return this.resolvedCardIds;
4662
+ }
4663
+ const includedCardIds = /* @__PURE__ */ new Set();
4664
+ if (this.filter.include.length > 0) {
4665
+ for (const tagName of this.filter.include) {
4666
+ try {
4667
+ const tagDoc = await getTag(this.courseId, tagName);
4668
+ tagDoc.taggedCards.forEach((cardId) => includedCardIds.add(cardId));
4669
+ } catch (error) {
4670
+ logger.warn(
4671
+ `[TagFilteredContentSource] Could not resolve tag "${tagName}" for inclusion:`,
4672
+ error
4673
+ );
4674
+ }
4675
+ }
4676
+ }
4677
+ if (includedCardIds.size === 0 && this.filter.include.length > 0) {
4678
+ logger.warn(
4679
+ `[TagFilteredContentSource] No cards found for include tags: ${this.filter.include.join(", ")}`
4680
+ );
4681
+ this.resolvedCardIds = /* @__PURE__ */ new Set();
4682
+ return this.resolvedCardIds;
4683
+ }
4684
+ const excludedCardIds = /* @__PURE__ */ new Set();
4685
+ if (this.filter.exclude.length > 0) {
4686
+ for (const tagName of this.filter.exclude) {
4687
+ try {
4688
+ const tagDoc = await getTag(this.courseId, tagName);
4689
+ tagDoc.taggedCards.forEach((cardId) => excludedCardIds.add(cardId));
4690
+ } catch (error) {
4691
+ logger.warn(
4692
+ `[TagFilteredContentSource] Could not resolve tag "${tagName}" for exclusion:`,
4693
+ error
4694
+ );
4695
+ }
4696
+ }
4697
+ }
4698
+ const finalCardIds = /* @__PURE__ */ new Set();
4699
+ for (const cardId of includedCardIds) {
4700
+ if (!excludedCardIds.has(cardId)) {
4701
+ finalCardIds.add(cardId);
4702
+ }
4703
+ }
4704
+ logger.info(
4705
+ `[TagFilteredContentSource] Resolved ${finalCardIds.size} cards (included: ${includedCardIds.size}, excluded: ${excludedCardIds.size})`
4706
+ );
4707
+ this.resolvedCardIds = finalCardIds;
4708
+ return finalCardIds;
4709
+ }
4710
+ /**
4711
+ * Gets new cards that match the tag filter and are not already active for the user.
4712
+ */
4713
+ async getNewCards(limit) {
4714
+ if (!(0, import_common14.hasActiveFilter)(this.filter)) {
4715
+ logger.warn("[TagFilteredContentSource] getNewCards called with no active filter");
4716
+ return [];
4717
+ }
4718
+ const eligibleCardIds = await this.resolveFilteredCardIds();
4719
+ const activeCards = await this.user.getActiveCards();
4720
+ const activeCardIds = new Set(activeCards.map((c) => c.cardID));
4721
+ const newItems = [];
4722
+ for (const cardId of eligibleCardIds) {
4723
+ if (!activeCardIds.has(cardId)) {
4724
+ newItems.push({
4725
+ courseID: this.courseId,
4726
+ cardID: cardId,
4727
+ contentSourceType: "course",
4728
+ contentSourceID: this.courseId,
4729
+ status: "new"
4730
+ });
4731
+ }
4732
+ if (limit !== void 0 && newItems.length >= limit) {
4733
+ break;
4734
+ }
4735
+ }
4736
+ logger.info(`[TagFilteredContentSource] Found ${newItems.length} new cards matching filter`);
4737
+ return newItems;
4738
+ }
4739
+ /**
4740
+ * Gets pending reviews, filtered to only include cards that match the tag filter.
4741
+ */
4742
+ async getPendingReviews() {
4743
+ if (!(0, import_common14.hasActiveFilter)(this.filter)) {
4744
+ logger.warn("[TagFilteredContentSource] getPendingReviews called with no active filter");
4745
+ return [];
4746
+ }
4747
+ const eligibleCardIds = await this.resolveFilteredCardIds();
4748
+ const allReviews = await this.user.getPendingReviews(this.courseId);
4749
+ const filteredReviews = allReviews.filter((review) => {
4750
+ return eligibleCardIds.has(review.cardId);
4751
+ });
4752
+ logger.info(
4753
+ `[TagFilteredContentSource] Found ${filteredReviews.length} pending reviews matching filter (of ${allReviews.length} total)`
4754
+ );
4755
+ return filteredReviews.map((r) => ({
4756
+ ...r,
4757
+ courseID: r.courseId,
4758
+ cardID: r.cardId,
4759
+ contentSourceType: "course",
4760
+ contentSourceID: this.courseId,
4761
+ reviewID: r._id,
4762
+ status: "review"
4763
+ }));
4764
+ }
4765
+ /**
4766
+ * Get cards with suitability scores for presentation.
4767
+ *
4768
+ * This implementation wraps the legacy getNewCards/getPendingReviews methods,
4769
+ * assigning score=1.0 to all cards. TagFilteredContentSource does not currently
4770
+ * support pluggable navigation strategies - it returns flat-scored candidates.
4771
+ *
4772
+ * @param limit - Maximum number of cards to return
4773
+ * @returns Cards sorted by score descending (all scores = 1.0)
4774
+ */
4775
+ async getWeightedCards(limit) {
4776
+ const [newCards, reviews] = await Promise.all([
4777
+ this.getNewCards(limit),
4778
+ this.getPendingReviews()
4779
+ ]);
4780
+ const weighted = [
4781
+ ...reviews.map((r) => ({
4782
+ cardId: r.cardID,
4783
+ courseId: r.courseID,
4784
+ score: 1,
4785
+ provenance: [
4786
+ {
4787
+ strategy: "tagFilter",
4788
+ strategyName: "Tag Filter",
4789
+ strategyId: "TAG_FILTER",
4790
+ action: "generated",
4791
+ score: 1,
4792
+ reason: `Tag-filtered review (tags: ${this.filter.include.join(", ")})`
4793
+ }
4794
+ ]
4795
+ })),
4796
+ ...newCards.map((c) => ({
4797
+ cardId: c.cardID,
4798
+ courseId: c.courseID,
4799
+ score: 1,
4800
+ provenance: [
4801
+ {
4802
+ strategy: "tagFilter",
4803
+ strategyName: "Tag Filter",
4804
+ strategyId: "TAG_FILTER",
4805
+ action: "generated",
4806
+ score: 1,
4807
+ reason: `Tag-filtered new card (tags: ${this.filter.include.join(", ")})`
4808
+ }
4809
+ ]
4810
+ }))
4811
+ ];
4812
+ return weighted.slice(0, limit);
4813
+ }
4814
+ /**
4815
+ * Clears the cached resolved card IDs.
4816
+ * Call this if the underlying tag data may have changed during a session.
4817
+ */
4818
+ clearCache() {
4819
+ this.resolvedCardIds = null;
4820
+ }
4821
+ /**
4822
+ * Returns the course ID this source is filtering.
4823
+ */
4824
+ getCourseId() {
4825
+ return this.courseId;
4826
+ }
4827
+ /**
4828
+ * Returns the active tag filter.
4829
+ */
4830
+ getFilter() {
4831
+ return this.filter;
4832
+ }
4833
+ };
4834
+ }
4835
+ });
4836
+
2738
4837
  // src/core/interfaces/contentSource.ts
2739
4838
  function isReview(item) {
2740
4839
  const ret = item.status === "review" || item.status === "failed-review" || "reviewID" in item;
@@ -2744,14 +4843,20 @@ async function getStudySource(source, user) {
2744
4843
  if (source.type === "classroom") {
2745
4844
  return await StudentClassroomDB.factory(source.id, user);
2746
4845
  } else {
4846
+ if ((0, import_common15.hasActiveFilter)(source.tagFilter)) {
4847
+ return new TagFilteredContentSource(source.id, source.tagFilter, user);
4848
+ }
2747
4849
  return getDataLayer().getCourseDB(source.id);
2748
4850
  }
2749
4851
  }
4852
+ var import_common15;
2750
4853
  var init_contentSource = __esm({
2751
4854
  "src/core/interfaces/contentSource.ts"() {
2752
4855
  "use strict";
2753
4856
  init_factory();
2754
4857
  init_classroomDB2();
4858
+ import_common15 = require("@vue-skuilder/common");
4859
+ init_TagFilteredContentSource();
2755
4860
  }
2756
4861
  });
2757
4862
 
@@ -2796,6 +4901,16 @@ var init_user = __esm({
2796
4901
  }
2797
4902
  });
2798
4903
 
4904
+ // src/core/types/strategyState.ts
4905
+ function buildStrategyStateId(courseId, strategyKey) {
4906
+ return `STRATEGY_STATE::${courseId}::${strategyKey}`;
4907
+ }
4908
+ var init_strategyState = __esm({
4909
+ "src/core/types/strategyState.ts"() {
4910
+ "use strict";
4911
+ }
4912
+ });
4913
+
2799
4914
  // src/core/bulkImport/cardProcessor.ts
2800
4915
  async function importParsedCards(parsedCards, courseDB, config) {
2801
4916
  const results = [];
@@ -2864,7 +4979,7 @@ elo: ${elo}`;
2864
4979
  misc: {}
2865
4980
  } : void 0
2866
4981
  );
2867
- if (result.status === import_common10.Status.ok) {
4982
+ if (result.status === import_common16.Status.ok) {
2868
4983
  return {
2869
4984
  originalText,
2870
4985
  status: "success",
@@ -2908,17 +5023,17 @@ function validateProcessorConfig(config) {
2908
5023
  }
2909
5024
  return { isValid: true };
2910
5025
  }
2911
- var import_common10;
5026
+ var import_common16;
2912
5027
  var init_cardProcessor = __esm({
2913
5028
  "src/core/bulkImport/cardProcessor.ts"() {
2914
5029
  "use strict";
2915
- import_common10 = require("@vue-skuilder/common");
5030
+ import_common16 = require("@vue-skuilder/common");
2916
5031
  init_logger();
2917
5032
  }
2918
5033
  });
2919
5034
 
2920
5035
  // src/core/bulkImport/types.ts
2921
- var init_types = __esm({
5036
+ var init_types3 = __esm({
2922
5037
  "src/core/bulkImport/types.ts"() {
2923
5038
  "use strict";
2924
5039
  }
@@ -2929,7 +5044,7 @@ var init_bulkImport = __esm({
2929
5044
  "src/core/bulkImport/index.ts"() {
2930
5045
  "use strict";
2931
5046
  init_cardProcessor();
2932
- init_types();
5047
+ init_types3();
2933
5048
  }
2934
5049
  });
2935
5050
 
@@ -2941,12 +5056,18 @@ __export(core_exports, {
2941
5056
  DocTypePrefixes: () => DocTypePrefixes,
2942
5057
  GuestUsername: () => GuestUsername,
2943
5058
  Loggable: () => Loggable,
5059
+ NavigatorRole: () => NavigatorRole,
5060
+ NavigatorRoles: () => NavigatorRoles,
2944
5061
  Navigators: () => Navigators,
2945
5062
  areQuestionRecords: () => areQuestionRecords,
5063
+ buildStrategyStateId: () => buildStrategyStateId,
2946
5064
  docIsDeleted: () => docIsDeleted,
2947
5065
  getCardHistoryID: () => getCardHistoryID,
5066
+ getCardOrigin: () => getCardOrigin,
2948
5067
  getStudySource: () => getStudySource,
2949
5068
  importParsedCards: () => importParsedCards,
5069
+ isFilter: () => isFilter,
5070
+ isGenerator: () => isGenerator,
2950
5071
  isQuestionRecord: () => isQuestionRecord,
2951
5072
  isReview: () => isReview,
2952
5073
  log: () => log,
@@ -2959,6 +5080,7 @@ var init_core = __esm({
2959
5080
  init_interfaces();
2960
5081
  init_types_legacy();
2961
5082
  init_user();
5083
+ init_strategyState();
2962
5084
  init_Loggable();
2963
5085
  init_util();
2964
5086
  init_navigators();
@@ -2973,12 +5095,18 @@ init_core();
2973
5095
  DocTypePrefixes,
2974
5096
  GuestUsername,
2975
5097
  Loggable,
5098
+ NavigatorRole,
5099
+ NavigatorRoles,
2976
5100
  Navigators,
2977
5101
  areQuestionRecords,
5102
+ buildStrategyStateId,
2978
5103
  docIsDeleted,
2979
5104
  getCardHistoryID,
5105
+ getCardOrigin,
2980
5106
  getStudySource,
2981
5107
  importParsedCards,
5108
+ isFilter,
5109
+ isGenerator,
2982
5110
  isQuestionRecord,
2983
5111
  isReview,
2984
5112
  log,