@vue-skuilder/db 0.1.18 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/CLAUDE.md +2 -2
  2. package/dist/{classroomDB-BgfrVb8d.d.ts → contentSource-BP9hznNV.d.ts} +220 -197
  3. package/dist/{classroomDB-CTOenngH.d.cts → contentSource-DsJadoBU.d.cts} +220 -197
  4. package/dist/core/index.d.cts +80 -6
  5. package/dist/core/index.d.ts +80 -6
  6. package/dist/core/index.js +735 -1560
  7. package/dist/core/index.js.map +1 -1
  8. package/dist/core/index.mjs +708 -1539
  9. package/dist/core/index.mjs.map +1 -1
  10. package/dist/{dataLayerProvider-D6PoCwS6.d.cts → dataLayerProvider-CHYrQ5pB.d.cts} +1 -1
  11. package/dist/{dataLayerProvider-CZxC9GtB.d.ts → dataLayerProvider-MDTxXq2l.d.ts} +1 -1
  12. package/dist/impl/couch/index.d.cts +8 -23
  13. package/dist/impl/couch/index.d.ts +8 -23
  14. package/dist/impl/couch/index.js +723 -1578
  15. package/dist/impl/couch/index.js.map +1 -1
  16. package/dist/impl/couch/index.mjs +692 -1552
  17. package/dist/impl/couch/index.mjs.map +1 -1
  18. package/dist/impl/static/index.d.cts +25 -8
  19. package/dist/impl/static/index.d.ts +25 -8
  20. package/dist/impl/static/index.js +700 -1400
  21. package/dist/impl/static/index.js.map +1 -1
  22. package/dist/impl/static/index.mjs +688 -1393
  23. package/dist/impl/static/index.mjs.map +1 -1
  24. package/dist/{index-D-Fa4Smt.d.cts → index-B_j6u5E4.d.cts} +1 -1
  25. package/dist/{index-CD8BZz2k.d.ts → index-Dj0SEgk3.d.ts} +1 -1
  26. package/dist/index.d.cts +71 -63
  27. package/dist/index.d.ts +71 -63
  28. package/dist/index.js +1162 -1996
  29. package/dist/index.js.map +1 -1
  30. package/dist/index.mjs +1124 -1955
  31. package/dist/index.mjs.map +1 -1
  32. package/dist/pouch/index.js +3 -0
  33. package/dist/pouch/index.js.map +1 -1
  34. package/dist/pouch/index.mjs +3 -0
  35. package/dist/pouch/index.mjs.map +1 -1
  36. package/dist/{types-CzPDLAK6.d.cts → types-Bn0itutr.d.cts} +1 -1
  37. package/dist/{types-CewsN87z.d.ts → types-DQaXnuoc.d.ts} +1 -1
  38. package/dist/{types-legacy-6ettoclI.d.cts → types-legacy-DDY4N-Uq.d.cts} +3 -1
  39. package/dist/{types-legacy-6ettoclI.d.ts → types-legacy-DDY4N-Uq.d.ts} +3 -1
  40. package/dist/util/packer/index.d.cts +3 -3
  41. package/dist/util/packer/index.d.ts +3 -3
  42. package/docs/navigators-architecture.md +115 -17
  43. package/package.json +4 -4
  44. package/src/core/index.ts +1 -0
  45. package/src/core/interfaces/classroomDB.ts +5 -13
  46. package/src/core/interfaces/contentSource.ts +6 -66
  47. package/src/core/interfaces/courseDB.ts +15 -7
  48. package/src/core/interfaces/userDB.ts +32 -0
  49. package/src/core/navigators/Pipeline.ts +136 -52
  50. package/src/core/navigators/PipelineAssembler.ts +1 -1
  51. package/src/core/navigators/defaults.ts +84 -0
  52. package/src/core/navigators/{hierarchyDefinition.ts → filters/hierarchyDefinition.ts} +15 -29
  53. package/src/core/navigators/filters/index.ts +3 -0
  54. package/src/core/navigators/filters/inferredPreferenceStub.ts +107 -0
  55. package/src/core/navigators/{interferenceMitigator.ts → filters/interferenceMitigator.ts} +11 -37
  56. package/src/core/navigators/{relativePriority.ts → filters/relativePriority.ts} +12 -38
  57. package/src/core/navigators/filters/userGoalStub.ts +136 -0
  58. package/src/core/navigators/filters/userTagPreference.ts +217 -0
  59. package/src/core/navigators/{CompositeGenerator.ts → generators/CompositeGenerator.ts} +15 -64
  60. package/src/core/navigators/{elo.ts → generators/elo.ts} +13 -63
  61. package/src/core/navigators/{srs.ts → generators/srs.ts} +11 -40
  62. package/src/core/navigators/generators/types.ts +1 -1
  63. package/src/core/navigators/index.ts +95 -91
  64. package/src/core/types/strategyState.ts +84 -0
  65. package/src/core/types/types-legacy.ts +2 -0
  66. package/src/impl/common/BaseUserDB.ts +74 -7
  67. package/src/impl/couch/adminDB.ts +1 -2
  68. package/src/impl/couch/classroomDB.ts +100 -103
  69. package/src/impl/couch/courseDB.ts +35 -91
  70. package/src/impl/couch/pouchdb-setup.ts +7 -0
  71. package/src/impl/static/StaticDataUnpacker.ts +50 -1
  72. package/src/impl/static/courseDB.ts +87 -37
  73. package/src/study/SessionController.ts +122 -202
  74. package/src/study/SourceMixer.ts +65 -0
  75. package/src/study/TagFilteredContentSource.ts +49 -92
  76. package/src/study/index.ts +1 -0
  77. package/src/study/services/CardHydrationService.ts +165 -81
  78. package/src/util/dataDirectory.ts +1 -1
  79. package/src/util/index.ts +0 -1
  80. package/tests/core/navigators/CompositeGenerator.test.ts +44 -168
  81. package/tests/core/navigators/Pipeline.test.ts +6 -72
  82. package/tests/core/navigators/PipelineAssembler.test.ts +8 -58
  83. package/tests/core/navigators/navigators.test.ts +118 -151
  84. package/docs/todo-pipeline-optimization.md +0 -117
  85. package/docs/todo-strategy-state-storage.md +0 -278
  86. package/src/core/navigators/hardcodedOrder.ts +0 -163
  87. package/src/util/tuiLogger.ts +0 -139
@@ -1,17 +1,7 @@
1
- var __defProp = Object.defineProperty;
2
1
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __glob = (map) => (path2) => {
4
- var fn = map[path2];
5
- if (fn) return fn();
6
- throw new Error("Module not found in bundle: " + path2);
7
- };
8
2
  var __esm = (fn, res) => function __init() {
9
3
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
4
  };
11
- var __export = (target, all) => {
12
- for (var name in all)
13
- __defProp(target, name, { get: all[name], enumerable: true });
14
- };
15
5
 
16
6
  // src/util/logger.ts
17
7
  var isDevelopment, logger;
@@ -97,7 +87,8 @@ var init_types_legacy = __esm({
97
87
  ["QUESTION" /* QUESTIONTYPE */]: "QUESTION",
98
88
  ["VIEW" /* VIEW */]: "VIEW",
99
89
  ["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
100
- ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY"
90
+ ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
91
+ ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE"
101
92
  };
102
93
  }
103
94
  });
