@vue-skuilder/db 0.1.20 → 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 (70) hide show
  1. package/CLAUDE.md +2 -2
  2. package/dist/{classroomDB-CZdMBiTU.d.ts → contentSource-BP9hznNV.d.ts} +150 -196
  3. package/dist/{classroomDB-PxDZTky3.d.cts → contentSource-DsJadoBU.d.cts} +150 -196
  4. package/dist/core/index.d.cts +3 -3
  5. package/dist/core/index.d.ts +3 -3
  6. package/dist/core/index.js +615 -1758
  7. package/dist/core/index.js.map +1 -1
  8. package/dist/core/index.mjs +579 -1727
  9. package/dist/core/index.mjs.map +1 -1
  10. package/dist/{dataLayerProvider-D8o6ZnKW.d.ts → dataLayerProvider-CHYrQ5pB.d.cts} +1 -1
  11. package/dist/{dataLayerProvider-D0MoZMjH.d.cts → dataLayerProvider-MDTxXq2l.d.ts} +1 -1
  12. package/dist/impl/couch/index.d.cts +6 -22
  13. package/dist/impl/couch/index.d.ts +6 -22
  14. package/dist/impl/couch/index.js +598 -1769
  15. package/dist/impl/couch/index.js.map +1 -1
  16. package/dist/impl/couch/index.mjs +579 -1755
  17. package/dist/impl/couch/index.mjs.map +1 -1
  18. package/dist/impl/static/index.d.cts +22 -6
  19. package/dist/impl/static/index.d.ts +22 -6
  20. package/dist/impl/static/index.js +617 -1629
  21. package/dist/impl/static/index.js.map +1 -1
  22. package/dist/impl/static/index.mjs +607 -1624
  23. package/dist/impl/static/index.mjs.map +1 -1
  24. package/dist/index.d.cts +64 -56
  25. package/dist/index.d.ts +64 -56
  26. package/dist/index.js +1000 -2161
  27. package/dist/index.js.map +1 -1
  28. package/dist/index.mjs +970 -2127
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/pouch/index.js +3 -0
  31. package/dist/pouch/index.js.map +1 -1
  32. package/dist/pouch/index.mjs +3 -0
  33. package/dist/pouch/index.mjs.map +1 -1
  34. package/docs/navigators-architecture.md +2 -9
  35. package/package.json +3 -3
  36. package/src/core/interfaces/classroomDB.ts +5 -13
  37. package/src/core/interfaces/contentSource.ts +6 -66
  38. package/src/core/interfaces/courseDB.ts +2 -7
  39. package/src/core/navigators/Pipeline.ts +24 -53
  40. package/src/core/navigators/PipelineAssembler.ts +1 -1
  41. package/src/core/navigators/defaults.ts +84 -0
  42. package/src/core/navigators/{hierarchyDefinition.ts → filters/hierarchyDefinition.ts} +11 -25
  43. package/src/core/navigators/{interferenceMitigator.ts → filters/interferenceMitigator.ts} +10 -24
  44. package/src/core/navigators/{relativePriority.ts → filters/relativePriority.ts} +10 -24
  45. package/src/core/navigators/filters/userTagPreference.ts +1 -16
  46. package/src/core/navigators/{CompositeGenerator.ts → generators/CompositeGenerator.ts} +15 -64
  47. package/src/core/navigators/{elo.ts → generators/elo.ts} +13 -63
  48. package/src/core/navigators/{srs.ts → generators/srs.ts} +11 -40
  49. package/src/core/navigators/generators/types.ts +1 -1
  50. package/src/core/navigators/index.ts +36 -91
  51. package/src/impl/couch/classroomDB.ts +100 -103
  52. package/src/impl/couch/courseDB.ts +5 -81
  53. package/src/impl/couch/pouchdb-setup.ts +7 -0
  54. package/src/impl/static/StaticDataUnpacker.ts +50 -1
  55. package/src/impl/static/courseDB.ts +76 -37
  56. package/src/study/SessionController.ts +122 -202
  57. package/src/study/SourceMixer.ts +65 -0
  58. package/src/study/TagFilteredContentSource.ts +49 -92
  59. package/src/study/index.ts +1 -0
  60. package/src/study/services/CardHydrationService.ts +165 -81
  61. package/src/util/dataDirectory.ts +1 -1
  62. package/src/util/index.ts +0 -1
  63. package/tests/core/navigators/CompositeGenerator.test.ts +44 -168
  64. package/tests/core/navigators/Pipeline.test.ts +5 -72
  65. package/tests/core/navigators/PipelineAssembler.test.ts +8 -58
  66. package/tests/core/navigators/navigators.test.ts +118 -151
  67. package/src/core/navigators/hardcodedOrder.ts +0 -163
  68. package/src/util/tuiLogger.ts +0 -139
  69. /package/src/core/navigators/{inferredPreference.ts → filters/inferredPreferenceStub.ts} +0 -0
  70. /package/src/core/navigators/{userGoal.ts → filters/userGoalStub.ts} +0 -0
@@ -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
  };
@@ -146,6 +141,9 @@ var init_pouchdb_setup = __esm({
146
141
  import_pouchdb_authentication = __toESM(require("@nilock2/pouchdb-authentication"), 1);
147
142
  import_pouchdb.default.plugin(import_pouchdb_find.default);
148
143
  import_pouchdb.default.plugin(import_pouchdb_authentication.default);
144
+ if (typeof import_pouchdb.default.debug !== "undefined") {
145
+ import_pouchdb.default.debug.disable();
146
+ }
149
147
  import_pouchdb.default.defaults({
150
148
  // ajax: {
151
149
  // timeout: 60000,
@@ -155,14 +153,6 @@ var init_pouchdb_setup = __esm({
155
153
  }
156
154
  });
157
155
 
158
- // src/util/tuiLogger.ts
159
- var init_tuiLogger = __esm({
160
- "src/util/tuiLogger.ts"() {
161
- "use strict";
162
- init_dataDirectory();
163
- }
164
- });
165
-
166
156
  // src/util/dataDirectory.ts
167
157
  function getAppDataDirectory() {
168
158
  if (ENV.LOCAL_STORAGE_PREFIX) {
@@ -180,7 +170,7 @@ var init_dataDirectory = __esm({
180
170
  "use strict";
181
171
  path = __toESM(require("path"), 1);
182
172
  os = __toESM(require("os"), 1);
183
- init_tuiLogger();
173
+ init_logger();
184
174
  init_factory();
185
175
  }
186
176
  });
@@ -500,195 +490,159 @@ var init_courseLookupDB = __esm({
500
490
  }
501
491
  });
502
492
 
503
- // src/core/navigators/CompositeGenerator.ts
504
- var CompositeGenerator_exports = {};
505
- __export(CompositeGenerator_exports, {
506
- AggregationMode: () => AggregationMode,
507
- default: () => CompositeGenerator
508
- });
509
- var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
510
- var init_CompositeGenerator = __esm({
511
- "src/core/navigators/CompositeGenerator.ts"() {
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"() {
512
503
  "use strict";
513
- init_navigators();
514
504
  init_logger();
515
- AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
516
- AggregationMode2["MAX"] = "max";
517
- AggregationMode2["AVERAGE"] = "average";
518
- AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
519
- return AggregationMode2;
520
- })(AggregationMode || {});
521
- DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
522
- FREQUENCY_BOOST_FACTOR = 0.1;
523
- CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
524
- /** Human-readable name for CardGenerator interface */
525
- name = "Composite Generator";
526
- generators;
527
- aggregationMode;
528
- constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
529
- super();
530
- this.generators = generators;
531
- this.aggregationMode = aggregationMode;
532
- if (generators.length === 0) {
533
- throw new Error("CompositeGenerator requires at least one generator");
534
- }
535
- logger.debug(
536
- `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
537
- );
538
- }
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;
539
522
  /**
540
- * Creates a CompositeGenerator from strategy data.
523
+ * Constructor for standard navigators.
524
+ * Call this from subclass constructors to initialize common fields.
541
525
  *
542
- * This is a convenience factory for use by PipelineAssembler.
526
+ * Note: CompositeGenerator and Pipeline call super() without args, then set
527
+ * user/course fields directly if needed.
543
528
  */
544
- static async fromStrategies(user, course, strategies, aggregationMode = DEFAULT_AGGREGATION_MODE) {
545
- const generators = await Promise.all(
546
- strategies.map((s) => ContentNavigator.create(user, course, s))
547
- );
548
- return new _CompositeGenerator(generators, aggregationMode);
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
+ }
549
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
+ // ============================================================================
550
545
  /**
551
- * Get weighted cards from all generators, merge and deduplicate.
552
- *
553
- * Cards appearing in multiple generators receive a score boost.
554
- * Provenance tracks which generators produced each card and how scores were aggregated.
555
- *
556
- * This method supports both the legacy signature (limit only) and the
557
- * CardGenerator interface signature (limit, context).
546
+ * Unique key identifying this strategy for state storage.
558
547
  *
559
- * @param limit - Maximum number of cards to return
560
- * @param context - Optional GeneratorContext passed to child generators
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.
561
551
  */
562
- async getWeightedCards(limit, context) {
563
- const results = await Promise.all(
564
- this.generators.map((g) => g.getWeightedCards(limit, context))
565
- );
566
- const byCardId = /* @__PURE__ */ new Map();
567
- for (const cards of results) {
568
- for (const card of cards) {
569
- const existing = byCardId.get(card.cardId) || [];
570
- existing.push(card);
571
- byCardId.set(card.cardId, existing);
572
- }
573
- }
574
- const merged = [];
575
- for (const [, cards] of byCardId) {
576
- const aggregatedScore = this.aggregateScores(cards);
577
- const finalScore = Math.min(1, aggregatedScore);
578
- const mergedProvenance = cards.flatMap((c) => c.provenance);
579
- const initialScore = cards[0].score;
580
- const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
581
- const reason = this.buildAggregationReason(cards, finalScore);
582
- merged.push({
583
- ...cards[0],
584
- score: finalScore,
585
- provenance: [
586
- ...mergedProvenance,
587
- {
588
- strategy: "composite",
589
- strategyName: "Composite Generator",
590
- strategyId: "COMPOSITE_GENERATOR",
591
- action,
592
- score: finalScore,
593
- reason
594
- }
595
- ]
596
- });
597
- }
598
- return merged.sort((a, b) => b.score - a.score).slice(0, limit);
552
+ get strategyKey() {
553
+ return this.constructor.name;
599
554
  }
600
555
  /**
601
- * Build human-readable reason for score aggregation.
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
602
560
  */
603
- buildAggregationReason(cards, finalScore) {
604
- const count = cards.length;
605
- const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
606
- if (count === 1) {
607
- return `Single generator, score ${finalScore.toFixed(2)}`;
608
- }
609
- const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
610
- switch (this.aggregationMode) {
611
- case "max" /* MAX */:
612
- return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
613
- case "average" /* AVERAGE */:
614
- return `Average of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
615
- case "frequencyBoost" /* FREQUENCY_BOOST */: {
616
- const avg = cards.reduce((sum, c) => sum + c.score, 0) / count;
617
- const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
618
- return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
619
- }
620
- default:
621
- return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
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
+ );
622
566
  }
567
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
623
568
  }
624
569
  /**
625
- * Aggregate scores from multiple generators for the same card.
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
626
574
  */
627
- aggregateScores(cards) {
628
- const scores = cards.map((c) => c.score);
629
- switch (this.aggregationMode) {
630
- case "max" /* MAX */:
631
- return Math.max(...scores);
632
- case "average" /* AVERAGE */:
633
- return scores.reduce((sum, s) => sum + s, 0) / scores.length;
634
- case "frequencyBoost" /* FREQUENCY_BOOST */: {
635
- const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
636
- const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (cards.length - 1);
637
- return avg * frequencyBoost;
638
- }
639
- default:
640
- return scores[0];
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
+ );
641
580
  }
581
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
642
582
  }
643
583
  /**
644
- * Get new cards from all generators, merged and deduplicated.
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.
645
590
  */
646
- async getNewCards(n) {
647
- const legacyGenerators = this.generators.filter(
648
- (g) => g instanceof ContentNavigator
649
- );
650
- const results = await Promise.all(legacyGenerators.map((g) => g.getNewCards(n)));
651
- const seen = /* @__PURE__ */ new Set();
652
- const merged = [];
653
- for (const cards of results) {
654
- for (const card of cards) {
655
- if (!seen.has(card.cardID)) {
656
- seen.add(card.cardID);
657
- merged.push(card);
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);
658
605
  }
659
606
  }
660
607
  }
661
- return n ? merged.slice(0, n) : merged;
608
+ if (!NavigatorImpl) {
609
+ throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
610
+ }
611
+ return new NavigatorImpl(user, course, strategyData);
662
612
  }
