@vue-skuilder/db 0.1.18 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CLAUDE.md +2 -2
  2. package/dist/{classroomDB-BgfrVb8d.d.ts → contentSource-BP9hznNV.d.ts} +220 -197
  3. package/dist/{classroomDB-CTOenngH.d.cts → contentSource-DsJadoBU.d.cts} +220 -197
  4. package/dist/core/index.d.cts +80 -6
  5. package/dist/core/index.d.ts +80 -6
  6. package/dist/core/index.js +735 -1560
  7. package/dist/core/index.js.map +1 -1
  8. package/dist/core/index.mjs +708 -1539
  9. package/dist/core/index.mjs.map +1 -1
  10. package/dist/{dataLayerProvider-D6PoCwS6.d.cts → dataLayerProvider-CHYrQ5pB.d.cts} +1 -1
  11. package/dist/{dataLayerProvider-CZxC9GtB.d.ts → dataLayerProvider-MDTxXq2l.d.ts} +1 -1
  12. package/dist/impl/couch/index.d.cts +8 -23
  13. package/dist/impl/couch/index.d.ts +8 -23
  14. package/dist/impl/couch/index.js +723 -1578
  15. package/dist/impl/couch/index.js.map +1 -1
  16. package/dist/impl/couch/index.mjs +692 -1552
  17. package/dist/impl/couch/index.mjs.map +1 -1
  18. package/dist/impl/static/index.d.cts +25 -8
  19. package/dist/impl/static/index.d.ts +25 -8
  20. package/dist/impl/static/index.js +700 -1400
  21. package/dist/impl/static/index.js.map +1 -1
  22. package/dist/impl/static/index.mjs +688 -1393
  23. package/dist/impl/static/index.mjs.map +1 -1
  24. package/dist/{index-D-Fa4Smt.d.cts → index-B_j6u5E4.d.cts} +1 -1
  25. package/dist/{index-CD8BZz2k.d.ts → index-Dj0SEgk3.d.ts} +1 -1
  26. package/dist/index.d.cts +71 -63
  27. package/dist/index.d.ts +71 -63
  28. package/dist/index.js +1162 -1996
  29. package/dist/index.js.map +1 -1
  30. package/dist/index.mjs +1124 -1955
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/pouch/index.js +3 -0
  33. package/dist/pouch/index.js.map +1 -1
  34. package/dist/pouch/index.mjs +3 -0
  35. package/dist/pouch/index.mjs.map +1 -1
  36. package/dist/{types-CzPDLAK6.d.cts → types-Bn0itutr.d.cts} +1 -1
  37. package/dist/{types-CewsN87z.d.ts → types-DQaXnuoc.d.ts} +1 -1
  38. package/dist/{types-legacy-6ettoclI.d.cts → types-legacy-DDY4N-Uq.d.cts} +3 -1
  39. package/dist/{types-legacy-6ettoclI.d.ts → types-legacy-DDY4N-Uq.d.ts} +3 -1
  40. package/dist/util/packer/index.d.cts +3 -3
  41. package/dist/util/packer/index.d.ts +3 -3
  42. package/docs/navigators-architecture.md +115 -17
  43. package/package.json +4 -4
  44. package/src/core/index.ts +1 -0
  45. package/src/core/interfaces/classroomDB.ts +5 -13
  46. package/src/core/interfaces/contentSource.ts +6 -66
  47. package/src/core/interfaces/courseDB.ts +15 -7
  48. package/src/core/interfaces/userDB.ts +32 -0
  49. package/src/core/navigators/Pipeline.ts +136 -52
  50. package/src/core/navigators/PipelineAssembler.ts +1 -1
  51. package/src/core/navigators/defaults.ts +84 -0
  52. package/src/core/navigators/{hierarchyDefinition.ts → filters/hierarchyDefinition.ts} +15 -29
  53. package/src/core/navigators/filters/index.ts +3 -0
  54. package/src/core/navigators/filters/inferredPreferenceStub.ts +107 -0
  55. package/src/core/navigators/{interferenceMitigator.ts → filters/interferenceMitigator.ts} +11 -37
  56. package/src/core/navigators/{relativePriority.ts → filters/relativePriority.ts} +12 -38
  57. package/src/core/navigators/filters/userGoalStub.ts +136 -0
  58. package/src/core/navigators/filters/userTagPreference.ts +217 -0
  59. package/src/core/navigators/{CompositeGenerator.ts → generators/CompositeGenerator.ts} +15 -64
  60. package/src/core/navigators/{elo.ts → generators/elo.ts} +13 -63
  61. package/src/core/navigators/{srs.ts → generators/srs.ts} +11 -40
  62. package/src/core/navigators/generators/types.ts +1 -1
  63. package/src/core/navigators/index.ts +95 -91
  64. package/src/core/types/strategyState.ts +84 -0
  65. package/src/core/types/types-legacy.ts +2 -0
  66. package/src/impl/common/BaseUserDB.ts +74 -7
  67. package/src/impl/couch/adminDB.ts +1 -2
  68. package/src/impl/couch/classroomDB.ts +100 -103
  69. package/src/impl/couch/courseDB.ts +35 -91
  70. package/src/impl/couch/pouchdb-setup.ts +7 -0
  71. package/src/impl/static/StaticDataUnpacker.ts +50 -1
  72. package/src/impl/static/courseDB.ts +87 -37
  73. package/src/study/SessionController.ts +122 -202
  74. package/src/study/SourceMixer.ts +65 -0
  75. package/src/study/TagFilteredContentSource.ts +49 -92
  76. package/src/study/index.ts +1 -0
  77. package/src/study/services/CardHydrationService.ts +165 -81
  78. package/src/util/dataDirectory.ts +1 -1
  79. package/src/util/index.ts +0 -1
  80. package/tests/core/navigators/CompositeGenerator.test.ts +44 -168
  81. package/tests/core/navigators/Pipeline.test.ts +6 -72
  82. package/tests/core/navigators/PipelineAssembler.test.ts +8 -58
  83. package/tests/core/navigators/navigators.test.ts +118 -151
  84. package/docs/todo-pipeline-optimization.md +0 -117
  85. package/docs/todo-strategy-state-storage.md +0 -278
  86. package/src/core/navigators/hardcodedOrder.ts +0 -163
  87. package/src/util/tuiLogger.ts +0 -139
@@ -5,11 +5,6 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __glob = (map) => (path2) => {
9
- var fn = map[path2];
10
- if (fn) return fn();
11
- throw new Error("Module not found in bundle: " + path2);
12
- };
13
8
  var __esm = (fn, res) => function __init() {
14
9
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
15
10
  };
@@ -119,7 +114,8 @@ var init_types_legacy = __esm({
119
114
  ["QUESTION" /* QUESTIONTYPE */]: "QUESTION",
120
115
  ["VIEW" /* VIEW */]: "VIEW",
121
116
  ["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
122
- ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY"
117
+ ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
118
+ ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE"
123
119
  };
124
120
  }
125
121
  });