@@ -123,6 +114,9 @@ var init_pouchdb_setup = __esm({
123
114
  "use strict";
124
115
  PouchDB.plugin(PouchDBFind);
125
116
  PouchDB.plugin(PouchDBAuth);
117
+ if (typeof PouchDB.debug !== "undefined") {
118
+ PouchDB.debug.disable();
119
+ }
126
120
  PouchDB.defaults({
127
121
  // ajax: {
128
122
  // timeout: 60000,
@@ -132,14 +126,6 @@ var init_pouchdb_setup = __esm({
132
126
  }
133
127
  });
134
128
 
135
- // src/util/tuiLogger.ts
136
- var init_tuiLogger = __esm({
137
- "src/util/tuiLogger.ts"() {
138
- "use strict";
139
- init_dataDirectory();
140
- }
141
- });
142
-
143
129
  // src/util/dataDirectory.ts
144
130
  import * as path from "path";
145
131
  import * as os from "os";
@@ -156,7 +142,7 @@ function getDbPath(dbName) {
156
142
  var init_dataDirectory = __esm({
157
143
  "src/util/dataDirectory.ts"() {
158
144
  "use strict";
159
- init_tuiLogger();
145
+ init_logger();
160
146
  init_factory();
161
147
  }
162
148
  });
@@ -475,24 +461,331 @@ var init_courseLookupDB = __esm({
475
461
  }
476
462
  });
477
463
 
478
- // src/core/navigators/CompositeGenerator.ts
479
- var CompositeGenerator_exports = {};
480
- __export(CompositeGenerator_exports, {
481
- AggregationMode: () => AggregationMode,
482
- default: () => CompositeGenerator
464
+ // src/core/navigators/index.ts
465
+ function isGenerator(impl) {
466
+ return NavigatorRoles[impl] === "generator" /* GENERATOR */;
467
+ }
468
+ function isFilter(impl) {
469
+ return NavigatorRoles[impl] === "filter" /* FILTER */;
470
+ }
471
+ var NavigatorRoles, ContentNavigator;
472
+ var init_navigators = __esm({
473
+ "src/core/navigators/index.ts"() {
474
+ "use strict";
475
+ init_logger();
476
+ NavigatorRoles = {
477
+ ["elo" /* ELO */]: "generator" /* GENERATOR */,
478
+ ["srs" /* SRS */]: "generator" /* GENERATOR */,
479
+ ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
480
+ ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
481
+ ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
482
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
483
+ };
484
+ ContentNavigator = class {
485
+ /** User interface for this navigation session */
486
+ user;
487
+ /** Course interface for this navigation session */
488
+ course;
489
+ /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
490
+ strategyName;
491
+ /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
492
+ strategyId;
493
+ /**
494
+ * Constructor for standard navigators.
495
+ * Call this from subclass constructors to initialize common fields.
496
+ *
497
+ * Note: CompositeGenerator and Pipeline call super() without args, then set
498
+ * user/course fields directly if needed.
499
+ */
500
+ constructor(user, course, strategyData) {
501
+ this.user = user;
502
+ this.course = course;
503
+ if (strategyData) {
504
+ this.strategyName = strategyData.name;
505
+ this.strategyId = strategyData._id;
506
+ }
507
+ }
508
+ // ============================================================================
509
+ // STRATEGY STATE HELPERS
510
+ // ============================================================================
511
+ //
512
+ // These methods allow strategies to persist their own state (user preferences,
513
+ // learned patterns, temporal tracking) in the user database.
514
+ //
515
+ // ============================================================================
516
+ /**
517
+ * Unique key identifying this strategy for state storage.
518
+ *
519
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
520
+ * Override in subclasses if multiple instances of the same strategy type
521
+ * need separate state storage.
522
+ */
523
+ get strategyKey() {
524
+ return this.constructor.name;
525
+ }
526
+ /**
527
+ * Get this strategy's persisted state for the current course.
528
+ *
529
+ * @returns The strategy's data payload, or null if no state exists
530
+ * @throws Error if user or course is not initialized
531
+ */
532
+ async getStrategyState() {
533
+ if (!this.user || !this.course) {
534
+ throw new Error(
535
+ `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
536
+ );
537
+ }
538
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
539
+ }
540
+ /**
541
+ * Persist this strategy's state for the current course.
542
+ *
543
+ * @param data - The strategy's data payload to store
544
+ * @throws Error if user or course is not initialized
545
+ */
546
+ async putStrategyState(data) {
547
+ if (!this.user || !this.course) {
548
+ throw new Error(
549
+ `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
550
+ );
551
+ }
552
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
553
+ }
554
+ /**
555
+ * Factory method to create navigator instances dynamically.
556
+ *
557
+ * @param user - User interface
558
+ * @param course - Course interface
559
+ * @param strategyData - Strategy configuration document
560
+ * @returns the runtime object used to steer a study session.
561
+ */
562
+ static async create(user, course, strategyData) {
563
+ const implementingClass = strategyData.implementingClass;
564
+ let NavigatorImpl;
565
+ const variations = [".ts", ".js", ""];
566
+ const dirs = ["filters", "generators"];
567
+ for (const ext of variations) {
568
+ for (const dir of dirs) {
569
+ const loadFrom = `./${dir}/${implementingClass}${ext}`;
570
+ try {
571
+ const module = await import(loadFrom);
572
+ NavigatorImpl = module.default;
573
+ break;
574
+ } catch (e) {
575
+ logger.debug(`Failed to load extension from ${loadFrom}:`, e);
576
+ }
577
+ }
578
+ }
579
+ if (!NavigatorImpl) {
580
+ throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
581
+ }
582
+ return new NavigatorImpl(user, course, strategyData);
583
+ }
584
+ /**
585
+ * Get cards with suitability scores and provenance trails.
586
+ *
587
+ * **This is the PRIMARY API for navigation strategies.**
588
+ *
589
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
590
+ * better candidates for presentation. Each card includes a provenance trail
591
+ * documenting how strategies contributed to the final score.
592
+ *
593
+ * ## Implementation Required
594
+ * All navigation strategies MUST override this method. The base class does
595
+ * not provide a default implementation.
596
+ *
597
+ * ## For Generators
598
+ * Override this method to generate candidates and compute scores based on
599
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
600
+ * initial provenance entry with action='generated'.
601
+ *
602
+ * ## For Filters
603
+ * Filters should implement the CardFilter interface instead and be composed
604
+ * via Pipeline. Filters do not directly implement getWeightedCards().
605
+ *
606
+ * @param limit - Maximum cards to return
607
+ * @returns Cards sorted by score descending, with provenance trails
608
+ */
609
+ async getWeightedCards(_limit) {
610
+ throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
611
+ }
612
+ };
613
+ }
614
+ });
615
+
616
+ // src/core/navigators/Pipeline.ts
617
+ import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
618
+ function logPipelineConfig(generator, filters) {
619
+ const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
620
+ logger.info(
621
+ `[Pipeline] Configuration:
622
+ Generator: ${generator.name}
623
+ Filters:${filterList}`
624
+ );
625
+ }
626
+ function logTagHydration(cards, tagsByCard) {
627
+ const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
628
+ const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
629
+ logger.debug(
630
+ `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
631
+ );
632
+ }
633
+ function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores) {
634
+ const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
635
+ logger.info(
636
+ `[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})`
637
+ );
638
+ }
639
+ function logCardProvenance(cards, maxCards = 3) {
640
+ const cardsToLog = cards.slice(0, maxCards);
641
+ logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
642
+ for (const card of cardsToLog) {
643
+ logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
644
+ for (const entry of card.provenance) {
645
+ const scoreChange = entry.score.toFixed(3);
646
+ const action = entry.action.padEnd(9);
647
+ logger.debug(
648
+ `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
649
+ );
650
+ }
651
+ }
652
+ }
653
+ var Pipeline;
654
+ var init_Pipeline = __esm({
655
+ "src/core/navigators/Pipeline.ts"() {
656
+ "use strict";
657
+ init_navigators();
658
+ init_logger();
659
+ Pipeline = class extends ContentNavigator {
660
+ generator;
661
+ filters;
662
+ /**
663
+ * Create a new pipeline.
664
+ *
665
+ * @param generator - The generator (or CompositeGenerator) that produces candidates
666
+ * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
667
+ * @param user - User database interface
668
+ * @param course - Course database interface
669
+ */
670
+ constructor(generator, filters, user, course) {
671
+ super();
672
+ this.generator = generator;
673
+ this.filters = filters;
674
+ this.user = user;
675
+ this.course = course;
676
+ course.getCourseConfig().then((cfg) => {
677
+ logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);
678
+ }).catch((e) => {
679
+ logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);
680
+ });
681
+ logPipelineConfig(generator, filters);
682
+ }
683
+ /**
684
+ * Get weighted cards by running generator and applying filters.
685
+ *
686
+ * 1. Build shared context (user ELO, etc.)
687
+ * 2. Get candidates from generator (passing context)
688
+ * 3. Batch hydrate tags for all candidates
689
+ * 4. Apply each filter sequentially
690
+ * 5. Remove zero-score cards
691
+ * 6. Sort by score descending
692
+ * 7. Return top N
693
+ *
694
+ * @param limit - Maximum number of cards to return
695
+ * @returns Cards sorted by score descending
696
+ */
697
+ async getWeightedCards(limit) {
698
+ const context = await this.buildContext();
699
+ const overFetchMultiplier = 2 + this.filters.length * 0.5;
700
+ const fetchLimit = Math.ceil(limit * overFetchMultiplier);
701
+ logger.debug(
702
+ `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
703
+ );
704
+ let cards = await this.generator.getWeightedCards(fetchLimit, context);
705
+ const generatedCount = cards.length;
706
+ logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
707
+ cards = await this.hydrateTags(cards);
708
+ for (const filter of this.filters) {
709
+ const beforeCount = cards.length;
710
+ cards = await filter.transform(cards, context);
711
+ logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeCount} \u2192 ${cards.length} cards`);
712
+ }
713
+ cards = cards.filter((c) => c.score > 0);
714
+ cards.sort((a, b) => b.score - a.score);
715
+ const result = cards.slice(0, limit);
716
+ const topScores = result.slice(0, 3).map((c) => c.score);
717
+ logExecutionSummary(
718
+ this.generator.name,
719
+ generatedCount,
720
+ this.filters.length,
721
+ result.length,
722
+ topScores
723
+ );
724
+ logCardProvenance(result, 3);
725
+ return result;
726
+ }
727
+ /**
728
+ * Batch hydrate tags for all cards.
729
+ *
730
+ * Fetches tags for all cards in a single database query and attaches them
731
+ * to the WeightedCard objects. Filters can then use card.tags instead of
732
+ * making individual getAppliedTags() calls.
733
+ *
734
+ * @param cards - Cards to hydrate
735
+ * @returns Cards with tags populated
736
+ */
737
+ async hydrateTags(cards) {
738
+ if (cards.length === 0) {
739
+ return cards;
740
+ }
741
+ const cardIds = cards.map((c) => c.cardId);
742
+ const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
743
+ logTagHydration(cards, tagsByCard);
744
+ return cards.map((card) => ({
745
+ ...card,
746
+ tags: tagsByCard.get(card.cardId) ?? []
747
+ }));
748
+ }
749
+ /**
750
+ * Build shared context for generator and filters.
751
+ *
752
+ * Called once per getWeightedCards() invocation.
753
+ * Contains data that the generator and multiple filters might need.
754
+ *
755
+ * The context satisfies both GeneratorContext and FilterContext interfaces.
756
+ */
757
+ async buildContext() {
758
+ let userElo = 1e3;
759
+ try {
760
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
761
+ const courseElo = toCourseElo2(courseReg.elo);
762
+ userElo = courseElo.global.score;
763
+ } catch (e) {
764
+ logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
765
+ }
766
+ return {
767
+ user: this.user,
768
+ course: this.course,
769
+ userElo
770
+ };
771
+ }
772
+ /**
773
+ * Get the course ID for this pipeline.
774
+ */
775
+ getCourseID() {
776
+ return this.course.getCourseID();
777
+ }
778
+ };
779
+ }
483
780
  });