663
613
  /**
664
- * Get pending reviews from all generators, merged and deduplicated.
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
665
637
  */
666
- async getPendingReviews() {
667
- const legacyGenerators = this.generators.filter(
668
- (g) => g instanceof ContentNavigator
669
- );
670
- const results = await Promise.all(legacyGenerators.map((g) => g.getPendingReviews()));
671
- const seen = /* @__PURE__ */ new Set();
672
- const merged = [];
673
- for (const reviews of results) {
674
- for (const review of reviews) {
675
- if (!seen.has(review.cardID)) {
676
- seen.add(review.cardID);
677
- merged.push(review);
678
- }
679
- }
680
- }
681
- return merged;
638
+ async getWeightedCards(_limit) {
639
+ throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
682
640
  }
683
641
  };
684
642
  }
685
643
  });
686
644
 
687
645
  // src/core/navigators/Pipeline.ts
688
- var Pipeline_exports = {};
689
- __export(Pipeline_exports, {
690
- Pipeline: () => Pipeline
691
- });
692
646
  function logPipelineConfig(generator, filters) {
693
647
  const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
694
648
  logger.info(
@@ -748,6 +702,11 @@ var init_Pipeline = __esm({
748
702
  this.filters = filters;
749
703
  this.user = user;
750
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
+ });
751
710
  logPipelineConfig(generator, filters);
752
711
  }
753
712
  /**
@@ -784,7 +743,13 @@ var init_Pipeline = __esm({
784
743
  cards.sort((a, b) => b.score - a.score);
785
744
  const result = cards.slice(0, limit);
786
745
  const topScores = result.slice(0, 3).map((c) => c.score);
787
- logExecutionSummary(this.generator.name, generatedCount, this.filters.length, result.length, topScores);
746
+ logExecutionSummary(
747
+ this.generator.name,
748
+ generatedCount,
749
+ this.filters.length,
750
+ result.length,
751
+ topScores
752
+ );
788
753
  logCardProvenance(result, 3);
789
754
  return result;
790
755
  }
@@ -833,33 +798,6 @@ var init_Pipeline = __esm({
833
798
  userElo
834
799
  };
835
800
  }
836
- // ===========================================================================
837
- // Legacy StudyContentSource methods
838
- // ===========================================================================
839
- //
840
- // These delegate to the generator for backward compatibility.
841
- // Eventually SessionController will use getWeightedCards() exclusively.
842
- //
843
- /**
844
- * Get new cards via legacy API.
845
- * Delegates to the generator if it supports the legacy interface.
846
- */
847
- async getNewCards(n) {
848
- if ("getNewCards" in this.generator && typeof this.generator.getNewCards === "function") {
849
- return this.generator.getNewCards(n);
850
- }
851
- return [];
852
- }
853
- /**
854
- * Get pending reviews via legacy API.
855
- * Delegates to the generator if it supports the legacy interface.
856
- */
857
- async getPendingReviews() {
858
- if ("getPendingReviews" in this.generator && typeof this.generator.getPendingReviews === "function") {
859
- return this.generator.getPendingReviews();
860
- }
861
- return [];
862
- }
863
801
  /**
864
802
  * Get the course ID for this pipeline.
865
803
  */
@@ -870,21 +808,155 @@ var init_Pipeline = __esm({
870
808
  }
871
809
  });
872
810
 
