@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
@@ -258,7 +258,8 @@ var init_types_legacy = __esm({
258
258
  ["QUESTION" /* QUESTIONTYPE */]: "QUESTION",
259
259
  ["VIEW" /* VIEW */]: "VIEW",
260
260
  ["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
261
- ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY"
261
+ ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
262
+ ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE"
262
263
  };
263
264
  }
264
265
  });
@@ -599,23 +600,518 @@ var init_courseLookupDB = __esm({
599
600
  }
600
601
  });
601
602
 
603
+ // src/core/navigators/CompositeGenerator.ts
604
+ var CompositeGenerator_exports = {};
605
+ __export(CompositeGenerator_exports, {
606
+ AggregationMode: () => AggregationMode,
607
+ default: () => CompositeGenerator
608
+ });
609
+ var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
610
+ var init_CompositeGenerator = __esm({
611
+ "src/core/navigators/CompositeGenerator.ts"() {
612
+ "use strict";
613
+ init_navigators();
614
+ init_logger();
615
+ AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
616
+ AggregationMode2["MAX"] = "max";
617
+ AggregationMode2["AVERAGE"] = "average";
618
+ AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
619
+ return AggregationMode2;
620
+ })(AggregationMode || {});
621
+ DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
622
+ FREQUENCY_BOOST_FACTOR = 0.1;
623
+ CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
624
+ /** Human-readable name for CardGenerator interface */
625
+ name = "Composite Generator";
626
+ generators;
627
+ aggregationMode;
628
+ constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
629
+ super();
630
+ this.generators = generators;
631
+ this.aggregationMode = aggregationMode;
632
+ if (generators.length === 0) {
633
+ throw new Error("CompositeGenerator requires at least one generator");
634
+ }
635
+ logger.debug(
636
+ `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
637
+ );
638
+ }
639
+ /**
640
+ * Creates a CompositeGenerator from strategy data.
641
+ *
642
+ * This is a convenience factory for use by PipelineAssembler.
643
+ */
644
+ static async fromStrategies(user, course, strategies, aggregationMode = DEFAULT_AGGREGATION_MODE) {
645
+ const generators = await Promise.all(
646
+ strategies.map((s) => ContentNavigator.create(user, course, s))
647
+ );
648
+ return new _CompositeGenerator(generators, aggregationMode);
649
+ }
650
+ /**
651
+ * Get weighted cards from all generators, merge and deduplicate.
652
+ *
653
+ * Cards appearing in multiple generators receive a score boost.
654
+ * Provenance tracks which generators produced each card and how scores were aggregated.
655
+ *
656
+ * This method supports both the legacy signature (limit only) and the
657
+ * CardGenerator interface signature (limit, context).
658
+ *
659
+ * @param limit - Maximum number of cards to return
660
+ * @param context - Optional GeneratorContext passed to child generators
661
+ */
662
+ async getWeightedCards(limit, context) {
663
+ const results = await Promise.all(
664
+ this.generators.map((g) => g.getWeightedCards(limit, context))
665
+ );
666
+ const byCardId = /* @__PURE__ */ new Map();
667
+ for (const cards of results) {
668
+ for (const card of cards) {
669
+ const existing = byCardId.get(card.cardId) || [];
670
+ existing.push(card);
671
+ byCardId.set(card.cardId, existing);
672
+ }
673
+ }
674
+ const merged = [];
675
+ for (const [, cards] of byCardId) {
676
+ const aggregatedScore = this.aggregateScores(cards);
677
+ const finalScore = Math.min(1, aggregatedScore);
678
+ const mergedProvenance = cards.flatMap((c) => c.provenance);
679
+ const initialScore = cards[0].score;
680
+ const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
681
+ const reason = this.buildAggregationReason(cards, finalScore);
682
+ merged.push({
683
+ ...cards[0],
684
+ score: finalScore,
685
+ provenance: [
686
+ ...mergedProvenance,
687
+ {
688
+ strategy: "composite",
689
+ strategyName: "Composite Generator",
690
+ strategyId: "COMPOSITE_GENERATOR",
691
+ action,
692
+ score: finalScore,
693
+ reason
694
+ }
695
+ ]
696
+ });
697
+ }
698
+ return merged.sort((a, b) => b.score - a.score).slice(0, limit);
699
+ }
700
+ /**
701
+ * Build human-readable reason for score aggregation.
702
+ */
703
+ buildAggregationReason(cards, finalScore) {
704
+ const count = cards.length;
705
+ const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
706
+ if (count === 1) {
707
+ return `Single generator, score ${finalScore.toFixed(2)}`;
708
+ }
709
+ const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
710
+ switch (this.aggregationMode) {
711
+ case "max" /* MAX */:
712
+ return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
713
+ case "average" /* AVERAGE */:
714
+ return `Average of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
715
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
716
+ const avg = cards.reduce((sum, c) => sum + c.score, 0) / count;
717
+ const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
718
+ return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
719
+ }
720
+ default:
721
+ return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
722
+ }
723
+ }
724
+ /**
725
+ * Aggregate scores from multiple generators for the same card.
726
+ */
727
+ aggregateScores(cards) {
728
+ const scores = cards.map((c) => c.score);
729
+ switch (this.aggregationMode) {
730
+ case "max" /* MAX */:
731
+ return Math.max(...scores);
732
+ case "average" /* AVERAGE */:
733
+ return scores.reduce((sum, s) => sum + s, 0) / scores.length;
734
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
735
+ const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
736
+ const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (cards.length - 1);
737
+ return avg * frequencyBoost;
738
+ }
739
+ default:
740
+ return scores[0];
741
+ }
742
+ }
743
+ /**
744
+ * Get new cards from all generators, merged and deduplicated.
745
+ */
746
+ async getNewCards(n) {
747
+ const legacyGenerators = this.generators.filter(
748
+ (g) => g instanceof ContentNavigator
749
+ );
750
+ const results = await Promise.all(legacyGenerators.map((g) => g.getNewCards(n)));
751
+ const seen = /* @__PURE__ */ new Set();
752
+ const merged = [];
753
+ for (const cards of results) {
754
+ for (const card of cards) {
755
+ if (!seen.has(card.cardID)) {
756
+ seen.add(card.cardID);
757
+ merged.push(card);
758
+ }
759
+ }
760
+ }
761
+ return n ? merged.slice(0, n) : merged;
762
+ }
763
+ /**
764
+ * Get pending reviews from all generators, merged and deduplicated.
765
+ */
766
+ async getPendingReviews() {
767
+ const legacyGenerators = this.generators.filter(
768
+ (g) => g instanceof ContentNavigator
769
+ );
770
+ const results = await Promise.all(legacyGenerators.map((g) => g.getPendingReviews()));
771
+ const seen = /* @__PURE__ */ new Set();
772
+ const merged = [];
773
+ for (const reviews of results) {
774
+ for (const review of reviews) {
775
+ if (!seen.has(review.cardID)) {
776
+ seen.add(review.cardID);
777
+ merged.push(review);
778
+ }
779
+ }
780
+ }
781
+ return merged;
782
+ }
783
+ };
784
+ }
785
+ });
786
+
787
+ // src/core/navigators/Pipeline.ts
788
+ var Pipeline_exports = {};
789
+ __export(Pipeline_exports, {
790
+ Pipeline: () => Pipeline
791
+ });
792
+ import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
793
+ function logPipelineConfig(generator, filters) {
794
+ const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
795
+ logger.info(
796
+ `[Pipeline] Configuration:
797
+ Generator: ${generator.name}
798
+ Filters:${filterList}`
799
+ );
800
+ }
801
+ function logTagHydration(cards, tagsByCard) {
802
+ const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
803
+ const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
804
+ logger.debug(
805
+ `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
806
+ );
807
+ }
808
+ function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores) {
809
+ const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
810
+ logger.info(
811
+ `[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})`
812
+ );
813
+ }
814
+ function logCardProvenance(cards, maxCards = 3) {
815
+ const cardsToLog = cards.slice(0, maxCards);
816
+ logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
817
+ for (const card of cardsToLog) {
818
+ logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
819
+ for (const entry of card.provenance) {
820
+ const scoreChange = entry.score.toFixed(3);
821
+ const action = entry.action.padEnd(9);
822
+ logger.debug(
823
+ `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
824
+ );
825
+ }
826
+ }
827
+ }
828
+ var Pipeline;
829
+ var init_Pipeline = __esm({
830
+ "src/core/navigators/Pipeline.ts"() {
831
+ "use strict";
832
+ init_navigators();
833
+ init_logger();
834
+ Pipeline = class extends ContentNavigator {
835
+ generator;
836
+ filters;
837
+ /**
838
+ * Create a new pipeline.
839
+ *
840
+ * @param generator - The generator (or CompositeGenerator) that produces candidates
841
+ * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
842
+ * @param user - User database interface
843
+ * @param course - Course database interface
844
+ */
845
+ constructor(generator, filters, user, course) {
846
+ super();
847
+ this.generator = generator;
848
+ this.filters = filters;
849
+ this.user = user;
850
+ this.course = course;
851
+ logPipelineConfig(generator, filters);
852
+ }
853
+ /**
854
+ * Get weighted cards by running generator and applying filters.
855
+ *
856
+ * 1. Build shared context (user ELO, etc.)
857
+ * 2. Get candidates from generator (passing context)
858
+ * 3. Batch hydrate tags for all candidates
859
+ * 4. Apply each filter sequentially
860
+ * 5. Remove zero-score cards
861
+ * 6. Sort by score descending
862
+ * 7. Return top N
863
+ *
864
+ * @param limit - Maximum number of cards to return
865
+ * @returns Cards sorted by score descending
866
+ */
867
+ async getWeightedCards(limit) {
868
+ const context = await this.buildContext();
869
+ const overFetchMultiplier = 2 + this.filters.length * 0.5;
870
+ const fetchLimit = Math.ceil(limit * overFetchMultiplier);
871
+ logger.debug(
872
+ `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
873
+ );
874
+ let cards = await this.generator.getWeightedCards(fetchLimit, context);
875
+ const generatedCount = cards.length;
876
+ logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
877
+ cards = await this.hydrateTags(cards);
878
+ for (const filter of this.filters) {
879
+ const beforeCount = cards.length;
880
+ cards = await filter.transform(cards, context);
881
+ logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeCount} \u2192 ${cards.length} cards`);
882
+ }
883
+ cards = cards.filter((c) => c.score > 0);
884
+ cards.sort((a, b) => b.score - a.score);
885
+ const result = cards.slice(0, limit);
886
+ const topScores = result.slice(0, 3).map((c) => c.score);
887
+ logExecutionSummary(this.generator.name, generatedCount, this.filters.length, result.length, topScores);
888
+ logCardProvenance(result, 3);
889
+ return result;
890
+ }
891
+ /**
892
+ * Batch hydrate tags for all cards.
893
+ *
894
+ * Fetches tags for all cards in a single database query and attaches them
895
+ * to the WeightedCard objects. Filters can then use card.tags instead of
896
+ * making individual getAppliedTags() calls.
897
+ *
898
+ * @param cards - Cards to hydrate
899
+ * @returns Cards with tags populated
900
+ */
901
+ async hydrateTags(cards) {
902
+ if (cards.length === 0) {
903
+ return cards;
904
+ }
905
+ const cardIds = cards.map((c) => c.cardId);
906
+ const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
907
+ logTagHydration(cards, tagsByCard);
908
+ return cards.map((card) => ({
909
+ ...card,
910
+ tags: tagsByCard.get(card.cardId) ?? []
911
+ }));
912
+ }
913
+ /**
914
+ * Build shared context for generator and filters.
915
+ *
916
+ * Called once per getWeightedCards() invocation.
917
+ * Contains data that the generator and multiple filters might need.
918
+ *
919
+ * The context satisfies both GeneratorContext and FilterContext interfaces.
920
+ */
921
+ async buildContext() {
922
+ let userElo = 1e3;
923
+ try {
924
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
925
+ const courseElo = toCourseElo2(courseReg.elo);
926
+ userElo = courseElo.global.score;
927
+ } catch (e) {
928
+ logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
929
+ }
930
+ return {
931
+ user: this.user,
932
+ course: this.course,
933
+ userElo
934
+ };
935
+ }
936
+ // ===========================================================================
937
+ // Legacy StudyContentSource methods
938
+ // ===========================================================================
939
+ //
940
+ // These delegate to the generator for backward compatibility.
941
+ // Eventually SessionController will use getWeightedCards() exclusively.
942
+ //
943
+ /**
944
+ * Get new cards via legacy API.
945
+ * Delegates to the generator if it supports the legacy interface.
946
+ */
947
+ async getNewCards(n) {
948
+ if ("getNewCards" in this.generator && typeof this.generator.getNewCards === "function") {
949
+ return this.generator.getNewCards(n);
950
+ }
951
+ return [];
952
+ }
953
+ /**
954
+ * Get pending reviews via legacy API.
955
+ * Delegates to the generator if it supports the legacy interface.
956
+ */
957
+ async getPendingReviews() {
958
+ if ("getPendingReviews" in this.generator && typeof this.generator.getPendingReviews === "function") {
959
+ return this.generator.getPendingReviews();
960
+ }
961
+ return [];
962
+ }
963
+ /**
964
+ * Get the course ID for this pipeline.
965
+ */
966
+ getCourseID() {
967
+ return this.course.getCourseID();
968
+ }
969
+ };
970
+ }
971
+ });
972
+
973
+ // src/core/navigators/PipelineAssembler.ts
974
+ var PipelineAssembler_exports = {};
975
+ __export(PipelineAssembler_exports, {
976
+ PipelineAssembler: () => PipelineAssembler
977
+ });
978
+ var PipelineAssembler;
979
+ var init_PipelineAssembler = __esm({
980
+ "src/core/navigators/PipelineAssembler.ts"() {
981
+ "use strict";
982
+ init_navigators();
983
+ init_Pipeline();
984
+ init_types_legacy();
985
+ init_logger();
986
+ init_CompositeGenerator();
987
+ PipelineAssembler = class {
988
+ /**
989
+ * Assembles a navigation pipeline from strategy documents.
990
+ *
991
+ * 1. Separates into generators and filters by role
992
+ * 2. Validates at least one generator exists (or creates default ELO)
993
+ * 3. Instantiates generators - wraps multiple in CompositeGenerator
994
+ * 4. Instantiates filters
995
+ * 5. Returns Pipeline(generator, filters)
996
+ *
997
+ * @param input - Strategy documents plus user/course interfaces
998
+ * @returns Assembled pipeline and any warnings
999
+ */
1000
+ async assemble(input) {
1001
+ const { strategies, user, course } = input;
1002
+ const warnings = [];
1003
+ if (strategies.length === 0) {
1004
+ return {
1005
+ pipeline: null,
1006
+ generatorStrategies: [],
1007
+ filterStrategies: [],
1008
+ warnings
1009
+ };
1010
+ }
1011
+ const generatorStrategies = [];
1012
+ const filterStrategies = [];
1013
+ for (const s of strategies) {
1014
+ if (isGenerator(s.implementingClass)) {
1015
+ generatorStrategies.push(s);
1016
+ } else if (isFilter(s.implementingClass)) {
1017
+ filterStrategies.push(s);
1018
+ } else {
1019
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
1020
+ }
1021
+ }
1022
+ if (generatorStrategies.length === 0) {
1023
+ if (filterStrategies.length > 0) {
1024
+ logger.debug(
1025
+ "[PipelineAssembler] No generator found, using default ELO with configured filters"
1026
+ );
1027
+ generatorStrategies.push(this.makeDefaultEloStrategy(course.getCourseID()));
1028
+ } else {
1029
+ warnings.push("No generator strategy found");
1030
+ return {
1031
+ pipeline: null,
1032
+ generatorStrategies: [],
1033
+ filterStrategies: [],
1034
+ warnings
1035
+ };
1036
+ }
1037
+ }
1038
+ let generator;
1039
+ if (generatorStrategies.length === 1) {
1040
+ const nav = await ContentNavigator.create(user, course, generatorStrategies[0]);
1041
+ generator = nav;
1042
+ logger.debug(`[PipelineAssembler] Using single generator: ${generatorStrategies[0].name}`);
1043
+ } else {
1044
+ logger.debug(
1045
+ `[PipelineAssembler] Using CompositeGenerator for ${generatorStrategies.length} generators: ${generatorStrategies.map((g) => g.name).join(", ")}`
1046
+ );
1047
+ generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
1048
+ }
1049
+ const filters = [];
1050
+ const sortedFilterStrategies = [...filterStrategies].sort(
1051
+ (a, b) => a.name.localeCompare(b.name)
1052
+ );
1053
+ for (const filterStrategy of sortedFilterStrategies) {
1054
+ try {
1055
+ const nav = await ContentNavigator.create(user, course, filterStrategy);
1056
+ if ("transform" in nav && typeof nav.transform === "function") {
1057
+ filters.push(nav);
1058
+ logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
1059
+ } else {
1060
+ warnings.push(
1061
+ `Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
1062
+ );
1063
+ }
1064
+ } catch (e) {
1065
+ warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
1066
+ }
1067
+ }
1068
+ const pipeline = new Pipeline(generator, filters, user, course);
1069
+ logger.debug(
1070
+ `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
1071
+ );
1072
+ return {
1073
+ pipeline,
1074
+ generatorStrategies,
1075
+ filterStrategies: sortedFilterStrategies,
1076
+ warnings
1077
+ };
1078
+ }
1079
+ /**
1080
+ * Creates a default ELO generator strategy.
1081
+ * Used when filters are configured but no generator is specified.
1082
+ */
1083
+ makeDefaultEloStrategy(courseId) {
1084
+ return {
1085
+ _id: "NAVIGATION_STRATEGY-ELO-default",
1086
+ course: courseId,
1087
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1088
+ name: "ELO (default)",
1089
+ description: "Default ELO-based generator",
1090
+ implementingClass: "elo" /* ELO */,
1091
+ serializedData: ""
1092
+ };
1093
+ }
1094
+ };
1095
+ }
1096
+ });
1097
+
602
1098
  // src/core/navigators/elo.ts
603
1099
  var elo_exports = {};
604
1100
  __export(elo_exports, {
605
1101
  default: () => ELONavigator
606
1102
  });
1103
+ import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
607
1104
  var ELONavigator;
608
1105
  var init_elo = __esm({
609
1106
  "src/core/navigators/elo.ts"() {
610
1107
  "use strict";
611
1108
  init_navigators();
612
1109
  ELONavigator = class extends ContentNavigator {
613
- user;
614
- course;
615
- constructor(user, course) {
616
- super();
617
- this.user = user;
618
- this.course = course;
1110
+ /** Human-readable name for CardGenerator interface */
1111
+ name;
1112
+ constructor(user, course, strategyData) {
1113
+ super(user, course, strategyData);
1114
+ this.name = strategyData?.name || "ELO";
619
1115
  }
620
1116
  async getPendingReviews() {
621
1117
  const reviews = await this.user.getPendingReviews(this.course.getCourseID());
@@ -661,10 +1157,283 @@ var init_elo = __esm({
661
1157
  };
662
1158
  });
663
1159
  }
1160
+ /**
1161
+ * Get new cards with suitability scores based on ELO distance.
1162
+ *
1163
+ * Cards closer to user's ELO get higher scores.
1164
+ * Score formula: max(0, 1 - distance / 500)
1165
+ *
1166
+ * NOTE: This generator only handles NEW cards. Reviews are handled by
1167
+ * SRSNavigator. Use CompositeGenerator to combine both.
1168
+ *
1169
+ * This method supports both the legacy signature (limit only) and the
1170
+ * CardGenerator interface signature (limit, context).
1171
+ *
1172
+ * @param limit - Maximum number of cards to return
1173
+ * @param context - Optional GeneratorContext (used when called via Pipeline)
1174
+ */
1175
+ async getWeightedCards(limit, context) {
1176
+ let userGlobalElo;
1177
+ if (context?.userElo !== void 0) {
1178
+ userGlobalElo = context.userElo;
1179
+ } else {
1180
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1181
+ const userElo = toCourseElo3(courseReg.elo);
1182
+ userGlobalElo = userElo.global.score;
1183
+ }
1184
+ const newCards = await this.getNewCards(limit);
1185
+ const cardIds = newCards.map((c) => c.cardID);
1186
+ const cardEloData = await this.course.getCardEloData(cardIds);
1187
+ const scored = newCards.map((c, i) => {
1188
+ const cardElo = cardEloData[i]?.global?.score ?? 1e3;
1189
+ const distance = Math.abs(cardElo - userGlobalElo);
1190
+ const score = Math.max(0, 1 - distance / 500);
1191
+ return {
1192
+ cardId: c.cardID,
1193
+ courseId: c.courseID,
1194
+ score,
1195
+ provenance: [
1196
+ {
1197
+ strategy: "elo",
1198
+ strategyName: this.strategyName || this.name,
1199
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1200
+ action: "generated",
1201
+ score,
1202
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), new card`
1203
+ }
1204
+ ]
1205
+ };
1206
+ });
1207
+ scored.sort((a, b) => b.score - a.score);
1208
+ return scored.slice(0, limit);
1209
+ }
664
1210
  };
665
1211
  }
666
1212
  });
667
1213
 
1214
+ // src/core/navigators/filters/eloDistance.ts
1215
+ var eloDistance_exports = {};
1216
+ __export(eloDistance_exports, {
1217
+ DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1218
+ DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1219
+ DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1220
+ createEloDistanceFilter: () => createEloDistanceFilter
1221
+ });
1222
+ function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1223
+ const normalizedDistance = distance / halfLife;
1224
+ const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1225
+ return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1226
+ }
1227
+ function createEloDistanceFilter(config) {
1228
+ const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1229
+ const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1230
+ const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1231
+ return {
1232
+ name: "ELO Distance Filter",
1233
+ async transform(cards, context) {
1234
+ const { course, userElo } = context;
1235
+ const cardIds = cards.map((c) => c.cardId);
1236
+ const cardElos = await course.getCardEloData(cardIds);
1237
+ return cards.map((card, i) => {
1238
+ const cardElo = cardElos[i]?.global?.score ?? 1e3;
1239
+ const distance = Math.abs(cardElo - userElo);
1240
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1241
+ const newScore = card.score * multiplier;
1242
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1243
+ return {
1244
+ ...card,
1245
+ score: newScore,
1246
+ provenance: [
1247
+ ...card.provenance,
1248
+ {
1249
+ strategy: "eloDistance",
1250
+ strategyName: "ELO Distance Filter",
1251
+ strategyId: "ELO_DISTANCE_FILTER",
1252
+ action,
1253
+ score: newScore,
1254
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1255
+ }
1256
+ ]
1257
+ };
1258
+ });
1259
+ }
1260
+ };
1261
+ }
1262
+ var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1263
+ var init_eloDistance = __esm({
1264
+ "src/core/navigators/filters/eloDistance.ts"() {
1265
+ "use strict";
1266
+ DEFAULT_HALF_LIFE = 200;
1267
+ DEFAULT_MIN_MULTIPLIER = 0.3;
1268
+ DEFAULT_MAX_MULTIPLIER = 1;
1269
+ }
1270
+ });
1271
+
1272
+ // src/core/navigators/filters/userTagPreference.ts
1273
+ var userTagPreference_exports = {};
1274
+ __export(userTagPreference_exports, {
1275
+ default: () => UserTagPreferenceFilter
1276
+ });
1277
+ var UserTagPreferenceFilter;
1278
+ var init_userTagPreference = __esm({
1279
+ "src/core/navigators/filters/userTagPreference.ts"() {
1280
+ "use strict";
1281
+ init_navigators();
1282
+ UserTagPreferenceFilter = class extends ContentNavigator {
1283
+ _strategyData;
1284
+ /** Human-readable name for CardFilter interface */
1285
+ name;
1286
+ constructor(user, course, strategyData) {
1287
+ super(user, course, strategyData);
1288
+ this._strategyData = strategyData;
1289
+ this.name = strategyData.name || "User Tag Preferences";
1290
+ }
1291
+ /**
1292
+ * Compute multiplier for a card based on its tags and user preferences.
1293
+ * Returns the maximum multiplier among all matching tags, or 1.0 if no matches.
1294
+ */
1295
+ computeMultiplier(cardTags, boostMap) {
1296
+ const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== void 0);
1297
+ if (multipliers.length === 0) {
1298
+ return 1;
1299
+ }
1300
+ return Math.max(...multipliers);
1301
+ }
1302
+ /**
1303
+ * Build human-readable reason for the filter's decision.
1304
+ */
1305
+ buildReason(cardTags, boostMap, multiplier) {
1306
+ const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);
1307
+ if (multiplier === 0) {
1308
+ return `Excluded by user preference: ${matchingTags.join(", ")} (${multiplier}x)`;
1309
+ }
1310
+ if (multiplier < 1) {
1311
+ return `Penalized by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1312
+ }
1313
+ if (multiplier > 1) {
1314
+ return `Boosted by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1315
+ }
1316
+ return "No matching user preferences";
1317
+ }
1318
+ /**
1319
+ * CardFilter.transform implementation.
1320
+ *
1321
+ * Apply user tag preferences:
1322
+ * 1. Read preferences from strategy state
1323
+ * 2. If no preferences, pass through unchanged
1324
+ * 3. For each card:
1325
+ * - Look up tag in boost record
1326
+ * - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)
1327
+ * - If multiple tags match: use max multiplier
1328
+ * - Append provenance with clear reason
1329
+ */
1330
+ async transform(cards, _context) {
1331
+ const prefs = await this.getStrategyState();
1332
+ if (!prefs || Object.keys(prefs.boost).length === 0) {
1333
+ return cards.map((card) => ({
1334
+ ...card,
1335
+ provenance: [
1336
+ ...card.provenance,
1337
+ {
1338
+ strategy: "userTagPreference",
1339
+ strategyName: this.strategyName || this.name,
1340
+ strategyId: this.strategyId || this._strategyData._id,
1341
+ action: "passed",
1342
+ score: card.score,
1343
+ reason: "No user tag preferences configured"
1344
+ }
1345
+ ]
1346
+ }));
1347
+ }
1348
+ const adjusted = await Promise.all(
1349
+ cards.map(async (card) => {
1350
+ const cardTags = card.tags ?? [];
1351
+ const multiplier = this.computeMultiplier(cardTags, prefs.boost);
1352
+ const finalScore = Math.min(1, card.score * multiplier);
1353
+ let action;
1354
+ if (multiplier === 0 || multiplier < 1) {
1355
+ action = "penalized";
1356
+ } else if (multiplier > 1) {
1357
+ action = "boosted";
1358
+ } else {
1359
+ action = "passed";
1360
+ }
1361
+ return {
1362
+ ...card,
1363
+ score: finalScore,
1364
+ provenance: [
1365
+ ...card.provenance,
1366
+ {
1367
+ strategy: "userTagPreference",
1368
+ strategyName: this.strategyName || this.name,
1369
+ strategyId: this.strategyId || this._strategyData._id,
1370
+ action,
1371
+ score: finalScore,
1372
+ reason: this.buildReason(cardTags, prefs.boost, multiplier)
1373
+ }
1374
+ ]
1375
+ };
1376
+ })
1377
+ );
1378
+ return adjusted;
1379
+ }
1380
+ /**
1381
+ * Legacy getWeightedCards - throws as filters should not be used as generators.
1382
+ */
1383
+ async getWeightedCards(_limit) {
1384
+ throw new Error(
1385
+ "UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1386
+ );
1387
+ }
1388
+ // Legacy methods - stub implementations since filters don't generate cards
1389
+ async getNewCards(_n) {
1390
+ return [];
1391
+ }
1392
+ async getPendingReviews() {
1393
+ return [];
1394
+ }
1395
+ };
1396
+ }
1397
+ });
1398
+
1399
+ // src/core/navigators/filters/index.ts
1400
+ var filters_exports = {};
1401
+ __export(filters_exports, {
1402
+ UserTagPreferenceFilter: () => UserTagPreferenceFilter,
1403
+ createEloDistanceFilter: () => createEloDistanceFilter
1404
+ });
1405
+ var init_filters = __esm({
1406
+ "src/core/navigators/filters/index.ts"() {
1407
+ "use strict";
1408
+ init_eloDistance();
1409
+ init_userTagPreference();
1410
+ }
1411
+ });
1412
+
1413
+ // src/core/navigators/filters/types.ts
1414
+ var types_exports = {};
1415
+ var init_types = __esm({
1416
+ "src/core/navigators/filters/types.ts"() {
1417
+ "use strict";
1418
+ }
1419
+ });
1420
+
1421
+ // src/core/navigators/generators/index.ts
1422
+ var generators_exports = {};
1423
+ var init_generators = __esm({
1424
+ "src/core/navigators/generators/index.ts"() {
1425
+ "use strict";
1426
+ }
1427
+ });
1428
+
1429
+ // src/core/navigators/generators/types.ts
1430
+ var types_exports2 = {};
1431
+ var init_types2 = __esm({
1432
+ "src/core/navigators/generators/types.ts"() {
1433
+ "use strict";
1434
+ }
1435
+ });
1436
+
668
1437
  // src/core/navigators/hardcodedOrder.ts
669
1438
  var hardcodedOrder_exports = {};
670
1439
  __export(hardcodedOrder_exports, {
@@ -677,13 +1446,12 @@ var init_hardcodedOrder = __esm({
677
1446
  init_navigators();
678
1447
  init_logger();
679
1448
  HardcodedOrderNavigator = class extends ContentNavigator {
1449
+ /** Human-readable name for CardGenerator interface */
1450
+ name;
680
1451
  orderedCardIds = [];
681
- user;
682
- course;
683
1452
  constructor(user, course, strategyData) {
684
- super();
685
- this.user = user;
686
- this.course = course;
1453
+ super(user, course, strategyData);
1454
+ this.name = strategyData.name || "Hardcoded Order";
687
1455
  if (strategyData.serializedData) {
688
1456
  try {
689
1457
  this.orderedCardIds = JSON.parse(strategyData.serializedData);
@@ -708,32 +1476,806 @@ var init_hardcodedOrder = __esm({
708
1476
  }
709
1477
  async getNewCards(limit = 99) {
710
1478
  const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
711
- const newCardIds = this.orderedCardIds.filter(
712
- (cardId) => !activeCardIds.includes(cardId)
713
- );
1479
+ const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
714
1480
  const cardsToReturn = newCardIds.slice(0, limit);
715
1481
  return cardsToReturn.map((cardId) => {
716
1482
  return {
717
- cardID: cardId,
718
- courseID: this.course.getCourseID(),
719
- contentSourceType: "course",
720
- contentSourceID: this.course.getCourseID(),
721
- status: "new"
1483
+ cardID: cardId,
1484
+ courseID: this.course.getCourseID(),
1485
+ contentSourceType: "course",
1486
+ contentSourceID: this.course.getCourseID(),
1487
+ status: "new"
1488
+ };
1489
+ });
1490
+ }
1491
+ /**
1492
+ * Get cards in hardcoded order with scores based on position.
1493
+ *
1494
+ * Earlier cards in the sequence get higher scores.
1495
+ * Score formula: 1.0 - (position / totalCards) * 0.5
1496
+ * This ensures scores range from 1.0 (first card) to 0.5+ (last card).
1497
+ *
1498
+ * This method supports both the legacy signature (limit only) and the
1499
+ * CardGenerator interface signature (limit, context).
1500
+ *
1501
+ * @param limit - Maximum number of cards to return
1502
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1503
+ */
1504
+ async getWeightedCards(limit, _context) {
1505
+ const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
1506
+ const reviews = await this.getPendingReviews();
1507
+ const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
1508
+ const totalCards = newCardIds.length;
1509
+ const scoredNew = newCardIds.slice(0, limit).map((cardId, index) => {
1510
+ const position = index + 1;
1511
+ const score = Math.max(0.5, 1 - index / totalCards * 0.5);
1512
+ return {
1513
+ cardId,
1514
+ courseId: this.course.getCourseID(),
1515
+ score,
1516
+ provenance: [
1517
+ {
1518
+ strategy: "hardcodedOrder",
1519
+ strategyName: this.strategyName || this.name,
1520
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1521
+ action: "generated",
1522
+ score,
1523
+ reason: `Position ${position} of ${totalCards} in fixed sequence, new card`
1524
+ }
1525
+ ]
1526
+ };
1527
+ });
1528
+ const scoredReviews = reviews.map((r) => ({
1529
+ cardId: r.cardID,
1530
+ courseId: r.courseID,
1531
+ score: 1,
1532
+ provenance: [
1533
+ {
1534
+ strategy: "hardcodedOrder",
1535
+ strategyName: this.strategyName || this.name,
1536
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1537
+ action: "generated",
1538
+ score: 1,
1539
+ reason: "Scheduled review, highest priority"
1540
+ }
1541
+ ]
1542
+ }));
1543
+ const all = [...scoredReviews, ...scoredNew];
1544
+ all.sort((a, b) => b.score - a.score);
1545
+ return all.slice(0, limit);
1546
+ }
1547
+ };
1548
+ }
1549
+ });
1550
+
1551
+ // src/core/navigators/hierarchyDefinition.ts
1552
+ var hierarchyDefinition_exports = {};
1553
+ __export(hierarchyDefinition_exports, {
1554
+ default: () => HierarchyDefinitionNavigator
1555
+ });
1556
+ import { toCourseElo as toCourseElo4 } from "@vue-skuilder/common";
1557
+ var DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1558
+ var init_hierarchyDefinition = __esm({
1559
+ "src/core/navigators/hierarchyDefinition.ts"() {
1560
+ "use strict";
1561
+ init_navigators();
1562
+ DEFAULT_MIN_COUNT = 3;
1563
+ HierarchyDefinitionNavigator = class extends ContentNavigator {
1564
+ config;
1565
+ _strategyData;
1566
+ /** Human-readable name for CardFilter interface */
1567
+ name;
1568
+ constructor(user, course, _strategyData) {
1569
+ super(user, course, _strategyData);
1570
+ this._strategyData = _strategyData;
1571
+ this.config = this.parseConfig(_strategyData.serializedData);
1572
+ this.name = _strategyData.name || "Hierarchy Definition";
1573
+ }
1574
+ parseConfig(serializedData) {
1575
+ try {
1576
+ const parsed = JSON.parse(serializedData);
1577
+ return {
1578
+ prerequisites: parsed.prerequisites || {}
1579
+ };
1580
+ } catch {
1581
+ return {
1582
+ prerequisites: {}
1583
+ };
1584
+ }
1585
+ }
1586
+ /**
1587
+ * Check if a specific prerequisite is satisfied
1588
+ */
1589
+ isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1590
+ if (!userTagElo) return false;
1591
+ const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1592
+ if (userTagElo.count < minCount) return false;
1593
+ if (prereq.masteryThreshold?.minElo !== void 0) {
1594
+ return userTagElo.score >= prereq.masteryThreshold.minElo;
1595
+ } else {
1596
+ return userTagElo.score >= userGlobalElo;
1597
+ }
1598
+ }
1599
+ /**
1600
+ * Get the set of tags the user has mastered.
1601
+ * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1602
+ */
1603
+ async getMasteredTags(context) {
1604
+ const mastered = /* @__PURE__ */ new Set();
1605
+ try {
1606
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1607
+ const userElo = toCourseElo4(courseReg.elo);
1608
+ for (const prereqs of Object.values(this.config.prerequisites)) {
1609
+ for (const prereq of prereqs) {
1610
+ const tagElo = userElo.tags[prereq.tag];
1611
+ if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1612
+ mastered.add(prereq.tag);
1613
+ }
1614
+ }
1615
+ }
1616
+ } catch {
1617
+ }
1618
+ return mastered;
1619
+ }
1620
+ /**
1621
+ * Get the set of tags that are unlocked (prerequisites met)
1622
+ */
1623
+ getUnlockedTags(masteredTags) {
1624
+ const unlocked = /* @__PURE__ */ new Set();
1625
+ for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1626
+ const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1627
+ if (allPrereqsMet) {
1628
+ unlocked.add(tagId);
1629
+ }
1630
+ }
1631
+ return unlocked;
1632
+ }
1633
+ /**
1634
+ * Check if a tag has prerequisites defined in config
1635
+ */
1636
+ hasPrerequisites(tagId) {
1637
+ return tagId in this.config.prerequisites;
1638
+ }
1639
+ /**
1640
+ * Check if a card is unlocked and generate reason.
1641
+ */
1642
+ async checkCardUnlock(card, course, unlockedTags, masteredTags) {
1643
+ try {
1644
+ const cardTags = card.tags ?? [];
1645
+ const lockedTags = cardTags.filter(
1646
+ (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1647
+ );
1648
+ if (lockedTags.length === 0) {
1649
+ const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1650
+ return {
1651
+ isUnlocked: true,
1652
+ reason: `Prerequisites met, tags: ${tagList}`
1653
+ };
1654
+ }
1655
+ const missingPrereqs = lockedTags.flatMap((tag) => {
1656
+ const prereqs = this.config.prerequisites[tag] || [];
1657
+ return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1658
+ });
1659
+ return {
1660
+ isUnlocked: false,
1661
+ reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1662
+ };
1663
+ } catch {
1664
+ return {
1665
+ isUnlocked: true,
1666
+ reason: "Prerequisites check skipped (tag lookup failed)"
1667
+ };
1668
+ }
1669
+ }
1670
+ /**
1671
+ * CardFilter.transform implementation.
1672
+ *
1673
+ * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1674
+ */
1675
+ async transform(cards, context) {
1676
+ const masteredTags = await this.getMasteredTags(context);
1677
+ const unlockedTags = this.getUnlockedTags(masteredTags);
1678
+ const gated = [];
1679
+ for (const card of cards) {
1680
+ const { isUnlocked, reason } = await this.checkCardUnlock(
1681
+ card,
1682
+ context.course,
1683
+ unlockedTags,
1684
+ masteredTags
1685
+ );
1686
+ const finalScore = isUnlocked ? card.score : 0;
1687
+ const action = isUnlocked ? "passed" : "penalized";
1688
+ gated.push({
1689
+ ...card,
1690
+ score: finalScore,
1691
+ provenance: [
1692
+ ...card.provenance,
1693
+ {
1694
+ strategy: "hierarchyDefinition",
1695
+ strategyName: this.strategyName || this.name,
1696
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1697
+ action,
1698
+ score: finalScore,
1699
+ reason
1700
+ }
1701
+ ]
1702
+ });
1703
+ }
1704
+ return gated;
1705
+ }
1706
+ /**
1707
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1708
+ *
1709
+ * Use transform() via Pipeline instead.
1710
+ */
1711
+ async getWeightedCards(_limit) {
1712
+ throw new Error(
1713
+ "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1714
+ );
1715
+ }
1716
+ // Legacy methods - stub implementations since filters don't generate cards
1717
+ async getNewCards(_n) {
1718
+ return [];
1719
+ }
1720
+ async getPendingReviews() {
1721
+ return [];
1722
+ }
1723
+ };
1724
+ }
1725
+ });
1726
+
1727
+ // src/core/navigators/inferredPreference.ts
1728
+ var inferredPreference_exports = {};
1729
+ __export(inferredPreference_exports, {
1730
+ INFERRED_PREFERENCE_NAVIGATOR_STUB: () => INFERRED_PREFERENCE_NAVIGATOR_STUB
1731
+ });
1732
+ var INFERRED_PREFERENCE_NAVIGATOR_STUB;
1733
+ var init_inferredPreference = __esm({
1734
+ "src/core/navigators/inferredPreference.ts"() {
1735
+ "use strict";
1736
+ INFERRED_PREFERENCE_NAVIGATOR_STUB = true;
1737
+ }
1738
+ });
1739
+
1740
+ // src/core/navigators/interferenceMitigator.ts
1741
+ var interferenceMitigator_exports = {};
1742
+ __export(interferenceMitigator_exports, {
1743
+ default: () => InterferenceMitigatorNavigator
1744
+ });
1745
+ import { toCourseElo as toCourseElo5 } from "@vue-skuilder/common";
1746
+ var DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1747
+ var init_interferenceMitigator = __esm({
1748
+ "src/core/navigators/interferenceMitigator.ts"() {
1749
+ "use strict";
1750
+ init_navigators();
1751
+ DEFAULT_MIN_COUNT2 = 10;
1752
+ DEFAULT_MIN_ELAPSED_DAYS = 3;
1753
+ DEFAULT_INTERFERENCE_DECAY = 0.8;
1754
+ InterferenceMitigatorNavigator = class extends ContentNavigator {
1755
+ config;
1756
+ _strategyData;
1757
+ /** Human-readable name for CardFilter interface */
1758
+ name;
1759
+ /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1760
+ interferenceMap;
1761
+ constructor(user, course, _strategyData) {
1762
+ super(user, course, _strategyData);
1763
+ this._strategyData = _strategyData;
1764
+ this.config = this.parseConfig(_strategyData.serializedData);
1765
+ this.interferenceMap = this.buildInterferenceMap();
1766
+ this.name = _strategyData.name || "Interference Mitigator";
1767
+ }
1768
+ parseConfig(serializedData) {
1769
+ try {
1770
+ const parsed = JSON.parse(serializedData);
1771
+ let sets = parsed.interferenceSets || [];
1772
+ if (sets.length > 0 && Array.isArray(sets[0])) {
1773
+ sets = sets.map((tags) => ({ tags }));
1774
+ }
1775
+ return {
1776
+ interferenceSets: sets,
1777
+ maturityThreshold: {
1778
+ minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1779
+ minElo: parsed.maturityThreshold?.minElo,
1780
+ minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1781
+ },
1782
+ defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1783
+ };
1784
+ } catch {
1785
+ return {
1786
+ interferenceSets: [],
1787
+ maturityThreshold: {
1788
+ minCount: DEFAULT_MIN_COUNT2,
1789
+ minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1790
+ },
1791
+ defaultDecay: DEFAULT_INTERFERENCE_DECAY
1792
+ };
1793
+ }
1794
+ }
1795
+ /**
1796
+ * Build a map from each tag to its interference partners with decay coefficients.
1797
+ * If tags A, B, C are in an interference group with decay 0.8, then:
1798
+ * - A interferes with B (decay 0.8) and C (decay 0.8)
1799
+ * - B interferes with A (decay 0.8) and C (decay 0.8)
1800
+ * - etc.
1801
+ */
1802
+ buildInterferenceMap() {
1803
+ const map = /* @__PURE__ */ new Map();
1804
+ for (const group of this.config.interferenceSets) {
1805
+ const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
1806
+ for (const tag of group.tags) {
1807
+ if (!map.has(tag)) {
1808
+ map.set(tag, []);
1809
+ }
1810
+ const partners = map.get(tag);
1811
+ for (const other of group.tags) {
1812
+ if (other !== tag) {
1813
+ const existing = partners.find((p) => p.partner === other);
1814
+ if (existing) {
1815
+ existing.decay = Math.max(existing.decay, decay);
1816
+ } else {
1817
+ partners.push({ partner: other, decay });
1818
+ }
1819
+ }
1820
+ }
1821
+ }
1822
+ }
1823
+ return map;
1824
+ }
1825
+ /**
1826
+ * Get the set of tags that are currently immature for this user.
1827
+ * A tag is immature if the user has interacted with it but hasn't
1828
+ * reached the maturity threshold.
1829
+ */
1830
+ async getImmatureTags(context) {
1831
+ const immature = /* @__PURE__ */ new Set();
1832
+ try {
1833
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1834
+ const userElo = toCourseElo5(courseReg.elo);
1835
+ const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
1836
+ const minElo = this.config.maturityThreshold?.minElo;
1837
+ const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
1838
+ const minCountForElapsed = minElapsedDays * 2;
1839
+ for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
1840
+ if (tagElo.count === 0) continue;
1841
+ const belowCount = tagElo.count < minCount;
1842
+ const belowElo = minElo !== void 0 && tagElo.score < minElo;
1843
+ const belowElapsed = tagElo.count < minCountForElapsed;
1844
+ if (belowCount || belowElo || belowElapsed) {
1845
+ immature.add(tagId);
1846
+ }
1847
+ }
1848
+ } catch {
1849
+ }
1850
+ return immature;
1851
+ }
1852
+ /**
1853
+ * Get all tags that interfere with any immature tag, along with their decay coefficients.
1854
+ * These are the tags we want to avoid introducing.
1855
+ */
1856
+ getTagsToAvoid(immatureTags) {
1857
+ const avoid = /* @__PURE__ */ new Map();
1858
+ for (const immatureTag of immatureTags) {
1859
+ const partners = this.interferenceMap.get(immatureTag);
1860
+ if (partners) {
1861
+ for (const { partner, decay } of partners) {
1862
+ if (!immatureTags.has(partner)) {
1863
+ const existing = avoid.get(partner) ?? 0;
1864
+ avoid.set(partner, Math.max(existing, decay));
1865
+ }
1866
+ }
1867
+ }
1868
+ }
1869
+ return avoid;
1870
+ }
1871
+ /**
1872
+ * Compute interference score reduction for a card.
1873
+ * Returns: { multiplier, interfering tags, reason }
1874
+ */
1875
+ computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
1876
+ if (tagsToAvoid.size === 0) {
1877
+ return {
1878
+ multiplier: 1,
1879
+ interferingTags: [],
1880
+ reason: "No interference detected"
1881
+ };
1882
+ }
1883
+ let multiplier = 1;
1884
+ const interferingTags = [];
1885
+ for (const tag of cardTags) {
1886
+ const decay = tagsToAvoid.get(tag);
1887
+ if (decay !== void 0) {
1888
+ interferingTags.push(tag);
1889
+ multiplier *= 1 - decay;
1890
+ }
1891
+ }
1892
+ if (interferingTags.length === 0) {
1893
+ return {
1894
+ multiplier: 1,
1895
+ interferingTags: [],
1896
+ reason: "No interference detected"
1897
+ };
1898
+ }
1899
+ const causingTags = /* @__PURE__ */ new Set();
1900
+ for (const tag of interferingTags) {
1901
+ for (const immatureTag of immatureTags) {
1902
+ const partners = this.interferenceMap.get(immatureTag);
1903
+ if (partners?.some((p) => p.partner === tag)) {
1904
+ causingTags.add(immatureTag);
1905
+ }
1906
+ }
1907
+ }
1908
+ const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
1909
+ return { multiplier, interferingTags, reason };
1910
+ }
1911
+ /**
1912
+ * CardFilter.transform implementation.
1913
+ *
1914
+ * Apply interference-aware scoring. Cards with tags that interfere with
1915
+ * immature learnings get reduced scores.
1916
+ */
1917
+ async transform(cards, context) {
1918
+ const immatureTags = await this.getImmatureTags(context);
1919
+ const tagsToAvoid = this.getTagsToAvoid(immatureTags);
1920
+ const adjusted = [];
1921
+ for (const card of cards) {
1922
+ const cardTags = card.tags ?? [];
1923
+ const { multiplier, reason } = this.computeInterferenceEffect(
1924
+ cardTags,
1925
+ tagsToAvoid,
1926
+ immatureTags
1927
+ );
1928
+ const finalScore = card.score * multiplier;
1929
+ const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
1930
+ adjusted.push({
1931
+ ...card,
1932
+ score: finalScore,
1933
+ provenance: [
1934
+ ...card.provenance,
1935
+ {
1936
+ strategy: "interferenceMitigator",
1937
+ strategyName: this.strategyName || this.name,
1938
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
1939
+ action,
1940
+ score: finalScore,
1941
+ reason
1942
+ }
1943
+ ]
1944
+ });
1945
+ }
1946
+ return adjusted;
1947
+ }
1948
+ /**
1949
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1950
+ *
1951
+ * Use transform() via Pipeline instead.
1952
+ */
1953
+ async getWeightedCards(_limit) {
1954
+ throw new Error(
1955
+ "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1956
+ );
1957
+ }
1958
+ // Legacy methods - stub implementations since filters don't generate cards
1959
+ async getNewCards(_n) {
1960
+ return [];
1961
+ }
1962
+ async getPendingReviews() {
1963
+ return [];
1964
+ }
1965
+ };
1966
+ }
1967
+ });
1968
+
1969
+ // src/core/navigators/relativePriority.ts
1970
+ var relativePriority_exports = {};
1971
+ __export(relativePriority_exports, {
1972
+ default: () => RelativePriorityNavigator
1973
+ });
1974
+ var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
1975
+ var init_relativePriority = __esm({
1976
+ "src/core/navigators/relativePriority.ts"() {
1977
+ "use strict";
1978
+ init_navigators();
1979
+ DEFAULT_PRIORITY = 0.5;
1980
+ DEFAULT_PRIORITY_INFLUENCE = 0.5;
1981
+ DEFAULT_COMBINE_MODE = "max";
1982
+ RelativePriorityNavigator = class extends ContentNavigator {
1983
+ config;
1984
+ _strategyData;
1985
+ /** Human-readable name for CardFilter interface */
1986
+ name;
1987
+ constructor(user, course, _strategyData) {
1988
+ super(user, course, _strategyData);
1989
+ this._strategyData = _strategyData;
1990
+ this.config = this.parseConfig(_strategyData.serializedData);
1991
+ this.name = _strategyData.name || "Relative Priority";
1992
+ }
1993
+ parseConfig(serializedData) {
1994
+ try {
1995
+ const parsed = JSON.parse(serializedData);
1996
+ return {
1997
+ tagPriorities: parsed.tagPriorities || {},
1998
+ defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
1999
+ combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
2000
+ priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
2001
+ };
2002
+ } catch {
2003
+ return {
2004
+ tagPriorities: {},
2005
+ defaultPriority: DEFAULT_PRIORITY,
2006
+ combineMode: DEFAULT_COMBINE_MODE,
2007
+ priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
2008
+ };
2009
+ }
2010
+ }
2011
+ /**
2012
+ * Look up the priority for a tag.
2013
+ */
2014
+ getTagPriority(tagId) {
2015
+ return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
2016
+ }
2017
+ /**
2018
+ * Compute combined priority for a card based on its tags.
2019
+ */
2020
+ computeCardPriority(cardTags) {
2021
+ if (cardTags.length === 0) {
2022
+ return this.config.defaultPriority ?? DEFAULT_PRIORITY;
2023
+ }
2024
+ const priorities = cardTags.map((tag) => this.getTagPriority(tag));
2025
+ switch (this.config.combineMode) {
2026
+ case "max":
2027
+ return Math.max(...priorities);
2028
+ case "min":
2029
+ return Math.min(...priorities);
2030
+ case "average":
2031
+ return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
2032
+ default:
2033
+ return Math.max(...priorities);
2034
+ }
2035
+ }
2036
+ /**
2037
+ * Compute boost factor based on priority.
2038
+ *
2039
+ * The formula: 1 + (priority - 0.5) * priorityInfluence
2040
+ *
2041
+ * This creates a multiplier centered around 1.0:
2042
+ * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
2043
+ * - Priority 0.5 with any influence → 1.00 (neutral)
2044
+ * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
2045
+ */
2046
+ computeBoostFactor(priority) {
2047
+ const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
2048
+ return 1 + (priority - 0.5) * influence;
2049
+ }
2050
+ /**
2051
+ * Build human-readable reason for priority adjustment.
2052
+ */
2053
+ buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
2054
+ if (cardTags.length === 0) {
2055
+ return `No tags, neutral priority (${priority.toFixed(2)})`;
2056
+ }
2057
+ const tagList = cardTags.slice(0, 3).join(", ");
2058
+ const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
2059
+ if (boostFactor === 1) {
2060
+ return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
2061
+ } else if (boostFactor > 1) {
2062
+ return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
2063
+ } else {
2064
+ return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
2065
+ }
2066
+ }
2067
+ /**
2068
+ * CardFilter.transform implementation.
2069
+ *
2070
+ * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
2071
+ * cards with low-priority tags get reduced scores.
2072
+ */
2073
+ async transform(cards, _context) {
2074
+ const adjusted = await Promise.all(
2075
+ cards.map(async (card) => {
2076
+ const cardTags = card.tags ?? [];
2077
+ const priority = this.computeCardPriority(cardTags);
2078
+ const boostFactor = this.computeBoostFactor(priority);
2079
+ const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
2080
+ const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
2081
+ const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
2082
+ return {
2083
+ ...card,
2084
+ score: finalScore,
2085
+ provenance: [
2086
+ ...card.provenance,
2087
+ {
2088
+ strategy: "relativePriority",
2089
+ strategyName: this.strategyName || this.name,
2090
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
2091
+ action,
2092
+ score: finalScore,
2093
+ reason
2094
+ }
2095
+ ]
2096
+ };
2097
+ })
2098
+ );
2099
+ return adjusted;
2100
+ }
2101
+ /**
2102
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
2103
+ *
2104
+ * Use transform() via Pipeline instead.
2105
+ */
2106
+ async getWeightedCards(_limit) {
2107
+ throw new Error(
2108
+ "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
2109
+ );
2110
+ }
2111
+ // Legacy methods - stub implementations since filters don't generate cards
2112
+ async getNewCards(_n) {
2113
+ return [];
2114
+ }
2115
+ async getPendingReviews() {
2116
+ return [];
2117
+ }
2118
+ };
2119
+ }
2120
+ });
2121
+
2122
+ // src/core/navigators/srs.ts
2123
+ var srs_exports = {};
2124
+ __export(srs_exports, {
2125
+ default: () => SRSNavigator
2126
+ });
2127
+ import moment from "moment";
2128
+ var SRSNavigator;
2129
+ var init_srs = __esm({
2130
+ "src/core/navigators/srs.ts"() {
2131
+ "use strict";
2132
+ init_navigators();
2133
+ SRSNavigator = class extends ContentNavigator {
2134
+ /** Human-readable name for CardGenerator interface */
2135
+ name;
2136
+ constructor(user, course, strategyData) {
2137
+ super(user, course, strategyData);
2138
+ this.name = strategyData?.name || "SRS";
2139
+ }
2140
+ /**
2141
+ * Get review cards scored by urgency.
2142
+ *
2143
+ * Score formula combines:
2144
+ * - Relative overdueness: hoursOverdue / intervalHours
2145
+ * - Interval recency: exponential decay favoring shorter intervals
2146
+ *
2147
+ * Cards not yet due are excluded (not scored as 0).
2148
+ *
2149
+ * This method supports both the legacy signature (limit only) and the
2150
+ * CardGenerator interface signature (limit, context).
2151
+ *
2152
+ * @param limit - Maximum number of cards to return
2153
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
2154
+ */
2155
+ async getWeightedCards(limit, _context) {
2156
+ if (!this.user || !this.course) {
2157
+ throw new Error("SRSNavigator requires user and course to be set");
2158
+ }
2159
+ const reviews = await this.user.getPendingReviews(this.course.getCourseID());
2160
+ const now = moment.utc();
2161
+ const dueReviews = reviews.filter((r) => now.isAfter(moment.utc(r.reviewTime)));
2162
+ const scored = dueReviews.map((review) => {
2163
+ const { score, reason } = this.computeUrgencyScore(review, now);
2164
+ return {
2165
+ cardId: review.cardId,
2166
+ courseId: review.courseId,
2167
+ score,
2168
+ provenance: [
2169
+ {
2170
+ strategy: "srs",
2171
+ strategyName: this.strategyName || this.name,
2172
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
2173
+ action: "generated",
2174
+ score,
2175
+ reason
2176
+ }
2177
+ ]
722
2178
  };
723
2179
  });
2180
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
2181
+ }
2182
+ /**
2183
+ * Compute urgency score for a review card.
2184
+ *
2185
+ * Two factors:
2186
+ * 1. Relative overdueness = hoursOverdue / intervalHours
2187
+ * - 2 days overdue on 3-day interval = 0.67 (urgent)
2188
+ * - 2 days overdue on 180-day interval = 0.01 (not urgent)
2189
+ *
2190
+ * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
2191
+ * - 24h interval → ~1.0 (very recent learning)
2192
+ * - 30 days (720h) → ~0.56
2193
+ * - 180 days → ~0.30
2194
+ *
2195
+ * Combined: base 0.5 + weighted average of factors * 0.45
2196
+ * Result range: approximately 0.5 to 0.95
2197
+ */
2198
+ computeUrgencyScore(review, now) {
2199
+ const scheduledAt = moment.utc(review.scheduledAt);
2200
+ const due = moment.utc(review.reviewTime);
2201
+ const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
2202
+ const hoursOverdue = now.diff(due, "hours");
2203
+ const relativeOverdue = hoursOverdue / intervalHours;
2204
+ const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
2205
+ const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
2206
+ const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
2207
+ const score = Math.min(0.95, 0.5 + urgency * 0.45);
2208
+ const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
2209
+ return { score, reason };
2210
+ }
2211
+ /**
2212
+ * Get pending reviews in legacy format.
2213
+ *
2214
+ * Returns all pending reviews for the course, enriched with session item fields.
2215
+ */
2216
+ async getPendingReviews() {
2217
+ if (!this.user || !this.course) {
2218
+ throw new Error("SRSNavigator requires user and course to be set");
2219
+ }
2220
+ const reviews = await this.user.getPendingReviews(this.course.getCourseID());
2221
+ return reviews.map((r) => ({
2222
+ ...r,
2223
+ contentSourceType: "course",
2224
+ contentSourceID: this.course.getCourseID(),
2225
+ cardID: r.cardId,
2226
+ courseID: r.courseId,
2227
+ qualifiedID: `${r.courseId}-${r.cardId}`,
2228
+ reviewID: r._id,
2229
+ status: "review"
2230
+ }));
2231
+ }
2232
+ /**
2233
+ * SRS does not generate new cards.
2234
+ * Use ELONavigator or another generator for new cards.
2235
+ */
2236
+ async getNewCards(_n) {
2237
+ return [];
724
2238
  }
725
2239
  };
726
2240
  }
727
2241
  });
728
2242
 
2243
+ // src/core/navigators/userGoal.ts
2244
+ var userGoal_exports = {};
2245
+ __export(userGoal_exports, {
2246
+ USER_GOAL_NAVIGATOR_STUB: () => USER_GOAL_NAVIGATOR_STUB
2247
+ });
2248
+ var USER_GOAL_NAVIGATOR_STUB;
2249
+ var init_userGoal = __esm({
2250
+ "src/core/navigators/userGoal.ts"() {
2251
+ "use strict";
2252
+ USER_GOAL_NAVIGATOR_STUB = true;
2253
+ }
2254
+ });
2255
+
729
2256
  // import("./**/*") in src/core/navigators/index.ts
730
2257
  var globImport;
731
2258
  var init_ = __esm({
732
2259
  'import("./**/*") in src/core/navigators/index.ts'() {
733
2260
  globImport = __glob({
2261
+ "./CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
2262
+ "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
2263
+ "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
734
2264
  "./elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
2265
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2266
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2267
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
2268
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
2269
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
2270
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
735
2271
  "./hardcodedOrder.ts": () => Promise.resolve().then(() => (init_hardcodedOrder(), hardcodedOrder_exports)),
736
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
2272
+ "./hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2273
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
2274
+ "./inferredPreference.ts": () => Promise.resolve().then(() => (init_inferredPreference(), inferredPreference_exports)),
2275
+ "./interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2276
+ "./relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2277
+ "./srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
2278
+ "./userGoal.ts": () => Promise.resolve().then(() => (init_userGoal(), userGoal_exports))
737
2279
  });
738
2280
  }
739
2281
  });
@@ -742,9 +2284,34 @@ var init_ = __esm({
742
2284
  var navigators_exports = {};
743
2285
  __export(navigators_exports, {
744
2286
  ContentNavigator: () => ContentNavigator,
745
- Navigators: () => Navigators
2287
+ NavigatorRole: () => NavigatorRole,
2288
+ NavigatorRoles: () => NavigatorRoles,
2289
+ Navigators: () => Navigators,
2290
+ getCardOrigin: () => getCardOrigin,
2291
+ isFilter: () => isFilter,
2292
+ isGenerator: () => isGenerator
746
2293
  });
747
- var Navigators, ContentNavigator;
2294
+ function getCardOrigin(card) {
2295
+ if (card.provenance.length === 0) {
2296
+ throw new Error("Card has no provenance - cannot determine origin");
2297
+ }
2298
+ const firstEntry = card.provenance[0];
2299
+ const reason = firstEntry.reason.toLowerCase();
2300
+ if (reason.includes("failed")) {
2301
+ return "failed";
2302
+ }
2303
+ if (reason.includes("review")) {
2304
+ return "review";
2305
+ }
2306
+ return "new";
2307
+ }
2308
+ function isGenerator(impl) {
2309
+ return NavigatorRoles[impl] === "generator" /* GENERATOR */;
2310
+ }
2311
+ function isFilter(impl) {
2312
+ return NavigatorRoles[impl] === "filter" /* FILTER */;
2313
+ }
2314
+ var Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
748
2315
  var init_navigators = __esm({
749
2316
  "src/core/navigators/index.ts"() {
750
2317
  "use strict";
@@ -752,14 +2319,103 @@ var init_navigators = __esm({
752
2319
  init_();
753
2320
  Navigators = /* @__PURE__ */ ((Navigators2) => {
754
2321
  Navigators2["ELO"] = "elo";
2322
+ Navigators2["SRS"] = "srs";
755
2323
  Navigators2["HARDCODED"] = "hardcodedOrder";
2324
+ Navigators2["HIERARCHY"] = "hierarchyDefinition";
2325
+ Navigators2["INTERFERENCE"] = "interferenceMitigator";
2326
+ Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
2327
+ Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
756
2328
  return Navigators2;
757
2329
  })(Navigators || {});
2330
+ NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
2331
+ NavigatorRole2["GENERATOR"] = "generator";
2332
+ NavigatorRole2["FILTER"] = "filter";
2333
+ return NavigatorRole2;
2334
+ })(NavigatorRole || {});
2335
+ NavigatorRoles = {
2336
+ ["elo" /* ELO */]: "generator" /* GENERATOR */,
2337
+ ["srs" /* SRS */]: "generator" /* GENERATOR */,
2338
+ ["hardcodedOrder" /* HARDCODED */]: "generator" /* GENERATOR */,
2339
+ ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
2340
+ ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
2341
+ ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
2342
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
2343
+ };
758
2344
  ContentNavigator = class {
2345
+ /** User interface for this navigation session */
2346
+ user;
2347
+ /** Course interface for this navigation session */
2348
+ course;
2349
+ /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
2350
+ strategyName;
2351
+ /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
2352
+ strategyId;
2353
+ /**
2354
+ * Constructor for standard navigators.
2355
+ * Call this from subclass constructors to initialize common fields.
2356
+ *
2357
+ * Note: CompositeGenerator doesn't use this pattern and should call super() without args.
2358
+ */
2359
+ constructor(user, course, strategyData) {
2360
+ if (user && course && strategyData) {
2361
+ this.user = user;
2362
+ this.course = course;
2363
+ this.strategyName = strategyData.name;
2364
+ this.strategyId = strategyData._id;
2365
+ }
2366
+ }
2367
+ // ============================================================================
2368
+ // STRATEGY STATE HELPERS
2369
+ // ============================================================================
2370
+ //
2371
+ // These methods allow strategies to persist their own state (user preferences,
2372
+ // learned patterns, temporal tracking) in the user database.
2373
+ //
2374
+ // ============================================================================
2375
+ /**
2376
+ * Unique key identifying this strategy for state storage.
2377
+ *
2378
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
2379
+ * Override in subclasses if multiple instances of the same strategy type
2380
+ * need separate state storage.
2381
+ */
2382
+ get strategyKey() {
2383
+ return this.constructor.name;
2384
+ }
2385
+ /**
2386
+ * Get this strategy's persisted state for the current course.
2387
+ *
2388
+ * @returns The strategy's data payload, or null if no state exists
2389
+ * @throws Error if user or course is not initialized
2390
+ */
2391
+ async getStrategyState() {
2392
+ if (!this.user || !this.course) {
2393
+ throw new Error(
2394
+ `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2395
+ );
2396
+ }
2397
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
2398
+ }
2399
+ /**
2400
+ * Persist this strategy's state for the current course.
2401
+ *
2402
+ * @param data - The strategy's data payload to store
2403
+ * @throws Error if user or course is not initialized
2404
+ */
2405
+ async putStrategyState(data) {
2406
+ if (!this.user || !this.course) {
2407
+ throw new Error(
2408
+ `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2409
+ );
2410
+ }
2411
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
2412
+ }
759
2413
  /**
2414
+ * Factory method to create navigator instances dynamically.
760
2415
  *
761
- * @param user
762
- * @param strategyData
2416
+ * @param user - User interface
2417
+ * @param course - Course interface
2418
+ * @param strategyData - Strategy configuration document
763
2419
  * @returns the runtime object used to steer a study session.
764
2420
  */
765
2421
  static async create(user, course, strategyData) {
@@ -780,6 +2436,70 @@ var init_navigators = __esm({
780
2436
  }
781
2437
  return new NavigatorImpl(user, course, strategyData);
782
2438
  }
2439
+ /**
2440
+ * Get cards with suitability scores and provenance trails.
2441
+ *
2442
+ * **This is the PRIMARY API for navigation strategies.**
2443
+ *
2444
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
2445
+ * better candidates for presentation. Each card includes a provenance trail
2446
+ * documenting how strategies contributed to the final score.
2447
+ *
2448
+ * ## For Generators
2449
+ * Override this method to generate candidates and compute scores based on
2450
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
2451
+ * initial provenance entry with action='generated'.
2452
+ *
2453
+ * ## Default Implementation
2454
+ * The base class provides a backward-compatible default that:
2455
+ * 1. Calls legacy getNewCards() and getPendingReviews()
2456
+ * 2. Assigns score=1.0 to all cards
2457
+ * 3. Creates minimal provenance from legacy methods
2458
+ * 4. Returns combined results up to limit
2459
+ *
2460
+ * This allows existing strategies to work without modification while
2461
+ * new strategies can override with proper scoring and provenance.
2462
+ *
2463
+ * @param limit - Maximum cards to return
2464
+ * @returns Cards sorted by score descending, with provenance trails
2465
+ */
2466
+ async getWeightedCards(limit) {
2467
+ const newCards = await this.getNewCards(limit);
2468
+ const reviews = await this.getPendingReviews();
2469
+ const weighted = [
2470
+ ...newCards.map((c) => ({
2471
+ cardId: c.cardID,
2472
+ courseId: c.courseID,
2473
+ score: 1,
2474
+ provenance: [
2475
+ {
2476
+ strategy: "legacy",
2477
+ strategyName: this.strategyName || "Legacy API",
2478
+ strategyId: this.strategyId || "legacy-fallback",
2479
+ action: "generated",
2480
+ score: 1,
2481
+ reason: "Generated via legacy getNewCards(), new card"
2482
+ }
2483
+ ]
2484
+ })),
2485
+ ...reviews.map((r) => ({
2486
+ cardId: r.cardID,
2487
+ courseId: r.courseID,
2488
+ score: 1,
2489
+ provenance: [
2490
+ {
2491
+ strategy: "legacy",
2492
+ strategyName: this.strategyName || "Legacy API",
2493
+ strategyId: this.strategyId || "legacy-fallback",
2494
+ action: "generated",
2495
+ score: 1,
2496
+ reason: "Generated via legacy getPendingReviews(), review"
2497
+ }
2498
+ ]
2499
+ }))
2500
+ ];
2501
+ return weighted.slice(0, limit);
2502
+ }
783
2503
  };
784
2504
  }
785
2505
  });
@@ -789,7 +2509,7 @@ import {
789
2509
  EloToNumber,
790
2510
  Status,
791
2511
  blankCourseElo as blankCourseElo2,
792
- toCourseElo as toCourseElo2
2512
+ toCourseElo as toCourseElo6
793
2513
  } from "@vue-skuilder/common";
794
2514
  function randIntWeightedTowardZero(n) {
795
2515
  return Math.floor(Math.random() * Math.random() * Math.random() * n);
@@ -920,6 +2640,12 @@ var init_courseDB = __esm({
920
2640
  init_courseAPI();
921
2641
  init_courseLookupDB();
922
2642
  init_navigators();
2643
+ init_Pipeline();
2644
+ init_PipelineAssembler();
2645
+ init_CompositeGenerator();
2646
+ init_elo();
2647
+ init_srs();
2648
+ init_eloDistance();
923
2649
  CoursesDB = class {
924
2650
  _courseIDs;
925
2651
  constructor(courseIDs) {
@@ -1031,7 +2757,7 @@ var init_courseDB = __esm({
1031
2757
  docs.rows.forEach((r) => {
1032
2758
  if (isSuccessRow(r)) {
1033
2759
  if (r.doc && r.doc.elo) {
1034
- ret.push(toCourseElo2(r.doc.elo));
2760
+ ret.push(toCourseElo6(r.doc.elo));
1035
2761
  } else {
1036
2762
  logger.warn("no elo data for card: " + r.id);
1037
2763
  ret.push(blankCourseElo2());
@@ -1100,15 +2826,6 @@ var init_courseDB = __esm({
1100
2826
  ret[r.id] = r.doc.id_displayable_data;
1101
2827
  }
1102
2828
  });
1103
- await Promise.all(
1104
- cards.rows.map((r) => {
1105
- return async () => {
1106
- if (isSuccessRow(r)) {
1107
- ret[r.id] = r.doc.id_displayable_data;
1108
- }
1109
- };
1110
- })
1111
- );
1112
2829
  return ret;
1113
2830
  }
1114
2831
  async getCardsByELO(elo, cardLimit) {
@@ -1193,6 +2910,28 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1193
2910
  throw new Error(`Failed to find tags for card ${this.id}-${cardId}`);
1194
2911
  }
1195
2912
  }
2913
+ async getAppliedTagsBatch(cardIds) {
2914
+ if (cardIds.length === 0) {
2915
+ return /* @__PURE__ */ new Map();
2916
+ }
2917
+ const db = getCourseDB2(this.id);
2918
+ const result = await db.query("getTags", {
2919
+ keys: cardIds,
2920
+ include_docs: false
2921
+ });
2922
+ const tagsByCard = /* @__PURE__ */ new Map();
2923
+ for (const cardId of cardIds) {
2924
+ tagsByCard.set(cardId, []);
2925
+ }
2926
+ for (const row of result.rows) {
2927
+ const cardId = row.key;
2928
+ const tagName = row.value?.name;
2929
+ if (tagName && tagsByCard.has(cardId)) {
2930
+ tagsByCard.get(cardId).push(tagName);
2931
+ }
2932
+ }
2933
+ return tagsByCard;
2934
+ }
1196
2935
  async addTagToCard(cardId, tagId, updateELO) {
1197
2936
  return await addTagToCard(
1198
2937
  this.id,
@@ -1304,42 +3043,82 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1304
3043
  logger.debug(JSON.stringify(data));
1305
3044
  return Promise.resolve();
1306
3045
  }
1307
- async surfaceNavigationStrategy() {
3046
+ /**
3047
+ * Creates an instantiated navigator for this course.
3048
+ *
3049
+ * Handles multiple generators by wrapping them in CompositeGenerator.
3050
+ * This is the preferred method for getting a ready-to-use navigator.
3051
+ *
3052
+ * @param user - User database interface
3053
+ * @returns Instantiated ContentNavigator ready for use
3054
+ */
3055
+ async createNavigator(user) {
1308
3056
  try {
1309
- const config = await this.getCourseConfig();
1310
- if (config.defaultNavigationStrategyId) {
1311
- try {
1312
- const strategy = await this.getNavigationStrategy(config.defaultNavigationStrategyId);
1313
- if (strategy) {
1314
- logger.debug(`Surfacing strategy ${strategy.name} from course config`);
1315
- return strategy;
1316
- }
1317
- } catch (e) {
1318
- logger.warn(
1319
- // @ts-expect-error tmp: defaultNavigationStrategyId property does not yet exist
1320
- `Failed to load strategy '${config.defaultNavigationStrategyId}' specified in course config. Falling back to ELO.`,
1321
- e
1322
- );
1323
- }
3057
+ const allStrategies = await this.getAllNavigationStrategies();
3058
+ if (allStrategies.length === 0) {
3059
+ logger.debug(
3060
+ "[courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])"
3061
+ );
3062
+ return this.createDefaultPipeline(user);
1324
3063
  }
1325
- } catch (e) {
1326
- logger.warn(
1327
- "Could not retrieve course config to determine navigation strategy. Falling back to ELO.",
1328
- e
3064
+ const assembler = new PipelineAssembler();
3065
+ const { pipeline, generatorStrategies, filterStrategies, warnings } = await assembler.assemble({
3066
+ strategies: allStrategies,
3067
+ user,
3068
+ course: this
3069
+ });
3070
+ for (const warning of warnings) {
3071
+ logger.warn(`[PipelineAssembler] ${warning}`);
3072
+ }
3073
+ if (!pipeline) {
3074
+ logger.debug("[courseDB] Pipeline assembly failed, using default pipeline");
3075
+ return this.createDefaultPipeline(user);
3076
+ }
3077
+ logger.debug(
3078
+ `[courseDB] Using assembled pipeline with ${generatorStrategies.length} generator(s) and ${filterStrategies.length} filter(s)`
1329
3079
  );
3080
+ return pipeline;
3081
+ } catch (e) {
3082
+ logger.error(`[courseDB] Error creating navigator: ${e}`);
3083
+ throw e;
1330
3084
  }
1331
- logger.warn(`Returning hard-coded default ELO navigator`);
1332
- const ret = {
1333
- _id: "NAVIGATION_STRATEGY-ELO",
3085
+ }
3086
+ makeDefaultEloStrategy() {
3087
+ return {
3088
+ _id: "NAVIGATION_STRATEGY-ELO-default",
1334
3089
  docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1335
- name: "ELO",
1336
- description: "ELO-based navigation strategy",
3090
+ name: "ELO (default)",
3091
+ description: "Default ELO-based navigation strategy for new cards",
1337
3092
  implementingClass: "elo" /* ELO */,
1338
3093
  course: this.id,
1339
3094
  serializedData: ""
1340
- // serde is a noop for ELO navigator.
1341
3095
  };
1342
- return Promise.resolve(ret);
3096
+ }
3097
+ makeDefaultSrsStrategy() {
3098
+ return {
3099
+ _id: "NAVIGATION_STRATEGY-SRS-default",
3100
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
3101
+ name: "SRS (default)",
3102
+ description: "Default SRS-based navigation strategy for reviews",
3103
+ implementingClass: "srs" /* SRS */,
3104
+ course: this.id,
3105
+ serializedData: ""
3106
+ };
3107
+ }
3108
+ /**
3109
+ * Creates the default navigation pipeline for courses with no configured strategies.
3110
+ *
3111
+ * Default: Pipeline(Composite(ELO, SRS), [eloDistanceFilter])
3112
+ * - ELO generator: scores new cards by skill proximity
3113
+ * - SRS generator: scores reviews by overdueness and interval recency
3114
+ * - ELO distance filter: penalizes cards far from user's current level
3115
+ */
3116
+ createDefaultPipeline(user) {
3117
+ const eloNavigator = new ELONavigator(user, this, this.makeDefaultEloStrategy());
3118
+ const srsNavigator = new SRSNavigator(user, this, this.makeDefaultSrsStrategy());
3119
+ const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
3120
+ const eloDistanceFilter = createEloDistanceFilter();
3121
+ return new Pipeline(compositeGenerator, [eloDistanceFilter], user, this);
1343
3122
  }
1344
3123
  ////////////////////////////////////
1345
3124
  // END NavigationStrategyManager implementation
@@ -1350,22 +3129,39 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1350
3129
  async getNewCards(limit = 99) {
1351
3130
  const u = await this._getCurrentUser();
1352
3131
  try {
1353
- const strategy = await this.surfaceNavigationStrategy();
1354
- const navigator = await ContentNavigator.create(u, this, strategy);
3132
+ const navigator = await this.createNavigator(u);
1355
3133
  return navigator.getNewCards(limit);
1356
3134
  } catch (e) {
1357
- logger.error(`[courseDB] Error surfacing a NavigationStrategy: ${e}`);
3135
+ logger.error(`[courseDB] Error in getNewCards: ${e}`);
1358
3136
  throw e;
1359
3137
  }
1360
3138
  }
1361
3139
  async getPendingReviews() {
1362
3140
  const u = await this._getCurrentUser();
1363
3141
  try {
1364
- const strategy = await this.surfaceNavigationStrategy();
1365
- const navigator = await ContentNavigator.create(u, this, strategy);
3142
+ const navigator = await this.createNavigator(u);
1366
3143
  return navigator.getPendingReviews();
1367
3144
  } catch (e) {
1368
- logger.error(`[courseDB] Error surfacing a NavigationStrategy: ${e}`);
3145
+ logger.error(`[courseDB] Error in getPendingReviews: ${e}`);
3146
+ throw e;
3147
+ }
3148
+ }
3149
+ /**
3150
+ * Get cards with suitability scores for presentation.
3151
+ *
3152
+ * This is the PRIMARY API for content sources going forward. Delegates to the
3153
+ * course's configured NavigationStrategy to get scored candidates.
3154
+ *
3155
+ * @param limit - Maximum number of cards to return
3156
+ * @returns Cards sorted by score descending
3157
+ */
3158
+ async getWeightedCards(limit) {
3159
+ const u = await this._getCurrentUser();
3160
+ try {
3161
+ const navigator = await this.createNavigator(u);
3162
+ return navigator.getWeightedCards(limit);
3163
+ } catch (e) {
3164
+ logger.error(`[courseDB] Error getting weighted cards: ${e}`);
1369
3165
  throw e;
1370
3166
  }
1371
3167
  }
@@ -1505,7 +3301,7 @@ ${above.rows.map((r) => ` ${r.id}-${r.key}
1505
3301
  });
1506
3302
 
1507
3303
  // src/impl/couch/classroomDB.ts
1508
- import moment from "moment";
3304
+ import moment2 from "moment";
1509
3305
  function getClassroomDB(classID, version) {
1510
3306
  const dbName = `classdb-${version}-${classID}`;
1511
3307
  logger.info(`Retrieving classroom db: ${dbName}`);
@@ -1617,9 +3413,9 @@ var init_classroomDB2 = __esm({
1617
3413
  }
1618
3414
  async getNewCards() {
1619
3415
  const activeCards = await this._user.getActiveCards();
1620
- const now = moment.utc();
3416
+ const now = moment2.utc();
1621
3417
  const assigned = await this.getAssignedContent();
1622
- const due = assigned.filter((c) => now.isAfter(moment.utc(c.activeOn, REVIEW_TIME_FORMAT)));
3418
+ const due = assigned.filter((c) => now.isAfter(moment2.utc(c.activeOn, REVIEW_TIME_FORMAT)));
1623
3419
  logger.info(`Due content: ${JSON.stringify(due)}`);
1624
3420
  let ret = [];
1625
3421
  for (let i = 0; i < due.length; i++) {
@@ -1656,6 +3452,52 @@ var init_classroomDB2 = __esm({
1656
3452
  }
1657
3453
  });
1658
3454
  }
3455
+ /**
3456
+ * Get cards with suitability scores for presentation.
3457
+ *
3458
+ * This implementation wraps the legacy getNewCards/getPendingReviews methods,
3459
+ * assigning score=1.0 to all cards. StudentClassroomDB does not currently
3460
+ * support pluggable navigation strategies.
3461
+ *
3462
+ * @param limit - Maximum number of cards to return
3463
+ * @returns Cards sorted by score descending (all scores = 1.0)
3464
+ */
3465
+ async getWeightedCards(limit) {
3466
+ const [newCards, reviews] = await Promise.all([this.getNewCards(), this.getPendingReviews()]);
3467
+ const weighted = [
3468
+ ...newCards.map((c) => ({
3469
+ cardId: c.cardID,
3470
+ courseId: c.courseID,
3471
+ score: 1,
3472
+ provenance: [
3473
+ {
3474
+ strategy: "classroom",
3475
+ strategyName: "Classroom",
3476
+ strategyId: "CLASSROOM",
3477
+ action: "generated",
3478
+ score: 1,
3479
+ reason: "Classroom legacy getNewCards(), new card"
3480
+ }
3481
+ ]
3482
+ })),
3483
+ ...reviews.map((r) => ({
3484
+ cardId: r.cardID,
3485
+ courseId: r.courseID,
3486
+ score: 1,
3487
+ provenance: [
3488
+ {
3489
+ strategy: "classroom",
3490
+ strategyName: "Classroom",
3491
+ strategyId: "CLASSROOM",
3492
+ action: "generated",
3493
+ score: 1,
3494
+ reason: "Classroom legacy getPendingReviews(), review"
3495
+ }
3496
+ ]
3497
+ }))
3498
+ ];
3499
+ return weighted.slice(0, limit);
3500
+ }
1659
3501
  };
1660
3502
  TeacherClassroomDB = class _TeacherClassroomDB extends ClassroomDBBase {
1661
3503
  _stuDb;
@@ -1712,8 +3554,8 @@ var init_classroomDB2 = __esm({
1712
3554
  type: "tag",
1713
3555
  _id: id,
1714
3556
  assignedBy: content.assignedBy,
1715
- assignedOn: moment.utc(),
1716
- activeOn: content.activeOn || moment.utc()
3557
+ assignedOn: moment2.utc(),
3558
+ activeOn: content.activeOn || moment2.utc()
1717
3559
  });
1718
3560
  } else {
1719
3561
  put = await this._db.put({
@@ -1721,8 +3563,8 @@ var init_classroomDB2 = __esm({
1721
3563
  type: "course",
1722
3564
  _id: id,
1723
3565
  assignedBy: content.assignedBy,
1724
- assignedOn: moment.utc(),
1725
- activeOn: content.activeOn || moment.utc()
3566
+ assignedOn: moment2.utc(),
3567
+ activeOn: content.activeOn || moment2.utc()
1726
3568
  });
1727
3569
  }
1728
3570
  if (put.ok) {
@@ -1741,7 +3583,215 @@ var init_classroomDB2 = __esm({
1741
3583
  }
1742
3584
  });
1743
3585
 
3586
+ // src/study/TagFilteredContentSource.ts
3587
+ import { hasActiveFilter } from "@vue-skuilder/common";
3588
+ var TagFilteredContentSource;
3589
+ var init_TagFilteredContentSource = __esm({
3590
+ "src/study/TagFilteredContentSource.ts"() {
3591
+ "use strict";
3592
+ init_courseDB();
3593
+ init_logger();
3594
+ TagFilteredContentSource = class {
3595
+ courseId;
3596
+ filter;
3597
+ user;
3598
+ // Cache resolved card IDs to avoid repeated lookups within a session
3599
+ resolvedCardIds = null;
3600
+ constructor(courseId, filter, user) {
3601
+ this.courseId = courseId;
3602
+ this.filter = filter;
3603
+ this.user = user;
3604
+ logger.info(
3605
+ `[TagFilteredContentSource] Created for course "${courseId}" with filter:`,
3606
+ JSON.stringify(filter)
3607
+ );
3608
+ }
3609
+ /**
3610
+ * Resolves the TagFilter to a set of eligible card IDs.
3611
+ *
3612
+ * - Cards in `include` tags are OR'd together (card needs at least one)
3613
+ * - Cards in `exclude` tags are removed from the result
3614
+ */
3615
+ async resolveFilteredCardIds() {
3616
+ if (this.resolvedCardIds !== null) {
3617
+ return this.resolvedCardIds;
3618
+ }
3619
+ const includedCardIds = /* @__PURE__ */ new Set();
3620
+ if (this.filter.include.length > 0) {
3621
+ for (const tagName of this.filter.include) {
3622
+ try {
3623
+ const tagDoc = await getTag(this.courseId, tagName);
3624
+ tagDoc.taggedCards.forEach((cardId) => includedCardIds.add(cardId));
3625
+ } catch (error) {
3626
+ logger.warn(
3627
+ `[TagFilteredContentSource] Could not resolve tag "${tagName}" for inclusion:`,
3628
+ error
3629
+ );
3630
+ }
3631
+ }
3632
+ }
3633
+ if (includedCardIds.size === 0 && this.filter.include.length > 0) {
3634
+ logger.warn(
3635
+ `[TagFilteredContentSource] No cards found for include tags: ${this.filter.include.join(", ")}`
3636
+ );
3637
+ this.resolvedCardIds = /* @__PURE__ */ new Set();
3638
+ return this.resolvedCardIds;
3639
+ }
3640
+ const excludedCardIds = /* @__PURE__ */ new Set();
3641
+ if (this.filter.exclude.length > 0) {
3642
+ for (const tagName of this.filter.exclude) {
3643
+ try {
3644
+ const tagDoc = await getTag(this.courseId, tagName);
3645
+ tagDoc.taggedCards.forEach((cardId) => excludedCardIds.add(cardId));
3646
+ } catch (error) {
3647
+ logger.warn(
3648
+ `[TagFilteredContentSource] Could not resolve tag "${tagName}" for exclusion:`,
3649
+ error
3650
+ );
3651
+ }
3652
+ }
3653
+ }
3654
+ const finalCardIds = /* @__PURE__ */ new Set();
3655
+ for (const cardId of includedCardIds) {
3656
+ if (!excludedCardIds.has(cardId)) {
3657
+ finalCardIds.add(cardId);
3658
+ }
3659
+ }
3660
+ logger.info(
3661
+ `[TagFilteredContentSource] Resolved ${finalCardIds.size} cards (included: ${includedCardIds.size}, excluded: ${excludedCardIds.size})`
3662
+ );
3663
+ this.resolvedCardIds = finalCardIds;
3664
+ return finalCardIds;
3665
+ }
3666
+ /**
3667
+ * Gets new cards that match the tag filter and are not already active for the user.
3668
+ */
3669
+ async getNewCards(limit) {
3670
+ if (!hasActiveFilter(this.filter)) {
3671
+ logger.warn("[TagFilteredContentSource] getNewCards called with no active filter");
3672
+ return [];
3673
+ }
3674
+ const eligibleCardIds = await this.resolveFilteredCardIds();
3675
+ const activeCards = await this.user.getActiveCards();
3676
+ const activeCardIds = new Set(activeCards.map((c) => c.cardID));
3677
+ const newItems = [];
3678
+ for (const cardId of eligibleCardIds) {
3679
+ if (!activeCardIds.has(cardId)) {
3680
+ newItems.push({
3681
+ courseID: this.courseId,
3682
+ cardID: cardId,
3683
+ contentSourceType: "course",
3684
+ contentSourceID: this.courseId,
3685
+ status: "new"
3686
+ });
3687
+ }
3688
+ if (limit !== void 0 && newItems.length >= limit) {
3689
+ break;
3690
+ }
3691
+ }
3692
+ logger.info(`[TagFilteredContentSource] Found ${newItems.length} new cards matching filter`);
3693
+ return newItems;
3694
+ }
3695
+ /**
3696
+ * Gets pending reviews, filtered to only include cards that match the tag filter.
3697
+ */
3698
+ async getPendingReviews() {
3699
+ if (!hasActiveFilter(this.filter)) {
3700
+ logger.warn("[TagFilteredContentSource] getPendingReviews called with no active filter");
3701
+ return [];
3702
+ }
3703
+ const eligibleCardIds = await this.resolveFilteredCardIds();
3704
+ const allReviews = await this.user.getPendingReviews(this.courseId);
3705
+ const filteredReviews = allReviews.filter((review) => {
3706
+ return eligibleCardIds.has(review.cardId);
3707
+ });
3708
+ logger.info(
3709
+ `[TagFilteredContentSource] Found ${filteredReviews.length} pending reviews matching filter (of ${allReviews.length} total)`
3710
+ );
3711
+ return filteredReviews.map((r) => ({
3712
+ ...r,
3713
+ courseID: r.courseId,
3714
+ cardID: r.cardId,
3715
+ contentSourceType: "course",
3716
+ contentSourceID: this.courseId,
3717
+ reviewID: r._id,
3718
+ status: "review"
3719
+ }));
3720
+ }
3721
+ /**
3722
+ * Get cards with suitability scores for presentation.
3723
+ *
3724
+ * This implementation wraps the legacy getNewCards/getPendingReviews methods,
3725
+ * assigning score=1.0 to all cards. TagFilteredContentSource does not currently
3726
+ * support pluggable navigation strategies - it returns flat-scored candidates.
3727
+ *
3728
+ * @param limit - Maximum number of cards to return
3729
+ * @returns Cards sorted by score descending (all scores = 1.0)
3730
+ */
3731
+ async getWeightedCards(limit) {
3732
+ const [newCards, reviews] = await Promise.all([
3733
+ this.getNewCards(limit),
3734
+ this.getPendingReviews()
3735
+ ]);
3736
+ const weighted = [
3737
+ ...reviews.map((r) => ({
3738
+ cardId: r.cardID,
3739
+ courseId: r.courseID,
3740
+ score: 1,
3741
+ provenance: [
3742
+ {
3743
+ strategy: "tagFilter",
3744
+ strategyName: "Tag Filter",
3745
+ strategyId: "TAG_FILTER",
3746
+ action: "generated",
3747
+ score: 1,
3748
+ reason: `Tag-filtered review (tags: ${this.filter.include.join(", ")})`
3749
+ }
3750
+ ]
3751
+ })),
3752
+ ...newCards.map((c) => ({
3753
+ cardId: c.cardID,
3754
+ courseId: c.courseID,
3755
+ score: 1,
3756
+ provenance: [
3757
+ {
3758
+ strategy: "tagFilter",
3759
+ strategyName: "Tag Filter",
3760
+ strategyId: "TAG_FILTER",
3761
+ action: "generated",
3762
+ score: 1,
3763
+ reason: `Tag-filtered new card (tags: ${this.filter.include.join(", ")})`
3764
+ }
3765
+ ]
3766
+ }))
3767
+ ];
3768
+ return weighted.slice(0, limit);
3769
+ }
3770
+ /**
3771
+ * Clears the cached resolved card IDs.
3772
+ * Call this if the underlying tag data may have changed during a session.
3773
+ */
3774
+ clearCache() {
3775
+ this.resolvedCardIds = null;
3776
+ }
3777
+ /**
3778
+ * Returns the course ID this source is filtering.
3779
+ */
3780
+ getCourseId() {
3781
+ return this.courseId;
3782
+ }
3783
+ /**
3784
+ * Returns the active tag filter.
3785
+ */
3786
+ getFilter() {
3787
+ return this.filter;
3788
+ }
3789
+ };
3790
+ }
3791
+ });
3792
+
1744
3793
  // src/core/interfaces/contentSource.ts
3794
+ import { hasActiveFilter as hasActiveFilter2 } from "@vue-skuilder/common";
1745
3795
  function isReview(item) {
1746
3796
  const ret = item.status === "review" || item.status === "failed-review" || "reviewID" in item;
1747
3797
  return ret;
@@ -1750,6 +3800,9 @@ async function getStudySource(source, user) {
1750
3800
  if (source.type === "classroom") {
1751
3801
  return await StudentClassroomDB.factory(source.id, user);
1752
3802
  } else {
3803
+ if (hasActiveFilter2(source.tagFilter)) {
3804
+ return new TagFilteredContentSource(source.id, source.tagFilter, user);
3805
+ }
1753
3806
  return getDataLayer().getCourseDB(source.id);
1754
3807
  }
1755
3808
  }
@@ -1758,6 +3811,7 @@ var init_contentSource = __esm({
1758
3811
  "use strict";
1759
3812
  init_factory();
1760
3813
  init_classroomDB2();
3814
+ init_TagFilteredContentSource();
1761
3815
  }
1762
3816
  });
1763
3817
 
@@ -1802,6 +3856,16 @@ var init_user = __esm({
1802
3856
  }
1803
3857
  });
1804
3858
 
3859
+ // src/core/types/strategyState.ts
3860
+ function buildStrategyStateId(courseId, strategyKey) {
3861
+ return `STRATEGY_STATE::${courseId}::${strategyKey}`;
3862
+ }
3863
+ var init_strategyState = __esm({
3864
+ "src/core/types/strategyState.ts"() {
3865
+ "use strict";
3866
+ }
3867
+ });
3868
+
1805
3869
  // src/core/util/index.ts
1806
3870
  function getCardHistoryID(courseID, cardID) {
1807
3871
  return `${DocTypePrefixes["CARDRECORD" /* CARDRECORD */]}-${courseID}-${cardID}`;
@@ -1823,7 +3887,7 @@ var init_cardProcessor = __esm({
1823
3887
  });
1824
3888
 
1825
3889
  // src/core/bulkImport/types.ts
1826
- var init_types = __esm({
3890
+ var init_types3 = __esm({
1827
3891
  "src/core/bulkImport/types.ts"() {
1828
3892
  "use strict";
1829
3893
  }
@@ -1834,7 +3898,7 @@ var init_bulkImport = __esm({
1834
3898
  "src/core/bulkImport/index.ts"() {
1835
3899
  "use strict";
1836
3900
  init_cardProcessor();
1837
- init_types();
3901
+ init_types3();
1838
3902
  }
1839
3903
  });
1840
3904
 
@@ -1845,6 +3909,7 @@ var init_core = __esm({
1845
3909
  init_interfaces();
1846
3910
  init_types_legacy();
1847
3911
  init_user();
3912
+ init_strategyState();
1848
3913
  init_Loggable();
1849
3914
  init_util();
1850
3915
  init_navigators();
@@ -1882,7 +3947,7 @@ var init_dataDirectory = __esm({
1882
3947
  });
1883
3948
 
1884
3949
  // src/impl/common/userDBHelpers.ts
1885
- import moment2 from "moment";
3950
+ import moment3 from "moment";
1886
3951
  function hexEncode(str) {
1887
3952
  let hex;
1888
3953
  let returnStr = "";
@@ -1910,7 +3975,7 @@ function getStartAndEndKeys2(key) {
1910
3975
  };
1911
3976
  }
1912
3977
  function updateGuestAccountExpirationDate(guestDB) {
1913
- const currentTime = moment2.utc();
3978
+ const currentTime = moment3.utc();
1914
3979
  const expirationDate = currentTime.add(2, "months").toISOString();
1915
3980
  const expiryDocID2 = "GuestAccountExpirationDate";
1916
3981
  void guestDB.get(expiryDocID2).then((doc) => {
@@ -1935,7 +4000,7 @@ function getLocalUserDB(username) {
1935
4000
  }
1936
4001
  }
1937
4002
  function scheduleCardReviewLocal(userDB, review) {
1938
- const now = moment2.utc();
4003
+ const now = moment3.utc();
1939
4004
  logger.info(`Scheduling for review in: ${review.time.diff(now, "h") / 24} days`);
1940
4005
  void userDB.put({
1941
4006
  _id: DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */] + review.time.format(REVIEW_TIME_FORMAT2),
@@ -1974,7 +4039,7 @@ var init_userDBHelpers = __esm({
1974
4039
  });
1975
4040
 
1976
4041
  // src/impl/couch/user-course-relDB.ts
1977
- import moment3 from "moment";
4042
+ import moment4 from "moment";
1978
4043
  var UsrCrsData;
1979
4044
  var init_user_course_relDB = __esm({
1980
4045
  "src/impl/couch/user-course-relDB.ts"() {
@@ -1988,11 +4053,11 @@ var init_user_course_relDB = __esm({
1988
4053
  this._courseId = courseId;
1989
4054
  }
1990
4055
  async getReviewsForcast(daysCount) {
1991
- const time = moment3.utc().add(daysCount, "days");
4056
+ const time = moment4.utc().add(daysCount, "days");
1992
4057
  return this.getReviewstoDate(time);
1993
4058
  }
1994
4059
  async getPendingReviews() {
1995
- const now = moment3.utc();
4060
+ const now = moment4.utc();
1996
4061
  return this.getReviewstoDate(now);
1997
4062
  }
1998
4063
  async getScheduledReviewCount() {
@@ -2019,7 +4084,7 @@ var init_user_course_relDB = __esm({
2019
4084
  `Fetching ${this.user.getUsername()}'s scheduled reviews for course ${this._courseId}.`
2020
4085
  );
2021
4086
  return allReviews.filter((review) => {
2022
- const reviewTime = moment3.utc(review.reviewTime);
4087
+ const reviewTime = moment4.utc(review.reviewTime);
2023
4088
  return targetDate.isAfter(reviewTime);
2024
4089
  });
2025
4090
  }
@@ -2029,11 +4094,13 @@ var init_user_course_relDB = __esm({
2029
4094
 
2030
4095
  // src/impl/common/BaseUserDB.ts
2031
4096
  import { Status as Status3 } from "@vue-skuilder/common";
2032
- import moment4 from "moment";
4097
+ import moment5 from "moment";
2033
4098
  function accomodateGuest() {
2034
4099
  logger.log("[funnel] accomodateGuest() called");
2035
4100
  if (typeof localStorage === "undefined") {
2036
- logger.log("[funnel] localStorage not available (Node.js environment), returning default guest");
4101
+ logger.log(
4102
+ "[funnel] localStorage not available (Node.js environment), returning default guest"
4103
+ );
2037
4104
  return {
2038
4105
  username: GuestUsername + "nodejs-test",
2039
4106
  firstVisit: true
@@ -2467,7 +4534,7 @@ Currently logged-in as ${this._username}.`
2467
4534
  );
2468
4535
  return reviews.rows.filter((r) => {
2469
4536
  if (r.id.startsWith(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */])) {
2470
- const date = moment4.utc(
4537
+ const date = moment5.utc(
2471
4538
  r.id.substr(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */].length),
2472
4539
  REVIEW_TIME_FORMAT2
2473
4540
  );
@@ -2480,11 +4547,11 @@ Currently logged-in as ${this._username}.`
2480
4547
  }).map((r) => r.doc);
2481
4548
  }
2482
4549
  async getReviewsForcast(daysCount) {
2483
- const time = moment4.utc().add(daysCount, "days");
4550
+ const time = moment5.utc().add(daysCount, "days");
2484
4551
  return this.getReviewstoDate(time);
2485
4552
  }
2486
4553
  async getPendingReviews(course_id) {
2487
- const now = moment4.utc();
4554
+ const now = moment5.utc();
2488
4555
  return this.getReviewstoDate(now, course_id);
2489
4556
  }
2490
4557
  async getScheduledReviewCount(course_id) {
@@ -2771,7 +4838,7 @@ Currently logged-in as ${this._username}.`
2771
4838
  */
2772
4839
  async putCardRecord(record) {
2773
4840
  const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
2774
- record.timeStamp = moment4.utc(record.timeStamp).toString();
4841
+ record.timeStamp = moment5.utc(record.timeStamp).toString();
2775
4842
  try {
2776
4843
  const cardHistory = await this.update(
2777
4844
  cardHistoryID,
@@ -2787,7 +4854,7 @@ Currently logged-in as ${this._username}.`
2787
4854
  const ret = {
2788
4855
  ...record2
2789
4856
  };
2790
- ret.timeStamp = moment4.utc(record2.timeStamp);
4857
+ ret.timeStamp = moment5.utc(record2.timeStamp);
2791
4858
  return ret;
2792
4859
  });
2793
4860
  return cardHistory;
@@ -3011,6 +5078,55 @@ Currently logged-in as ${this._username}.`
3011
5078
  async updateUserElo(courseId, elo) {
3012
5079
  return updateUserElo(this._username, courseId, elo);
3013
5080
  }
5081
+ async getStrategyState(courseId, strategyKey) {
5082
+ const docId = buildStrategyStateId(courseId, strategyKey);
5083
+ try {
5084
+ const doc = await this.localDB.get(docId);
5085
+ return doc.data;
5086
+ } catch (e) {
5087
+ const err = e;
5088
+ if (err.status === 404) {
5089
+ return null;
5090
+ }
5091
+ throw e;
5092
+ }
5093
+ }
5094
+ async putStrategyState(courseId, strategyKey, data) {
5095
+ const docId = buildStrategyStateId(courseId, strategyKey);
5096
+ let existingRev;
5097
+ try {
5098
+ const existing = await this.localDB.get(docId);
5099
+ existingRev = existing._rev;
5100
+ } catch (e) {
5101
+ const err = e;
5102
+ if (err.status !== 404) {
5103
+ throw e;
5104
+ }
5105
+ }
5106
+ const doc = {
5107
+ _id: docId,
5108
+ _rev: existingRev,
5109
+ docType: "STRATEGY_STATE" /* STRATEGY_STATE */,
5110
+ courseId,
5111
+ strategyKey,
5112
+ data,
5113
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
5114
+ };
5115
+ await this.localDB.put(doc);
5116
+ }
5117
+ async deleteStrategyState(courseId, strategyKey) {
5118
+ const docId = buildStrategyStateId(courseId, strategyKey);
5119
+ try {
5120
+ const doc = await this.localDB.get(docId);
5121
+ await this.localDB.remove(doc);
5122
+ } catch (e) {
5123
+ const err = e;
5124
+ if (err.status === 404) {
5125
+ return;
5126
+ }
5127
+ throw e;
5128
+ }
5129
+ }
3014
5130
  };
3015
5131
  userCoursesDoc = "CourseRegistrations";
3016
5132
  userClassroomsDoc = "ClassroomRegistrations";
@@ -3111,8 +5227,7 @@ var init_adminDB2 = __esm({
3111
5227
  }
3112
5228
  }
3113
5229
  }
3114
- const dbs = await Promise.all(promisedCRDbs);
3115
- return dbs.map((db) => {
5230
+ return promisedCRDbs.map((db) => {
3116
5231
  return {
3117
5232
  ...db.getConfig(),
3118
5233
  _id: db._id
@@ -3392,7 +5507,7 @@ var init_CouchDBSyncStrategy = __esm({
3392
5507
 
3393
5508
  // src/impl/couch/index.ts
3394
5509
  import fetch2 from "cross-fetch";
3395
- import moment5 from "moment";
5510
+ import moment6 from "moment";
3396
5511
  import process2 from "process";
3397
5512
  function hexEncode2(str) {
3398
5513
  let hex;
@@ -3461,7 +5576,7 @@ async function usernameIsAvailable(username) {
3461
5576
  }
3462
5577
  }
3463
5578
  function updateGuestAccountExpirationDate2(guestDB) {
3464
- const currentTime = moment5.utc();
5579
+ const currentTime = moment6.utc();
3465
5580
  const expirationDate = currentTime.add(2, "months").toISOString();
3466
5581
  void guestDB.get(expiryDocID).then((doc) => {
3467
5582
  return guestDB.put({
@@ -3524,7 +5639,7 @@ function getCouchUserDB(username) {
3524
5639
  return ret;
3525
5640
  }
3526
5641
  function scheduleCardReview(review) {
3527
- const now = moment5.utc();
5642
+ const now = moment6.utc();
3528
5643
  logger.info(`Scheduling for review in: ${review.time.diff(now, "h") / 24} days`);
3529
5644
  void getCouchUserDB(review.user).put({
3530
5645
  _id: DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */] + review.time.format(REVIEW_TIME_FORMAT),