484
- var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
781
+
782
+ // src/core/navigators/generators/CompositeGenerator.ts
783
+ var DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
485
784
  var init_CompositeGenerator = __esm({
486
- "src/core/navigators/CompositeGenerator.ts"() {
785
+ "src/core/navigators/generators/CompositeGenerator.ts"() {
487
786
  "use strict";
488
787
  init_navigators();
489
788
  init_logger();
490
- AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
491
- AggregationMode2["MAX"] = "max";
492
- AggregationMode2["AVERAGE"] = "average";
493
- AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
494
- return AggregationMode2;
495
- })(AggregationMode || {});
496
789
  DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
497
790
  FREQUENCY_BOOST_FACTOR = 0.1;
498
791
  CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
@@ -532,9 +825,14 @@ var init_CompositeGenerator = __esm({
532
825
  * CardGenerator interface signature (limit, context).
533
826
  *
534
827
  * @param limit - Maximum number of cards to return
535
- * @param context - Optional GeneratorContext passed to child generators
828
+ * @param context - GeneratorContext passed to child generators (required when called via Pipeline)
536
829
  */
537
830
  async getWeightedCards(limit, context) {
831
+ if (!context) {
832
+ throw new Error(
833
+ "CompositeGenerator.getWeightedCards requires a GeneratorContext. It should be called via Pipeline, not directly."
834
+ );
835
+ }
538
836
  const results = await Promise.all(
539
837
  this.generators.map((g) => g.getWeightedCards(limit, context))
540
838
  );
@@ -615,186 +913,14 @@ var init_CompositeGenerator = __esm({
615
913
  return scores[0];
616
914
  }
617
915
  }
618
- /**
619
- * Get new cards from all generators, merged and deduplicated.
620
- */
621
- async getNewCards(n) {
622
- const legacyGenerators = this.generators.filter(
623
- (g) => g instanceof ContentNavigator
624
- );
625
- const results = await Promise.all(legacyGenerators.map((g) => g.getNewCards(n)));
626
- const seen = /* @__PURE__ */ new Set();
627
- const merged = [];
628
- for (const cards of results) {
629
- for (const card of cards) {
630
- if (!seen.has(card.cardID)) {
631
- seen.add(card.cardID);
632
- merged.push(card);
633
- }
634
- }
635
- }
636
- return n ? merged.slice(0, n) : merged;
637
- }
638
- /**
639
- * Get pending reviews from all generators, merged and deduplicated.
640
- */
641
- async getPendingReviews() {
642
- const legacyGenerators = this.generators.filter(
643
- (g) => g instanceof ContentNavigator
644
- );
645
- const results = await Promise.all(legacyGenerators.map((g) => g.getPendingReviews()));
646
- const seen = /* @__PURE__ */ new Set();
647
- const merged = [];
648
- for (const reviews of results) {
649
- for (const review of reviews) {
650
- if (!seen.has(review.cardID)) {
651
- seen.add(review.cardID);
652
- merged.push(review);
653
- }
654
- }
655
- }
656
- return merged;
657
- }
658
916
  };
659
917
  }
660
918
  });
661
919
 
662
- // src/core/navigators/Pipeline.ts
663
- var Pipeline_exports = {};
664
- __export(Pipeline_exports, {
665
- Pipeline: () => Pipeline
666
- });
667
- import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
668
- var Pipeline;
669
- var init_Pipeline = __esm({
670
- "src/core/navigators/Pipeline.ts"() {
671
- "use strict";
672
- init_navigators();
673
- init_logger();
674
- Pipeline = class extends ContentNavigator {
675
- generator;
676
- filters;
677
- /**
678
- * Create a new pipeline.
679
- *
680
- * @param generator - The generator (or CompositeGenerator) that produces candidates
681
- * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
682
- * @param user - User database interface
683
- * @param course - Course database interface
684
- */
685
- constructor(generator, filters, user, course) {
686
- super();
687
- this.generator = generator;
688
- this.filters = filters;
689
- this.user = user;
690
- this.course = course;
691
- logger.debug(
692
- `[Pipeline] Created with generator '${generator.name}' and ${filters.length} filters: ${filters.map((f) => f.name).join(", ")}`
693
- );
694
- }
695
- /**
696
- * Get weighted cards by running generator and applying filters.
697
- *
698
- * 1. Build shared context (user ELO, etc.)
699
- * 2. Get candidates from generator (passing context)
700
- * 3. Apply each filter sequentially
701
- * 4. Remove zero-score cards
702
- * 5. Sort by score descending
703
- * 6. Return top N
704
- *
705
- * @param limit - Maximum number of cards to return
706
- * @returns Cards sorted by score descending
707
- */
708
- async getWeightedCards(limit) {
709
- const context = await this.buildContext();
710
- const overFetchMultiplier = 2 + this.filters.length * 0.5;
711
- const fetchLimit = Math.ceil(limit * overFetchMultiplier);
712
- logger.debug(
713
- `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
714
- );
715
- let cards = await this.generator.getWeightedCards(fetchLimit, context);
716
- logger.debug(`[Pipeline] Generator returned ${cards.length} candidates`);
717
- for (const filter of this.filters) {
718
- const beforeCount = cards.length;
719
- cards = await filter.transform(cards, context);
720
- logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeCount} \u2192 ${cards.length} cards`);
721
- }
722
- cards = cards.filter((c) => c.score > 0);
723
- cards.sort((a, b) => b.score - a.score);
724
- const result = cards.slice(0, limit);
725
- logger.debug(
726
- `[Pipeline] Returning ${result.length} cards (top scores: ${result.slice(0, 3).map((c) => c.score.toFixed(2)).join(", ")}...)`
727
- );
728
- return result;
729
- }
730
- /**
731
- * Build shared context for generator and filters.
732
- *
733
- * Called once per getWeightedCards() invocation.
734
- * Contains data that the generator and multiple filters might need.
735
- *
736
- * The context satisfies both GeneratorContext and FilterContext interfaces.
737
- */
738
- async buildContext() {
739
- let userElo = 1e3;
740
- try {
741
- const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
742
- const courseElo = toCourseElo2(courseReg.elo);
743
- userElo = courseElo.global.score;
744
- } catch (e) {
745
- logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
746
- }
747
- return {
748
- user: this.user,
749
- course: this.course,
750
- userElo
751
- };
752
- }
753
- // ===========================================================================
754
- // Legacy StudyContentSource methods
755
- // ===========================================================================
756
- //
757
- // These delegate to the generator for backward compatibility.
758
- // Eventually SessionController will use getWeightedCards() exclusively.
759
- //
760
- /**
761
- * Get new cards via legacy API.
762
- * Delegates to the generator if it supports the legacy interface.
763
- */
764
- async getNewCards(n) {
765
- if ("getNewCards" in this.generator && typeof this.generator.getNewCards === "function") {
766
- return this.generator.getNewCards(n);
767
- }
768
- return [];
769
- }
770
- /**
771
- * Get pending reviews via legacy API.
772
- * Delegates to the generator if it supports the legacy interface.
773
- */
774
- async getPendingReviews() {
775
- if ("getPendingReviews" in this.generator && typeof this.generator.getPendingReviews === "function") {
776
- return this.generator.getPendingReviews();
777
- }
778
- return [];
779
- }
780
- /**
781
- * Get the course ID for this pipeline.
782
- */
783
- getCourseID() {
784
- return this.course.getCourseID();
785
- }
786
- };
787
- }
788
- });
789
-
790
- // src/core/navigators/PipelineAssembler.ts
791
- var PipelineAssembler_exports = {};
792
- __export(PipelineAssembler_exports, {
793
- PipelineAssembler: () => PipelineAssembler
794
- });
795
- var PipelineAssembler;
796
- var init_PipelineAssembler = __esm({
797
- "src/core/navigators/PipelineAssembler.ts"() {
920
+ // src/core/navigators/PipelineAssembler.ts
921
+ var PipelineAssembler;
922
+ var init_PipelineAssembler = __esm({
923
+ "src/core/navigators/PipelineAssembler.ts"() {
798
924
  "use strict";
799
925
  init_navigators();
800
926
  init_Pipeline();
@@ -912,15 +1038,11 @@ var init_PipelineAssembler = __esm({
912
1038
  }
913
1039
  });
914
1040
 
915
- // src/core/navigators/elo.ts
916
- var elo_exports = {};
917
- __export(elo_exports, {
918
- default: () => ELONavigator
919
- });
1041
+ // src/core/navigators/generators/elo.ts
920
1042
  import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
921
1043
  var ELONavigator;
922
1044
  var init_elo = __esm({
923
- "src/core/navigators/elo.ts"() {
1045
+ "src/core/navigators/generators/elo.ts"() {
924
1046
  "use strict";
925
1047
  init_navigators();
926
1048
  ELONavigator = class extends ContentNavigator {
@@ -930,50 +1052,6 @@ var init_elo = __esm({
930
1052
  super(user, course, strategyData);
931
1053
  this.name = strategyData?.name || "ELO";
932
1054
  }
933
- async getPendingReviews() {
934
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
935
- const elo = await this.course.getCardEloData(reviews.map((r) => r.cardId));
936
- const ratedReviews = reviews.map((r, i) => {
937
- const ratedR = {
938
- ...r,
939
- ...elo[i]
940
- };
941
- return ratedR;
942
- });
943
- ratedReviews.sort((a, b) => {
944
- return a.global.score - b.global.score;
945
- });
946
- return ratedReviews.map((r) => {
947
- return {
948
- ...r,
949
- contentSourceType: "course",
950
- contentSourceID: this.course.getCourseID(),
951
- cardID: r.cardId,
952
- courseID: r.courseId,
953
- qualifiedID: `${r.courseId}-${r.cardId}`,
954
- reviewID: r._id,
955
- status: "review"
956
- };
957
- });
958
- }
959
- async getNewCards(limit = 99) {
960
- const activeCards = await this.user.getActiveCards();
961
- return (await this.course.getCardsCenteredAtELO(
962
- { limit, elo: "user" },
963
- (c) => {
964
- if (activeCards.some((ac) => c.cardID === ac.cardID)) {
965
- return false;
966
- } else {
967
- return true;
968
- }
969
- }
970
- )).map((c) => {
971
- return {
972
- ...c,
973
- status: "new"
974
- };
975
- });
976
- }
977
1055
  /**
978
1056
  * Get new cards with suitability scores based on ELO distance.
979
1057
  *
@@ -998,7 +1076,11 @@ var init_elo = __esm({
998
1076
  const userElo = toCourseElo3(courseReg.elo);
999
1077
  userGlobalElo = userElo.global.score;
1000
1078
  }
1001
- const newCards = await this.getNewCards(limit);
1079
+ const activeCards = await this.user.getActiveCards();
1080
+ const newCards = (await this.course.getCardsCenteredAtELO(
1081
+ { limit, elo: "user" },
1082
+ (c) => !activeCards.some((ac) => c.cardID === ac.cardID)
1083
+ )).map((c) => ({ ...c, status: "new" }));
1002
1084
  const cardIds = newCards.map((c) => c.cardID);
1003
1085
  const cardEloData = await this.course.getCardEloData(cardIds);
1004
1086
  const scored = newCards.map((c, i) => {
@@ -1028,1122 +1110,199 @@ var init_elo = __esm({
1028
1110
  }
1029
1111
  });
1030
1112
 
1031
- // src/core/navigators/filters/eloDistance.ts
1032
- var eloDistance_exports = {};
1033
- __export(eloDistance_exports, {
1034
- DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1035
- DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1036
- DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1037
- createEloDistanceFilter: () => createEloDistanceFilter
1038
- });
1039
- function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1040
- const normalizedDistance = distance / halfLife;
1041
- const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1042
- return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1043
- }
1044
- function createEloDistanceFilter(config) {
1045
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1046
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1047
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1048
- return {
1049
- name: "ELO Distance Filter",
1050
- async transform(cards, context) {
1051
- const { course, userElo } = context;
1052
- const cardIds = cards.map((c) => c.cardId);
1053
- const cardElos = await course.getCardEloData(cardIds);
1054
- return cards.map((card, i) => {
1055
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
1056
- const distance = Math.abs(cardElo - userElo);
1057
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1058
- const newScore = card.score * multiplier;
1059
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1060
- return {
1061
- ...card,
1062
- score: newScore,
1063
- provenance: [
1064
- ...card.provenance,
1065
- {
1066
- strategy: "eloDistance",
1067
- strategyName: "ELO Distance Filter",
1068
- strategyId: "ELO_DISTANCE_FILTER",
1069
- action,
1070
- score: newScore,
1071
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1072
- }
1073
- ]
1074
- };
1075
- });
1076
- }
1077
- };
1078
- }
1079
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1080
- var init_eloDistance = __esm({
1081
- "src/core/navigators/filters/eloDistance.ts"() {
1082
- "use strict";
1083
- DEFAULT_HALF_LIFE = 200;
1084
- DEFAULT_MIN_MULTIPLIER = 0.3;
1085
- DEFAULT_MAX_MULTIPLIER = 1;
1086
- }
1087
- });
1088
-
1089
- // src/core/navigators/filters/index.ts
1090
- var filters_exports = {};
1091
- __export(filters_exports, {
1092
- createEloDistanceFilter: () => createEloDistanceFilter
1093
- });
1094
- var init_filters = __esm({
1095
- "src/core/navigators/filters/index.ts"() {
1096
- "use strict";
1097
- init_eloDistance();
1098
- }
1099
- });
1100
-
1101
- // src/core/navigators/filters/types.ts
1102
- var types_exports = {};
1103
- var init_types = __esm({
1104
- "src/core/navigators/filters/types.ts"() {
1105
- "use strict";
1106
- }
1107
- });
1108
-
1109
- // src/core/navigators/generators/index.ts
1110
- var generators_exports = {};
1111
- var init_generators = __esm({
1112
- "src/core/navigators/generators/index.ts"() {
1113
- "use strict";
1114
- }
1115
- });
1116
-
1117
- // src/core/navigators/generators/types.ts
1118
- var types_exports2 = {};
1119
- var init_types2 = __esm({
1120
- "src/core/navigators/generators/types.ts"() {
1121
- "use strict";
1122
- }
1123
- });
1124
-
1125
- // src/core/navigators/hardcodedOrder.ts
1126
- var hardcodedOrder_exports = {};
1127
- __export(hardcodedOrder_exports, {
1128
- default: () => HardcodedOrderNavigator
1129
- });
1130
- var HardcodedOrderNavigator;
1131
- var init_hardcodedOrder = __esm({
1132
- "src/core/navigators/hardcodedOrder.ts"() {
1133
- "use strict";
1134
- init_navigators();
1135
- init_logger();
1136
- HardcodedOrderNavigator = class extends ContentNavigator {
1137
- /** Human-readable name for CardGenerator interface */
1138
- name;
1139
- orderedCardIds = [];
1140
- constructor(user, course, strategyData) {
1141
- super(user, course, strategyData);
1142
- this.name = strategyData.name || "Hardcoded Order";
1143
- if (strategyData.serializedData) {
1144
- try {
1145
- this.orderedCardIds = JSON.parse(strategyData.serializedData);
1146
- } catch (e) {
1147
- logger.error("Failed to parse serializedData for HardcodedOrderNavigator", e);
1148
- }
1149
- }
1150
- }
1151
- async getPendingReviews() {
1152
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1153
- return reviews.map((r) => {
1154
- return {
1155
- ...r,
1156
- contentSourceType: "course",
1157
- contentSourceID: this.course.getCourseID(),
1158
- cardID: r.cardId,
1159
- courseID: r.courseId,
1160
- reviewID: r._id,
1161
- status: "review"
1162
- };
1163
- });
1164
- }
1165
- async getNewCards(limit = 99) {
1166
- const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
1167
- const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
1168
- const cardsToReturn = newCardIds.slice(0, limit);
1169
- return cardsToReturn.map((cardId) => {
1170
- return {
1171
- cardID: cardId,
1172
- courseID: this.course.getCourseID(),
1173
- contentSourceType: "course",
1174
- contentSourceID: this.course.getCourseID(),
1175
- status: "new"
1176
- };
1177
- });
1178
- }
1179
- /**
1180
- * Get cards in hardcoded order with scores based on position.
1181
- *
1182
- * Earlier cards in the sequence get higher scores.
1183
- * Score formula: 1.0 - (position / totalCards) * 0.5
1184
- * This ensures scores range from 1.0 (first card) to 0.5+ (last card).
1185
- *
1186
- * This method supports both the legacy signature (limit only) and the
1187
- * CardGenerator interface signature (limit, context).
1188
- *
1189
- * @param limit - Maximum number of cards to return
1190
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1191
- */
1192
- async getWeightedCards(limit, _context) {
1193
- const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
1194
- const reviews = await this.getPendingReviews();
1195
- const newCardIds = this.orderedCardIds.filter((cardId) => !activeCardIds.includes(cardId));
1196
- const totalCards = newCardIds.length;
1197
- const scoredNew = newCardIds.slice(0, limit).map((cardId, index) => {
1198
- const position = index + 1;
1199
- const score = Math.max(0.5, 1 - index / totalCards * 0.5);
1200
- return {
1201
- cardId,
1202
- courseId: this.course.getCourseID(),
1203
- score,
1204
- provenance: [
1205
- {
1206
- strategy: "hardcodedOrder",
1207
- strategyName: this.strategyName || this.name,
1208
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1209
- action: "generated",
1210
- score,
1211
- reason: `Position ${position} of ${totalCards} in fixed sequence, new card`
1212
- }
1213
- ]
1214
- };
1215
- });
1216
- const scoredReviews = reviews.map((r) => ({
1217
- cardId: r.cardID,
1218
- courseId: r.courseID,
1219
- score: 1,
1220
- provenance: [
1221
- {
1222
- strategy: "hardcodedOrder",
1223
- strategyName: this.strategyName || this.name,
1224
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hardcoded",
1225
- action: "generated",
1226
- score: 1,
1227
- reason: "Scheduled review, highest priority"
1228
- }
1229
- ]
1230
- }));
1231
- const all = [...scoredReviews, ...scoredNew];
1232
- all.sort((a, b) => b.score - a.score);
1233
- return all.slice(0, limit);
1234
- }
1235
- };
1236
- }
1237
- });
1238
-
1239
- // src/core/navigators/hierarchyDefinition.ts
1240
- var hierarchyDefinition_exports = {};
1241
- __export(hierarchyDefinition_exports, {
1242
- default: () => HierarchyDefinitionNavigator
1243
- });
1244
- import { toCourseElo as toCourseElo4 } from "@vue-skuilder/common";
1245
- var DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1246
- var init_hierarchyDefinition = __esm({
1247
- "src/core/navigators/hierarchyDefinition.ts"() {
1248
- "use strict";
1249
- init_navigators();
1250
- DEFAULT_MIN_COUNT = 3;
1251
- HierarchyDefinitionNavigator = class extends ContentNavigator {
1252
- config;
1253
- _strategyData;
1254
- /** Human-readable name for CardFilter interface */
1255
- name;
1256
- constructor(user, course, _strategyData) {
1257
- super(user, course, _strategyData);
1258
- this._strategyData = _strategyData;
1259
- this.config = this.parseConfig(_strategyData.serializedData);
1260
- this.name = _strategyData.name || "Hierarchy Definition";
1261
- }
1262
- parseConfig(serializedData) {
1263
- try {
1264
- const parsed = JSON.parse(serializedData);
1265
- return {
1266
- prerequisites: parsed.prerequisites || {}
1267
- };
1268
- } catch {
1269
- return {
1270
- prerequisites: {}
1271
- };
1272
- }
1273
- }
1274
- /**
1275
- * Check if a specific prerequisite is satisfied
1276
- */
1277
- isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1278
- if (!userTagElo) return false;
1279
- const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1280
- if (userTagElo.count < minCount) return false;
1281
- if (prereq.masteryThreshold?.minElo !== void 0) {
1282
- return userTagElo.score >= prereq.masteryThreshold.minElo;
1283
- } else {
1284
- return userTagElo.score >= userGlobalElo;
1285
- }
1286
- }
1287
- /**
1288
- * Get the set of tags the user has mastered.
1289
- * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1290
- */
1291
- async getMasteredTags(context) {
1292
- const mastered = /* @__PURE__ */ new Set();
1293
- try {
1294
- const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1295
- const userElo = toCourseElo4(courseReg.elo);
1296
- for (const prereqs of Object.values(this.config.prerequisites)) {
1297
- for (const prereq of prereqs) {
1298
- const tagElo = userElo.tags[prereq.tag];
1299
- if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1300
- mastered.add(prereq.tag);
1301
- }
1302
- }
1303
- }
1304
- } catch {
1305
- }
1306
- return mastered;
1307
- }
1308
- /**
1309
- * Get the set of tags that are unlocked (prerequisites met)
1310
- */
1311
- getUnlockedTags(masteredTags) {
1312
- const unlocked = /* @__PURE__ */ new Set();
1313
- for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1314
- const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1315
- if (allPrereqsMet) {
1316
- unlocked.add(tagId);
1317
- }
1318
- }
1319
- return unlocked;
1320
- }
1321
- /**
1322
- * Check if a tag has prerequisites defined in config
1323
- */
1324
- hasPrerequisites(tagId) {
1325
- return tagId in this.config.prerequisites;
1326
- }
1327
- /**
1328
- * Check if a card is unlocked and generate reason.
1329
- */
1330
- async checkCardUnlock(cardId, course, unlockedTags, masteredTags) {
1331
- try {
1332
- const tagResponse = await course.getAppliedTags(cardId);
1333
- const cardTags = tagResponse.rows.map((row) => row.value?.name || row.key);
1334
- const lockedTags = cardTags.filter(
1335
- (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1336
- );
1337
- if (lockedTags.length === 0) {
1338
- const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1339
- return {
1340
- isUnlocked: true,
1341
- reason: `Prerequisites met, tags: ${tagList}`
1342
- };
1343
- }
1344
- const missingPrereqs = lockedTags.flatMap((tag) => {
1345
- const prereqs = this.config.prerequisites[tag] || [];
1346
- return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1347
- });
1348
- return {
1349
- isUnlocked: false,
1350
- reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1351
- };
1352
- } catch {
1353
- return {
1354
- isUnlocked: true,
1355
- reason: "Prerequisites check skipped (tag lookup failed)"
1356
- };
1357
- }
1358
- }
1359
- /**
1360
- * CardFilter.transform implementation.
1361
- *
1362
- * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1363
- */
1364
- async transform(cards, context) {
1365
- const masteredTags = await this.getMasteredTags(context);
1366
- const unlockedTags = this.getUnlockedTags(masteredTags);
1367
- const gated = [];
1368
- for (const card of cards) {
1369
- const { isUnlocked, reason } = await this.checkCardUnlock(
1370
- card.cardId,
1371
- context.course,
1372
- unlockedTags,
1373
- masteredTags
1374
- );
1375
- const finalScore = isUnlocked ? card.score : 0;
1376
- const action = isUnlocked ? "passed" : "penalized";
1377
- gated.push({
1378
- ...card,
1379
- score: finalScore,
1380
- provenance: [
1381
- ...card.provenance,
1382
- {
1383
- strategy: "hierarchyDefinition",
1384
- strategyName: this.strategyName || this.name,
1385
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1386
- action,
1387
- score: finalScore,
1388
- reason
1389
- }
1390
- ]
1391
- });
1392
- }
1393
- return gated;
1394
- }
1395
- /**
1396
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
1397
- *
1398
- * Use transform() via Pipeline instead.
1399
- */
1400
- async getWeightedCards(_limit) {
1401
- throw new Error(
1402
- "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1403
- );
1404
- }
1405
- // Legacy methods - stub implementations since filters don't generate cards
1406
- async getNewCards(_n) {
1407
- return [];
1408
- }
1409
- async getPendingReviews() {
1410
- return [];
1411
- }
1412
- };
1413
- }
1414
- });
1415
-
1416
- // src/core/navigators/interferenceMitigator.ts
1417
- var interferenceMitigator_exports = {};
1418
- __export(interferenceMitigator_exports, {
1419
- default: () => InterferenceMitigatorNavigator
1420
- });
1421
- import { toCourseElo as toCourseElo5 } from "@vue-skuilder/common";
1422
- var DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1423
- var init_interferenceMitigator = __esm({
1424
- "src/core/navigators/interferenceMitigator.ts"() {
1425
- "use strict";
1426
- init_navigators();
1427
- DEFAULT_MIN_COUNT2 = 10;
1428
- DEFAULT_MIN_ELAPSED_DAYS = 3;
1429
- DEFAULT_INTERFERENCE_DECAY = 0.8;
1430
- InterferenceMitigatorNavigator = class extends ContentNavigator {
1431
- config;
1432
- _strategyData;
1433
- /** Human-readable name for CardFilter interface */
1434
- name;
1435
- /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1436
- interferenceMap;
1437
- constructor(user, course, _strategyData) {
1438
- super(user, course, _strategyData);
1439
- this._strategyData = _strategyData;
1440
- this.config = this.parseConfig(_strategyData.serializedData);
1441
- this.interferenceMap = this.buildInterferenceMap();
1442
- this.name = _strategyData.name || "Interference Mitigator";
1443
- }
1444
- parseConfig(serializedData) {
1445
- try {
1446
- const parsed = JSON.parse(serializedData);
1447
- let sets = parsed.interferenceSets || [];
1448
- if (sets.length > 0 && Array.isArray(sets[0])) {
1449
- sets = sets.map((tags) => ({ tags }));
1450
- }
1451
- return {
1452
- interferenceSets: sets,
1453
- maturityThreshold: {
1454
- minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1455
- minElo: parsed.maturityThreshold?.minElo,
1456
- minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1457
- },
1458
- defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1459
- };
1460
- } catch {
1461
- return {
1462
- interferenceSets: [],
1463
- maturityThreshold: {
1464
- minCount: DEFAULT_MIN_COUNT2,
1465
- minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1466
- },
1467
- defaultDecay: DEFAULT_INTERFERENCE_DECAY
1468
- };
1469
- }
1470
- }
1471
- /**
1472
- * Build a map from each tag to its interference partners with decay coefficients.
1473
- * If tags A, B, C are in an interference group with decay 0.8, then:
1474
- * - A interferes with B (decay 0.8) and C (decay 0.8)
1475
- * - B interferes with A (decay 0.8) and C (decay 0.8)
1476
- * - etc.
1477
- */
1478
- buildInterferenceMap() {
1479
- const map = /* @__PURE__ */ new Map();
1480
- for (const group of this.config.interferenceSets) {
1481
- const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
1482
- for (const tag of group.tags) {
1483
- if (!map.has(tag)) {
1484
- map.set(tag, []);
1485
- }
1486
- const partners = map.get(tag);
1487
- for (const other of group.tags) {
1488
- if (other !== tag) {
1489
- const existing = partners.find((p) => p.partner === other);
1490
- if (existing) {
1491
- existing.decay = Math.max(existing.decay, decay);
1492
- } else {
1493
- partners.push({ partner: other, decay });
1494
- }
1495
- }
1496
- }
1497
- }
1498
- }
1499
- return map;
1500
- }
1501
- /**
1502
- * Get the set of tags that are currently immature for this user.
1503
- * A tag is immature if the user has interacted with it but hasn't
1504
- * reached the maturity threshold.
1505
- */
1506
- async getImmatureTags(context) {
1507
- const immature = /* @__PURE__ */ new Set();
1508
- try {
1509
- const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1510
- const userElo = toCourseElo5(courseReg.elo);
1511
- const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
1512
- const minElo = this.config.maturityThreshold?.minElo;
1513
- const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
1514
- const minCountForElapsed = minElapsedDays * 2;
1515
- for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
1516
- if (tagElo.count === 0) continue;
1517
- const belowCount = tagElo.count < minCount;
1518
- const belowElo = minElo !== void 0 && tagElo.score < minElo;
1519
- const belowElapsed = tagElo.count < minCountForElapsed;
1520
- if (belowCount || belowElo || belowElapsed) {
1521
- immature.add(tagId);
1522
- }
1523
- }
1524
- } catch {
1525
- }
1526
- return immature;
1527
- }
1528
- /**
1529
- * Get all tags that interfere with any immature tag, along with their decay coefficients.
1530
- * These are the tags we want to avoid introducing.
1531
- */
1532
- getTagsToAvoid(immatureTags) {
1533
- const avoid = /* @__PURE__ */ new Map();
1534
- for (const immatureTag of immatureTags) {
1535
- const partners = this.interferenceMap.get(immatureTag);
1536
- if (partners) {
1537
- for (const { partner, decay } of partners) {
1538
- if (!immatureTags.has(partner)) {
1539
- const existing = avoid.get(partner) ?? 0;
1540
- avoid.set(partner, Math.max(existing, decay));
1541
- }
1542
- }
1543
- }
1544
- }
1545
- return avoid;
1546
- }
1547
- /**
1548
- * Get tags for a single card
1549
- */
1550
- async getCardTags(cardId, course) {
1551
- try {
1552
- const tagResponse = await course.getAppliedTags(cardId);
1553
- return tagResponse.rows.map((row) => row.value?.name || row.key).filter(Boolean);
1554
- } catch {
1555
- return [];
1556
- }
1557
- }
1558
- /**
1559
- * Compute interference score reduction for a card.
1560
- * Returns: { multiplier, interfering tags, reason }
1561
- */
1562
- computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
1563
- if (tagsToAvoid.size === 0) {
1564
- return {
1565
- multiplier: 1,
1566
- interferingTags: [],
1567
- reason: "No interference detected"
1568
- };
1569
- }
1570
- let multiplier = 1;
1571
- const interferingTags = [];
1572
- for (const tag of cardTags) {
1573
- const decay = tagsToAvoid.get(tag);
1574
- if (decay !== void 0) {
1575
- interferingTags.push(tag);
1576
- multiplier *= 1 - decay;
1577
- }
1578
- }
1579
- if (interferingTags.length === 0) {
1580
- return {
1581
- multiplier: 1,
1582
- interferingTags: [],
1583
- reason: "No interference detected"
1584
- };
1585
- }
1586
- const causingTags = /* @__PURE__ */ new Set();
1587
- for (const tag of interferingTags) {
1588
- for (const immatureTag of immatureTags) {
1589
- const partners = this.interferenceMap.get(immatureTag);
1590
- if (partners?.some((p) => p.partner === tag)) {
1591
- causingTags.add(immatureTag);
1592
- }
1593
- }
1594
- }
1595
- const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
1596
- return { multiplier, interferingTags, reason };
1597
- }
1598
- /**
1599
- * CardFilter.transform implementation.
1600
- *
1601
- * Apply interference-aware scoring. Cards with tags that interfere with
1602
- * immature learnings get reduced scores.
1603
- */
1604
- async transform(cards, context) {
1605
- const immatureTags = await this.getImmatureTags(context);
1606
- const tagsToAvoid = this.getTagsToAvoid(immatureTags);
1607
- const adjusted = [];
1608
- for (const card of cards) {
1609
- const cardTags = await this.getCardTags(card.cardId, context.course);
1610
- const { multiplier, reason } = this.computeInterferenceEffect(
1611
- cardTags,
1612
- tagsToAvoid,
1613
- immatureTags
1614
- );
1615
- const finalScore = card.score * multiplier;
1616
- const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
1617
- adjusted.push({
1618
- ...card,
1619
- score: finalScore,
1620
- provenance: [
1621
- ...card.provenance,
1622
- {
1623
- strategy: "interferenceMitigator",
1624
- strategyName: this.strategyName || this.name,
1625
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
1626
- action,
1627
- score: finalScore,
1628
- reason
1629
- }
1630
- ]
1631
- });
1632
- }
1633
- return adjusted;
1634
- }
1635
- /**
1636
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
1637
- *
1638
- * Use transform() via Pipeline instead.
1639
- */
1640
- async getWeightedCards(_limit) {
1641
- throw new Error(
1642
- "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1643
- );
1644
- }
1645
- // Legacy methods - stub implementations since filters don't generate cards
1646
- async getNewCards(_n) {
1647
- return [];
1648
- }
1649
- async getPendingReviews() {
1650
- return [];
1651
- }
1652
- };
1653
- }
1654
- });
1655
-
1656
- // src/core/navigators/relativePriority.ts
1657
- var relativePriority_exports = {};
1658
- __export(relativePriority_exports, {
1659
- default: () => RelativePriorityNavigator
1660
- });
1661
- var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
1662
- var init_relativePriority = __esm({
1663
- "src/core/navigators/relativePriority.ts"() {
1664
- "use strict";
1665
- init_navigators();
1666
- DEFAULT_PRIORITY = 0.5;
1667
- DEFAULT_PRIORITY_INFLUENCE = 0.5;
1668
- DEFAULT_COMBINE_MODE = "max";
1669
- RelativePriorityNavigator = class extends ContentNavigator {
1670
- config;
1671
- _strategyData;
1672
- /** Human-readable name for CardFilter interface */
1673
- name;
1674
- constructor(user, course, _strategyData) {
1675
- super(user, course, _strategyData);
1676
- this._strategyData = _strategyData;
1677
- this.config = this.parseConfig(_strategyData.serializedData);
1678
- this.name = _strategyData.name || "Relative Priority";
1679
- }
1680
- parseConfig(serializedData) {
1681
- try {
1682
- const parsed = JSON.parse(serializedData);
1683
- return {
1684
- tagPriorities: parsed.tagPriorities || {},
1685
- defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
1686
- combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
1687
- priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
1688
- };
1689
- } catch {
1690
- return {
1691
- tagPriorities: {},
1692
- defaultPriority: DEFAULT_PRIORITY,
1693
- combineMode: DEFAULT_COMBINE_MODE,
1694
- priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
1695
- };
1696
- }
1697
- }
1698
- /**
1699
- * Look up the priority for a tag.
1700
- */
1701
- getTagPriority(tagId) {
1702
- return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
1703
- }
1704
- /**
1705
- * Compute combined priority for a card based on its tags.
1706
- */
1707
- computeCardPriority(cardTags) {
1708
- if (cardTags.length === 0) {
1709
- return this.config.defaultPriority ?? DEFAULT_PRIORITY;
1710
- }
1711
- const priorities = cardTags.map((tag) => this.getTagPriority(tag));
1712
- switch (this.config.combineMode) {
1713
- case "max":
1714
- return Math.max(...priorities);
1715
- case "min":
1716
- return Math.min(...priorities);
1717
- case "average":
1718
- return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
1719
- default:
1720
- return Math.max(...priorities);
1721
- }
1722
- }
1723
- /**
1724
- * Compute boost factor based on priority.
1725
- *
1726
- * The formula: 1 + (priority - 0.5) * priorityInfluence
1727
- *
1728
- * This creates a multiplier centered around 1.0:
1729
- * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
1730
- * - Priority 0.5 with any influence → 1.00 (neutral)
1731
- * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
1732
- */
1733
- computeBoostFactor(priority) {
1734
- const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
1735
- return 1 + (priority - 0.5) * influence;
1736
- }
1737
- /**
1738
- * Build human-readable reason for priority adjustment.
1739
- */
1740
- buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
1741
- if (cardTags.length === 0) {
1742
- return `No tags, neutral priority (${priority.toFixed(2)})`;
1743
- }
1744
- const tagList = cardTags.slice(0, 3).join(", ");
1745
- const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
1746
- if (boostFactor === 1) {
1747
- return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
1748
- } else if (boostFactor > 1) {
1749
- return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1750
- } else {
1751
- return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
1752
- }
1753
- }
1754
- /**
1755
- * Get tags for a single card.
1756
- */
1757
- async getCardTags(cardId, course) {
1758
- try {
1759
- const tagResponse = await course.getAppliedTags(cardId);
1760
- return tagResponse.rows.map((r) => r.doc?.name).filter((x) => !!x);
1761
- } catch {
1762
- return [];
1763
- }
1764
- }
1765
- /**
1766
- * CardFilter.transform implementation.
1767
- *
1768
- * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
1769
- * cards with low-priority tags get reduced scores.
1770
- */
1771
- async transform(cards, context) {
1772
- const adjusted = await Promise.all(
1773
- cards.map(async (card) => {
1774
- const cardTags = await this.getCardTags(card.cardId, context.course);
1775
- const priority = this.computeCardPriority(cardTags);
1776
- const boostFactor = this.computeBoostFactor(priority);
1777
- const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
1778
- const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
1779
- const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
1780
- return {
1781
- ...card,
1782
- score: finalScore,
1783
- provenance: [
1784
- ...card.provenance,
1785
- {
1786
- strategy: "relativePriority",
1787
- strategyName: this.strategyName || this.name,
1788
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
1789
- action,
1790
- score: finalScore,
1791
- reason
1792
- }
1793
- ]
1794
- };
1795
- })
1796
- );
1797
- return adjusted;
1798
- }
1799
- /**
1800
- * Legacy getWeightedCards - now throws as filters should not be used as generators.
1801
- *
1802
- * Use transform() via Pipeline instead.
1803
- */
1804
- async getWeightedCards(_limit) {
1805
- throw new Error(
1806
- "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1807
- );
1808
- }
1809
- // Legacy methods - stub implementations since filters don't generate cards
1810
- async getNewCards(_n) {
1811
- return [];
1812
- }
1813
- async getPendingReviews() {
1814
- return [];
1815
- }
1816
- };
1817
- }
1818
- });
1819
-
1820
- // src/core/navigators/srs.ts
1821
- var srs_exports = {};
1822
- __export(srs_exports, {
1823
- default: () => SRSNavigator
1824
- });
1825
- import moment3 from "moment";
1826
- var SRSNavigator;
1827
- var init_srs = __esm({
1828
- "src/core/navigators/srs.ts"() {
1829
- "use strict";
1830
- init_navigators();
1831
- SRSNavigator = class extends ContentNavigator {
1832
- /** Human-readable name for CardGenerator interface */
1833
- name;
1834
- constructor(user, course, strategyData) {
1835
- super(user, course, strategyData);
1836
- this.name = strategyData?.name || "SRS";
1837
- }
1838
- /**
1839
- * Get review cards scored by urgency.
1840
- *
1841
- * Score formula combines:
1842
- * - Relative overdueness: hoursOverdue / intervalHours
1843
- * - Interval recency: exponential decay favoring shorter intervals
1844
- *
1845
- * Cards not yet due are excluded (not scored as 0).
1846
- *
1847
- * This method supports both the legacy signature (limit only) and the
1848
- * CardGenerator interface signature (limit, context).
1849
- *
1850
- * @param limit - Maximum number of cards to return
1851
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1852
- */
1853
- async getWeightedCards(limit, _context) {
1854
- if (!this.user || !this.course) {
1855
- throw new Error("SRSNavigator requires user and course to be set");
1856
- }
1857
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1858
- const now = moment3.utc();
1859
- const dueReviews = reviews.filter((r) => now.isAfter(moment3.utc(r.reviewTime)));
1860
- const scored = dueReviews.map((review) => {
1861
- const { score, reason } = this.computeUrgencyScore(review, now);
1862
- return {
1863
- cardId: review.cardId,
1864
- courseId: review.courseId,
1865
- score,
1866
- provenance: [
1867
- {
1868
- strategy: "srs",
1869
- strategyName: this.strategyName || this.name,
1870
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1871
- action: "generated",
1872
- score,
1873
- reason
1874
- }
1875
- ]
1876
- };
1877
- });
1878
- return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1879
- }
1880
- /**
1881
- * Compute urgency score for a review card.
1882
- *
1883
- * Two factors:
1884
- * 1. Relative overdueness = hoursOverdue / intervalHours
1885
- * - 2 days overdue on 3-day interval = 0.67 (urgent)
1886
- * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1887
- *
1888
- * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1889
- * - 24h interval → ~1.0 (very recent learning)
1890
- * - 30 days (720h) → ~0.56
1891
- * - 180 days → ~0.30
1892
- *
1893
- * Combined: base 0.5 + weighted average of factors * 0.45
1894
- * Result range: approximately 0.5 to 0.95
1895
- */
1896
- computeUrgencyScore(review, now) {
1897
- const scheduledAt = moment3.utc(review.scheduledAt);
1898
- const due = moment3.utc(review.reviewTime);
1899
- const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1900
- const hoursOverdue = now.diff(due, "hours");
1901
- const relativeOverdue = hoursOverdue / intervalHours;
1902
- const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1903
- const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1904
- const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1905
- const score = Math.min(0.95, 0.5 + urgency * 0.45);
1906
- const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
1907
- return { score, reason };
1908
- }
1909
- /**
1910
- * Get pending reviews in legacy format.
1911
- *
1912
- * Returns all pending reviews for the course, enriched with session item fields.
1913
- */
1914
- async getPendingReviews() {
1915
- if (!this.user || !this.course) {
1916
- throw new Error("SRSNavigator requires user and course to be set");
1917
- }
1918
- const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1919
- return reviews.map((r) => ({
1920
- ...r,
1921
- contentSourceType: "course",
1922
- contentSourceID: this.course.getCourseID(),
1923
- cardID: r.cardId,
1924
- courseID: r.courseId,
1925
- qualifiedID: `${r.courseId}-${r.cardId}`,
1926
- reviewID: r._id,
1927
- status: "review"
1928
- }));
1929
- }
1930
- /**
1931
- * SRS does not generate new cards.
1932
- * Use ELONavigator or another generator for new cards.
1933
- */
1934
- async getNewCards(_n) {
1935
- return [];
1936
- }
1937
- };
1938
- }
1939
- });
1940
-
1941
- // import("./**/*") in src/core/navigators/index.ts
1942
- var globImport;
1943
- var init_ = __esm({
1944
- 'import("./**/*") in src/core/navigators/index.ts'() {
1945
- globImport = __glob({
1946
- "./CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
1947
- "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
1948
- "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
1949
- "./elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
1950
- "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
1951
- "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
1952
- "./filters/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
1953
- "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
1954
- "./generators/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
1955
- "./hardcodedOrder.ts": () => Promise.resolve().then(() => (init_hardcodedOrder(), hardcodedOrder_exports)),
1956
- "./hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
1957
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
1958
- "./interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
1959
- "./relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
1960
- "./srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports))
1961
- });
1962
- }
1963
- });
1964
-
1965
- // src/core/navigators/index.ts
1966
- var navigators_exports = {};
1967
- __export(navigators_exports, {
1968
- ContentNavigator: () => ContentNavigator,
1969
- NavigatorRole: () => NavigatorRole,
1970
- NavigatorRoles: () => NavigatorRoles,
1971
- Navigators: () => Navigators,
1972
- getCardOrigin: () => getCardOrigin,
1973
- isFilter: () => isFilter,
1974
- isGenerator: () => isGenerator
1975
- });
1976
- function getCardOrigin(card) {
1977
- if (card.provenance.length === 0) {
1978
- throw new Error("Card has no provenance - cannot determine origin");
1979
- }
1980
- const firstEntry = card.provenance[0];
1981
- const reason = firstEntry.reason.toLowerCase();
1982
- if (reason.includes("failed")) {
1983
- return "failed";
1984
- }
1985
- if (reason.includes("review")) {
1986
- return "review";
1987
- }
1988
- return "new";
1989
- }
1990
- function isGenerator(impl) {
1991
- return NavigatorRoles[impl] === "generator" /* GENERATOR */;
1992
- }
1993
- function isFilter(impl) {
1994
- return NavigatorRoles[impl] === "filter" /* FILTER */;
1995
- }
1996
- var Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
1997
- var init_navigators = __esm({
1998
- "src/core/navigators/index.ts"() {
1999
- "use strict";
2000
- init_logger();
2001
- init_();
2002
- Navigators = /* @__PURE__ */ ((Navigators2) => {
2003
- Navigators2["ELO"] = "elo";
2004
- Navigators2["SRS"] = "srs";
2005
- Navigators2["HARDCODED"] = "hardcodedOrder";
2006
- Navigators2["HIERARCHY"] = "hierarchyDefinition";
2007
- Navigators2["INTERFERENCE"] = "interferenceMitigator";
2008
- Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
2009
- return Navigators2;
2010
- })(Navigators || {});
2011
- NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
2012
- NavigatorRole2["GENERATOR"] = "generator";
2013
- NavigatorRole2["FILTER"] = "filter";
2014
- return NavigatorRole2;
2015
- })(NavigatorRole || {});
2016
- NavigatorRoles = {
2017
- ["elo" /* ELO */]: "generator" /* GENERATOR */,
2018
- ["srs" /* SRS */]: "generator" /* GENERATOR */,
2019
- ["hardcodedOrder" /* HARDCODED */]: "generator" /* GENERATOR */,
2020
- ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
2021
- ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
2022
- ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */
2023
- };
2024
- ContentNavigator = class {
2025
- /** User interface for this navigation session */
2026
- user;
2027
- /** Course interface for this navigation session */
2028
- course;
2029
- /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
2030
- strategyName;
2031
- /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
2032
- strategyId;
2033
- /**
2034
- * Constructor for standard navigators.
2035
- * Call this from subclass constructors to initialize common fields.
2036
- *
2037
- * Note: CompositeGenerator doesn't use this pattern and should call super() without args.
2038
- */
2039
- constructor(user, course, strategyData) {
2040
- if (user && course && strategyData) {
2041
- this.user = user;
2042
- this.course = course;
2043
- this.strategyName = strategyData.name;
2044
- this.strategyId = strategyData._id;
2045
- }
2046
- }
2047
- /**
2048
- * Factory method to create navigator instances dynamically.
2049
- *
2050
- * @param user - User interface
2051
- * @param course - Course interface
2052
- * @param strategyData - Strategy configuration document
2053
- * @returns the runtime object used to steer a study session.
2054
- */
2055
- static async create(user, course, strategyData) {
2056
- const implementingClass = strategyData.implementingClass;
2057
- let NavigatorImpl;
2058
- const variations = [".ts", ".js", ""];
2059
- for (const ext of variations) {
2060
- try {
2061
- const module = await globImport(`./${implementingClass}${ext}`);
2062
- NavigatorImpl = module.default;
2063
- break;
2064
- } catch (e) {
2065
- logger.debug(`Failed to load with extension ${ext}:`, e);
2066
- }
2067
- }
2068
- if (!NavigatorImpl) {
2069
- throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
2070
- }
2071
- return new NavigatorImpl(user, course, strategyData);
1113
+ // src/core/navigators/generators/srs.ts
1114
+ import moment3 from "moment";
1115
+ var SRSNavigator;
1116
+ var init_srs = __esm({
1117
+ "src/core/navigators/generators/srs.ts"() {
1118
+ "use strict";
1119
+ init_navigators();
1120
+ init_logger();
1121
+ SRSNavigator = class extends ContentNavigator {
1122
+ /** Human-readable name for CardGenerator interface */
1123
+ name;
1124
+ constructor(user, course, strategyData) {
1125
+ super(user, course, strategyData);
1126
+ this.name = strategyData?.name || "SRS";
2072
1127
  }
2073
1128
  /**
2074
- * Get cards with suitability scores and provenance trails.
2075
- *
2076
- * **This is the PRIMARY API for navigation strategies.**
2077
- *
2078
- * Returns cards ranked by suitability score (0-1). Higher scores indicate
2079
- * better candidates for presentation. Each card includes a provenance trail
2080
- * documenting how strategies contributed to the final score.
1129
+ * Get review cards scored by urgency.
2081
1130
  *
2082
- * ## For Generators
2083
- * Override this method to generate candidates and compute scores based on
2084
- * your strategy's logic (e.g., ELO proximity, review urgency). Create the
2085
- * initial provenance entry with action='generated'.
1131
+ * Score formula combines:
1132
+ * - Relative overdueness: hoursOverdue / intervalHours
1133
+ * - Interval recency: exponential decay favoring shorter intervals
2086
1134
  *
2087
- * ## Default Implementation
2088
- * The base class provides a backward-compatible default that:
2089
- * 1. Calls legacy getNewCards() and getPendingReviews()
2090
- * 2. Assigns score=1.0 to all cards
2091
- * 3. Creates minimal provenance from legacy methods
2092
- * 4. Returns combined results up to limit
1135
+ * Cards not yet due are excluded (not scored as 0).
2093
1136
  *
2094
- * This allows existing strategies to work without modification while
2095
- * new strategies can override with proper scoring and provenance.
1137
+ * This method supports both the legacy signature (limit only) and the
1138
+ * CardGenerator interface signature (limit, context).
2096
1139
  *
2097
- * @param limit - Maximum cards to return
2098
- * @returns Cards sorted by score descending, with provenance trails
1140
+ * @param limit - Maximum number of cards to return
1141
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
2099
1142
  */
2100
- async getWeightedCards(limit) {
2101
- const newCards = await this.getNewCards(limit);
2102
- const reviews = await this.getPendingReviews();
2103
- const weighted = [
2104
- ...newCards.map((c) => ({
2105
- cardId: c.cardID,
2106
- courseId: c.courseID,
2107
- score: 1,
2108
- provenance: [
2109
- {
2110
- strategy: "legacy",
2111
- strategyName: this.strategyName || "Legacy API",
2112
- strategyId: this.strategyId || "legacy-fallback",
2113
- action: "generated",
2114
- score: 1,
2115
- reason: "Generated via legacy getNewCards(), new card"
2116
- }
2117
- ]
2118
- })),
2119
- ...reviews.map((r) => ({
2120
- cardId: r.cardID,
2121
- courseId: r.courseID,
2122
- score: 1,
1143
+ async getWeightedCards(limit, _context) {
1144
+ if (!this.user || !this.course) {
1145
+ throw new Error("SRSNavigator requires user and course to be set");
1146
+ }
1147
+ const reviews = await this.user.getPendingReviews(this.course.getCourseID());
1148
+ const now = moment3.utc();
1149
+ const dueReviews = reviews.filter((r) => now.isAfter(moment3.utc(r.reviewTime)));
1150
+ const scored = dueReviews.map((review) => {
1151
+ const { score, reason } = this.computeUrgencyScore(review, now);
1152
+ return {
1153
+ cardId: review.cardId,
1154
+ courseId: review.courseId,
1155
+ score,
1156
+ reviewID: review._id,
2123
1157
  provenance: [
2124
1158
  {
2125
- strategy: "legacy",
2126
- strategyName: this.strategyName || "Legacy API",
2127
- strategyId: this.strategyId || "legacy-fallback",
1159
+ strategy: "srs",
1160
+ strategyName: this.strategyName || this.name,
1161
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
2128
1162
  action: "generated",
2129
- score: 1,
2130
- reason: "Generated via legacy getPendingReviews(), review"
1163
+ score,
1164
+ reason
2131
1165
  }
2132
1166
  ]
2133
- }))
2134
- ];
2135
- return weighted.slice(0, limit);
1167
+ };
1168
+ });
1169
+ logger.debug(`[srsNav] got ${scored.length} weighted cards`);
1170
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1171
+ }
1172
+ /**
1173
+ * Compute urgency score for a review card.
1174
+ *
1175
+ * Two factors:
1176
+ * 1. Relative overdueness = hoursOverdue / intervalHours
1177
+ * - 2 days overdue on 3-day interval = 0.67 (urgent)
1178
+ * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1179
+ *
1180
+ * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1181
+ * - 24h interval → ~1.0 (very recent learning)
1182
+ * - 30 days (720h) → ~0.56
1183
+ * - 180 days → ~0.30
1184
+ *
1185
+ * Combined: base 0.5 + weighted average of factors * 0.45
1186
+ * Result range: approximately 0.5 to 0.95
1187
+ */
1188
+ computeUrgencyScore(review, now) {
1189
+ const scheduledAt = moment3.utc(review.scheduledAt);
1190
+ const due = moment3.utc(review.reviewTime);
1191
+ const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1192
+ const hoursOverdue = now.diff(due, "hours");
1193
+ const relativeOverdue = hoursOverdue / intervalHours;
1194
+ const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1195
+ const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1196
+ const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1197
+ const score = Math.min(0.95, 0.5 + urgency * 0.45);
1198
+ const reason = `${Math.round(hoursOverdue)}h overdue (interval: ${Math.round(intervalHours)}h, relative: ${relativeOverdue.toFixed(2)}), recency: ${recencyFactor.toFixed(2)}, review`;
1199
+ return { score, reason };
2136
1200
  }
2137
1201
  };
2138
1202
  }
2139
1203
  });
2140
1204
 
1205
+ // src/core/navigators/filters/eloDistance.ts
1206
+ function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1207
+ const normalizedDistance = distance / halfLife;
1208
+ const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1209
+ return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1210
+ }
1211
+ function createEloDistanceFilter(config) {
1212
+ const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1213
+ const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1214
+ const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1215
+ return {
1216
+ name: "ELO Distance Filter",
1217
+ async transform(cards, context) {
1218
+ const { course, userElo } = context;
1219
+ const cardIds = cards.map((c) => c.cardId);
1220
+ const cardElos = await course.getCardEloData(cardIds);
1221
+ return cards.map((card, i) => {
1222
+ const cardElo = cardElos[i]?.global?.score ?? 1e3;
1223
+ const distance = Math.abs(cardElo - userElo);
1224
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1225
+ const newScore = card.score * multiplier;
1226
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1227
+ return {
1228
+ ...card,
1229
+ score: newScore,
1230
+ provenance: [
1231
+ ...card.provenance,
1232
+ {
1233
+ strategy: "eloDistance",
1234
+ strategyName: "ELO Distance Filter",
1235
+ strategyId: "ELO_DISTANCE_FILTER",
1236
+ action,
1237
+ score: newScore,
1238
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1239
+ }
1240
+ ]
1241
+ };
1242
+ });
1243
+ }
1244
+ };
1245
+ }
1246
+ var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1247
+ var init_eloDistance = __esm({
1248
+ "src/core/navigators/filters/eloDistance.ts"() {
1249
+ "use strict";
1250
+ DEFAULT_HALF_LIFE = 200;
1251
+ DEFAULT_MIN_MULTIPLIER = 0.3;
1252
+ DEFAULT_MAX_MULTIPLIER = 1;
1253
+ }
1254
+ });
1255
+
1256
+ // src/core/navigators/defaults.ts
1257
+ function createDefaultEloStrategy(courseId) {
1258
+ return {
1259
+ _id: "NAVIGATION_STRATEGY-ELO-default",
1260
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1261
+ name: "ELO (default)",
1262
+ description: "Default ELO-based navigation strategy for new cards",
1263
+ implementingClass: "elo" /* ELO */,
1264
+ course: courseId,
1265
+ serializedData: ""
1266
+ };
1267
+ }
1268
+ function createDefaultSrsStrategy(courseId) {
1269
+ return {
1270
+ _id: "NAVIGATION_STRATEGY-SRS-default",
1271
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1272
+ name: "SRS (default)",
1273
+ description: "Default SRS-based navigation strategy for reviews",
1274
+ implementingClass: "srs" /* SRS */,
1275
+ course: courseId,
1276
+ serializedData: ""
1277
+ };
1278
+ }
1279
+ function createDefaultPipeline(user, course) {
1280
+ const courseId = course.getCourseID();
1281
+ const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
1282
+ const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
1283
+ const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
1284
+ const eloDistanceFilter = createEloDistanceFilter();
1285
+ return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
1286
+ }
1287
+ var init_defaults = __esm({
1288
+ "src/core/navigators/defaults.ts"() {
1289
+ "use strict";
1290
+ init_navigators();
1291
+ init_Pipeline();
1292
+ init_CompositeGenerator();
1293
+ init_elo();
1294
+ init_srs();
1295
+ init_eloDistance();
1296
+ init_types_legacy();
1297
+ }
1298
+ });
1299
+
2141
1300
  // src/impl/couch/courseDB.ts
2142
1301
  import {
2143
1302
  EloToNumber,
2144
1303
  Status,
2145
1304
  blankCourseElo as blankCourseElo2,
2146
- toCourseElo as toCourseElo6
1305
+ toCourseElo as toCourseElo4
2147
1306
  } from "@vue-skuilder/common";
2148
1307
  var init_courseDB = __esm({
2149
1308
  "src/impl/couch/courseDB.ts"() {
@@ -2156,12 +1315,8 @@ var init_courseDB = __esm({
2156
1315
  init_courseAPI();
2157
1316
  init_courseLookupDB();
2158
1317
  init_navigators();
2159
- init_Pipeline();
2160
1318
  init_PipelineAssembler();
2161
- init_CompositeGenerator();
2162
- init_elo();
2163
- init_srs();
2164
- init_eloDistance();
1319
+ init_defaults();
2165
1320
  }
2166
1321
  });
2167
1322
 
@@ -2274,7 +1429,9 @@ import moment6 from "moment";
2274
1429
  function accomodateGuest() {
2275
1430
  logger.log("[funnel] accomodateGuest() called");
2276
1431
  if (typeof localStorage === "undefined") {
2277
- logger.log("[funnel] localStorage not available (Node.js environment), returning default guest");
1432
+ logger.log(
1433
+ "[funnel] localStorage not available (Node.js environment), returning default guest"
1434
+ );
2278
1435
  return {
2279
1436
  username: GuestUsername + "nodejs-test",
2280
1437
  firstVisit: true
@@ -3252,6 +2409,55 @@ Currently logged-in as ${this._username}.`
3252
2409
  async updateUserElo(courseId, elo) {
3253
2410
  return updateUserElo(this._username, courseId, elo);
3254
2411
  }
2412
+ async getStrategyState(courseId, strategyKey) {
2413
+ const docId = buildStrategyStateId(courseId, strategyKey);
2414
+ try {
2415
+ const doc = await this.localDB.get(docId);
2416
+ return doc.data;
2417
+ } catch (e) {
2418
+ const err = e;
2419
+ if (err.status === 404) {
2420
+ return null;
2421
+ }
2422
+ throw e;
2423
+ }
2424
+ }
2425
+ async putStrategyState(courseId, strategyKey, data) {
2426
+ const docId = buildStrategyStateId(courseId, strategyKey);
2427
+ let existingRev;
2428
+ try {
2429
+ const existing = await this.localDB.get(docId);
2430
+ existingRev = existing._rev;
2431
+ } catch (e) {
2432
+ const err = e;
2433
+ if (err.status !== 404) {
2434
+ throw e;
2435
+ }
2436
+ }
2437
+ const doc = {
2438
+ _id: docId,
2439
+ _rev: existingRev,
2440
+ docType: "STRATEGY_STATE" /* STRATEGY_STATE */,
2441
+ courseId,
2442
+ strategyKey,
2443
+ data,
2444
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
2445
+ };
2446
+ await this.localDB.put(doc);
2447
+ }
2448
+ async deleteStrategyState(courseId, strategyKey) {
2449
+ const docId = buildStrategyStateId(courseId, strategyKey);
2450
+ try {
2451
+ const doc = await this.localDB.get(docId);
2452
+ await this.localDB.remove(doc);
2453
+ } catch (e) {
2454
+ const err = e;
2455
+ if (err.status === 404) {
2456
+ return;
2457
+ }
2458
+ throw e;
2459
+ }
2460
+ }
3255
2461
  };
3256
2462
  userCoursesDoc = "CourseRegistrations";
3257
2463
  userClassroomsDoc = "ClassroomRegistrations";
@@ -3346,6 +2552,16 @@ var init_user = __esm({
3346
2552
  }
3347
2553
  });
3348
2554
 
2555
+ // src/core/types/strategyState.ts
2556
+ function buildStrategyStateId(courseId, strategyKey) {
2557
+ return `STRATEGY_STATE::${courseId}::${strategyKey}`;
2558
+ }
2559
+ var init_strategyState = __esm({
2560
+ "src/core/types/strategyState.ts"() {
2561
+ "use strict";
2562
+ }
2563
+ });
2564
+
3349
2565
  // src/core/bulkImport/cardProcessor.ts
3350
2566
  import { Status as Status4 } from "@vue-skuilder/common";
3351
2567
  var init_cardProcessor = __esm({
@@ -3356,7 +2572,7 @@ var init_cardProcessor = __esm({
3356
2572
  });
3357
2573
 
3358
2574
  // src/core/bulkImport/types.ts
3359
- var init_types3 = __esm({
2575
+ var init_types = __esm({
3360
2576
  "src/core/bulkImport/types.ts"() {
3361
2577
  "use strict";
3362
2578
  }
@@ -3367,7 +2583,7 @@ var init_bulkImport = __esm({
3367
2583
  "src/core/bulkImport/index.ts"() {
3368
2584
  "use strict";
3369
2585
  init_cardProcessor();
3370
- init_types3();
2586
+ init_types();
3371
2587
  }
3372
2588
  });
3373
2589
 
@@ -3378,6 +2594,7 @@ var init_core = __esm({
3378
2594
  init_interfaces();
3379
2595
  init_types_legacy();
3380
2596
  init_user();
2597
+ init_strategyState();
3381
2598
  init_Loggable();
3382
2599
  init_util();
3383
2600
  init_navigators();
@@ -3444,6 +2661,36 @@ var init_StaticDataUnpacker = __esm({
3444
2661
  logger.error(`Document ${id} not found in chunk ${chunk.id}`);
3445
2662
  throw new Error(`Document ${id} not found in chunk ${chunk.id}`);
3446
2663
  }
2664
+ /**
2665
+ * Get all documents with IDs starting with a specific prefix.
2666
+ *
2667
+ * This method loads the relevant chunk(s) and returns all matching documents.
2668
+ * Useful for querying documents by type (e.g., all NAVIGATION_STRATEGY documents).
2669
+ *
2670
+ * @param prefix - Document ID prefix to match (e.g., "NAVIGATION_STRATEGY")
2671
+ * @returns Array of all documents with IDs starting with the prefix
2672
+ */
2673
+ async getAllDocumentsByPrefix(prefix) {
2674
+ const relevantChunks = this.manifest.chunks.filter((chunk) => {
2675
+ const prefixEnd = prefix + "\uFFF0";
2676
+ return chunk.startKey <= prefixEnd && chunk.endKey >= prefix;
2677
+ });
2678
+ if (relevantChunks.length === 0) {
2679
+ logger.debug(`[StaticDataUnpacker] No chunks found for prefix: ${prefix}`);
2680
+ return [];
2681
+ }
2682
+ await Promise.all(relevantChunks.map((chunk) => this.loadChunk(chunk.id)));
2683
+ const matchingDocs = [];
2684
+ for (const [docId, doc] of this.documentCache.entries()) {
2685
+ if (docId.startsWith(prefix)) {
2686
+ matchingDocs.push(await this.hydrateAttachments(doc));
2687
+ }
2688
+ }
2689
+ logger.debug(
2690
+ `[StaticDataUnpacker] Found ${matchingDocs.length} documents with prefix: ${prefix}`
2691
+ );
2692
+ return matchingDocs;
2693
+ }
3447
2694
  /**
3448
2695
  * Query cards by ELO score, returning card IDs sorted by ELO
3449
2696
  */
@@ -3480,7 +2727,14 @@ var init_StaticDataUnpacker = __esm({
3480
2727
  * Get all tag names mapped to their card arrays
3481
2728
  */
3482
2729
  async getTagsIndex() {
3483
- return await this.loadIndex("tags");
2730
+ try {
2731
+ return await this.loadIndex("tags");
2732
+ } catch {
2733
+ return {
2734
+ byCard: {},
2735
+ byTag: {}
2736
+ };
2737
+ }
3484
2738
  }
3485
2739
  getDocTypeFromId(id) {
3486
2740
  for (const docTypeKey in DocTypePrefixes) {
@@ -3771,8 +3025,9 @@ var init_courseDB3 = __esm({
3771
3025
  "src/impl/static/courseDB.ts"() {
3772
3026
  "use strict";
3773
3027
  init_types_legacy();
3774
- init_navigators();
3775
3028
  init_logger();
3029
+ init_defaults();
3030
+ init_PipelineAssembler();
3776
3031
  StaticCourseDB = class {
3777
3032
  constructor(courseId, unpacker, userDB, manifest) {
3778
3033
  this.courseId = courseId;
@@ -3851,21 +3106,6 @@ var init_courseDB3 = __esm({
3851
3106
  async updateCardElo(cardId, _elo) {
3852
3107
  return { ok: true, id: cardId, rev: "1-static" };
3853
3108
  }
3854
- async getNewCards(limit = 99) {
3855
- const activeCards = await this.userDB.getActiveCards();
3856
- return (await this.getCardsCenteredAtELO({ limit, elo: "user" }, (c) => {
3857
- if (activeCards.some((ac) => c.cardID === ac.cardID)) {
3858
- return false;
3859
- } else {
3860
- return true;
3861
- }
3862
- })).map((c) => {
3863
- return {
3864
- ...c,
3865
- status: "new"
3866
- };
3867
- });
3868
- }
3869
3109
  async getCardsCenteredAtELO(options, filter) {
3870
3110
  let targetElo = typeof options.elo === "number" ? options.elo : 1e3;
3871
3111
  if (options.elo === "user") {
@@ -3950,6 +3190,14 @@ var init_courseDB3 = __esm({
3950
3190
  };
3951
3191
  }
3952
3192
  }
3193
+ async getAppliedTagsBatch(cardIds) {
3194
+ const tagsIndex = await this.unpacker.getTagsIndex();
3195
+ const tagsByCard = /* @__PURE__ */ new Map();
3196
+ for (const cardId of cardIds) {
3197
+ tagsByCard.set(cardId, tagsIndex.byCard[cardId] || []);
3198
+ }
3199
+ return tagsByCard;
3200
+ }
3953
3201
  async addTagToCard(_cardId, _tagId) {
3954
3202
  throw new Error("Cannot modify tags in static mode");
3955
3203
  }
@@ -4043,19 +3291,23 @@ var init_courseDB3 = __esm({
4043
3291
  return [];
4044
3292
  }
4045
3293
  // Navigation Strategy Manager implementation
4046
- async getNavigationStrategy(_id) {
4047
- return {
4048
- _id: "NAVIGATION_STRATEGY-ELO",
4049
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
4050
- name: "ELO",
4051
- description: "ELO-based navigation strategy",
4052
- implementingClass: "elo" /* ELO */,
4053
- course: this.courseId,
4054
- serializedData: ""
4055
- };
3294
+ async getNavigationStrategy(id) {
3295
+ try {
3296
+ return await this.unpacker.getDocument(id);
3297
+ } catch (error) {
3298
+ logger.error(`[static/courseDB] Strategy ${id} not found: ${error}`);
3299
+ throw error;
3300
+ }
4056
3301
  }
4057
3302
  async getAllNavigationStrategies() {
4058
- return [await this.getNavigationStrategy("ELO")];
3303
+ const prefix = DocTypePrefixes["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */];
3304
+ try {
3305
+ const docs = await this.unpacker.getAllDocumentsByPrefix(prefix);
3306
+ return docs;
3307
+ } catch (error) {
3308
+ logger.warn(`[static/courseDB] Error loading navigation strategies: ${error}`);
3309
+ return [];
3310
+ }
4059
3311
  }
4060
3312
  async addNavigationStrategy(_data) {
4061
3313
  throw new Error("Cannot add navigation strategies in static mode");
@@ -4063,9 +3315,52 @@ var init_courseDB3 = __esm({
4063
3315
  async updateNavigationStrategy(_id, _data) {
4064
3316
  throw new Error("Cannot update navigation strategies in static mode");
4065
3317
  }
3318
+ /**
3319
+ * Create a ContentNavigator for this course.
3320
+ *
3321
+ * Loads navigation strategy documents from static data and uses PipelineAssembler
3322
+ * to build a Pipeline. Falls back to default pipeline if no strategies found.
3323
+ */
3324
+ async createNavigator(user) {
3325
+ try {
3326
+ const allStrategies = await this.getAllNavigationStrategies();
3327
+ if (allStrategies.length === 0) {
3328
+ logger.debug(
3329
+ "[static/courseDB] No strategy documents found, using default Pipeline(Composite(ELO, SRS), [eloDistanceFilter])"
3330
+ );
3331
+ return createDefaultPipeline(user, this);
3332
+ }
3333
+ const assembler = new PipelineAssembler();
3334
+ const { pipeline, generatorStrategies, filterStrategies, warnings } = await assembler.assemble({
3335
+ strategies: allStrategies,
3336
+ user,
3337
+ course: this
3338
+ });
3339
+ for (const warning of warnings) {
3340
+ logger.warn(`[PipelineAssembler] ${warning}`);
3341
+ }
3342
+ if (!pipeline) {
3343
+ logger.debug("[static/courseDB] Pipeline assembly failed, using default pipeline");
3344
+ return createDefaultPipeline(user, this);
3345
+ }
3346
+ logger.debug(
3347
+ `[static/courseDB] Using assembled pipeline with ${generatorStrategies.length} generator(s) and ${filterStrategies.length} filter(s)`
3348
+ );
3349
+ return pipeline;
3350
+ } catch (e) {
3351
+ logger.error(`[static/courseDB] Error creating navigator: ${e}`);
3352
+ throw e;
3353
+ }
3354
+ }
4066
3355
  // Study Content Source implementation
4067
- async getPendingReviews() {
4068
- return [];
3356
+ async getWeightedCards(limit) {
3357
+ try {
3358
+ const navigator = await this.createNavigator(this.userDB);
3359
+ return navigator.getWeightedCards(limit);
3360
+ } catch (e) {
3361
+ logger.error(`[static/courseDB] Error getting weighted cards: ${e}`);
3362
+ throw e;
3363
+ }
4069
3364
  }
4070
3365
  // Attachment helper methods (internal use, not part of interface)
4071
3366
  /**