@@ -145,6 +141,9 @@ var init_pouchdb_setup = __esm({
145
141
  import_pouchdb_authentication = __toESM(require("@nilock2/pouchdb-authentication"), 1);
146
142
  import_pouchdb.default.plugin(import_pouchdb_find.default);
147
143
  import_pouchdb.default.plugin(import_pouchdb_authentication.default);
144
+ if (typeof import_pouchdb.default.debug !== "undefined") {
145
+ import_pouchdb.default.debug.disable();
146
+ }
148
147
  import_pouchdb.default.defaults({
149
148
  // ajax: {
150
149
  // timeout: 60000,
@@ -154,14 +153,6 @@ var init_pouchdb_setup = __esm({
154
153
  }
155
154
  });
156
155
 
157
- // src/util/tuiLogger.ts
158
- var init_tuiLogger = __esm({
159
- "src/util/tuiLogger.ts"() {
160
- "use strict";
161
- init_dataDirectory();
162
- }
163
- });
164
-
165
156
  // src/util/dataDirectory.ts
166
157
  function getAppDataDirectory() {
167
158
  if (ENV.LOCAL_STORAGE_PREFIX) {
@@ -179,7 +170,7 @@ var init_dataDirectory = __esm({
179
170
  "use strict";
180
171
  path = __toESM(require("path"), 1);
181
172
  os = __toESM(require("os"), 1);
182
- init_tuiLogger();
173
+ init_logger();
183
174
  init_factory();
184
175
  }
185
176
  });
@@ -499,24 +490,331 @@ var init_courseLookupDB = __esm({
499
490
  }
500
491
  });
501
492
 
502
- // src/core/navigators/CompositeGenerator.ts
503
- var CompositeGenerator_exports = {};
504
- __export(CompositeGenerator_exports, {
505
- AggregationMode: () => AggregationMode,
506
- default: () => CompositeGenerator
493
+ // src/core/navigators/index.ts
494
+ function isGenerator(impl) {
495
+ return NavigatorRoles[impl] === "generator" /* GENERATOR */;
496
+ }
497
+ function isFilter(impl) {
498
+ return NavigatorRoles[impl] === "filter" /* FILTER */;
499
+ }
500
+ var NavigatorRoles, ContentNavigator;
501
+ var init_navigators = __esm({
502
+ "src/core/navigators/index.ts"() {
503
+ "use strict";
504
+ init_logger();
505
+ NavigatorRoles = {
506
+ ["elo" /* ELO */]: "generator" /* GENERATOR */,
507
+ ["srs" /* SRS */]: "generator" /* GENERATOR */,
508
+ ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
509
+ ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
510
+ ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
511
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
512
+ };
513
+ ContentNavigator = class {
514
+ /** User interface for this navigation session */
515
+ user;
516
+ /** Course interface for this navigation session */
517
+ course;
518
+ /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
519
+ strategyName;
520
+ /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
521
+ strategyId;
522
+ /**
523
+ * Constructor for standard navigators.
524
+ * Call this from subclass constructors to initialize common fields.
525
+ *
526
+ * Note: CompositeGenerator and Pipeline call super() without args, then set
527
+ * user/course fields directly if needed.
528
+ */
529
+ constructor(user, course, strategyData) {
530
+ this.user = user;
531
+ this.course = course;
532
+ if (strategyData) {
533
+ this.strategyName = strategyData.name;
534
+ this.strategyId = strategyData._id;
535
+ }
536
+ }
537
+ // ============================================================================
538
+ // STRATEGY STATE HELPERS
539
+ // ============================================================================
540
+ //
541
+ // These methods allow strategies to persist their own state (user preferences,
542
+ // learned patterns, temporal tracking) in the user database.
543
+ //
544
+ // ============================================================================
545
+ /**
546
+ * Unique key identifying this strategy for state storage.
547
+ *
548
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
549
+ * Override in subclasses if multiple instances of the same strategy type
550
+ * need separate state storage.
551
+ */
552
+ get strategyKey() {
553
+ return this.constructor.name;
554
+ }
555
+ /**
556
+ * Get this strategy's persisted state for the current course.
557
+ *
558
+ * @returns The strategy's data payload, or null if no state exists
559
+ * @throws Error if user or course is not initialized
560
+ */
561
+ async getStrategyState() {
562
+ if (!this.user || !this.course) {
563
+ throw new Error(
564
+ `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
565
+ );
566
+ }
567
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
568
+ }
569
+ /**
570
+ * Persist this strategy's state for the current course.
571
+ *
572
+ * @param data - The strategy's data payload to store
573
+ * @throws Error if user or course is not initialized
574
+ */
575
+ async putStrategyState(data) {
576
+ if (!this.user || !this.course) {
577
+ throw new Error(
578
+ `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
579
+ );
580
+ }
581
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
582
+ }
583
+ /**
584
+ * Factory method to create navigator instances dynamically.
585
+ *
586
+ * @param user - User interface
587
+ * @param course - Course interface
588
+ * @param strategyData - Strategy configuration document
589
+ * @returns the runtime object used to steer a study session.
590
+ */
591
+ static async create(user, course, strategyData) {
592
+ const implementingClass = strategyData.implementingClass;
593
+ let NavigatorImpl;
594
+ const variations = [".ts", ".js", ""];
595
+ const dirs = ["filters", "generators"];
596
+ for (const ext of variations) {
597
+ for (const dir of dirs) {
598
+ const loadFrom = `./${dir}/${implementingClass}${ext}`;
599
+ try {
600
+ const module2 = await import(loadFrom);
601
+ NavigatorImpl = module2.default;
602
+ break;
603
+ } catch (e) {
604
+ logger.debug(`Failed to load extension from ${loadFrom}:`, e);
605
+ }
606
+ }
607
+ }
608
+ if (!NavigatorImpl) {
609
+ throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
610
+ }
611
+ return new NavigatorImpl(user, course, strategyData);
612
+ }
613
+ /**
614
+ * Get cards with suitability scores and provenance trails.
615
+ *
616
+ * **This is the PRIMARY API for navigation strategies.**
617
+ *
618
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
619
+ * better candidates for presentation. Each card includes a provenance trail
620
+ * documenting how strategies contributed to the final score.
621
+ *
622
+ * ## Implementation Required
623
+ * All navigation strategies MUST override this method. The base class does
624
+ * not provide a default implementation.
625
+ *
626
+ * ## For Generators
627
+ * Override this method to generate candidates and compute scores based on
628
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
629
+ * initial provenance entry with action='generated'.
630
+ *
631
+ * ## For Filters
632
+ * Filters should implement the CardFilter interface instead and be composed
633
+ * via Pipeline. Filters do not directly implement getWeightedCards().
634
+ *
635
+ * @param limit - Maximum cards to return
636
+ * @returns Cards sorted by score descending, with provenance trails
637
+ */
638
+ async getWeightedCards(_limit) {
639
+ throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
640
+ }
641
+ };
642
+ }
643
+ });
644
+
645
+ // src/core/navigators/Pipeline.ts
646
+ function logPipelineConfig(generator, filters) {
647
+ const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
648
+ logger.info(
649
+ `[Pipeline] Configuration:
650
+ Generator: ${generator.name}
651
+ Filters:${filterList}`
652
+ );
653
+ }
654
+ function logTagHydration(cards, tagsByCard) {
655
+ const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
656
+ const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
657
+ logger.debug(
658
+ `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
659
+ );
660
+ }
661
+ function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores) {
662
+ const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
663
+ logger.info(
664
+ `[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})`
665
+ );
666
+ }
667
+ function logCardProvenance(cards, maxCards = 3) {
668
+ const cardsToLog = cards.slice(0, maxCards);
669
+ logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
670
+ for (const card of cardsToLog) {
671
+ logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
672
+ for (const entry of card.provenance) {
673
+ const scoreChange = entry.score.toFixed(3);
674
+ const action = entry.action.padEnd(9);
675
+ logger.debug(
676
+ `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
677
+ );
678
+ }
679
+ }
680
+ }
681
+ var import_common5, Pipeline;
682
+ var init_Pipeline = __esm({
683
+ "src/core/navigators/Pipeline.ts"() {
684
+ "use strict";
685
+ import_common5 = require("@vue-skuilder/common");
686
+ init_navigators();
687
+ init_logger();
688
+ Pipeline = class extends ContentNavigator {
689
+ generator;
690
+ filters;
691
+ /**
692
+ * Create a new pipeline.
693
+ *
694
+ * @param generator - The generator (or CompositeGenerator) that produces candidates
695
+ * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
696
+ * @param user - User database interface
697
+ * @param course - Course database interface
698
+ */
699
+ constructor(generator, filters, user, course) {
700
+ super();
701
+ this.generator = generator;
702
+ this.filters = filters;
703
+ this.user = user;
704
+ this.course = course;
705
+ course.getCourseConfig().then((cfg) => {
706
+ logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);
707
+ }).catch((e) => {
708
+ logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);
709
+ });
710
+ logPipelineConfig(generator, filters);
711
+ }
712
+ /**
713
+ * Get weighted cards by running generator and applying filters.
714
+ *
715
+ * 1. Build shared context (user ELO, etc.)
716
+ * 2. Get candidates from generator (passing context)
717
+ * 3. Batch hydrate tags for all candidates
718
+ * 4. Apply each filter sequentially
719
+ * 5. Remove zero-score cards
720
+ * 6. Sort by score descending
721
+ * 7. Return top N
722
+ *
723
+ * @param limit - Maximum number of cards to return
724
+ * @returns Cards sorted by score descending
725
+ */
726
+ async getWeightedCards(limit) {
727
+ const context = await this.buildContext();
728
+ const overFetchMultiplier = 2 + this.filters.length * 0.5;
729
+ const fetchLimit = Math.ceil(limit * overFetchMultiplier);
730
+ logger.debug(
731
+ `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
732
+ );
733
+ let cards = await this.generator.getWeightedCards(fetchLimit, context);
734
+ const generatedCount = cards.length;
735
+ logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
736
+ cards = await this.hydrateTags(cards);
737
+ for (const filter of this.filters) {
738
+ const beforeCount = cards.length;
739
+ cards = await filter.transform(cards, context);
740
+ logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeCount} \u2192 ${cards.length} cards`);
741
+ }
742
+ cards = cards.filter((c) => c.score > 0);
743
+ cards.sort((a, b) => b.score - a.score);
744
+ const result = cards.slice(0, limit);
745
+ const topScores = result.slice(0, 3).map((c) => c.score);
746
+ logExecutionSummary(
747
+ this.generator.name,
748
+ generatedCount,
749
+ this.filters.length,
750
+ result.length,
751
+ topScores
752
+ );
753
+ logCardProvenance(result, 3);
754
+ return result;
755
+ }
756
+ /**
757
+ * Batch hydrate tags for all cards.
758
+ *
759
+ * Fetches tags for all cards in a single database query and attaches them
760
+ * to the WeightedCard objects. Filters can then use card.tags instead of
761
+ * making individual getAppliedTags() calls.
762
+ *
763
+ * @param cards - Cards to hydrate
764
+ * @returns Cards with tags populated
765
+ */
766
+ async hydrateTags(cards) {
767
+ if (cards.length === 0) {
768
+ return cards;
769
+ }
770
+ const cardIds = cards.map((c) => c.cardId);
771
+ const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
772
+ logTagHydration(cards, tagsByCard);
773
+ return cards.map((card) => ({
774
+ ...card,
775
+ tags: tagsByCard.get(card.cardId) ?? []
776
+ }));
777
+ }
778
+ /**
779
+ * Build shared context for generator and filters.
780
+ *
781
+ * Called once per getWeightedCards() invocation.
782
+ * Contains data that the generator and multiple filters might need.
783
+ *
784
+ * The context satisfies both GeneratorContext and FilterContext interfaces.
785
+ */
786
+ async buildContext() {
787
+ let userElo = 1e3;
788
+ try {
789
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
790
+ const courseElo = (0, import_common5.toCourseElo)(courseReg.elo);
791
+ userElo = courseElo.global.score;
792
+ } catch (e) {
793
+ logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
794
+ }
795
+ return {
796
+ user: this.user,
797
+ course: this.course,
798
+ userElo
799
+ };
800
+ }
801
+ /**
802
+ * Get the course ID for this pipeline.
803
+ */
804
+ getCourseID() {
805
+ return this.course.getCourseID();
806
+ }
807
+ };
808
+ }
507
809
  });