873
- // src/core/navigators/PipelineAssembler.ts
874
- var PipelineAssembler_exports = {};
875
- __export(PipelineAssembler_exports, {
876
- PipelineAssembler: () => PipelineAssembler
877
- });
878
- var PipelineAssembler;
879
- var init_PipelineAssembler = __esm({
880
- "src/core/navigators/PipelineAssembler.ts"() {
811
+ // src/core/navigators/generators/CompositeGenerator.ts
812
+ var DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
813
+ var init_CompositeGenerator = __esm({
814
+ "src/core/navigators/generators/CompositeGenerator.ts"() {
881
815
  "use strict";
882
816
  init_navigators();
883
- init_Pipeline();
884
- init_types_legacy();
885
817
  init_logger();
886
- init_CompositeGenerator();
887
- PipelineAssembler = class {
818
+ DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
819
+ FREQUENCY_BOOST_FACTOR = 0.1;
820
+ CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
821
+ /** Human-readable name for CardGenerator interface */
822
+ name = "Composite Generator";
823
+ generators;
824
+ aggregationMode;
825
+ constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
826
+ super();
827
+ this.generators = generators;
828
+ this.aggregationMode = aggregationMode;
829
+ if (generators.length === 0) {
830
+ throw new Error("CompositeGenerator requires at least one generator");
831
+ }
832
+ logger.debug(
833
+ `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
834
+ );
835
+ }
836
+ /**
837
+ * Creates a CompositeGenerator from strategy data.
838
+ *
839
+ * This is a convenience factory for use by PipelineAssembler.
840
+ */
841
+ static async fromStrategies(user, course, strategies, aggregationMode = DEFAULT_AGGREGATION_MODE) {
842
+ const generators = await Promise.all(
843
+ strategies.map((s) => ContentNavigator.create(user, course, s))
844
+ );
845
+ return new _CompositeGenerator(generators, aggregationMode);
846
+ }
847
+ /**
848
+ * Get weighted cards from all generators, merge and deduplicate.
849
+ *
850
+ * Cards appearing in multiple generators receive a score boost.
851
+ * Provenance tracks which generators produced each card and how scores were aggregated.
852
+ *
853
+ * This method supports both the legacy signature (limit only) and the
854
+ * CardGenerator interface signature (limit, context).
855
+ *
856
+ * @param limit - Maximum number of cards to return
857
+ * @param context - GeneratorContext passed to child generators (required when called via Pipeline)
858
+ */
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
+ }
865
+ const results = await Promise.all(
866
+ this.generators.map((g) => g.getWeightedCards(limit, context))
867
+ );
868
+ const byCardId = /* @__PURE__ */ new Map();
869
+ for (const cards of results) {
870
+ for (const card of cards) {
871
+ const existing = byCardId.get(card.cardId) || [];
872
+ existing.push(card);
873
+ byCardId.set(card.cardId, existing);
874
+ }
875
+ }
876
+ const merged = [];
877
+ for (const [, cards] of byCardId) {
878
+ const aggregatedScore = this.aggregateScores(cards);
879
+ const finalScore = Math.min(1, aggregatedScore);
880
+ const mergedProvenance = cards.flatMap((c) => c.provenance);
881
+ const initialScore = cards[0].score;
882
+ const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
883
+ const reason = this.buildAggregationReason(cards, finalScore);
884
+ merged.push({
885
+ ...cards[0],
886
+ score: finalScore,
887
+ provenance: [
888
+ ...mergedProvenance,
889
+ {
890
+ strategy: "composite",
891
+ strategyName: "Composite Generator",
892
+ strategyId: "COMPOSITE_GENERATOR",
893
+ action,
894
+ score: finalScore,
895
+ reason
896
+ }
897
+ ]
898
+ });
899
+ }
900
+ return merged.sort((a, b) => b.score - a.score).slice(0, limit);
901
+ }
902
+ /**
903
+ * Build human-readable reason for score aggregation.
904
+ */
905
+ buildAggregationReason(cards, finalScore) {
906
+ const count = cards.length;
907
+ const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
908
+ if (count === 1) {
909
+ return `Single generator, score ${finalScore.toFixed(2)}`;
910
+ }
911
+ const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
912
+ switch (this.aggregationMode) {
913
+ case "max" /* MAX */:
914
+ return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
915
+ case "average" /* AVERAGE */:
916
+ return `Average of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
917
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
918
+ const avg = cards.reduce((sum, c) => sum + c.score, 0) / count;
919
+ const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
920
+ return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
921
+ }
922
+ default:
923
+ return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
924
+ }
925
+ }
926
+ /**
927
+ * Aggregate scores from multiple generators for the same card.
928
+ */
929
+ aggregateScores(cards) {
930
+ const scores = cards.map((c) => c.score);
931
+ switch (this.aggregationMode) {
932
+ case "max" /* MAX */:
933
+ return Math.max(...scores);
934
+ case "average" /* AVERAGE */:
935
+ return scores.reduce((sum, s) => sum + s, 0) / scores.length;
936
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
937
+ const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
938
+ const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (cards.length - 1);
939
+ return avg * frequencyBoost;
940
+ }
941
+ default:
942
+ return scores[0];
943
+ }
944
+ }
945
+ };
946
+ }
947
+ });
948
+
949
+ // src/core/navigators/PipelineAssembler.ts
950
+ var PipelineAssembler;
951
+ var init_PipelineAssembler = __esm({
952
+ "src/core/navigators/PipelineAssembler.ts"() {
953
+ "use strict";
954
+ init_navigators();
955
+ init_Pipeline();
956
+ init_types_legacy();
957
+ init_logger();
958
+ init_CompositeGenerator();
959
+ PipelineAssembler = class {
888
960
  /**
889
961
  * Assembles a navigation pipeline from strategy documents.
890
962
  *
@@ -995,14 +1067,10 @@ var init_PipelineAssembler = __esm({
995
1067
  }
996
1068
  });
997
1069
 
998
- // src/core/navigators/elo.ts
999
- var elo_exports = {};
1000
- __export(elo_exports, {
1001
- default: () => ELONavigator
1002
- });
1070
+ // src/core/navigators/generators/elo.ts
1003
1071
  var import_common6, ELONavigator;
1004
1072
  var init_elo = __esm({
1005
- "src/core/navigators/elo.ts"() {
1073
+ "src/core/navigators/generators/elo.ts"() {
1006
1074
  "use strict";
1007
1075
  init_navigators();
1008
1076
  import_common6 = require("@vue-skuilder/common");
@@ -1013,50 +1081,6 @@ var init_elo = __esm({
1013
1081
  super(user, course, strategyData);
1014
1082
  this.name = strategyData?.name || "ELO";
1015
1083
  }
1016
- async getPendingReviews() {
1017
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1018
- const elo = await this.course.getCardEloData(reviews.map((r) => r.cardId));
1019
- const ratedReviews = reviews.map((r, i) => {
1020
- const ratedR = {
1021
- ...r,
1022
- ...elo[i]
1023
- };
1024
- return ratedR;
1025
- });
1026
- ratedReviews.sort((a, b) => {
1027
- return a.global.score - b.global.score;
1028
- });
1029
- return ratedReviews.map((r) => {
1030
- return {
1031
- ...r,
1032
- contentSourceType: "course",
1033
- contentSourceID: this.course.getCourseID(),
1034
- cardID: r.cardId,
1035
- courseID: r.courseId,
1036
- qualifiedID: `${r.courseId}-${r.cardId}`,
1037
- reviewID: r._id,
1038
- status: "review"
1039
- };
1040
- });
1041
- }
1042
- async getNewCards(limit = 99) {
1043
- const activeCards = await this.user.getActiveCards();
1044
- return (await this.course.getCardsCenteredAtELO(
1045
- { limit, elo: "user" },
1046
- (c) => {
1047
- if (activeCards.some((ac) => c.cardID === ac.cardID)) {
1048
- return false;
1049
- } else {
1050
- return true;
1051
- }
1052
- }
1053
- )).map((c) => {
1054
- return {
1055
- ...c,
1056
- status: "new"
1057
- };
1058
- });
1059
- }
1060
1084
  /**
1061
1085
  * Get new cards with suitability scores based on ELO distance.
1062
1086
  *
@@ -1075,1341 +1099,239 @@ var init_elo = __esm({
1075
1099
  async getWeightedCards(limit, context) {
1076
1100
  let userGlobalElo;
1077
1101
  if (context?.userElo !== void 0) {
1078
- userGlobalElo = context.userElo;
1079
- } else {
1080
- const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1081
- const userElo = (0, import_common6.toCourseElo)(courseReg.elo);
1082
- userGlobalElo = userElo.global.score;
1083
- }
1084
- const newCards = await this.getNewCards(limit);
1085
- const cardIds = newCards.map((c) => c.cardID);
1086
- const cardEloData = await this.course.getCardEloData(cardIds);
1087
- const scored = newCards.map((c, i) => {
1088
- const cardElo = cardEloData[i]?.global?.score ?? 1e3;
1089
- const distance = Math.abs(cardElo - userGlobalElo);
1090
- const score = Math.max(0, 1 - distance / 500);
1091
- return {
1092
- cardId: c.cardID,
1093
- courseId: c.courseID,
1094
- score,
1095
- provenance: [
1096
- {
1097
- strategy: "elo",
1098
- strategyName: this.strategyName || this.name,
1099
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1100
- action: "generated",
1101
- score,
1102
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), new card`
1103
- }
1104
- ]
1105
- };
1106
- });
1107
- scored.sort((a, b) => b.score - a.score);
1108
- return scored.slice(0, limit);
1109
- }
1110
- };
1111
- }
1112
- });
1113
-
1114
- // src/core/navigators/filters/eloDistance.ts
1115
- var eloDistance_exports = {};
1116
- __export(eloDistance_exports, {
1117
- DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1118
- DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1119
- DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1120
- createEloDistanceFilter: () => createEloDistanceFilter
1121
- });
1122
- function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1123
- const normalizedDistance = distance / halfLife;
1124
- const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1125
- return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1126
- }
1127
- function createEloDistanceFilter(config) {
1128
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1129
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1130
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1131
- return {
1132
- name: "ELO Distance Filter",
1133
- async transform(cards, context) {
1134
- const { course, userElo } = context;
1135
- const cardIds = cards.map((c) => c.cardId);
1136
- const cardElos = await course.getCardEloData(cardIds);
1137
- return cards.map((card, i) => {
1138
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
1139
- const distance = Math.abs(cardElo - userElo);
1140
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1141
- const newScore = card.score * multiplier;
1142
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1143
- return {
1144
- ...card,
1145
- score: newScore,
1146
- provenance: [
1147
- ...card.provenance,
1148
- {
1149
- strategy: "eloDistance",
1150
- strategyName: "ELO Distance Filter",
1151
- strategyId: "ELO_DISTANCE_FILTER",
1152
- action,
1153
- score: newScore,
1154
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1155
- }
1156
- ]
1157
- };
1158
- });
1159
- }
1160
- };
1161
- }
1162
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1163
- var init_eloDistance = __esm({
1164
- "src/core/navigators/filters/eloDistance.ts"() {
1165
- "use strict";
1166
- DEFAULT_HALF_LIFE = 200;
1167
- DEFAULT_MIN_MULTIPLIER = 0.3;
1168
- DEFAULT_MAX_MULTIPLIER = 1;
1169
- }
1170
- });
1171
-
1172
- // src/core/navigators/filters/userTagPreference.ts
1173
- var userTagPreference_exports = {};
1174
- __export(userTagPreference_exports, {
1175
- default: () => UserTagPreferenceFilter
1176
- });
1177
- var UserTagPreferenceFilter;
1178
- var init_userTagPreference = __esm({
1179
- "src/core/navigators/filters/userTagPreference.ts"() {
1180
- "use strict";
1181
- init_navigators();
1182
- UserTagPreferenceFilter = class extends ContentNavigator {
1183
- _strategyData;
1184
- /** Human-readable name for CardFilter interface */
1185
- name;
1186
- constructor(user, course, strategyData) {
1187
- super(user, course, strategyData);
1188
- this._strategyData = strategyData;
1189
- this.name = strategyData.name || "User Tag Preferences";
1190
- }
1191
- /**
1192
- * Compute multiplier for a card based on its tags and user preferences.
1193
- * Returns the maximum multiplier among all matching tags, or 1.0 if no matches.
1194
- */
1195
- computeMultiplier(cardTags, boostMap) {
1196
- const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== void 0);
1197
- if (multipliers.length === 0) {
1198
- return 1;
1199
- }
1200
- return Math.max(...multipliers);
1201
- }
1202
- /**
1203
- * Build human-readable reason for the filter's decision.
1204
- */
1205
- buildReason(cardTags, boostMap, multiplier) {
1206
- const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);
1207
- if (multiplier === 0) {
1208
- return `Excluded by user preference: ${matchingTags.join(", ")} (${multiplier}x)`;
1209
- }
1210
- if (multiplier < 1) {
1211
- return `Penalized by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1212
- }
1213
- if (multiplier > 1) {
1214
- return `Boosted by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1215
- }
1216
- return "No matching user preferences";
1217
- }
1218
- /**
1219
- * CardFilter.transform implementation.
1220
- *
1221
- * Apply user tag preferences:
1222
- * 1. Read preferences from strategy state
1223
- * 2. If no preferences, pass through unchanged
1224
- * 3. For each card:
1225
- * - Look up tag in boost record
1226
- * - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)
1227
- * - If multiple tags match: use max multiplier
1228
- * - Append provenance with clear reason
1229
- */
1230
- async transform(cards, _context) {
1231
- const prefs = await this.getStrategyState();
1232
- if (!prefs || Object.keys(prefs.boost).length === 0) {
1233
- return cards.map((card) => ({
1234
- ...card,
1235
- provenance: [
1236
- ...card.provenance,
1237
- {
1238
- strategy: "userTagPreference",
1239
- strategyName: this.strategyName || this.name,
1240
- strategyId: this.strategyId || this._strategyData._id,
1241
- action: "passed",
1242
- score: card.score,
1243
- reason: "No user tag preferences configured"
1244
- }
1245
- ]
1246
- }));
1247
- }
1248
- const adjusted = await Promise.all(
1249
- cards.map(async (card) => {
1250
- const cardTags = card.tags ?? [];
1251
- const multiplier = this.computeMultiplier(cardTags, prefs.boost);
1252
- const finalScore = Math.min(1, card.score * multiplier);
1253
- let action;
1254
- if (multiplier === 0 || multiplier < 1) {
1255
- action = "penalized";
1256
- } else if (multiplier > 1) {
1257
- action = "boosted";
1258
- } else {
1259
- action = "passed";
1260
- }
1261
- return {
1262
- ...card,
1263
- score: finalScore,
1264
- provenance: [
1265
- ...card.provenance,
1266
- {
1267
- strategy: "userTagPreference",
1268
- strategyName: this.strategyName || this.name,
1269
- strategyId: this.strategyId || this._strategyData._id,
1270
- action,
1271
- score: finalScore,
1272
- reason: this.buildReason(cardTags, prefs.boost, multiplier)
1273
- }
1274
- ]
1275
- };
1276
- })
1277
- );
1278
- return adjusted;
1279
- }
1280
- /**
1281
- * Legacy getWeightedCards - throws as filters should not be used as generators.
1282
- */
1283
- async getWeightedCards(_limit) {
1284
- throw new Error(
1285
- "UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1286
- );
1287
- }
1288
- // Legacy methods - stub implementations since filters don't generate cards
1289
- async getNewCards(_n) {
1290
- return [];
1291
- }
1292
- async getPendingReviews() {
1293
- return [];
1294
- }
1295
- };
1296
- }
1297
- });
1298
-
1299
- // src/core/navigators/filters/index.ts
1300
- var filters_exports = {};
1301
- __export(filters_exports, {
1302
- UserTagPreferenceFilter: () => UserTagPreferenceFilter,
1303
- createEloDistanceFilter: () => createEloDistanceFilter
1304
- });
1305
- var init_filters = __esm({
1306
- "src/core/navigators/filters/index.ts"() {
1307
- "use strict";
1308
- init_eloDistance();
1309
- init_userTagPreference();
1310
- }
1311
- });
1312
-
1313
- // src/core/navigators/filters/types.ts
1314
- var types_exports = {};
1315
- var init_types = __esm({
1316
- "src/core/navigators/filters/types.ts"() {
1317
- "use strict";
1318
- }
1319
- });
1320
-
1321
- // src/core/navigators/generators/index.ts
1322
- var generators_exports = {};
1323
- var init_generators = __esm({
1324
- "src/core/navigators/generators/index.ts"() {
1325
- "use strict";
1326
- }
1327
- });
1328
-
1329
- // src/core/navigators/generators/types.ts
1330
- var types_exports2 = {};
1331
- var init_types2 = __esm({
1332
- "src/core/navigators/generators/types.ts"() {
1333
- "use strict";
1334
- }
1335
- });
1336
-
1337
- // src/core/navigators/hardcodedOrder.ts
1338
- var hardcodedOrder_exports = {};
1339
- __export(hardcodedOrder_exports, {
1340
- default: () => HardcodedOrderNavigator
1341
- });
1342
- var HardcodedOrderNavigator;
1343
- var init_hardcodedOrder = __esm({
1344
- "src/core/navigators/hardcodedOrder.ts"() {
1345
- "use strict";
1346
- init_navigators();
1347
- init_logger();
1348
- HardcodedOrderNavigator = class extends ContentNavigator {
1349
- /** Human-readable name for CardGenerator interface */
1350
- name;
1351
- orderedCardIds = [];
1352
- constructor(user, course, strategyData) {
1353
- super(user, course, strategyData);
1354
- this.name = strategyData.name || "Hardcoded Order";
1355
- if (strategyData.serializedData) {
1356
- try {
1357
- this.orderedCardIds = JSON.parse(strategyData.serializedData);
1358
- } catch (e) {
1359
- logger.error("Failed to parse serializedData for HardcodedOrderNavigator", e);
1360
- }
1361
- }
1362
- }
1363
- async getPendingReviews() {
1364
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1365
- return reviews.map((r) => {
1366
- return {
1367
- ...r,
1368
- contentSourceType: "course",
1369
- contentSourceID: this.course.getCourseID(),
1370
- cardID: r.cardId,
1371
- courseID: r.courseId,
1372
- reviewID: r._id,
1373
- status: "review"
1374
- };
1375
- });
1376
- }
1377
- async getNewCards(limit = 99) {
1378
- const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
1379
- const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
1380
- const cardsToReturn = newCardIds.slice(0, limit);
1381
- return cardsToReturn.map((cardId) => {
1382
- return {
1383
- cardID: cardId,
1384
- courseID: this.course.getCourseID(),
1385
- contentSourceType: "course",
1386
- contentSourceID: this.course.getCourseID(),
1387
- status: "new"
1388
- };
1389
- });
1390
- }
1391
- /**
1392
- * Get cards in hardcoded order with scores based on position.
1393
- *
1394
- * Earlier cards in the sequence get higher scores.
1395
- * Score formula: 1.0 - (position / totalCards) * 0.5
1396
- * This ensures scores range from 1.0 (first card) to 0.5+ (last card).
1397
- *
1398
- * This method supports both the legacy signature (limit only) and the
1399
- * CardGenerator interface signature (limit, context).
1400
- *
1401
- * @param limit - Maximum number of cards to return
1402
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1403
- */
1404
- async getWeightedCards(limit, _context) {
1405
- const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
1406
- const reviews = await this.getPendingReviews();
1407
- const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
1408
- const totalCards = newCardIds.length;
1409
- const scoredNew = newCardIds.slice(0, limit).map((cardId, index) => {
1410
- const position = index + 1;
1411
- const score = Math.max(0.5, 1 - index / totalCards * 0.5);
1412
- return {
1413
- cardId,
1414
- courseId: this.course.getCourseID(),
1415
- score,
1416
- provenance: [
1417
- {
1418
- strategy: "hardcodedOrder",
1419
- strategyName: this.strategyName || this.name,
1420
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1421
- action: "generated",
1422
- score,
1423
- reason: `Position ${position} of ${totalCards} in fixed sequence, new card`
1424
- }
1425
- ]
1426
- };
1427
- });
1428
- const scoredReviews = reviews.map((r) => ({
1429
- cardId: r.cardID,
1430
- courseId: r.courseID,
1431
- score: 1,
1432
- provenance: [
1433
- {
1434
- strategy: "hardcodedOrder",
1435
- strategyName: this.strategyName || this.name,
1436
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1437
- action: "generated",
1438
- score: 1,
1439
- reason: "Scheduled review, highest priority"
1440
- }
1441
- ]
1442
- }));
1443
- const all = [...scoredReviews, ...scoredNew];
1444
- all.sort((a, b) => b.score - a.score);
1445
- return all.slice(0, limit);
1446
- }
1447
- };
1448
- }
1449
- });
1450
-
1451
- // src/core/navigators/hierarchyDefinition.ts
1452
- var hierarchyDefinition_exports = {};
1453
- __export(hierarchyDefinition_exports, {
1454
- default: () => HierarchyDefinitionNavigator
1455
- });
1456
- var import_common7, DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1457
- var init_hierarchyDefinition = __esm({
1458
- "src/core/navigators/hierarchyDefinition.ts"() {
1459
- "use strict";
1460
- init_navigators();
1461
- import_common7 = require("@vue-skuilder/common");
1462
- DEFAULT_MIN_COUNT = 3;
1463
- HierarchyDefinitionNavigator = class extends ContentNavigator {
1464
- config;
1465
- _strategyData;
1466
- /** Human-readable name for CardFilter interface */
1467
- name;
1468
- constructor(user, course, _strategyData) {
1469
- super(user, course, _strategyData);
1470
- this._strategyData = _strategyData;
1471
- this.config = this.parseConfig(_strategyData.serializedData);
1472
- this.name = _strategyData.name || "Hierarchy Definition";
1473
- }
1474
- parseConfig(serializedData) {
1475
- try {
1476
- const parsed = JSON.parse(serializedData);
1477
- return {
1478
- prerequisites: parsed.prerequisites || {}
1479
- };
1480
- } catch {
1481
- return {
1482
- prerequisites: {}
1483
- };
1484
- }
1485
- }
1486
- /**
1487
- * Check if a specific prerequisite is satisfied
1488
- */
1489
- isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1490
- if (!userTagElo) return false;
1491
- const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1492
- if (userTagElo.count < minCount) return false;
1493
- if (prereq.masteryThreshold?.minElo !== void 0) {
1494
- return userTagElo.score >= prereq.masteryThreshold.minElo;
1495
- } else {
1496
- return userTagElo.score >= userGlobalElo;
1497
- }
1498
- }
1499
- /**
1500
- * Get the set of tags the user has mastered.
1501
- * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1502
- */
1503
- async getMasteredTags(context) {
1504
- const mastered = /* @__PURE__ */ new Set();
1505
- try {
1506
- const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1507
- const userElo = (0, import_common7.toCourseElo)(courseReg.elo);
1508
- for (const prereqs of Object.values(this.config.prerequisites)) {
1509
- for (const prereq of prereqs) {
1510
- const tagElo = userElo.tags[prereq.tag];
1511
- if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1512
- mastered.add(prereq.tag);
1513
- }
1514
- }
1515
- }
1516
- } catch {
1517
- }
1518
- return mastered;
1519
- }
1520
- /**
1521
- * Get the set of tags that are unlocked (prerequisites met)
1522
- */
1523
- getUnlockedTags(masteredTags) {
1524
- const unlocked = /* @__PURE__ */ new Set();
1525
- for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1526
- const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1527
- if (allPrereqsMet) {
1528
- unlocked.add(tagId);
1529
- }
1530
- }
1531
- return unlocked;
1532
- }
1533
- /**
1534
- * Check if a tag has prerequisites defined in config
1535
- */
1536
- hasPrerequisites(tagId) {
1537
- return tagId in this.config.prerequisites;
1538
- }
1539
- /**
1540
- * Check if a card is unlocked and generate reason.
1541
- */
1542
- async checkCardUnlock(card, course, unlockedTags, masteredTags) {
1543
- try {
1544
- const cardTags = card.tags ?? [];
1545
- const lockedTags = cardTags.filter(
1546
- (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1547
- );
1548
- if (lockedTags.length === 0) {
1549
- const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1550
- return {
1551
- isUnlocked: true,
1552
- reason: `Prerequisites met, tags: ${tagList}`
1553
- };
1554
- }
1555
- const missingPrereqs = lockedTags.flatMap((tag) => {
1556
- const prereqs = this.config.prerequisites[tag] || [];
1557
- return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1558
- });
1559
- return {
1560
- isUnlocked: false,
1561
- reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1562
- };
1563
- } catch {
1564
- return {
1565
- isUnlocked: true,
1566
- reason: "Prerequisites check skipped (tag lookup failed)"
1567
- };
1568
- }
1569
- }
1570
- /**
1571
- * CardFilter.transform implementation.
1572
- *
1573
- * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1574
- */
1575
- async transform(cards, context) {
1576
- const masteredTags = await this.getMasteredTags(context);
1577
- const unlockedTags = this.getUnlockedTags(masteredTags);
1578
- const gated = [];
1579
- for (const card of cards) {
1580
- const { isUnlocked, reason } = await this.checkCardUnlock(
1581
- card,
1582
- context.course,
1583
- unlockedTags,
1584
- masteredTags
1585
- );
1586
- const finalScore = isUnlocked ? card.score : 0;
1587
- const action = isUnlocked ? "passed" : "penalized";
1588
- gated.push({
1589
- ...card,
1590
- score: finalScore,
1591
- provenance: [
1592
- ...card.provenance,
1593
- {
1594
- strategy: "hierarchyDefinition",
1595
- strategyName: this.strategyName || this.name,
1596
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1597
- action,
1598
- score: finalScore,
1599
- reason
1600
- }
1601
- ]
1602
- });
1603
- }
1604
- return gated;
1605
- }
1606
- /**
1607
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
1608
- *
1609
- * Use transform() via Pipeline instead.
1610
- */
1611
- async getWeightedCards(_limit) {
1612
- throw new Error(
1613
- "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1614
- );
1615
- }
1616
- // Legacy methods - stub implementations since filters don't generate cards
1617
- async getNewCards(_n) {
1618
- return [];
1619
- }
1620
- async getPendingReviews() {
1621
- return [];
1622
- }
1623
- };
1624
- }
1625
- });
1626
-
1627
- // src/core/navigators/inferredPreference.ts
1628
- var inferredPreference_exports = {};
1629
- __export(inferredPreference_exports, {
1630
- INFERRED_PREFERENCE_NAVIGATOR_STUB: () => INFERRED_PREFERENCE_NAVIGATOR_STUB
1631
- });
1632
- var INFERRED_PREFERENCE_NAVIGATOR_STUB;
1633
- var init_inferredPreference = __esm({
1634
- "src/core/navigators/inferredPreference.ts"() {
1635
- "use strict";
1636
- INFERRED_PREFERENCE_NAVIGATOR_STUB = true;
1637
- }
1638
- });
1639
-
1640
- // src/core/navigators/interferenceMitigator.ts
1641
- var interferenceMitigator_exports = {};
1642
- __export(interferenceMitigator_exports, {
1643
- default: () => InterferenceMitigatorNavigator
1644
- });
1645
- var import_common8, DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1646
- var init_interferenceMitigator = __esm({
1647
- "src/core/navigators/interferenceMitigator.ts"() {
1648
- "use strict";
1649
- init_navigators();
1650
- import_common8 = require("@vue-skuilder/common");
1651
- DEFAULT_MIN_COUNT2 = 10;
1652
- DEFAULT_MIN_ELAPSED_DAYS = 3;
1653
- DEFAULT_INTERFERENCE_DECAY = 0.8;
1654
- InterferenceMitigatorNavigator = class extends ContentNavigator {
1655
- config;
1656
- _strategyData;
1657
- /** Human-readable name for CardFilter interface */
1658
- name;
1659
- /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1660
- interferenceMap;
1661
- constructor(user, course, _strategyData) {
1662
- super(user, course, _strategyData);
1663
- this._strategyData = _strategyData;
1664
- this.config = this.parseConfig(_strategyData.serializedData);
1665
- this.interferenceMap = this.buildInterferenceMap();
1666
- this.name = _strategyData.name || "Interference Mitigator";
1667
- }
1668
- parseConfig(serializedData) {
1669
- try {
1670
- const parsed = JSON.parse(serializedData);
1671
- let sets = parsed.interferenceSets || [];
1672
- if (sets.length > 0 && Array.isArray(sets[0])) {
1673
- sets = sets.map((tags) => ({ tags }));
1674
- }
1675
- return {
1676
- interferenceSets: sets,
1677
- maturityThreshold: {
1678
- minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1679
- minElo: parsed.maturityThreshold?.minElo,
1680
- minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1681
- },
1682
- defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1683
- };
1684
- } catch {
1685
- return {
1686
- interferenceSets: [],
1687
- maturityThreshold: {
1688
- minCount: DEFAULT_MIN_COUNT2,
1689
- minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1690
- },
1691
- defaultDecay: DEFAULT_INTERFERENCE_DECAY
1692
- };
1693
- }
1694
- }
1695
- /**
1696
- * Build a map from each tag to its interference partners with decay coefficients.
1697
- * If tags A, B, C are in an interference group with decay 0.8, then:
1698
- * - A interferes with B (decay 0.8) and C (decay 0.8)
1699
- * - B interferes with A (decay 0.8) and C (decay 0.8)
1700
- * - etc.
1701
- */
1702
- buildInterferenceMap() {
1703
- const map = /* @__PURE__ */ new Map();
1704
- for (const group of this.config.interferenceSets) {
1705
- const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
1706
- for (const tag of group.tags) {
1707
- if (!map.has(tag)) {
1708
- map.set(tag, []);
1709
- }
1710
- const partners = map.get(tag);
1711
- for (const other of group.tags) {
1712
- if (other !== tag) {
1713
- const existing = partners.find((p) => p.partner === other);
1714
- if (existing) {
1715
- existing.decay = Math.max(existing.decay, decay);
1716
- } else {
1717
- partners.push({ partner: other, decay });
1718
- }
1719
- }
1720
- }
1721
- }
1722
- }
1723
- return map;
1724
- }
1725
- /**
1726
- * Get the set of tags that are currently immature for this user.
1727
- * A tag is immature if the user has interacted with it but hasn't
1728
- * reached the maturity threshold.
1729
- */
1730
- async getImmatureTags(context) {
1731
- const immature = /* @__PURE__ */ new Set();
1732
- try {
1733
- const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1734
- const userElo = (0, import_common8.toCourseElo)(courseReg.elo);
1735
- const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
1736
- const minElo = this.config.maturityThreshold?.minElo;
1737
- const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
1738
- const minCountForElapsed = minElapsedDays * 2;
1739
- for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
1740
- if (tagElo.count === 0) continue;
1741
- const belowCount = tagElo.count < minCount;
1742
- const belowElo = minElo !== void 0 && tagElo.score < minElo;
1743
- const belowElapsed = tagElo.count < minCountForElapsed;
1744
- if (belowCount || belowElo || belowElapsed) {
1745
- immature.add(tagId);
1746
- }
1747
- }
1748
- } catch {
1749
- }
1750
- return immature;
1751
- }
1752
- /**
1753
- * Get all tags that interfere with any immature tag, along with their decay coefficients.
1754
- * These are the tags we want to avoid introducing.
1755
- */
1756
- getTagsToAvoid(immatureTags) {
1757
- const avoid = /* @__PURE__ */ new Map();
1758
- for (const immatureTag of immatureTags) {
1759
- const partners = this.interferenceMap.get(immatureTag);
1760
- if (partners) {
1761
- for (const { partner, decay } of partners) {
1762
- if (!immatureTags.has(partner)) {
1763
- const existing = avoid.get(partner) ?? 0;
1764
- avoid.set(partner, Math.max(existing, decay));
1765
- }
1766
- }
1767
- }
1768
- }
1769
- return avoid;
1770
- }
1771
- /**
1772
- * Compute interference score reduction for a card.
1773
- * Returns: { multiplier, interfering tags, reason }
1774
- */
1775
- computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
1776
- if (tagsToAvoid.size === 0) {
1777
- return {
1778
- multiplier: 1,
1779
- interferingTags: [],
1780
- reason: "No interference detected"
1781
- };
1782
- }
1783
- let multiplier = 1;
1784
- const interferingTags = [];
1785
- for (const tag of cardTags) {
1786
- const decay = tagsToAvoid.get(tag);
1787
- if (decay !== void 0) {
1788
- interferingTags.push(tag);
1789
- multiplier *= 1 - decay;
1790
- }
1791
- }
1792
- if (interferingTags.length === 0) {
1793
- return {
1794
- multiplier: 1,
1795
- interferingTags: [],
1796
- reason: "No interference detected"
1797
- };
1798
- }
1799
- const causingTags = /* @__PURE__ */ new Set();
1800
- for (const tag of interferingTags) {
1801
- for (const immatureTag of immatureTags) {
1802
- const partners = this.interferenceMap.get(immatureTag);
1803
- if (partners?.some((p) => p.partner === tag)) {
1804
- causingTags.add(immatureTag);
1805
- }
1806
- }
1807
- }
1808
- const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
1809
- return { multiplier, interferingTags, reason };
1810
- }
1811
- /**
1812
- * CardFilter.transform implementation.
1813
- *
1814
- * Apply interference-aware scoring. Cards with tags that interfere with
1815
- * immature learnings get reduced scores.
1816
- */
1817
- async transform(cards, context) {
1818
- const immatureTags = await this.getImmatureTags(context);
1819
- const tagsToAvoid = this.getTagsToAvoid(immatureTags);
1820
- const adjusted = [];
1821
- for (const card of cards) {
1822
- const cardTags = card.tags ?? [];
1823
- const { multiplier, reason } = this.computeInterferenceEffect(
1824
- cardTags,
1825
- tagsToAvoid,
1826
- immatureTags
1827
- );
1828
- const finalScore = card.score * multiplier;
1829
- const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
1830
- adjusted.push({
1831
- ...card,
1832
- score: finalScore,
1833
- provenance: [
1834
- ...card.provenance,
1835
- {
1836
- strategy: "interferenceMitigator",
1837
- strategyName: this.strategyName || this.name,
1838
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
1839
- action,
1840
- score: finalScore,
1841
- reason
1842
- }
1843
- ]
1844
- });
1845
- }
1846
- return adjusted;
1847
- }
1848
- /**
1849
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
1850
- *
1851
- * Use transform() via Pipeline instead.
1852
- */
1853
- async getWeightedCards(_limit) {
1854
- throw new Error(
1855
- "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1856
- );
1857
- }
1858
- // Legacy methods - stub implementations since filters don't generate cards
1859
- async getNewCards(_n) {
1860
- return [];
1861
- }
1862
- async getPendingReviews() {
1863
- return [];
1864
- }
1865
- };
1866
- }
1867
- });
1868
-
1869
- // src/core/navigators/relativePriority.ts
1870
- var relativePriority_exports = {};
1871
- __export(relativePriority_exports, {
1872
- default: () => RelativePriorityNavigator
1873
- });
1874
- var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
1875
- var init_relativePriority = __esm({
1876
- "src/core/navigators/relativePriority.ts"() {
1877
- "use strict";
1878
- init_navigators();
1879
- DEFAULT_PRIORITY = 0.5;
1880
- DEFAULT_PRIORITY_INFLUENCE = 0.5;
1881
- DEFAULT_COMBINE_MODE = "max";
1882
- RelativePriorityNavigator = class extends ContentNavigator {
1883
- config;
1884
- _strategyData;
1885
- /** Human-readable name for CardFilter interface */
1886
- name;
1887
- constructor(user, course, _strategyData) {
1888
- super(user, course, _strategyData);
1889
- this._strategyData = _strategyData;
1890
- this.config = this.parseConfig(_strategyData.serializedData);
1891
- this.name = _strategyData.name || "Relative Priority";
1892
- }
1893
- parseConfig(serializedData) {
1894
- try {
1895
- const parsed = JSON.parse(serializedData);
1896
- return {
1897
- tagPriorities: parsed.tagPriorities || {},
1898
- defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
1899
- combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
1900
- priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
1901
- };
1902
- } catch {
1903
- return {
1904
- tagPriorities: {},
1905
- defaultPriority: DEFAULT_PRIORITY,
1906
- combineMode: DEFAULT_COMBINE_MODE,
1907
- priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
1908
- };
1909
- }
1910
- }
1911
- /**
1912
- * Look up the priority for a tag.
1913
- */
1914
- getTagPriority(tagId) {
1915
- return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
1916
- }
1917
- /**
1918
- * Compute combined priority for a card based on its tags.
1919
- */
1920
- computeCardPriority(cardTags) {
1921
- if (cardTags.length === 0) {
1922
- return this.config.defaultPriority ?? DEFAULT_PRIORITY;
1923
- }
1924
- const priorities = cardTags.map((tag) => this.getTagPriority(tag));
1925
- switch (this.config.combineMode) {
1926
- case "max":
1927
- return Math.max(...priorities);
1928
- case "min":
1929
- return Math.min(...priorities);
1930
- case "average":
1931
- return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
1932
- default:
1933
- return Math.max(...priorities);
1934
- }
1935
- }
1936
- /**
1937
- * Compute boost factor based on priority.
1938
- *
1939
- * The formula: 1 + (priority - 0.5) * priorityInfluence
1940
- *
1941
- * This creates a multiplier centered around 1.0:
1942
- * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
1943
- * - Priority 0.5 with any influence → 1.00 (neutral)
1944
- * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
1945
- */
1946
- computeBoostFactor(priority) {
1947
- const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
1948
- return 1 + (priority - 0.5) * influence;
1949
- }
1950
- /**
1951
- * Build human-readable reason for priority adjustment.
1952
- */
1953
- buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
1954
- if (cardTags.length === 0) {
1955
- return `No tags, neutral priority (${priority.toFixed(2)})`;
1956
- }
1957
- const tagList = cardTags.slice(0, 3).join(", ");
1958
- const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
1959
- if (boostFactor === 1) {
1960
- return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
1961
- } else if (boostFactor > 1) {
1962
- return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1963
- } else {
1964
- return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1965
- }
1966
- }
1967
- /**
1968
- * CardFilter.transform implementation.
1969
- *
1970
- * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
1971
- * cards with low-priority tags get reduced scores.
1972
- */
1973
- async transform(cards, _context) {
1974
- const adjusted = await Promise.all(
1975
- cards.map(async (card) => {
1976
- const cardTags = card.tags ?? [];
1977
- const priority = this.computeCardPriority(cardTags);
1978
- const boostFactor = this.computeBoostFactor(priority);
1979
- const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
1980
- const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
1981
- const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
1982
- return {
1983
- ...card,
1984
- score: finalScore,
1985
- provenance: [
1986
- ...card.provenance,
1987
- {
1988
- strategy: "relativePriority",
1989
- strategyName: this.strategyName || this.name,
1990
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
1991
- action,
1992
- score: finalScore,
1993
- reason
1994
- }
1995
- ]
1996
- };
1997
- })
1998
- );
1999
- return adjusted;
2000
- }
2001
- /**
2002
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
2003
- *
2004
- * Use transform() via Pipeline instead.
2005
- */
2006
- async getWeightedCards(_limit) {
2007
- throw new Error(
2008
- "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
2009
- );
2010
- }
2011
- // Legacy methods - stub implementations since filters don't generate cards
2012
- async getNewCards(_n) {
2013
- return [];
2014
- }
2015
- async getPendingReviews() {
2016
- return [];
2017
- }
2018
- };
2019
- }
2020
- });
2021
-
2022
- // src/core/navigators/srs.ts
2023
- var srs_exports = {};
2024
- __export(srs_exports, {
2025
- default: () => SRSNavigator
2026
- });
2027
- var import_moment3, SRSNavigator;
2028
- var init_srs = __esm({
2029
- "src/core/navigators/srs.ts"() {
2030
- "use strict";
2031
- import_moment3 = __toESM(require("moment"), 1);
2032
- init_navigators();
2033
- SRSNavigator = class extends ContentNavigator {
2034
- /** Human-readable name for CardGenerator interface */
2035
- name;
2036
- constructor(user, course, strategyData) {
2037
- super(user, course, strategyData);
2038
- this.name = strategyData?.name || "SRS";
2039
- }
2040
- /**
2041
- * Get review cards scored by urgency.
2042
- *
2043
- * Score formula combines:
2044
- * - Relative overdueness: hoursOverdue / intervalHours
2045
- * - Interval recency: exponential decay favoring shorter intervals
2046
- *
2047
- * Cards not yet due are excluded (not scored as 0).
2048
- *
2049
- * This method supports both the legacy signature (limit only) and the
2050
- * CardGenerator interface signature (limit, context).
2051
- *
2052
- * @param limit - Maximum number of cards to return
2053
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
2054
- */
2055
- async getWeightedCards(limit, _context) {
2056
- if (!this.user || !this.course) {
2057
- throw new Error("SRSNavigator requires user and course to be set");
2058
- }
2059
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
2060
- const now = import_moment3.default.utc();
2061
- const dueReviews = reviews.filter((r) => now.isAfter(import_moment3.default.utc(r.reviewTime)));
2062
- const scored = dueReviews.map((review) => {
2063
- const { score, reason } = this.computeUrgencyScore(review, now);
2064
- return {
2065
- cardId: review.cardId,
2066
- courseId: review.courseId,
2067
- score,
2068
- provenance: [
2069
- {
2070
- strategy: "srs",
2071
- strategyName: this.strategyName || this.name,
2072
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
2073
- action: "generated",
2074
- score,
2075
- reason
2076
- }
2077
- ]
2078
- };
2079
- });
2080
- return scored.sort((a, b) => b.score - a.score).slice(0, limit);
2081
- }
2082
- /**
2083
- * Compute urgency score for a review card.
2084
- *
2085
- * Two factors:
2086
- * 1. Relative overdueness = hoursOverdue / intervalHours
2087
- * - 2 days overdue on 3-day interval = 0.67 (urgent)
2088
- * - 2 days overdue on 180-day interval = 0.01 (not urgent)
2089
- *
2090
- * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
2091
- * - 24h interval → ~1.0 (very recent learning)
2092
- * - 30 days (720h) → ~0.56
2093
- * - 180 days → ~0.30
2094
- *
2095
- * Combined: base 0.5 + weighted average of factors * 0.45
2096
- * Result range: approximately 0.5 to 0.95
2097
- */
2098
- computeUrgencyScore(review, now) {
2099
- const scheduledAt = import_moment3.default.utc(review.scheduledAt);
2100
- const due = import_moment3.default.utc(review.reviewTime);
2101
- const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
2102
- const hoursOverdue = now.diff(due, "hours");
2103
- const relativeOverdue = hoursOverdue / intervalHours;
2104
- const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
2105
- const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
2106
- const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
2107
- const score = Math.min(0.95, 0.5 + urgency * 0.45);
2108
- const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
2109
- return { score, reason };
2110
- }
2111
- /**
2112
- * Get pending reviews in legacy format.
2113
- *
2114
- * Returns all pending reviews for the course, enriched with session item fields.
2115
- */
2116
- async getPendingReviews() {
2117
- if (!this.user || !this.course) {
2118
- throw new Error("SRSNavigator requires user and course to be set");
2119
- }
2120
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
2121
- return reviews.map((r) => ({
2122
- ...r,
2123
- contentSourceType: "course",
2124
- contentSourceID: this.course.getCourseID(),
2125
- cardID: r.cardId,
2126
- courseID: r.courseId,
2127
- qualifiedID: `${r.courseId}-${r.cardId}`,
2128
- reviewID: r._id,
2129
- status: "review"
2130
- }));
2131
- }
2132
- /**
2133
- * SRS does not generate new cards.
2134
- * Use ELONavigator or another generator for new cards.
2135
- */
2136
- async getNewCards(_n) {
2137
- return [];
2138
- }
2139
- };
2140
- }
2141
- });
2142
-
2143
- // src/core/navigators/userGoal.ts
2144
- var userGoal_exports = {};
2145
- __export(userGoal_exports, {
2146
- USER_GOAL_NAVIGATOR_STUB: () => USER_GOAL_NAVIGATOR_STUB
2147
- });
2148
- var USER_GOAL_NAVIGATOR_STUB;
2149
- var init_userGoal = __esm({
2150
- "src/core/navigators/userGoal.ts"() {
2151
- "use strict";
2152
- USER_GOAL_NAVIGATOR_STUB = true;
2153
- }
2154
- });
2155
-
2156
- // import("./**/*") in src/core/navigators/index.ts
2157
- var globImport;
2158
- var init_ = __esm({
2159
- 'import("./**/*") in src/core/navigators/index.ts'() {
2160
- globImport = __glob({
2161
- "./CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
2162
- "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
2163
- "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
2164
- "./elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
2165
- "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2166
- "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2167
- "./filters/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
2168
- "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
2169
- "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
2170
- "./generators/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
2171
- "./hardcodedOrder.ts": () => Promise.resolve().then(() => (init_hardcodedOrder(), hardcodedOrder_exports)),
2172
- "./hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2173
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
2174
- "./inferredPreference.ts": () => Promise.resolve().then(() => (init_inferredPreference(), inferredPreference_exports)),
2175
- "./interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2176
- "./relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2177
- "./srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
2178
- "./userGoal.ts": () => Promise.resolve().then(() => (init_userGoal(), userGoal_exports))
2179
- });
2180
- }
2181
- });
2182
-
2183
- // src/core/navigators/index.ts
2184
- var navigators_exports = {};
2185
- __export(navigators_exports, {
2186
- ContentNavigator: () => ContentNavigator,
2187
- NavigatorRole: () => NavigatorRole,
2188
- NavigatorRoles: () => NavigatorRoles,
2189
- Navigators: () => Navigators,
2190
- getCardOrigin: () => getCardOrigin,
2191
- isFilter: () => isFilter,
2192
- isGenerator: () => isGenerator
2193
- });
2194
- function getCardOrigin(card) {
2195
- if (card.provenance.length === 0) {
2196
- throw new Error("Card has no provenance - cannot determine origin");
2197
- }
2198
- const firstEntry = card.provenance[0];
2199
- const reason = firstEntry.reason.toLowerCase();
2200
- if (reason.includes("failed")) {
2201
- return "failed";
2202
- }
2203
- if (reason.includes("review")) {
2204
- return "review";
2205
- }
2206
- return "new";
2207
- }
2208
- function isGenerator(impl) {
2209
- return NavigatorRoles[impl] === "generator" /* GENERATOR */;
2210
- }
2211
- function isFilter(impl) {
2212
- return NavigatorRoles[impl] === "filter" /* FILTER */;
2213
- }
2214
- var Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
2215
- var init_navigators = __esm({
2216
- "src/core/navigators/index.ts"() {
2217
- "use strict";
2218
- init_logger();
2219
- init_();
2220
- Navigators = /* @__PURE__ */ ((Navigators2) => {
2221
- Navigators2["ELO"] = "elo";
2222
- Navigators2["SRS"] = "srs";
2223
- Navigators2["HARDCODED"] = "hardcodedOrder";
2224
- Navigators2["HIERARCHY"] = "hierarchyDefinition";
2225
- Navigators2["INTERFERENCE"] = "interferenceMitigator";
2226
- Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
2227
- Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
2228
- return Navigators2;
2229
- })(Navigators || {});
2230
- NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
2231
- NavigatorRole2["GENERATOR"] = "generator";
2232
- NavigatorRole2["FILTER"] = "filter";
2233
- return NavigatorRole2;
2234
- })(NavigatorRole || {});
2235
- NavigatorRoles = {
2236
- ["elo" /* ELO */]: "generator" /* GENERATOR */,
2237
- ["srs" /* SRS */]: "generator" /* GENERATOR */,
2238
- ["hardcodedOrder" /* HARDCODED */]: "generator" /* GENERATOR */,
2239
- ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
2240
- ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
2241
- ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
2242
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
2243
- };
2244
- ContentNavigator = class {
2245
- /** User interface for this navigation session */
2246
- user;
2247
- /** Course interface for this navigation session */
2248
- course;
2249
- /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
2250
- strategyName;
2251
- /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
2252
- strategyId;
2253
- /**
2254
- * Constructor for standard navigators.
2255
- * Call this from subclass constructors to initialize common fields.
2256
- *
2257
- * Note: CompositeGenerator doesn't use this pattern and should call super() without args.
2258
- */
2259
- constructor(user, course, strategyData) {
2260
- if (user && course && strategyData) {
2261
- this.user = user;
2262
- this.course = course;
2263
- this.strategyName = strategyData.name;
2264
- this.strategyId = strategyData._id;
2265
- }
2266
- }
2267
- // ============================================================================
2268
- // STRATEGY STATE HELPERS
2269
- // ============================================================================
2270
- //
2271
- // These methods allow strategies to persist their own state (user preferences,
2272
- // learned patterns, temporal tracking) in the user database.
2273
- //
2274
- // ============================================================================
2275
- /**
2276
- * Unique key identifying this strategy for state storage.
2277
- *
2278
- * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
2279
- * Override in subclasses if multiple instances of the same strategy type
2280
- * need separate state storage.
2281
- */
2282
- get strategyKey() {
2283
- return this.constructor.name;
2284
- }
2285
- /**
2286
- * Get this strategy's persisted state for the current course.
2287
- *
2288
- * @returns The strategy's data payload, or null if no state exists
2289
- * @throws Error if user or course is not initialized
2290
- */
2291
- async getStrategyState() {
2292
- if (!this.user || !this.course) {
2293
- throw new Error(
2294
- `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2295
- );
2296
- }
2297
- return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
2298
- }
2299
- /**
2300
- * Persist this strategy's state for the current course.
2301
- *
2302
- * @param data - The strategy's data payload to store
2303
- * @throws Error if user or course is not initialized
2304
- */
2305
- async putStrategyState(data) {
2306
- if (!this.user || !this.course) {
2307
- throw new Error(
2308
- `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2309
- );
2310
- }
2311
- return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
2312
- }
2313
- /**
2314
- * Factory method to create navigator instances dynamically.
2315
- *
2316
- * @param user - User interface
2317
- * @param course - Course interface
2318
- * @param strategyData - Strategy configuration document
2319
- * @returns the runtime object used to steer a study session.
2320
- */
2321
- static async create(user, course, strategyData) {
2322
- const implementingClass = strategyData.implementingClass;
2323
- let NavigatorImpl;
2324
- const variations = [".ts", ".js", ""];
2325
- for (const ext of variations) {
2326
- try {
2327
- const module2 = await globImport(`./${implementingClass}${ext}`);
2328
- NavigatorImpl = module2.default;
2329
- break;
2330
- } catch (e) {
2331
- logger.debug(`Failed to load with extension ${ext}:`, e);
2332
- }
2333
- }
2334
- if (!NavigatorImpl) {
2335
- throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
2336
- }
2337
- return new NavigatorImpl(user, course, strategyData);
2338
- }
2339
- /**
2340
- * Get cards with suitability scores and provenance trails.
2341
- *
2342
- * **This is the PRIMARY API for navigation strategies.**
2343
- *
2344
- * Returns cards ranked by suitability score (0-1). Higher scores indicate
2345
- * better candidates for presentation. Each card includes a provenance trail
2346
- * documenting how strategies contributed to the final score.
2347
- *
2348
- * ## For Generators
2349
- * Override this method to generate candidates and compute scores based on
2350
- * your strategy's logic (e.g., ELO proximity, review urgency). Create the
2351
- * initial provenance entry with action='generated'.
2352
- *
2353
- * ## Default Implementation
2354
- * The base class provides a backward-compatible default that:
2355
- * 1. Calls legacy getNewCards() and getPendingReviews()
2356
- * 2. Assigns score=1.0 to all cards
2357
- * 3. Creates minimal provenance from legacy methods
2358
- * 4. Returns combined results up to limit
2359
- *
2360
- * This allows existing strategies to work without modification while
2361
- * new strategies can override with proper scoring and provenance.
2362
- *
2363
- * @param limit - Maximum cards to return
2364
- * @returns Cards sorted by score descending, with provenance trails
2365
- */
2366
- async getWeightedCards(limit) {
2367
- const newCards = await this.getNewCards(limit);
2368
- const reviews = await this.getPendingReviews();
2369
- const weighted = [
2370
- ...newCards.map((c) => ({
1102
+ userGlobalElo = context.userElo;
1103
+ } else {
1104
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1105
+ const userElo = (0, import_common6.toCourseElo)(courseReg.elo);
1106
+ userGlobalElo = userElo.global.score;
1107
+ }
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" }));
1113
+ const cardIds = newCards.map((c) => c.cardID);
1114
+ const cardEloData = await this.course.getCardEloData(cardIds);
1115
+ const scored = newCards.map((c, i) => {
1116
+ const cardElo = cardEloData[i]?.global?.score ?? 1e3;
1117
+ const distance = Math.abs(cardElo - userGlobalElo);
1118
+ const score = Math.max(0, 1 - distance / 500);
1119
+ return {
2371
1120
  cardId: c.cardID,
2372
1121
  courseId: c.courseID,
2373
- score: 1,
1122
+ score,
2374
1123
  provenance: [
2375
1124
  {
2376
- strategy: "legacy",
2377
- strategyName: this.strategyName || "Legacy API",
2378
- strategyId: this.strategyId || "legacy-fallback",
1125
+ strategy: "elo",
1126
+ strategyName: this.strategyName || this.name,
1127
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
2379
1128
  action: "generated",
2380
- score: 1,
2381
- reason: "Generated via legacy getNewCards(), new card"
1129
+ score,
1130
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), new card`
2382
1131
  }
2383
1132
  ]
2384
- })),
2385
- ...reviews.map((r) => ({
2386
- cardId: r.cardID,
2387
- courseId: r.courseID,
2388
- score: 1,
1133
+ };
1134
+ });
1135
+ scored.sort((a, b) => b.score - a.score);
1136
+ return scored.slice(0, limit);
1137
+ }
1138
+ };
1139
+ }
1140
+ });
1141
+
1142
+ // src/core/navigators/generators/srs.ts
1143
+ var import_moment3, SRSNavigator;
1144
+ var init_srs = __esm({
1145
+ "src/core/navigators/generators/srs.ts"() {
1146
+ "use strict";
1147
+ import_moment3 = __toESM(require("moment"), 1);
1148
+ init_navigators();
1149
+ init_logger();
1150
+ SRSNavigator = class extends ContentNavigator {
1151
+ /** Human-readable name for CardGenerator interface */
1152
+ name;
1153
+ constructor(user, course, strategyData) {
1154
+ super(user, course, strategyData);
1155
+ this.name = strategyData?.name || "SRS";
1156
+ }
1157
+ /**
1158
+ * Get review cards scored by urgency.
1159
+ *
1160
+ * Score formula combines:
1161
+ * - Relative overdueness: hoursOverdue / intervalHours
1162
+ * - Interval recency: exponential decay favoring shorter intervals
1163
+ *
1164
+ * Cards not yet due are excluded (not scored as 0).
1165
+ *
1166
+ * This method supports both the legacy signature (limit only) and the
1167
+ * CardGenerator interface signature (limit, context).
1168
+ *
1169
+ * @param limit - Maximum number of cards to return
1170
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1171
+ */
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,
2389
1186
  provenance: [
2390
1187
  {
2391
- strategy: "legacy",
2392
- strategyName: this.strategyName || "Legacy API",
2393
- strategyId: this.strategyId || "legacy-fallback",
1188
+ strategy: "srs",
1189
+ strategyName: this.strategyName || this.name,
1190
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
2394
1191
  action: "generated",
2395
- score: 1,
2396
- reason: "Generated via legacy getPendingReviews(), review"
1192
+ score,
1193
+ reason
2397
1194
  }
2398
1195
  ]
2399
- }))
2400
- ];
2401
- 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 };
2402
1229
  }
2403
1230
  };
2404
1231
  }
2405
1232
  });
2406
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
+
2407
1329
  // src/impl/couch/courseDB.ts
2408
- var import_common9;
1330
+ var import_common7;
2409
1331
  var init_courseDB = __esm({
2410
1332
  "src/impl/couch/courseDB.ts"() {
2411
1333
  "use strict";
2412
- import_common9 = require("@vue-skuilder/common");
1334
+ import_common7 = require("@vue-skuilder/common");
2413
1335
  init_couch();
2414
1336
  init_updateQueue();
2415
1337
  init_types_legacy();
@@ -2418,12 +1340,8 @@ var init_courseDB = __esm({
2418
1340
  init_courseAPI();
2419
1341
  init_courseLookupDB();
2420
1342
  init_navigators();
2421
- init_Pipeline();
2422
1343
  init_PipelineAssembler();
2423
- init_CompositeGenerator();
2424
- init_elo();
2425
- init_srs();
2426
- init_eloDistance();
1344
+ init_defaults();
2427
1345
  }
2428
1346
  });
2429
1347
 
@@ -2466,14 +1384,14 @@ var init_auth = __esm({
2466
1384
  });
2467
1385
 
2468
1386
  // src/impl/couch/CouchDBSyncStrategy.ts
2469
- var import_common10;
1387
+ var import_common8;
2470
1388
  var init_CouchDBSyncStrategy = __esm({
2471
1389
  "src/impl/couch/CouchDBSyncStrategy.ts"() {
2472
1390
  "use strict";
2473
1391
  init_factory();
2474
1392
  init_types_legacy();
2475
1393
  init_logger();
2476
- import_common10 = require("@vue-skuilder/common");
1394
+ import_common8 = require("@vue-skuilder/common");
2477
1395
  init_common();
2478
1396
  init_pouchdb_setup();
2479
1397
  init_couch();
@@ -2707,13 +1625,13 @@ async function dropUserFromClassroom(user, classID) {
2707
1625
  async function getUserClassrooms(user) {
2708
1626
  return getOrCreateClassroomRegistrationsDoc(user);
2709
1627
  }
2710
- var import_common12, import_moment6, log3, BaseUser, userCoursesDoc, userClassroomsDoc;
1628
+ var import_common10, import_moment6, log3, BaseUser, userCoursesDoc, userClassroomsDoc;
2711
1629
  var init_BaseUserDB = __esm({
2712
1630
  "src/impl/common/BaseUserDB.ts"() {
2713
1631
  "use strict";
2714
1632
  init_core();
2715
1633
  init_util();
2716
- import_common12 = require("@vue-skuilder/common");
1634
+ import_common10 = require("@vue-skuilder/common");
2717
1635
  import_moment6 = __toESM(require("moment"), 1);
2718
1636
  init_types_legacy();
2719
1637
  init_logger();
@@ -2763,7 +1681,7 @@ Currently logged-in as ${this._username}.`
2763
1681
  );
2764
1682
  }
2765
1683
  const result = await this.syncStrategy.createAccount(username, password);
2766
- if (result.status === import_common12.Status.ok) {
1684
+ if (result.status === import_common10.Status.ok) {
2767
1685
  log3(`Account created successfully, updating username to ${username}`);
2768
1686
  this._username = username;
2769
1687
  try {
@@ -2805,7 +1723,7 @@ Currently logged-in as ${this._username}.`
2805
1723
  async resetUserData() {
2806
1724
  if (this.syncStrategy.canAuthenticate()) {
2807
1725
  return {
2808
- status: import_common12.Status.error,
1726
+ status: import_common10.Status.error,
2809
1727
  error: "Reset user data is only available for local-only mode. Use logout instead for remote sync."
2810
1728
  };
2811
1729
  }
@@ -2824,11 +1742,11 @@ Currently logged-in as ${this._username}.`
2824
1742
  await localDB.bulkDocs(docsToDelete);
2825
1743
  }
2826
1744
  await this.init();
2827
- return { status: import_common12.Status.ok };
1745
+ return { status: import_common10.Status.ok };
2828
1746
  } catch (error) {
2829
1747
  logger.error("Failed to reset user data:", error);
2830
1748
  return {
2831
- status: import_common12.Status.error,
1749
+ status: import_common10.Status.error,
2832
1750
  error: error instanceof Error ? error.message : "Unknown error during reset"
2833
1751
  };
2834
1752
  }
@@ -3601,24 +2519,24 @@ var init_factory = __esm({
3601
2519
  });
3602
2520
 
3603
2521
  // src/study/TagFilteredContentSource.ts
3604
- var import_common14;
2522
+ var import_common12;
3605
2523
  var init_TagFilteredContentSource = __esm({
3606
2524
  "src/study/TagFilteredContentSource.ts"() {
3607
2525
  "use strict";
3608
- import_common14 = require("@vue-skuilder/common");
2526
+ import_common12 = require("@vue-skuilder/common");
3609
2527
  init_courseDB();
3610
2528
  init_logger();
3611
2529
  }
3612
2530
  });
3613
2531
 
3614
2532
  // src/core/interfaces/contentSource.ts
3615
- var import_common15;
2533
+ var import_common13;
3616
2534
  var init_contentSource = __esm({
3617
2535
  "src/core/interfaces/contentSource.ts"() {
3618
2536
  "use strict";
3619
2537
  init_factory();
3620
2538
  init_classroomDB2();
3621
- import_common15 = require("@vue-skuilder/common");
2539
+ import_common13 = require("@vue-skuilder/common");
3622
2540
  init_TagFilteredContentSource();
3623
2541
  }
3624
2542
  });
@@ -3675,17 +2593,17 @@ var init_strategyState = __esm({
3675
2593
  });
3676
2594
 
3677
2595
  // src/core/bulkImport/cardProcessor.ts
3678
- var import_common16;
2596
+ var import_common14;
3679
2597
  var init_cardProcessor = __esm({
3680
2598
  "src/core/bulkImport/cardProcessor.ts"() {
3681
2599
  "use strict";
3682
- import_common16 = require("@vue-skuilder/common");
2600
+ import_common14 = require("@vue-skuilder/common");
3683
2601
  init_logger();
3684
2602
  }
3685
2603
  });
3686
2604
 
3687
2605
  // src/core/bulkImport/types.ts
3688
- var init_types3 = __esm({
2606
+ var init_types = __esm({
3689
2607
  "src/core/bulkImport/types.ts"() {
3690
2608
  "use strict";
3691
2609
  }
@@ -3696,7 +2614,7 @@ var init_bulkImport = __esm({
3696
2614
  "src/core/bulkImport/index.ts"() {
3697
2615
  "use strict";
3698
2616
  init_cardProcessor();
3699
- init_types3();
2617
+ init_types();
3700
2618
  }
3701
2619
  });
3702
2620
 
@@ -3774,6 +2692,36 @@ var init_StaticDataUnpacker = __esm({
3774
2692
  logger.error(`Document ${id} not found in chunk ${chunk.id}`);
3775
2693
  throw new Error(`Document ${id} not found in chunk ${chunk.id}`);
3776
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
+ }
3777
2725
  /**
3778
2726
  * Query cards by ELO score, returning card IDs sorted by ELO
3779
2727
  */
@@ -3810,7 +2758,14 @@ var init_StaticDataUnpacker = __esm({
3810
2758
  * Get all tag names mapped to their card arrays
3811
2759
  */
3812
2760
  async getTagsIndex() {
3813
- return await this.loadIndex("tags");
2761
+ try {
2762
+ return await this.loadIndex("tags");
2763
+ } catch {
2764
+ return {
2765
+ byCard: {},
2766
+ byTag: {}
2767
+ };
2768
+ }
3814
2769
  }
3815
2770
  getDocTypeFromId(id) {
3816
2771
  for (const docTypeKey in DocTypePrefixes) {
@@ -4095,14 +3050,15 @@ var init_StaticDataUnpacker = __esm({
4095
3050
  });
4096
3051
 
4097
3052
  // src/impl/static/courseDB.ts
4098
- var import_common17, StaticCourseDB;
3053
+ var import_common15, StaticCourseDB;
4099
3054
  var init_courseDB3 = __esm({
4100
3055
  "src/impl/static/courseDB.ts"() {
4101
3056
  "use strict";
4102
- import_common17 = require("@vue-skuilder/common");
3057
+ import_common15 = require("@vue-skuilder/common");
4103
3058
  init_types_legacy();
4104
- init_navigators();
4105
3059
  init_logger();
3060
+ init_defaults();
3061
+ init_PipelineAssembler();
4106
3062
  StaticCourseDB = class {
4107
3063
  constructor(courseId, unpacker, userDB, manifest) {
4108
3064
  this.courseId = courseId;
@@ -4181,21 +3137,6 @@ var init_courseDB3 = __esm({
4181
3137
  async updateCardElo(cardId, _elo) {
4182
3138
  return { ok: true, id: cardId, rev: "1-static" };
4183
3139
  }
4184
- async getNewCards(limit = 99) {
4185
- const activeCards = await this.userDB.getActiveCards();
4186
- return (await this.getCardsCenteredAtELO({ limit, elo: "user" }, (c) => {
4187
- if (activeCards.some((ac) => c.cardID === ac.cardID)) {
4188
- return false;
4189
- } else {
4190
- return true;
4191
- }
4192
- })).map((c) => {
4193
- return {
4194
- ...c,
4195
- status: "new"
4196
- };
4197
- });
4198
- }
4199
3140
  async getCardsCenteredAtELO(options, filter) {
4200
3141
  let targetElo = typeof options.elo === "number" ? options.elo : 1e3;
4201
3142
  if (options.elo === "user") {
@@ -4370,7 +3311,7 @@ var init_courseDB3 = __esm({
4370
3311
  }
4371
3312
  async addNote(_codeCourse, _shape, _data, _author, _tags, _uploads, _elo) {
4372
3313
  return {
4373
- status: import_common17.Status.error,
3314
+ status: import_common15.Status.error,
4374
3315
  message: "Cannot add notes in static mode"
4375
3316
  };
4376
3317
  }
@@ -4381,19 +3322,23 @@ var init_courseDB3 = __esm({
4381
3322
  return [];
4382
3323
  }
4383
3324
  // Navigation Strategy Manager implementation
4384
- async getNavigationStrategy(_id) {
4385
- return {
4386
- _id: "NAVIGATION_STRATEGY-ELO",
4387
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
4388
- name: "ELO",
4389
- description: "ELO-based navigation strategy",
4390
- implementingClass: "elo" /* ELO */,
4391
- course: this.courseId,
4392
- serializedData: ""
4393
- };
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
+ }
4394
3332
  }
4395
3333
  async getAllNavigationStrategies() {
4396
- 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
+ }
4397
3342
  }
4398
3343
  async addNavigationStrategy(_data) {
4399
3344
  throw new Error("Cannot add navigation strategies in static mode");
@@ -4401,9 +3346,52 @@ var init_courseDB3 = __esm({
4401
3346
  async updateNavigationStrategy(_id, _data) {
4402
3347
  throw new Error("Cannot update navigation strategies in static mode");
4403
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
+ }
4404
3386
  // Study Content Source implementation
4405
- async getPendingReviews() {
4406
- 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
+ }
4407
3395
  }
4408
3396
  // Attachment helper methods (internal use, not part of interface)
4409
3397
  /**