508
- var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
810
+
811
+ // src/core/navigators/generators/CompositeGenerator.ts
812
+ var DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
509
813
  var init_CompositeGenerator = __esm({
510
- "src/core/navigators/CompositeGenerator.ts"() {
814
+ "src/core/navigators/generators/CompositeGenerator.ts"() {
511
815
  "use strict";
512
816
  init_navigators();
513
817
  init_logger();
514
- AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
515
- AggregationMode2["MAX"] = "max";
516
- AggregationMode2["AVERAGE"] = "average";
517
- AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
518
- return AggregationMode2;
519
- })(AggregationMode || {});
520
818
  DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
521
819
  FREQUENCY_BOOST_FACTOR = 0.1;
522
820
  CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
@@ -556,9 +854,14 @@ var init_CompositeGenerator = __esm({
556
854
  * CardGenerator interface signature (limit, context).
557
855
  *
558
856
  * @param limit - Maximum number of cards to return
559
- * @param context - Optional GeneratorContext passed to child generators
857
+ * @param context - GeneratorContext passed to child generators (required when called via Pipeline)
560
858
  */
561
859
  async getWeightedCards(limit, context) {
860
+ if (!context) {
861
+ throw new Error(
862
+ "CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly."
863
+ );
864
+ }
562
865
  const results = await Promise.all(
563
866
  this.generators.map((g) => g.getWeightedCards(limit, context))
564
867
  );
@@ -639,190 +942,18 @@ var init_CompositeGenerator = __esm({
639
942
  return scores[0];
640
943
  }
641
944
  }
642
- /**
643
- * Get new cards from all generators, merged and deduplicated.
644
- */
645
- async getNewCards(n) {
646
- const legacyGenerators = this.generators.filter(
647
- (g) => g instanceof ContentNavigator
648
- );
649
- const results = await Promise.all(legacyGenerators.map((g) => g.getNewCards(n)));
650
- const seen = /* @__PURE__ */ new Set();
651
- const merged = [];
652
- for (const cards of results) {
653
- for (const card of cards) {
654
- if (!seen.has(card.cardID)) {
655
- seen.add(card.cardID);
656
- merged.push(card);
657
- }
658
- }
659
- }
660
- return n ? merged.slice(0, n) : merged;
661
- }
662
- /**
663
- * Get pending reviews from all generators, merged and deduplicated.
664
- */
665
- async getPendingReviews() {
666
- const legacyGenerators = this.generators.filter(
667
- (g) => g instanceof ContentNavigator
668
- );
669
- const results = await Promise.all(legacyGenerators.map((g) => g.getPendingReviews()));
670
- const seen = /* @__PURE__ */ new Set();
671
- const merged = [];
672
- for (const reviews of results) {
673
- for (const review of reviews) {
674
- if (!seen.has(review.cardID)) {
675
- seen.add(review.cardID);
676
- merged.push(review);
677
- }
678
- }
679
- }
680
- return merged;
681
- }
682
945
  };
683
946
  }
684
947
  });
685
948
 
686
- // src/core/navigators/Pipeline.ts
687
- var Pipeline_exports = {};
688
- __export(Pipeline_exports, {
689
- Pipeline: () => Pipeline
690
- });
691
- var import_common5, Pipeline;
692
- var init_Pipeline = __esm({
693
- "src/core/navigators/Pipeline.ts"() {
949
+ // src/core/navigators/PipelineAssembler.ts
950
+ var PipelineAssembler;
951
+ var init_PipelineAssembler = __esm({
952
+ "src/core/navigators/PipelineAssembler.ts"() {
694
953
  "use strict";
695
- import_common5 = require("@vue-skuilder/common");
696
954
  init_navigators();
697
- init_logger();
698
- Pipeline = class extends ContentNavigator {
699
- generator;
700
- filters;
701
- /**
702
- * Create a new pipeline.
703
- *
704
- * @param generator - The generator (or CompositeGenerator) that produces candidates
705
- * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
706
- * @param user - User database interface
707
- * @param course - Course database interface
708
- */
709
- constructor(generator, filters, user, course) {
710
- super();
711
- this.generator = generator;
712
- this.filters = filters;
713
- this.user = user;
714
- this.course = course;
715
- logger.debug(
716
- `[Pipeline] Created with generator '${generator.name}' and ${filters.length} filters: ${filters.map((f) => f.name).join(", ")}`
717
- );
718
- }
719
- /**
720
- * Get weighted cards by running generator and applying filters.
721
- *
722
- * 1. Build shared context (user ELO, etc.)
723
- * 2. Get candidates from generator (passing context)
724
- * 3. Apply each filter sequentially
725
- * 4. Remove zero-score cards
726
- * 5. Sort by score descending
727
- * 6. Return top N
728
- *
729
- * @param limit - Maximum number of cards to return
730
- * @returns Cards sorted by score descending
731
- */
732
- async getWeightedCards(limit) {
733
- const context = await this.buildContext();
734
- const overFetchMultiplier = 2 + this.filters.length * 0.5;
735
- const fetchLimit = Math.ceil(limit * overFetchMultiplier);
736
- logger.debug(
737
- `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
738
- );
739
- let cards = await this.generator.getWeightedCards(fetchLimit, context);
740
- logger.debug(`[Pipeline] Generator returned ${cards.length} candidates`);
741
- for (const filter of this.filters) {
742
- const beforeCount = cards.length;
743
- cards = await filter.transform(cards, context);
744
- logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeCount} \u2192 ${cards.length} cards`);
745
- }
746
- cards = cards.filter((c) => c.score > 0);
747
- cards.sort((a, b) => b.score - a.score);
748
- const result = cards.slice(0, limit);
749
- logger.debug(
750
- `[Pipeline] Returning ${result.length} cards (top scores: ${result.slice(0, 3).map((c) => c.score.toFixed(2)).join(", ")}...)`
751
- );
752
- return result;
753
- }
754
- /**
755
- * Build shared context for generator and filters.
756
- *
757
- * Called once per getWeightedCards() invocation.
758
- * Contains data that the generator and multiple filters might need.
759
- *
760
- * The context satisfies both GeneratorContext and FilterContext interfaces.
761
- */
762
- async buildContext() {
763
- let userElo = 1e3;
764
- try {
765
- const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
766
- const courseElo = (0, import_common5.toCourseElo)(courseReg.elo);
767
- userElo = courseElo.global.score;
768
- } catch (e) {
769
- logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
770
- }
771
- return {
772
- user: this.user,
773
- course: this.course,
774
- userElo
775
- };
776
- }
777
- // ===========================================================================
778
- // Legacy StudyContentSource methods
779
- // ===========================================================================
780
- //
781
- // These delegate to the generator for backward compatibility.
782
- // Eventually SessionController will use getWeightedCards() exclusively.
783
- //
784
- /**
785
- * Get new cards via legacy API.
786
- * Delegates to the generator if it supports the legacy interface.
787
- */
788
- async getNewCards(n) {
789
- if ("getNewCards" in this.generator && typeof this.generator.getNewCards === "function") {
790
- return this.generator.getNewCards(n);
791
- }
792
- return [];
793
- }
794
- /**
795
- * Get pending reviews via legacy API.
796
- * Delegates to the generator if it supports the legacy interface.
797
- */
798
- async getPendingReviews() {
799
- if ("getPendingReviews" in this.generator && typeof this.generator.getPendingReviews === "function") {
800
- return this.generator.getPendingReviews();
801
- }
802
- return [];
803
- }
804
- /**
805
- * Get the course ID for this pipeline.
806
- */
807
- getCourseID() {
808
- return this.course.getCourseID();
809
- }
810
- };
811
- }
812
- });
813
-
814
- // src/core/navigators/PipelineAssembler.ts
815
- var PipelineAssembler_exports = {};
816
- __export(PipelineAssembler_exports, {
817
- PipelineAssembler: () => PipelineAssembler
818
- });
819
- var PipelineAssembler;
820
- var init_PipelineAssembler = __esm({
821
- "src/core/navigators/PipelineAssembler.ts"() {
822
- "use strict";
823
- init_navigators();
824
- init_Pipeline();
825
- init_types_legacy();
955
+ init_Pipeline();
956
+ init_types_legacy();
826
957
  init_logger();
827
958
  init_CompositeGenerator();
828
959
  PipelineAssembler = class {
@@ -936,14 +1067,10 @@ var init_PipelineAssembler = __esm({
936
1067
  }
937
1068
  });
938
1069
 
939
- // src/core/navigators/elo.ts
940
- var elo_exports = {};
941
- __export(elo_exports, {
942
- default: () => ELONavigator
943
- });
1070
+ // src/core/navigators/generators/elo.ts
944
1071
  var import_common6, ELONavigator;
945
1072
  var init_elo = __esm({
946
- "src/core/navigators/elo.ts"() {
1073
+ "src/core/navigators/generators/elo.ts"() {
947
1074
  "use strict";
948
1075
  init_navigators();
949
1076
  import_common6 = require("@vue-skuilder/common");
@@ -954,50 +1081,6 @@ var init_elo = __esm({
954
1081
  super(user, course, strategyData);
955
1082
  this.name = strategyData?.name || "ELO";
956
1083
  }
957
- async getPendingReviews() {
958
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
959
- const elo = await this.course.getCardEloData(reviews.map((r) => r.cardId));
960
- const ratedReviews = reviews.map((r, i) => {
961
- const ratedR = {
962
- ...r,
963
- ...elo[i]
964
- };
965
- return ratedR;
966
- });
967
- ratedReviews.sort((a, b) => {
968
- return a.global.score - b.global.score;
969
- });
970
- return ratedReviews.map((r) => {
971
- return {
972
- ...r,
973
- contentSourceType: "course",
974
- contentSourceID: this.course.getCourseID(),
975
- cardID: r.cardId,
976
- courseID: r.courseId,
977
- qualifiedID: `${r.courseId}-${r.cardId}`,
978
- reviewID: r._id,
979
- status: "review"
980
- };
981
- });
982
- }
983
- async getNewCards(limit = 99) {
984
- const activeCards = await this.user.getActiveCards();
985
- return (await this.course.getCardsCenteredAtELO(
986
- { limit, elo: "user" },
987
- (c) => {
988
- if (activeCards.some((ac) => c.cardID === ac.cardID)) {
989
- return false;
990
- } else {
991
- return true;
992
- }
993
- }
994
- )).map((c) => {
995
- return {
996
- ...c,
997
- status: "new"
998
- };
999
- });
1000
- }
1001
1084
  /**
1002
1085
  * Get new cards with suitability scores based on ELO distance.
1003
1086
  *
@@ -1022,7 +1105,11 @@ var init_elo = __esm({
1022
1105
  const userElo = (0, import_common6.toCourseElo)(courseReg.elo);
1023
1106
  userGlobalElo = userElo.global.score;
1024
1107
  }
1025
- const newCards = await this.getNewCards(limit);
1108
+ const activeCards = await this.user.getActiveCards();
1109
+ const newCards = (await this.course.getCardsCenteredAtELO(
1110
+ { limit, elo: "user" },
1111
+ (c) => !activeCards.some((ac) => c.cardID === ac.cardID)
1112
+ )).map((c) => ({ ...c, status: "new" }));
1026
1113
  const cardIds = newCards.map((c) => c.cardID);
1027
1114
  const cardEloData = await this.course.getCardEloData(cardIds);
1028
1115
  const scored = newCards.map((c, i) => {
@@ -1052,807 +1139,15 @@ var init_elo = __esm({
1052
1139
  }
1053
1140
  });
1054
1141
 
1055
- // src/core/navigators/filters/eloDistance.ts
1056
- var eloDistance_exports = {};
1057
- __export(eloDistance_exports, {
1058
- DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1059
- DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1060
- DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1061
- createEloDistanceFilter: () => createEloDistanceFilter
1062
- });
1063
- function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1064
- const normalizedDistance = distance / halfLife;
1065
- const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1066
- return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1067
- }
1068
- function createEloDistanceFilter(config) {
1069
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1070
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1071
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1072
- return {
1073
- name: "ELO Distance Filter",
1074
- async transform(cards, context) {
1075
- const { course, userElo } = context;
1076
- const cardIds = cards.map((c) => c.cardId);
1077
- const cardElos = await course.getCardEloData(cardIds);
1078
- return cards.map((card, i) => {
1079
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
1080
- const distance = Math.abs(cardElo - userElo);
1081
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1082
- const newScore = card.score * multiplier;
1083
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1084
- return {
1085
- ...card,
1086
- score: newScore,
1087
- provenance: [
1088
- ...card.provenance,
1089
- {
1090
- strategy: "eloDistance",
1091
- strategyName: "ELO Distance Filter",
1092
- strategyId: "ELO_DISTANCE_FILTER",
1093
- action,
1094
- score: newScore,
1095
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1096
- }
1097
- ]
1098
- };
1099
- });
1100
- }
1101
- };
1102
- }
1103
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1104
- var init_eloDistance = __esm({
1105
- "src/core/navigators/filters/eloDistance.ts"() {
1106
- "use strict";
1107
- DEFAULT_HALF_LIFE = 200;
1108
- DEFAULT_MIN_MULTIPLIER = 0.3;
1109
- DEFAULT_MAX_MULTIPLIER = 1;
1110
- }
1111
- });
1112
-
1113
- // src/core/navigators/filters/index.ts
1114
- var filters_exports = {};
1115
- __export(filters_exports, {
1116
- createEloDistanceFilter: () => createEloDistanceFilter
1117
- });
1118
- var init_filters = __esm({
1119
- "src/core/navigators/filters/index.ts"() {
1120
- "use strict";
1121
- init_eloDistance();
1122
- }
1123
- });
1124
-
1125
- // src/core/navigators/filters/types.ts
1126
- var types_exports = {};
1127
- var init_types = __esm({
1128
- "src/core/navigators/filters/types.ts"() {
1129
- "use strict";
1130
- }
1131
- });
1132
-
1133
- // src/core/navigators/generators/index.ts
1134
- var generators_exports = {};
1135
- var init_generators = __esm({
1136
- "src/core/navigators/generators/index.ts"() {
1137
- "use strict";
1138
- }
1139
- });
1140
-
1141
- // src/core/navigators/generators/types.ts
1142
- var types_exports2 = {};
1143
- var init_types2 = __esm({
1144
- "src/core/navigators/generators/types.ts"() {
1145
- "use strict";
1146
- }
1147
- });
1148
-
1149
- // src/core/navigators/hardcodedOrder.ts
1150
- var hardcodedOrder_exports = {};
1151
- __export(hardcodedOrder_exports, {
1152
- default: () => HardcodedOrderNavigator
1153
- });
1154
- var HardcodedOrderNavigator;
1155
- var init_hardcodedOrder = __esm({
1156
- "src/core/navigators/hardcodedOrder.ts"() {
1142
+ // src/core/navigators/generators/srs.ts
1143
+ var import_moment3, SRSNavigator;
1144
+ var init_srs = __esm({
1145
+ "src/core/navigators/generators/srs.ts"() {
1157
1146
  "use strict";
1147
+ import_moment3 = __toESM(require("moment"), 1);
1158
1148
  init_navigators();
1159
1149
  init_logger();
1160
- HardcodedOrderNavigator = class extends ContentNavigator {
1161
- /** Human-readable name for CardGenerator interface */
1162
- name;
1163
- orderedCardIds = [];
1164
- constructor(user, course, strategyData) {
1165
- super(user, course, strategyData);
1166
- this.name = strategyData.name || "Hardcoded Order";
1167
- if (strategyData.serializedData) {
1168
- try {
1169
- this.orderedCardIds = JSON.parse(strategyData.serializedData);
1170
- } catch (e) {
1171
- logger.error("Failed to parse serializedData for HardcodedOrderNavigator", e);
1172
- }
1173
- }
1174
- }
1175
- async getPendingReviews() {
1176
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1177
- return reviews.map((r) => {
1178
- return {
1179
- ...r,
1180
- contentSourceType: "course",
1181
- contentSourceID: this.course.getCourseID(),
1182
- cardID: r.cardId,
1183
- courseID: r.courseId,
1184
- reviewID: r._id,
1185
- status: "review"
1186
- };
1187
- });
1188
- }
1189
- async getNewCards(limit = 99) {
1190
- const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
1191
- const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
1192
- const cardsToReturn = newCardIds.slice(0, limit);
1193
- return cardsToReturn.map((cardId) => {
1194
- return {
1195
- cardID: cardId,
1196
- courseID: this.course.getCourseID(),
1197
- contentSourceType: "course",
1198
- contentSourceID: this.course.getCourseID(),
1199
- status: "new"
1200
- };
1201
- });
1202
- }
1203
- /**
1204
- * Get cards in hardcoded order with scores based on position.
1205
- *
1206
- * Earlier cards in the sequence get higher scores.
1207
- * Score formula: 1.0 - (position / totalCards) * 0.5
1208
- * This ensures scores range from 1.0 (first card) to 0.5+ (last card).
1209
- *
1210
- * This method supports both the legacy signature (limit only) and the
1211
- * CardGenerator interface signature (limit, context).
1212
- *
1213
- * @param limit - Maximum number of cards to return
1214
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1215
- */
1216
- async getWeightedCards(limit, _context) {
1217
- const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
1218
- const reviews = await this.getPendingReviews();
1219
- const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
1220
- const totalCards = newCardIds.length;
1221
- const scoredNew = newCardIds.slice(0, limit).map((cardId, index) => {
1222
- const position = index + 1;
1223
- const score = Math.max(0.5, 1 - index / totalCards * 0.5);
1224
- return {
1225
- cardId,
1226
- courseId: this.course.getCourseID(),
1227
- score,
1228
- provenance: [
1229
- {
1230
- strategy: "hardcodedOrder",
1231
- strategyName: this.strategyName || this.name,
1232
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1233
- action: "generated",
1234
- score,
1235
- reason: `Position ${position} of ${totalCards} in fixed sequence, new card`
1236
- }
1237
- ]
1238
- };
1239
- });
1240
- const scoredReviews = reviews.map((r) => ({
1241
- cardId: r.cardID,
1242
- courseId: r.courseID,
1243
- score: 1,
1244
- provenance: [
1245
- {
1246
- strategy: "hardcodedOrder",
1247
- strategyName: this.strategyName || this.name,
1248
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1249
- action: "generated",
1250
- score: 1,
1251
- reason: "Scheduled review, highest priority"
1252
- }
1253
- ]
1254
- }));
1255
- const all = [...scoredReviews, ...scoredNew];
1256
- all.sort((a, b) => b.score - a.score);
1257
- return all.slice(0, limit);
1258
- }
1259
- };
1260
- }
1261
- });
1262
-
1263
- // src/core/navigators/hierarchyDefinition.ts
1264
- var hierarchyDefinition_exports = {};
1265
- __export(hierarchyDefinition_exports, {
1266
- default: () => HierarchyDefinitionNavigator
1267
- });
1268
- var import_common7, DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1269
- var init_hierarchyDefinition = __esm({
1270
- "src/core/navigators/hierarchyDefinition.ts"() {
1271
- "use strict";
1272
- init_navigators();
1273
- import_common7 = require("@vue-skuilder/common");
1274
- DEFAULT_MIN_COUNT = 3;
1275
- HierarchyDefinitionNavigator = class extends ContentNavigator {
1276
- config;
1277
- _strategyData;
1278
- /** Human-readable name for CardFilter interface */
1279
- name;
1280
- constructor(user, course, _strategyData) {
1281
- super(user, course, _strategyData);
1282
- this._strategyData = _strategyData;
1283
- this.config = this.parseConfig(_strategyData.serializedData);
1284
- this.name = _strategyData.name || "Hierarchy Definition";
1285
- }
1286
- parseConfig(serializedData) {
1287
- try {
1288
- const parsed = JSON.parse(serializedData);
1289
- return {
1290
- prerequisites: parsed.prerequisites || {}
1291
- };
1292
- } catch {
1293
- return {
1294
- prerequisites: {}
1295
- };
1296
- }
1297
- }
1298
- /**
1299
- * Check if a specific prerequisite is satisfied
1300
- */
1301
- isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1302
- if (!userTagElo) return false;
1303
- const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1304
- if (userTagElo.count < minCount) return false;
1305
- if (prereq.masteryThreshold?.minElo !== void 0) {
1306
- return userTagElo.score >= prereq.masteryThreshold.minElo;
1307
- } else {
1308
- return userTagElo.score >= userGlobalElo;
1309
- }
1310
- }
1311
- /**
1312
- * Get the set of tags the user has mastered.
1313
- * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1314
- */
1315
- async getMasteredTags(context) {
1316
- const mastered = /* @__PURE__ */ new Set();
1317
- try {
1318
- const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1319
- const userElo = (0, import_common7.toCourseElo)(courseReg.elo);
1320
- for (const prereqs of Object.values(this.config.prerequisites)) {
1321
- for (const prereq of prereqs) {
1322
- const tagElo = userElo.tags[prereq.tag];
1323
- if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1324
- mastered.add(prereq.tag);
1325
- }
1326
- }
1327
- }
1328
- } catch {
1329
- }
1330
- return mastered;
1331
- }
1332
- /**
1333
- * Get the set of tags that are unlocked (prerequisites met)
1334
- */
1335
- getUnlockedTags(masteredTags) {
1336
- const unlocked = /* @__PURE__ */ new Set();
1337
- for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1338
- const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1339
- if (allPrereqsMet) {
1340
- unlocked.add(tagId);
1341
- }
1342
- }
1343
- return unlocked;
1344
- }
1345
- /**
1346
- * Check if a tag has prerequisites defined in config
1347
- */
1348
- hasPrerequisites(tagId) {
1349
- return tagId in this.config.prerequisites;
1350
- }
1351
- /**
1352
- * Check if a card is unlocked and generate reason.
1353
- */
1354
- async checkCardUnlock(cardId, course, unlockedTags, masteredTags) {
1355
- try {
1356
- const tagResponse = await course.getAppliedTags(cardId);
1357
- const cardTags = tagResponse.rows.map((row) => row.value?.name || row.key);
1358
- const lockedTags = cardTags.filter(
1359
- (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1360
- );
1361
- if (lockedTags.length === 0) {
1362
- const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1363
- return {
1364
- isUnlocked: true,
1365
- reason: `Prerequisites met, tags: ${tagList}`
1366
- };
1367
- }
1368
- const missingPrereqs = lockedTags.flatMap((tag) => {
1369
- const prereqs = this.config.prerequisites[tag] || [];
1370
- return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1371
- });
1372
- return {
1373
- isUnlocked: false,
1374
- reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1375
- };
1376
- } catch {
1377
- return {
1378
- isUnlocked: true,
1379
- reason: "Prerequisites check skipped (tag lookup failed)"
1380
- };
1381
- }
1382
- }
1383
- /**
1384
- * CardFilter.transform implementation.
1385
- *
1386
- * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1387
- */
1388
- async transform(cards, context) {
1389
- const masteredTags = await this.getMasteredTags(context);
1390
- const unlockedTags = this.getUnlockedTags(masteredTags);
1391
- const gated = [];
1392
- for (const card of cards) {
1393
- const { isUnlocked, reason } = await this.checkCardUnlock(
1394
- card.cardId,
1395
- context.course,
1396
- unlockedTags,
1397
- masteredTags
1398
- );
1399
- const finalScore = isUnlocked ? card.score : 0;
1400
- const action = isUnlocked ? "passed" : "penalized";
1401
- gated.push({
1402
- ...card,
1403
- score: finalScore,
1404
- provenance: [
1405
- ...card.provenance,
1406
- {
1407
- strategy: "hierarchyDefinition",
1408
- strategyName: this.strategyName || this.name,
1409
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1410
- action,
1411
- score: finalScore,
1412
- reason
1413
- }
1414
- ]
1415
- });
1416
- }
1417
- return gated;
1418
- }
1419
- /**
1420
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
1421
- *
1422
- * Use transform() via Pipeline instead.
1423
- */
1424
- async getWeightedCards(_limit) {
1425
- throw new Error(
1426
- "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1427
- );
1428
- }
1429
- // Legacy methods - stub implementations since filters don't generate cards
1430
- async getNewCards(_n) {
1431
- return [];
1432
- }
1433
- async getPendingReviews() {
1434
- return [];
1435
- }
1436
- };
1437
- }
1438
- });
1439
-
1440
- // src/core/navigators/interferenceMitigator.ts
1441
- var interferenceMitigator_exports = {};
1442
- __export(interferenceMitigator_exports, {
1443
- default: () => InterferenceMitigatorNavigator
1444
- });
1445
- var import_common8, DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1446
- var init_interferenceMitigator = __esm({
1447
- "src/core/navigators/interferenceMitigator.ts"() {
1448
- "use strict";
1449
- init_navigators();
1450
- import_common8 = require("@vue-skuilder/common");
1451
- DEFAULT_MIN_COUNT2 = 10;
1452
- DEFAULT_MIN_ELAPSED_DAYS = 3;
1453
- DEFAULT_INTERFERENCE_DECAY = 0.8;
1454
- InterferenceMitigatorNavigator = class extends ContentNavigator {
1455
- config;
1456
- _strategyData;
1457
- /** Human-readable name for CardFilter interface */
1458
- name;
1459
- /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1460
- interferenceMap;
1461
- constructor(user, course, _strategyData) {
1462
- super(user, course, _strategyData);
1463
- this._strategyData = _strategyData;
1464
- this.config = this.parseConfig(_strategyData.serializedData);
1465
- this.interferenceMap = this.buildInterferenceMap();
1466
- this.name = _strategyData.name || "Interference Mitigator";
1467
- }
1468
- parseConfig(serializedData) {
1469
- try {
1470
- const parsed = JSON.parse(serializedData);
1471
- let sets = parsed.interferenceSets || [];
1472
- if (sets.length > 0 && Array.isArray(sets[0])) {
1473
- sets = sets.map((tags) => ({ tags }));
1474
- }
1475
- return {
1476
- interferenceSets: sets,
1477
- maturityThreshold: {
1478
- minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1479
- minElo: parsed.maturityThreshold?.minElo,
1480
- minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1481
- },
1482
- defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1483
- };
1484
- } catch {
1485
- return {
1486
- interferenceSets: [],
1487
- maturityThreshold: {
1488
- minCount: DEFAULT_MIN_COUNT2,
1489
- minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1490
- },
1491
- defaultDecay: DEFAULT_INTERFERENCE_DECAY
1492
- };
1493
- }
1494
- }
1495
- /**
1496
- * Build a map from each tag to its interference partners with decay coefficients.
1497
- * If tags A, B, C are in an interference group with decay 0.8, then:
1498
- * - A interferes with B (decay 0.8) and C (decay 0.8)
1499
- * - B interferes with A (decay 0.8) and C (decay 0.8)
1500
- * - etc.
1501
- */
1502
- buildInterferenceMap() {
1503
- const map = /* @__PURE__ */ new Map();
1504
- for (const group of this.config.interferenceSets) {
1505
- const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
1506
- for (const tag of group.tags) {
1507
- if (!map.has(tag)) {
1508
- map.set(tag, []);
1509
- }
1510
- const partners = map.get(tag);
1511
- for (const other of group.tags) {
1512
- if (other !== tag) {
1513
- const existing = partners.find((p) => p.partner === other);
1514
- if (existing) {
1515
- existing.decay = Math.max(existing.decay, decay);
1516
- } else {
1517
- partners.push({ partner: other, decay });
1518
- }
1519
- }
1520
- }
1521
- }
1522
- }
1523
- return map;
1524
- }
1525
- /**
1526
- * Get the set of tags that are currently immature for this user.
1527
- * A tag is immature if the user has interacted with it but hasn't
1528
- * reached the maturity threshold.
1529
- */
1530
- async getImmatureTags(context) {
1531
- const immature = /* @__PURE__ */ new Set();
1532
- try {
1533
- const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1534
- const userElo = (0, import_common8.toCourseElo)(courseReg.elo);
1535
- const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
1536
- const minElo = this.config.maturityThreshold?.minElo;
1537
- const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
1538
- const minCountForElapsed = minElapsedDays * 2;
1539
- for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
1540
- if (tagElo.count === 0) continue;
1541
- const belowCount = tagElo.count < minCount;
1542
- const belowElo = minElo !== void 0 && tagElo.score < minElo;
1543
- const belowElapsed = tagElo.count < minCountForElapsed;
1544
- if (belowCount || belowElo || belowElapsed) {
1545
- immature.add(tagId);
1546
- }
1547
- }
1548
- } catch {
1549
- }
1550
- return immature;
1551
- }
1552
- /**
1553
- * Get all tags that interfere with any immature tag, along with their decay coefficients.
1554
- * These are the tags we want to avoid introducing.
1555
- */
1556
- getTagsToAvoid(immatureTags) {
1557
- const avoid = /* @__PURE__ */ new Map();
1558
- for (const immatureTag of immatureTags) {
1559
- const partners = this.interferenceMap.get(immatureTag);
1560
- if (partners) {
1561
- for (const { partner, decay } of partners) {
1562
- if (!immatureTags.has(partner)) {
1563
- const existing = avoid.get(partner) ?? 0;
1564
- avoid.set(partner, Math.max(existing, decay));
1565
- }
1566
- }
1567
- }
1568
- }
1569
- return avoid;
1570
- }
1571
- /**
1572
- * Get tags for a single card
1573
- */
1574
- async getCardTags(cardId, course) {
1575
- try {
1576
- const tagResponse = await course.getAppliedTags(cardId);
1577
- return tagResponse.rows.map((row) => row.value?.name || row.key).filter(Boolean);
1578
- } catch {
1579
- return [];
1580
- }
1581
- }
1582
- /**
1583
- * Compute interference score reduction for a card.
1584
- * Returns: { multiplier, interfering tags, reason }
1585
- */
1586
- computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
1587
- if (tagsToAvoid.size === 0) {
1588
- return {
1589
- multiplier: 1,
1590
- interferingTags: [],
1591
- reason: "No interference detected"
1592
- };
1593
- }
1594
- let multiplier = 1;
1595
- const interferingTags = [];
1596
- for (const tag of cardTags) {
1597
- const decay = tagsToAvoid.get(tag);
1598
- if (decay !== void 0) {
1599
- interferingTags.push(tag);
1600
- multiplier *= 1 - decay;
1601
- }
1602
- }
1603
- if (interferingTags.length === 0) {
1604
- return {
1605
- multiplier: 1,
1606
- interferingTags: [],
1607
- reason: "No interference detected"
1608
- };
1609
- }
1610
- const causingTags = /* @__PURE__ */ new Set();
1611
- for (const tag of interferingTags) {
1612
- for (const immatureTag of immatureTags) {
1613
- const partners = this.interferenceMap.get(immatureTag);
1614
- if (partners?.some((p) => p.partner === tag)) {
1615
- causingTags.add(immatureTag);
1616
- }
1617
- }
1618
- }
1619
- const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
1620
- return { multiplier, interferingTags, reason };
1621
- }
1622
- /**
1623
- * CardFilter.transform implementation.
1624
- *
1625
- * Apply interference-aware scoring. Cards with tags that interfere with
1626
- * immature learnings get reduced scores.
1627
- */
1628
- async transform(cards, context) {
1629
- const immatureTags = await this.getImmatureTags(context);
1630
- const tagsToAvoid = this.getTagsToAvoid(immatureTags);
1631
- const adjusted = [];
1632
- for (const card of cards) {
1633
- const cardTags = await this.getCardTags(card.cardId, context.course);
1634
- const { multiplier, reason } = this.computeInterferenceEffect(
1635
- cardTags,
1636
- tagsToAvoid,
1637
- immatureTags
1638
- );
1639
- const finalScore = card.score * multiplier;
1640
- const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
1641
- adjusted.push({
1642
- ...card,
1643
- score: finalScore,
1644
- provenance: [
1645
- ...card.provenance,
1646
- {
1647
- strategy: "interferenceMitigator",
1648
- strategyName: this.strategyName || this.name,
1649
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
1650
- action,
1651
- score: finalScore,
1652
- reason
1653
- }
1654
- ]
1655
- });
1656
- }
1657
- return adjusted;
1658
- }
1659
- /**
1660
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
1661
- *
1662
- * Use transform() via Pipeline instead.
1663
- */
1664
- async getWeightedCards(_limit) {
1665
- throw new Error(
1666
- "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1667
- );
1668
- }
1669
- // Legacy methods - stub implementations since filters don't generate cards
1670
- async getNewCards(_n) {
1671
- return [];
1672
- }
1673
- async getPendingReviews() {
1674
- return [];
1675
- }
1676
- };
1677
- }
1678
- });
1679
-
1680
- // src/core/navigators/relativePriority.ts
1681
- var relativePriority_exports = {};
1682
- __export(relativePriority_exports, {
1683
- default: () => RelativePriorityNavigator
1684
- });
1685
- var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
1686
- var init_relativePriority = __esm({
1687
- "src/core/navigators/relativePriority.ts"() {
1688
- "use strict";
1689
- init_navigators();
1690
- DEFAULT_PRIORITY = 0.5;
1691
- DEFAULT_PRIORITY_INFLUENCE = 0.5;
1692
- DEFAULT_COMBINE_MODE = "max";
1693
- RelativePriorityNavigator = class extends ContentNavigator {
1694
- config;
1695
- _strategyData;
1696
- /** Human-readable name for CardFilter interface */
1697
- name;
1698
- constructor(user, course, _strategyData) {
1699
- super(user, course, _strategyData);
1700
- this._strategyData = _strategyData;
1701
- this.config = this.parseConfig(_strategyData.serializedData);
1702
- this.name = _strategyData.name || "Relative Priority";
1703
- }
1704
- parseConfig(serializedData) {
1705
- try {
1706
- const parsed = JSON.parse(serializedData);
1707
- return {
1708
- tagPriorities: parsed.tagPriorities || {},
1709
- defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
1710
- combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
1711
- priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
1712
- };
1713
- } catch {
1714
- return {
1715
- tagPriorities: {},
1716
- defaultPriority: DEFAULT_PRIORITY,
1717
- combineMode: DEFAULT_COMBINE_MODE,
1718
- priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
1719
- };
1720
- }
1721
- }
1722
- /**
1723
- * Look up the priority for a tag.
1724
- */
1725
- getTagPriority(tagId) {
1726
- return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
1727
- }
1728
- /**
1729
- * Compute combined priority for a card based on its tags.
1730
- */
1731
- computeCardPriority(cardTags) {
1732
- if (cardTags.length === 0) {
1733
- return this.config.defaultPriority ?? DEFAULT_PRIORITY;
1734
- }
1735
- const priorities = cardTags.map((tag) => this.getTagPriority(tag));
1736
- switch (this.config.combineMode) {
1737
- case "max":
1738
- return Math.max(...priorities);
1739
- case "min":
1740
- return Math.min(...priorities);
1741
- case "average":
1742
- return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
1743
- default:
1744
- return Math.max(...priorities);
1745
- }
1746
- }
1747
- /**
1748
- * Compute boost factor based on priority.
1749
- *
1750
- * The formula: 1 + (priority - 0.5) * priorityInfluence
1751
- *
1752
- * This creates a multiplier centered around 1.0:
1753
- * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
1754
- * - Priority 0.5 with any influence → 1.00 (neutral)
1755
- * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
1756
- */
1757
- computeBoostFactor(priority) {
1758
- const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
1759
- return 1 + (priority - 0.5) * influence;
1760
- }
1761
- /**
1762
- * Build human-readable reason for priority adjustment.
1763
- */
1764
- buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
1765
- if (cardTags.length === 0) {
1766
- return `No tags, neutral priority (${priority.toFixed(2)})`;
1767
- }
1768
- const tagList = cardTags.slice(0, 3).join(", ");
1769
- const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
1770
- if (boostFactor === 1) {
1771
- return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
1772
- } else if (boostFactor > 1) {
1773
- return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1774
- } else {
1775
- return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1776
- }
1777
- }
1778
- /**
1779
- * Get tags for a single card.
1780
- */
1781
- async getCardTags(cardId, course) {
1782
- try {
1783
- const tagResponse = await course.getAppliedTags(cardId);
1784
- return tagResponse.rows.map((r) => r.doc?.name).filter((x) => !!x);
1785
- } catch {
1786
- return [];
1787
- }
1788
- }
1789
- /**
1790
- * CardFilter.transform implementation.
1791
- *
1792
- * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
1793
- * cards with low-priority tags get reduced scores.
1794
- */
1795
- async transform(cards, context) {
1796
- const adjusted = await Promise.all(
1797
- cards.map(async (card) => {
1798
- const cardTags = await this.getCardTags(card.cardId, context.course);
1799
- const priority = this.computeCardPriority(cardTags);
1800
- const boostFactor = this.computeBoostFactor(priority);
1801
- const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
1802
- const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
1803
- const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
1804
- return {
1805
- ...card,
1806
- score: finalScore,
1807
- provenance: [
1808
- ...card.provenance,
1809
- {
1810
- strategy: "relativePriority",
1811
- strategyName: this.strategyName || this.name,
1812
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
1813
- action,
1814
- score: finalScore,
1815
- reason
1816
- }
1817
- ]
1818
- };
1819
- })
1820
- );
1821
- return adjusted;
1822
- }
1823
- /**
1824
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
1825
- *
1826
- * Use transform() via Pipeline instead.
1827
- */
1828
- async getWeightedCards(_limit) {
1829
- throw new Error(
1830
- "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1831
- );
1832
- }
1833
- // Legacy methods - stub implementations since filters don't generate cards
1834
- async getNewCards(_n) {
1835
- return [];
1836
- }
1837
- async getPendingReviews() {
1838
- return [];
1839
- }
1840
- };
1841
- }
1842
- });
1843
-
1844
- // src/core/navigators/srs.ts
1845
- var srs_exports = {};
1846
- __export(srs_exports, {
1847
- default: () => SRSNavigator
1848
- });
1849
- var import_moment3, SRSNavigator;
1850
- var init_srs = __esm({
1851
- "src/core/navigators/srs.ts"() {
1852
- "use strict";
1853
- import_moment3 = __toESM(require("moment"), 1);
1854
- init_navigators();
1855
- SRSNavigator = class extends ContentNavigator {
1150
+ SRSNavigator = class extends ContentNavigator {
1856
1151
  /** Human-readable name for CardGenerator interface */
1857
1152
  name;
1858
1153
  constructor(user, course, strategyData) {
@@ -1860,314 +1155,183 @@ var init_srs = __esm({
1860
1155
  this.name = strategyData?.name || "SRS";
1861
1156
  }
1862
1157
  /**
1863
- * Get review cards scored by urgency.
1864
- *
1865
- * Score formula combines:
1866
- * - Relative overdueness: hoursOverdue / intervalHours
1867
- * - Interval recency: exponential decay favoring shorter intervals
1868
- *
1869
- * Cards not yet due are excluded (not scored as 0).
1870
- *
1871
- * This method supports both the legacy signature (limit only) and the
1872
- * CardGenerator interface signature (limit, context).
1873
- *
1874
- * @param limit - Maximum number of cards to return
1875
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1876
- */
1877
- async getWeightedCards(limit, _context) {
1878
- if (!this.user || !this.course) {
1879
- throw new Error("SRSNavigator requires user and course to be set");
1880
- }
1881
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1882
- const now = import_moment3.default.utc();
1883
- const dueReviews = reviews.filter((r) => now.isAfter(import_moment3.default.utc(r.reviewTime)));
1884
- const scored = dueReviews.map((review) => {
1885
- const { score, reason } = this.computeUrgencyScore(review, now);
1886
- return {
1887
- cardId: review.cardId,
1888
- courseId: review.courseId,
1889
- score,
1890
- provenance: [
1891
- {
1892
- strategy: "srs",
1893
- strategyName: this.strategyName || this.name,
1894
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1895
- action: "generated",
1896
- score,
1897
- reason
1898
- }
1899
- ]
1900
- };
1901
- });
1902
- return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1903
- }
1904
- /**
1905
- * Compute urgency score for a review card.
1906
- *
1907
- * Two factors:
1908
- * 1. Relative overdueness = hoursOverdue / intervalHours
1909
- * - 2 days overdue on 3-day interval = 0.67 (urgent)
1910
- * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1911
- *
1912
- * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1913
- * - 24h interval → ~1.0 (very recent learning)
1914
- * - 30 days (720h) → ~0.56
1915
- * - 180 days → ~0.30
1916
- *
1917
- * Combined: base 0.5 + weighted average of factors * 0.45
1918
- * Result range: approximately 0.5 to 0.95
1919
- */
1920
- computeUrgencyScore(review, now) {
1921
- const scheduledAt = import_moment3.default.utc(review.scheduledAt);
1922
- const due = import_moment3.default.utc(review.reviewTime);
1923
- const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1924
- const hoursOverdue = now.diff(due, "hours");
1925
- const relativeOverdue = hoursOverdue / intervalHours;
1926
- const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1927
- const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1928
- const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1929
- const score = Math.min(0.95, 0.5 + urgency * 0.45);
1930
- const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
1931
- return { score, reason };
1932
- }
1933
- /**
1934
- * Get pending reviews in legacy format.
1935
- *
1936
- * Returns all pending reviews for the course, enriched with session item fields.
1937
- */
1938
- async getPendingReviews() {
1939
- if (!this.user || !this.course) {
1940
- throw new Error("SRSNavigator requires user and course to be set");
1941
- }
1942
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1943
- return reviews.map((r) => ({
1944
- ...r,
1945
- contentSourceType: "course",
1946
- contentSourceID: this.course.getCourseID(),
1947
- cardID: r.cardId,
1948
- courseID: r.courseId,
1949
- qualifiedID: `${r.courseId}-${r.cardId}`,
1950
- reviewID: r._id,
1951
- status: "review"
1952
- }));
1953
- }
1954
- /**
1955
- * SRS does not generate new cards.
1956
- * Use ELONavigator or another generator for new cards.
1957
- */
1958
- async getNewCards(_n) {
1959
- return [];
1960
- }
1961
- };
1962
- }
1963
- });
1964
-
1965
- // import("./**/*") in src/core/navigators/index.ts
1966
- var globImport;
1967
- var init_ = __esm({
1968
- 'import("./**/*") in src/core/navigators/index.ts'() {
1969
- globImport = __glob({
1970
- "./CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
1971
- "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
1972
- "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
1973
- "./elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
1974
- "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
1975
- "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
1976
- "./filters/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
1977
- "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
1978
- "./generators/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
1979
- "./hardcodedOrder.ts": () => Promise.resolve().then(() => (init_hardcodedOrder(), hardcodedOrder_exports)),
1980
- "./hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
1981
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
1982
- "./interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
1983
- "./relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
1984
- "./srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports))
1985
- });
1986
- }
1987
- });
1988
-
1989
- // src/core/navigators/index.ts
1990
- var navigators_exports = {};
1991
- __export(navigators_exports, {
1992
- ContentNavigator: () => ContentNavigator,
1993
- NavigatorRole: () => NavigatorRole,
1994
- NavigatorRoles: () => NavigatorRoles,
1995
- Navigators: () => Navigators,
1996
- getCardOrigin: () => getCardOrigin,
1997
- isFilter: () => isFilter,
1998
- isGenerator: () => isGenerator
1999
- });
2000
- function getCardOrigin(card) {
2001
- if (card.provenance.length === 0) {
2002
- throw new Error("Card has no provenance - cannot determine origin");
2003
- }
2004
- const firstEntry = card.provenance[0];
2005
- const reason = firstEntry.reason.toLowerCase();
2006
- if (reason.includes("failed")) {
2007
- return "failed";
2008
- }
2009
- if (reason.includes("review")) {
2010
- return "review";
2011
- }
2012
- return "new";
2013
- }
2014
- function isGenerator(impl) {
2015
- return NavigatorRoles[impl] === "generator" /* GENERATOR */;
2016
- }
2017
- function isFilter(impl) {
2018
- return NavigatorRoles[impl] === "filter" /* FILTER */;
2019
- }
2020
- var Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
2021
- var init_navigators = __esm({
2022
- "src/core/navigators/index.ts"() {
2023
- "use strict";
2024
- init_logger();
2025
- init_();
2026
- Navigators = /* @__PURE__ */ ((Navigators2) => {
2027
- Navigators2["ELO"] = "elo";
2028
- Navigators2["SRS"] = "srs";
2029
- Navigators2["HARDCODED"] = "hardcodedOrder";
2030
- Navigators2["HIERARCHY"] = "hierarchyDefinition";
2031
- Navigators2["INTERFERENCE"] = "interferenceMitigator";
2032
- Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
2033
- return Navigators2;
2034
- })(Navigators || {});
2035
- NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
2036
- NavigatorRole2["GENERATOR"] = "generator";
2037
- NavigatorRole2["FILTER"] = "filter";
2038
- return NavigatorRole2;
2039
- })(NavigatorRole || {});
2040
- NavigatorRoles = {
2041
- ["elo" /* ELO */]: "generator" /* GENERATOR */,
2042
- ["srs" /* SRS */]: "generator" /* GENERATOR */,
2043
- ["hardcodedOrder" /* HARDCODED */]: "generator" /* GENERATOR */,
2044
- ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
2045
- ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
2046
- ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */
2047
- };
2048
- ContentNavigator = class {
2049
- /** User interface for this navigation session */
2050
- user;
2051
- /** Course interface for this navigation session */
2052
- course;
2053
- /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
2054
- strategyName;
2055
- /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
2056
- strategyId;
2057
- /**
2058
- * Constructor for standard navigators.
2059
- * Call this from subclass constructors to initialize common fields.
2060
- *
2061
- * Note: CompositeGenerator doesn't use this pattern and should call super() without args.
2062
- */
2063
- constructor(user, course, strategyData) {
2064
- if (user && course && strategyData) {
2065
- this.user = user;
2066
- this.course = course;
2067
- this.strategyName = strategyData.name;
2068
- this.strategyId = strategyData._id;
2069
- }
2070
- }
2071
- /**
2072
- * Factory method to create navigator instances dynamically.
2073
- *
2074
- * @param user - User interface
2075
- * @param course - Course interface
2076
- * @param strategyData - Strategy configuration document
2077
- * @returns the runtime object used to steer a study session.
2078
- */
2079
- static async create(user, course, strategyData) {
2080
- const implementingClass = strategyData.implementingClass;
2081
- let NavigatorImpl;
2082
- const variations = [".ts", ".js", ""];
2083
- for (const ext of variations) {
2084
- try {
2085
- const module2 = await globImport(`./${implementingClass}${ext}`);
2086
- NavigatorImpl = module2.default;
2087
- break;
2088
- } catch (e) {
2089
- logger.debug(`Failed to load with extension ${ext}:`, e);
2090
- }
2091
- }
2092
- if (!NavigatorImpl) {
2093
- throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
2094
- }
2095
- return new NavigatorImpl(user, course, strategyData);
2096
- }
2097
- /**
2098
- * Get cards with suitability scores and provenance trails.
2099
- *
2100
- * **This is the PRIMARY API for navigation strategies.**
2101
- *
2102
- * Returns cards ranked by suitability score (0-1). Higher scores indicate
2103
- * better candidates for presentation. Each card includes a provenance trail
2104
- * documenting how strategies contributed to the final score.
1158
+ * Get review cards scored by urgency.
2105
1159
  *
2106
- * ## For Generators
2107
- * Override this method to generate candidates and compute scores based on
2108
- * your strategy's logic (e.g., ELO proximity, review urgency). Create the
2109
- * initial provenance entry with action='generated'.
1160
+ * Score formula combines:
1161
+ * - Relative overdueness: hoursOverdue / intervalHours
1162
+ * - Interval recency: exponential decay favoring shorter intervals
2110
1163
  *
2111
- * ## Default Implementation
2112
- * The base class provides a backward-compatible default that:
2113
- * 1. Calls legacy getNewCards() and getPendingReviews()
2114
- * 2. Assigns score=1.0 to all cards
2115
- * 3. Creates minimal provenance from legacy methods
2116
- * 4. Returns combined results up to limit
1164
+ * Cards not yet due are excluded (not scored as 0).
2117
1165
  *
2118
- * This allows existing strategies to work without modification while
2119
- * new strategies can override with proper scoring and provenance.
1166
+ * This method supports both the legacy signature (limit only) and the
1167
+ * CardGenerator interface signature (limit, context).
2120
1168
  *
2121
- * @param limit - Maximum cards to return
2122
- * @returns Cards sorted by score descending, with provenance trails
1169
+ * @param limit - Maximum number of cards to return
1170
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
2123
1171
  */
2124
- async getWeightedCards(limit) {
2125
- const newCards = await this.getNewCards(limit);
2126
- const reviews = await this.getPendingReviews();
2127
- const weighted = [
2128
- ...newCards.map((c) => ({
2129
- cardId: c.cardID,
2130
- courseId: c.courseID,
2131
- score: 1,
2132
- provenance: [
2133
- {
2134
- strategy: "legacy",
2135
- strategyName: this.strategyName || "Legacy API",
2136
- strategyId: this.strategyId || "legacy-fallback",
2137
- action: "generated",
2138
- score: 1,
2139
- reason: "Generated via legacy getNewCards(), new card"
2140
- }
2141
- ]
2142
- })),
2143
- ...reviews.map((r) => ({
2144
- cardId: r.cardID,
2145
- courseId: r.courseID,
2146
- score: 1,
1172
+ async getWeightedCards(limit, _context) {
1173
+ if (!this.user || !this.course) {
1174
+ throw new Error("SRSNavigator requires user and course to be set");
1175
+ }
1176
+ const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1177
+ const now = import_moment3.default.utc();
1178
+ const dueReviews = reviews.filter((r) => now.isAfter(import_moment3.default.utc(r.reviewTime)));
1179
+ const scored = dueReviews.map((review) => {
1180
+ const { score, reason } = this.computeUrgencyScore(review, now);
1181
+ return {
1182
+ cardId: review.cardId,
1183
+ courseId: review.courseId,
1184
+ score,
1185
+ reviewID: review._id,
2147
1186
  provenance: [
2148
1187
  {
2149
- strategy: "legacy",
2150
- strategyName: this.strategyName || "Legacy API",
2151
- strategyId: this.strategyId || "legacy-fallback",
1188
+ strategy: "srs",
1189
+ strategyName: this.strategyName || this.name,
1190
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
2152
1191
  action: "generated",
2153
- score: 1,
2154
- reason: "Generated via legacy getPendingReviews(), review"
1192
+ score,
1193
+ reason
2155
1194
  }
2156
1195
  ]
2157
- }))
2158
- ];
2159
- return weighted.slice(0, limit);
1196
+ };
1197
+ });
1198
+ logger.debug(`[srsNav] got ${scored.length} weighted cards`);
1199
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1200
+ }
1201
+ /**
1202
+ * Compute urgency score for a review card.
1203
+ *
1204
+ * Two factors:
1205
+ * 1. Relative overdueness = hoursOverdue / intervalHours
1206
+ * - 2 days overdue on 3-day interval = 0.67 (urgent)
1207
+ * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1208
+ *
1209
+ * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1210
+ * - 24h interval → ~1.0 (very recent learning)
1211
+ * - 30 days (720h) → ~0.56
1212
+ * - 180 days → ~0.30
1213
+ *
1214
+ * Combined: base 0.5 + weighted average of factors * 0.45
1215
+ * Result range: approximately 0.5 to 0.95
1216
+ */
1217
+ computeUrgencyScore(review, now) {
1218
+ const scheduledAt = import_moment3.default.utc(review.scheduledAt);
1219
+ const due = import_moment3.default.utc(review.reviewTime);
1220
+ const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1221
+ const hoursOverdue = now.diff(due, "hours");
1222
+ const relativeOverdue = hoursOverdue / intervalHours;
1223
+ const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1224
+ const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1225
+ const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1226
+ const score = Math.min(0.95, 0.5 + urgency * 0.45);
1227
+ const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
1228
+ return { score, reason };
2160
1229
  }
2161
1230
  };
2162
1231
  }
2163
1232
  });
2164
1233
 
1234
+ // src/core/navigators/filters/eloDistance.ts
1235
+ function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1236
+ const normalizedDistance = distance / halfLife;
1237
+ const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1238
+ return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1239
+ }
1240
+ function createEloDistanceFilter(config) {
1241
+ const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1242
+ const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1243
+ const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1244
+ return {
1245
+ name: "ELO Distance Filter",
1246
+ async transform(cards, context) {
1247
+ const { course, userElo } = context;
1248
+ const cardIds = cards.map((c) => c.cardId);
1249
+ const cardElos = await course.getCardEloData(cardIds);
1250
+ return cards.map((card, i) => {
1251
+ const cardElo = cardElos[i]?.global?.score ?? 1e3;
1252
+ const distance = Math.abs(cardElo - userElo);
1253
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1254
+ const newScore = card.score * multiplier;
1255
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1256
+ return {
1257
+ ...card,
1258
+ score: newScore,
1259
+ provenance: [
1260
+ ...card.provenance,
1261
+ {
1262
+ strategy: "eloDistance",
1263
+ strategyName: "ELO Distance Filter",
1264
+ strategyId: "ELO_DISTANCE_FILTER",
1265
+ action,
1266
+ score: newScore,
1267
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1268
+ }
1269
+ ]
1270
+ };
1271
+ });
1272
+ }
1273
+ };
1274
+ }
1275
+ var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1276
+ var init_eloDistance = __esm({
1277
+ "src/core/navigators/filters/eloDistance.ts"() {
1278
+ "use strict";
1279
+ DEFAULT_HALF_LIFE = 200;
1280
+ DEFAULT_MIN_MULTIPLIER = 0.3;
1281
+ DEFAULT_MAX_MULTIPLIER = 1;
1282
+ }
1283
+ });
1284
+
1285
+ // src/core/navigators/defaults.ts
1286
+ function createDefaultEloStrategy(courseId) {
1287
+ return {
1288
+ _id: "NAVIGATION_STRATEGY-ELO-default",
1289
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1290
+ name: "ELO (default)",
1291
+ description: "Default ELO-based navigation strategy for new cards",
1292
+ implementingClass: "elo" /* ELO */,
1293
+ course: courseId,
1294
+ serializedData: ""
1295
+ };
1296
+ }
1297
+ function createDefaultSrsStrategy(courseId) {
1298
+ return {
1299
+ _id: "NAVIGATION_STRATEGY-SRS-default",
1300
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1301
+ name: "SRS (default)",
1302
+ description: "Default SRS-based navigation strategy for reviews",
1303
+ implementingClass: "srs" /* SRS */,
1304
+ course: courseId,
1305
+ serializedData: ""
1306
+ };
1307
+ }
1308
+ function createDefaultPipeline(user, course) {
1309
+ const courseId = course.getCourseID();
1310
+ const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
1311
+ const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
1312
+ const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
1313
+ const eloDistanceFilter = createEloDistanceFilter();
1314
+ return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
1315
+ }
1316
+ var init_defaults = __esm({
1317
+ "src/core/navigators/defaults.ts"() {
1318
+ "use strict";
1319
+ init_navigators();
1320
+ init_Pipeline();
1321
+ init_CompositeGenerator();
1322
+ init_elo();
1323
+ init_srs();
1324
+ init_eloDistance();
1325
+ init_types_legacy();
1326
+ }
1327
+ });
1328
+
2165
1329
  // src/impl/couch/courseDB.ts
2166
- var import_common9;
1330
+ var import_common7;
2167
1331
  var init_courseDB = __esm({
2168
1332
  "src/impl/couch/courseDB.ts"() {
2169
1333
  "use strict";
2170
- import_common9 = require("@vue-skuilder/common");
1334
+ import_common7 = require("@vue-skuilder/common");
2171
1335
  init_couch();
2172
1336
  init_updateQueue();
2173
1337
  init_types_legacy();
@@ -2176,12 +1340,8 @@ var init_courseDB = __esm({
2176
1340
  init_courseAPI();
2177
1341
  init_courseLookupDB();
2178
1342
  init_navigators();
2179
- init_Pipeline();
2180
1343
  init_PipelineAssembler();
2181
- init_CompositeGenerator();
2182
- init_elo();
2183
- init_srs();
2184
- init_eloDistance();
1344
+ init_defaults();
2185
1345
  }
2186
1346
  });
2187
1347
 
@@ -2224,14 +1384,14 @@ var init_auth = __esm({
2224
1384
  });
2225
1385
 
2226
1386
  // src/impl/couch/CouchDBSyncStrategy.ts
2227
- var import_common10;
1387
+ var import_common8;
2228
1388
  var init_CouchDBSyncStrategy = __esm({
2229
1389
  "src/impl/couch/CouchDBSyncStrategy.ts"() {
2230
1390
  "use strict";
2231
1391
  init_factory();
2232
1392
  init_types_legacy();
2233
1393
  init_logger();
2234
- import_common10 = require("@vue-skuilder/common");
1394
+ import_common8 = require("@vue-skuilder/common");
2235
1395
  init_common();
2236
1396
  init_pouchdb_setup();
2237
1397
  init_couch();
@@ -2295,7 +1455,9 @@ var init_couch = __esm({
2295
1455
  function accomodateGuest() {
2296
1456
  logger.log("[funnel] accomodateGuest() called");
2297
1457
  if (typeof localStorage === "undefined") {
2298
- logger.log("[funnel] localStorage not available (Node.js environment), returning default guest");
1458
+ logger.log(
1459
+ "[funnel] localStorage not available (Node.js environment), returning default guest"
1460
+ );
2299
1461
  return {
2300
1462
  username: GuestUsername + "nodejs-test",
2301
1463
  firstVisit: true
@@ -2463,13 +1625,13 @@ async function dropUserFromClassroom(user, classID) {
2463
1625
  async function getUserClassrooms(user) {
2464
1626
  return getOrCreateClassroomRegistrationsDoc(user);
2465
1627
  }
2466
- var import_common12, import_moment6, log3, BaseUser, userCoursesDoc, userClassroomsDoc;
1628
+ var import_common10, import_moment6, log3, BaseUser, userCoursesDoc, userClassroomsDoc;
2467
1629
  var init_BaseUserDB = __esm({
2468
1630
  "src/impl/common/BaseUserDB.ts"() {
2469
1631
  "use strict";
2470
1632
  init_core();
2471
1633
  init_util();
2472
- import_common12 = require("@vue-skuilder/common");
1634
+ import_common10 = require("@vue-skuilder/common");
2473
1635
  import_moment6 = __toESM(require("moment"), 1);
2474
1636
  init_types_legacy();
2475
1637
  init_logger();
@@ -2519,7 +1681,7 @@ Currently logged-in as ${this._username}.`
2519
1681
  );
2520
1682
  }
2521
1683
  const result = await this.syncStrategy.createAccount(username, password);
2522
- if (result.status === import_common12.Status.ok) {
1684
+ if (result.status === import_common10.Status.ok) {
2523
1685
  log3(`Account created successfully, updating username to ${username}`);
2524
1686
  this._username = username;
2525
1687
  try {
@@ -2561,7 +1723,7 @@ Currently logged-in as ${this._username}.`
2561
1723
  async resetUserData() {
2562
1724
  if (this.syncStrategy.canAuthenticate()) {
2563
1725
  return {
2564
- status: import_common12.Status.error,
1726
+ status: import_common10.Status.error,
2565
1727
  error: "Reset user data is only available for local-only mode. Use logout instead for remote sync."
2566
1728
  };
2567
1729
  }
@@ -2580,11 +1742,11 @@ Currently logged-in as ${this._username}.`
2580
1742
  await localDB.bulkDocs(docsToDelete);
2581
1743
  }
2582
1744
  await this.init();
2583
- return { status: import_common12.Status.ok };
1745
+ return { status: import_common10.Status.ok };
2584
1746
  } catch (error) {
2585
1747
  logger.error("Failed to reset user data:", error);
2586
1748
  return {
2587
- status: import_common12.Status.error,
1749
+ status: import_common10.Status.error,
2588
1750
  error: error instanceof Error ? error.message : "Unknown error during reset"
2589
1751
  };
2590
1752
  }
@@ -3275,6 +2437,55 @@ Currently logged-in as ${this._username}.`
3275
2437
  async updateUserElo(courseId, elo) {
3276
2438
  return updateUserElo(this._username, courseId, elo);
3277
2439
  }
2440
+ async getStrategyState(courseId, strategyKey) {
2441
+ const docId = buildStrategyStateId(courseId, strategyKey);
2442
+ try {
2443
+ const doc = await this.localDB.get(docId);
2444
+ return doc.data;
2445
+ } catch (e) {
2446
+ const err = e;
2447
+ if (err.status === 404) {
2448
+ return null;
2449
+ }
2450
+ throw e;
2451
+ }
2452
+ }
2453
+ async putStrategyState(courseId, strategyKey, data) {
2454
+ const docId = buildStrategyStateId(courseId, strategyKey);
2455
+ let existingRev;
2456
+ try {
2457
+ const existing = await this.localDB.get(docId);
2458
+ existingRev = existing._rev;
2459
+ } catch (e) {
2460
+ const err = e;
2461
+ if (err.status !== 404) {
2462
+ throw e;
2463
+ }
2464
+ }
2465
+ const doc = {
2466
+ _id: docId,
2467
+ _rev: existingRev,
2468
+ docType: "STRATEGY_STATE" /* STRATEGY_STATE */,
2469
+ courseId,
2470
+ strategyKey,
2471
+ data,
2472
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2473
+ };
2474
+ await this.localDB.put(doc);
2475
+ }
2476
+ async deleteStrategyState(courseId, strategyKey) {
2477
+ const docId = buildStrategyStateId(courseId, strategyKey);
2478
+ try {
2479
+ const doc = await this.localDB.get(docId);
2480
+ await this.localDB.remove(doc);
2481
+ } catch (e) {
2482
+ const err = e;
2483
+ if (err.status === 404) {
2484
+ return;
2485
+ }
2486
+ throw e;
2487
+ }
2488
+ }
3278
2489
  };
3279
2490
  userCoursesDoc = "CourseRegistrations";
3280
2491
  userClassroomsDoc = "ClassroomRegistrations";
@@ -3308,24 +2519,24 @@ var init_factory = __esm({
3308
2519
  });
3309
2520
 
3310
2521
  // src/study/TagFilteredContentSource.ts
3311
- var import_common14;
2522
+ var import_common12;
3312
2523
  var init_TagFilteredContentSource = __esm({
3313
2524
  "src/study/TagFilteredContentSource.ts"() {
3314
2525
  "use strict";
3315
- import_common14 = require("@vue-skuilder/common");
2526
+ import_common12 = require("@vue-skuilder/common");
3316
2527
  init_courseDB();
3317
2528
  init_logger();
3318
2529
  }
3319
2530
  });
3320
2531
 
3321
2532
  // src/core/interfaces/contentSource.ts
3322
- var import_common15;
2533
+ var import_common13;
3323
2534
  var init_contentSource = __esm({
3324
2535
  "src/core/interfaces/contentSource.ts"() {
3325
2536
  "use strict";
3326
2537
  init_factory();
3327
2538
  init_classroomDB2();
3328
- import_common15 = require("@vue-skuilder/common");
2539
+ import_common13 = require("@vue-skuilder/common");
3329
2540
  init_TagFilteredContentSource();
3330
2541
  }
3331
2542
  });
@@ -3371,18 +2582,28 @@ var init_user = __esm({
3371
2582
  }
3372
2583
  });
3373
2584
 
2585
+ // src/core/types/strategyState.ts
2586
+ function buildStrategyStateId(courseId, strategyKey) {
2587
+ return `STRATEGY_STATE::${courseId}::${strategyKey}`;
2588
+ }
2589
+ var init_strategyState = __esm({
2590
+ "src/core/types/strategyState.ts"() {
2591
+ "use strict";
2592
+ }
2593
+ });
2594
+
3374
2595
  // src/core/bulkImport/cardProcessor.ts
3375
- var import_common16;
2596
+ var import_common14;
3376
2597
  var init_cardProcessor = __esm({
3377
2598
  "src/core/bulkImport/cardProcessor.ts"() {
3378
2599
  "use strict";
3379
- import_common16 = require("@vue-skuilder/common");
2600
+ import_common14 = require("@vue-skuilder/common");
3380
2601
  init_logger();
3381
2602
  }
3382
2603
  });
3383
2604
 
3384
2605
  // src/core/bulkImport/types.ts
3385
- var init_types3 = __esm({
2606
+ var init_types = __esm({
3386
2607
  "src/core/bulkImport/types.ts"() {
3387
2608
  "use strict";
3388
2609
  }
@@ -3393,7 +2614,7 @@ var init_bulkImport = __esm({
3393
2614
  "src/core/bulkImport/index.ts"() {
3394
2615
  "use strict";
3395
2616
  init_cardProcessor();
3396
- init_types3();
2617
+ init_types();
3397
2618
  }
3398
2619
  });
3399
2620
 
@@ -3404,6 +2625,7 @@ var init_core = __esm({
3404
2625
  init_interfaces();
3405
2626
  init_types_legacy();
3406
2627
  init_user();
2628
+ init_strategyState();
3407
2629
  init_Loggable();
3408
2630
  init_util();
3409
2631
  init_navigators();
@@ -3470,6 +2692,36 @@ var init_StaticDataUnpacker = __esm({
3470
2692
  logger.error(`Document ${id} not found in chunk ${chunk.id}`);
3471
2693
  throw new Error(`Document ${id} not found in chunk ${chunk.id}`);
3472
2694
  }
2695
+ /**
2696
+ * Get all documents with IDs starting with a specific prefix.
2697
+ *
2698
+ * This method loads the relevant chunk(s) and returns all matching documents.
2699
+ * Useful for querying documents by type (e.g., all NAVIGATION_STRATEGY documents).
2700
+ *
2701
+ * @param prefix - Document ID prefix to match (e.g., "NAVIGATION_STRATEGY")
2702
+ * @returns Array of all documents with IDs starting with the prefix
2703
+ */
2704
+ async getAllDocumentsByPrefix(prefix) {
2705
+ const relevantChunks = this.manifest.chunks.filter((chunk) => {
2706
+ const prefixEnd = prefix + "\uFFF0";
2707
+ return chunk.startKey <= prefixEnd && chunk.endKey >= prefix;
2708
+ });
2709
+ if (relevantChunks.length === 0) {
2710
+ logger.debug(`[StaticDataUnpacker] No chunks found for prefix: ${prefix}`);
2711
+ return [];
2712
+ }
2713
+ await Promise.all(relevantChunks.map((chunk) => this.loadChunk(chunk.id)));
2714
+ const matchingDocs = [];
2715
+ for (const [docId, doc] of this.documentCache.entries()) {
2716
+ if (docId.startsWith(prefix)) {
2717
+ matchingDocs.push(await this.hydrateAttachments(doc));
2718
+ }
2719
+ }
2720
+ logger.debug(
2721
+ `[StaticDataUnpacker] Found ${matchingDocs.length} documents with prefix: ${prefix}`
2722
+ );
2723
+ return matchingDocs;
2724
+ }
3473
2725
  /**
3474
2726
  * Query cards by ELO score, returning card IDs sorted by ELO
3475
2727
  */
@@ -3506,7 +2758,14 @@ var init_StaticDataUnpacker = __esm({
3506
2758
  * Get all tag names mapped to their card arrays
3507
2759
  */
3508
2760
  async getTagsIndex() {
3509
- return await this.loadIndex("tags");
2761
+ try {
2762
+ return await this.loadIndex("tags");
2763
+ } catch {
2764
+ return {
2765
+ byCard: {},
2766
+ byTag: {}
2767
+ };
2768
+ }
3510
2769
  }
3511
2770
  getDocTypeFromId(id) {
3512
2771
  for (const docTypeKey in DocTypePrefixes) {
@@ -3791,14 +3050,15 @@ var init_StaticDataUnpacker = __esm({
3791
3050
  });
3792
3051
 
3793
3052
  // src/impl/static/courseDB.ts
3794
- var import_common17, StaticCourseDB;
3053
+ var import_common15, StaticCourseDB;
3795
3054
  var init_courseDB3 = __esm({
3796
3055
  "src/impl/static/courseDB.ts"() {
3797
3056
  "use strict";
3798
- import_common17 = require("@vue-skuilder/common");
3057
+ import_common15 = require("@vue-skuilder/common");
3799
3058
  init_types_legacy();
3800
- init_navigators();
3801
3059
  init_logger();
3060
+ init_defaults();
3061
+ init_PipelineAssembler();
3802
3062
  StaticCourseDB = class {
3803
3063
  constructor(courseId, unpacker, userDB, manifest) {
3804
3064
  this.courseId = courseId;
@@ -3877,21 +3137,6 @@ var init_courseDB3 = __esm({
3877
3137
  async updateCardElo(cardId, _elo) {
3878
3138
  return { ok: true, id: cardId, rev: "1-static" };
3879
3139
  }
3880
- async getNewCards(limit = 99) {
3881
- const activeCards = await this.userDB.getActiveCards();
3882
- return (await this.getCardsCenteredAtELO({ limit, elo: "user" }, (c) => {
3883
- if (activeCards.some((ac) => c.cardID === ac.cardID)) {
3884
- return false;
3885
- } else {
3886
- return true;
3887
- }
3888
- })).map((c) => {
3889
- return {
3890
- ...c,
3891
- status: "new"
3892
- };
3893
- });
3894
- }
3895
3140
  async getCardsCenteredAtELO(options, filter) {
3896
3141
  let targetElo = typeof options.elo === "number" ? options.elo : 1e3;
3897
3142
  if (options.elo === "user") {
@@ -3976,6 +3221,14 @@ var init_courseDB3 = __esm({
3976
3221
  };
3977
3222
  }
3978
3223
  }
3224
+ async getAppliedTagsBatch(cardIds) {
3225
+ const tagsIndex = await this.unpacker.getTagsIndex();
3226
+ const tagsByCard = /* @__PURE__ */ new Map();
3227
+ for (const cardId of cardIds) {
3228
+ tagsByCard.set(cardId, tagsIndex.byCard[cardId] || []);
3229
+ }
3230
+ return tagsByCard;
3231
+ }
3979
3232
  async addTagToCard(_cardId, _tagId) {
3980
3233
  throw new Error("Cannot modify tags in static mode");
3981
3234
  }
@@ -4058,7 +3311,7 @@ var init_courseDB3 = __esm({
4058
3311
  }
4059
3312
  async addNote(_codeCourse, _shape, _data, _author, _tags, _uploads, _elo) {
4060
3313
  return {
4061
- status: import_common17.Status.error,
3314
+ status: import_common15.Status.error,
4062
3315
  message: "Cannot add notes in static mode"
4063
3316
  };
4064
3317
  }
@@ -4069,19 +3322,23 @@ var init_courseDB3 = __esm({
4069
3322
  return [];
4070
3323
  }
4071
3324
  // Navigation Strategy Manager implementation
4072
- async getNavigationStrategy(_id) {
4073
- return {
4074
- _id: "NAVIGATION_STRATEGY-ELO",
4075
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
4076
- name: "ELO",
4077
- description: "ELO-based navigation strategy",
4078
- implementingClass: "elo" /* ELO */,
4079
- course: this.courseId,
4080
- serializedData: ""
4081
- };
3325
+ async getNavigationStrategy(id) {
3326
+ try {
3327
+ return await this.unpacker.getDocument(id);
3328
+ } catch (error) {
3329
+ logger.error(`[static/courseDB] Strategy ${id} not found: ${error}`);
3330
+ throw error;
3331
+ }
4082
3332
  }
4083
3333
  async getAllNavigationStrategies() {
4084
- return [await this.getNavigationStrategy("ELO")];
3334
+ const prefix = DocTypePrefixes["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */];
3335
+ try {
3336
+ const docs = await this.unpacker.getAllDocumentsByPrefix(prefix);
3337
+ return docs;
3338
+ } catch (error) {
3339
+ logger.warn(`[static/courseDB] Error loading navigation strategies: ${error}`);
3340
+ return [];
3341
+ }
4085
3342
  }
4086
3343
  async addNavigationStrategy(_data) {
4087
3344
  throw new Error("Cannot add navigation strategies in static mode");
@@ -4089,9 +3346,52 @@ var init_courseDB3 = __esm({
4089
3346
  async updateNavigationStrategy(_id, _data) {
4090
3347
  throw new Error("Cannot update navigation strategies in static mode");
4091
3348
  }
3349
+ /**
3350
+ * Create a ContentNavigator for this course.
3351
+ *
3352
+ * Loads navigation strategy documents from static data and uses PipelineAssembler
3353
+ * to build a Pipeline. Falls back to default pipeline if no strategies found.
3354
+ */
3355
+ async createNavigator(user) {
3356
+ try {
3357
+ const allStrategies = await this.getAllNavigationStrategies();
3358
+ if (allStrategies.length === 0) {
3359
+ logger.debug(
3360
+ "[static/courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])"
3361
+ );
3362
+ return createDefaultPipeline(user, this);
3363
+ }
3364
+ const assembler = new PipelineAssembler();
3365
+ const { pipeline, generatorStrategies, filterStrategies, warnings } = await assembler.assemble({
3366
+ strategies: allStrategies,
3367
+ user,
3368
+ course: this
3369
+ });
3370
+ for (const warning of warnings) {
3371
+ logger.warn(`[PipelineAssembler] ${warning}`);
3372
+ }
3373
+ if (!pipeline) {
3374
+ logger.debug("[static/courseDB] Pipeline assembly failed, using default pipeline");
3375
+ return createDefaultPipeline(user, this);
3376
+ }
3377
+ logger.debug(
3378
+ `[static/courseDB] Using assembled pipeline with ${generatorStrategies.length} generator(s) and ${filterStrategies.length} filter(s)`
3379
+ );
3380
+ return pipeline;
3381
+ } catch (e) {
3382
+ logger.error(`[static/courseDB] Error creating navigator: ${e}`);
3383
+ throw e;
3384
+ }
3385
+ }
4092
3386
  // Study Content Source implementation
4093
- async getPendingReviews() {
4094
- return [];
3387
+ async getWeightedCards(limit) {
3388
+ try {
3389
+ const navigator = await this.createNavigator(this.userDB);
3390
+ return navigator.getWeightedCards(limit);
3391
+ } catch (e) {
3392
+ logger.error(`[static/courseDB] Error getting weighted cards: ${e}`);
3393
+ throw e;
3394
+ }
4095
3395
  }
4096
3396
  // Attachment helper methods (internal use, not part of interface)
4097
3397
  /**