@vue-skuilder/db 0.1.16 → 0.1.18

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 (80) hide show
  1. package/dist/{userDB-DNa0XPtn.d.ts → classroomDB-BgfrVb8d.d.ts} +357 -103
  2. package/dist/{userDB-BqwxtJ_7.d.mts → classroomDB-CTOenngH.d.cts} +358 -104
  3. package/dist/core/index.d.cts +230 -0
  4. package/dist/core/index.d.ts +161 -23
  5. package/dist/core/index.js +1964 -154
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +1925 -121
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-BV5iZqt_.d.ts → dataLayerProvider-CZxC9GtB.d.ts} +1 -1
  10. package/dist/{dataLayerProvider-VlngD19_.d.mts → dataLayerProvider-D6PoCwS6.d.cts} +1 -1
  11. package/dist/impl/couch/{index.d.mts → index.d.cts} +46 -5
  12. package/dist/impl/couch/index.d.ts +44 -3
  13. package/dist/impl/couch/index.js +1971 -171
  14. package/dist/impl/couch/index.js.map +1 -1
  15. package/dist/impl/couch/index.mjs +1933 -134
  16. package/dist/impl/couch/index.mjs.map +1 -1
  17. package/dist/impl/static/{index.d.mts → index.d.cts} +5 -6
  18. package/dist/impl/static/index.d.ts +2 -3
  19. package/dist/impl/static/index.js +1614 -119
  20. package/dist/impl/static/index.js.map +1 -1
  21. package/dist/impl/static/index.mjs +1585 -92
  22. package/dist/impl/static/index.mjs.map +1 -1
  23. package/dist/{index-Bmll7Xse.d.mts → index-D-Fa4Smt.d.cts} +1 -1
  24. package/dist/{index.d.mts → index.d.cts} +97 -13
  25. package/dist/index.d.ts +90 -6
  26. package/dist/index.js +2085 -153
  27. package/dist/index.js.map +1 -1
  28. package/dist/index.mjs +2031 -106
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/pouch/index.js +3 -3
  31. package/dist/{types-Dbp5DaRR.d.mts → types-CzPDLAK6.d.cts} +1 -1
  32. package/dist/util/packer/{index.d.mts → index.d.cts} +3 -3
  33. package/dist/util/packer/index.js.map +1 -1
  34. package/dist/util/packer/index.mjs.map +1 -1
  35. package/docs/brainstorm-navigation-paradigm.md +369 -0
  36. package/docs/navigators-architecture.md +265 -0
  37. package/docs/todo-evolutionary-orchestration.md +310 -0
  38. package/docs/todo-nominal-tag-types.md +121 -0
  39. package/docs/todo-pipeline-optimization.md +117 -0
  40. package/docs/todo-strategy-authoring.md +401 -0
  41. package/docs/todo-strategy-state-storage.md +278 -0
  42. package/eslint.config.mjs +1 -1
  43. package/package.json +9 -4
  44. package/src/core/interfaces/contentSource.ts +88 -4
  45. package/src/core/interfaces/navigationStrategyManager.ts +0 -5
  46. package/src/core/navigators/CompositeGenerator.ts +268 -0
  47. package/src/core/navigators/Pipeline.ts +205 -0
  48. package/src/core/navigators/PipelineAssembler.ts +194 -0
  49. package/src/core/navigators/elo.ts +104 -15
  50. package/src/core/navigators/filters/eloDistance.ts +132 -0
  51. package/src/core/navigators/filters/index.ts +6 -0
  52. package/src/core/navigators/filters/types.ts +115 -0
  53. package/src/core/navigators/generators/index.ts +2 -0
  54. package/src/core/navigators/generators/types.ts +107 -0
  55. package/src/core/navigators/hardcodedOrder.ts +111 -12
  56. package/src/core/navigators/hierarchyDefinition.ts +266 -0
  57. package/src/core/navigators/index.ts +345 -3
  58. package/src/core/navigators/interferenceMitigator.ts +367 -0
  59. package/src/core/navigators/relativePriority.ts +267 -0
  60. package/src/core/navigators/srs.ts +195 -0
  61. package/src/impl/couch/classroomDB.ts +51 -0
  62. package/src/impl/couch/courseDB.ts +117 -39
  63. package/src/impl/static/courseDB.ts +0 -4
  64. package/src/study/SessionController.ts +149 -1
  65. package/src/study/TagFilteredContentSource.ts +255 -0
  66. package/src/study/index.ts +1 -0
  67. package/src/util/dataDirectory.test.ts +51 -22
  68. package/src/util/logger.ts +0 -1
  69. package/tests/core/navigators/CompositeGenerator.test.ts +455 -0
  70. package/tests/core/navigators/Pipeline.test.ts +405 -0
  71. package/tests/core/navigators/PipelineAssembler.test.ts +351 -0
  72. package/tests/core/navigators/SRSNavigator.test.ts +344 -0
  73. package/tests/core/navigators/eloDistanceFilter.test.ts +192 -0
  74. package/tests/core/navigators/navigators.test.ts +710 -0
  75. package/tsconfig.json +1 -1
  76. package/vitest.config.ts +29 -0
  77. package/dist/core/index.d.mts +0 -92
  78. /package/dist/{SyncStrategy-CyATpyLQ.d.mts → SyncStrategy-CyATpyLQ.d.cts} +0 -0
  79. /package/dist/pouch/{index.d.mts → index.d.cts} +0 -0
  80. /package/dist/{types-legacy-6ettoclI.d.mts → types-legacy-6ettoclI.d.cts} +0 -0
@@ -475,23 +475,460 @@ var init_courseLookupDB = __esm({
475
475
  }
476
476
  });
477
477
 
478
+ // src/core/navigators/CompositeGenerator.ts
479
+ var CompositeGenerator_exports = {};
480
+ __export(CompositeGenerator_exports, {
481
+ AggregationMode: () => AggregationMode,
482
+ default: () => CompositeGenerator
483
+ });
484
+ var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
485
+ var init_CompositeGenerator = __esm({
486
+ "src/core/navigators/CompositeGenerator.ts"() {
487
+ "use strict";
488
+ init_navigators();
489
+ 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
+ DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
497
+ FREQUENCY_BOOST_FACTOR = 0.1;
498
+ CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
499
+ /** Human-readable name for CardGenerator interface */
500
+ name = "Composite Generator";
501
+ generators;
502
+ aggregationMode;
503
+ constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
504
+ super();
505
+ this.generators = generators;
506
+ this.aggregationMode = aggregationMode;
507
+ if (generators.length === 0) {
508
+ throw new Error("CompositeGenerator requires at least one generator");
509
+ }
510
+ logger.debug(
511
+ `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
512
+ );
513
+ }
514
+ /**
515
+ * Creates a CompositeGenerator from strategy data.
516
+ *
517
+ * This is a convenience factory for use by PipelineAssembler.
518
+ */
519
+ static async fromStrategies(user, course, strategies, aggregationMode = DEFAULT_AGGREGATION_MODE) {
520
+ const generators = await Promise.all(
521
+ strategies.map((s) => ContentNavigator.create(user, course, s))
522
+ );
523
+ return new _CompositeGenerator(generators, aggregationMode);
524
+ }
525
+ /**
526
+ * Get weighted cards from all generators, merge and deduplicate.
527
+ *
528
+ * Cards appearing in multiple generators receive a score boost.
529
+ * Provenance tracks which generators produced each card and how scores were aggregated.
530
+ *
531
+ * This method supports both the legacy signature (limit only) and the
532
+ * CardGenerator interface signature (limit, context).
533
+ *
534
+ * @param limit - Maximum number of cards to return
535
+ * @param context - Optional GeneratorContext passed to child generators
536
+ */
537
+ async getWeightedCards(limit, context) {
538
+ const results = await Promise.all(
539
+ this.generators.map((g) => g.getWeightedCards(limit, context))
540
+ );
541
+ const byCardId = /* @__PURE__ */ new Map();
542
+ for (const cards of results) {
543
+ for (const card of cards) {
544
+ const existing = byCardId.get(card.cardId) || [];
545
+ existing.push(card);
546
+ byCardId.set(card.cardId, existing);
547
+ }
548
+ }
549
+ const merged = [];
550
+ for (const [, cards] of byCardId) {
551
+ const aggregatedScore = this.aggregateScores(cards);
552
+ const finalScore = Math.min(1, aggregatedScore);
553
+ const mergedProvenance = cards.flatMap((c) => c.provenance);
554
+ const initialScore = cards[0].score;
555
+ const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
556
+ const reason = this.buildAggregationReason(cards, finalScore);
557
+ merged.push({
558
+ ...cards[0],
559
+ score: finalScore,
560
+ provenance: [
561
+ ...mergedProvenance,
562
+ {
563
+ strategy: "composite",
564
+ strategyName: "Composite Generator",
565
+ strategyId: "COMPOSITE_GENERATOR",
566
+ action,
567
+ score: finalScore,
568
+ reason
569
+ }
570
+ ]
571
+ });
572
+ }
573
+ return merged.sort((a, b) => b.score - a.score).slice(0, limit);
574
+ }
575
+ /**
576
+ * Build human-readable reason for score aggregation.
577
+ */
578
+ buildAggregationReason(cards, finalScore) {
579
+ const count = cards.length;
580
+ const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
581
+ if (count === 1) {
582
+ return `Single generator, score ${finalScore.toFixed(2)}`;
583
+ }
584
+ const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
585
+ switch (this.aggregationMode) {
586
+ case "max" /* MAX */:
587
+ return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
588
+ case "average" /* AVERAGE */:
589
+ return `Average of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
590
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
591
+ const avg = cards.reduce((sum, c) => sum + c.score, 0) / count;
592
+ const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
593
+ return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
594
+ }
595
+ default:
596
+ return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
597
+ }
598
+ }
599
+ /**
600
+ * Aggregate scores from multiple generators for the same card.
601
+ */
602
+ aggregateScores(cards) {
603
+ const scores = cards.map((c) => c.score);
604
+ switch (this.aggregationMode) {
605
+ case "max" /* MAX */:
606
+ return Math.max(...scores);
607
+ case "average" /* AVERAGE */:
608
+ return scores.reduce((sum, s) => sum + s, 0) / scores.length;
609
+ case "frequencyBoost" /* FREQUENCY_BOOST */: {
610
+ const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
611
+ const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (cards.length - 1);
612
+ return avg * frequencyBoost;
613
+ }
614
+ default:
615
+ return scores[0];
616
+ }
617
+ }
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
+ };
659
+ }
660
+ });
661
+
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"() {
798
+ "use strict";
799
+ init_navigators();
800
+ init_Pipeline();
801
+ init_types_legacy();
802
+ init_logger();
803
+ init_CompositeGenerator();
804
+ PipelineAssembler = class {
805
+ /**
806
+ * Assembles a navigation pipeline from strategy documents.
807
+ *
808
+ * 1. Separates into generators and filters by role
809
+ * 2. Validates at least one generator exists (or creates default ELO)
810
+ * 3. Instantiates generators - wraps multiple in CompositeGenerator
811
+ * 4. Instantiates filters
812
+ * 5. Returns Pipeline(generator, filters)
813
+ *
814
+ * @param input - Strategy documents plus user/course interfaces
815
+ * @returns Assembled pipeline and any warnings
816
+ */
817
+ async assemble(input) {
818
+ const { strategies, user, course } = input;
819
+ const warnings = [];
820
+ if (strategies.length === 0) {
821
+ return {
822
+ pipeline: null,
823
+ generatorStrategies: [],
824
+ filterStrategies: [],
825
+ warnings
826
+ };
827
+ }
828
+ const generatorStrategies = [];
829
+ const filterStrategies = [];
830
+ for (const s of strategies) {
831
+ if (isGenerator(s.implementingClass)) {
832
+ generatorStrategies.push(s);
833
+ } else if (isFilter(s.implementingClass)) {
834
+ filterStrategies.push(s);
835
+ } else {
836
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
837
+ }
838
+ }
839
+ if (generatorStrategies.length === 0) {
840
+ if (filterStrategies.length > 0) {
841
+ logger.debug(
842
+ "[PipelineAssembler] No generator found, using default ELO with configured filters"
843
+ );
844
+ generatorStrategies.push(this.makeDefaultEloStrategy(course.getCourseID()));
845
+ } else {
846
+ warnings.push("No generator strategy found");
847
+ return {
848
+ pipeline: null,
849
+ generatorStrategies: [],
850
+ filterStrategies: [],
851
+ warnings
852
+ };
853
+ }
854
+ }
855
+ let generator;
856
+ if (generatorStrategies.length === 1) {
857
+ const nav = await ContentNavigator.create(user, course, generatorStrategies[0]);
858
+ generator = nav;
859
+ logger.debug(`[PipelineAssembler] Using single generator: ${generatorStrategies[0].name}`);
860
+ } else {
861
+ logger.debug(
862
+ `[PipelineAssembler] Using CompositeGenerator for ${generatorStrategies.length} generators: ${generatorStrategies.map((g) => g.name).join(", ")}`
863
+ );
864
+ generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
865
+ }
866
+ const filters = [];
867
+ const sortedFilterStrategies = [...filterStrategies].sort(
868
+ (a, b) => a.name.localeCompare(b.name)
869
+ );
870
+ for (const filterStrategy of sortedFilterStrategies) {
871
+ try {
872
+ const nav = await ContentNavigator.create(user, course, filterStrategy);
873
+ if ("transform" in nav && typeof nav.transform === "function") {
874
+ filters.push(nav);
875
+ logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
876
+ } else {
877
+ warnings.push(
878
+ `Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
879
+ );
880
+ }
881
+ } catch (e) {
882
+ warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
883
+ }
884
+ }
885
+ const pipeline = new Pipeline(generator, filters, user, course);
886
+ logger.debug(
887
+ `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
888
+ );
889
+ return {
890
+ pipeline,
891
+ generatorStrategies,
892
+ filterStrategies: sortedFilterStrategies,
893
+ warnings
894
+ };
895
+ }
896
+ /**
897
+ * Creates a default ELO generator strategy.
898
+ * Used when filters are configured but no generator is specified.
899
+ */
900
+ makeDefaultEloStrategy(courseId) {
901
+ return {
902
+ _id: "NAVIGATION_STRATEGY-ELO-default",
903
+ course: courseId,
904
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
905
+ name: "ELO (default)",
906
+ description: "Default ELO-based generator",
907
+ implementingClass: "elo" /* ELO */,
908
+ serializedData: ""
909
+ };
910
+ }
911
+ };
912
+ }
913
+ });
914
+
478
915
  // src/core/navigators/elo.ts
479
916
  var elo_exports = {};
480
917
  __export(elo_exports, {
481
918
  default: () => ELONavigator
482
919
  });
920
+ import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
483
921
  var ELONavigator;
484
922
  var init_elo = __esm({
485
923
  "src/core/navigators/elo.ts"() {
486
924
  "use strict";
487
925
  init_navigators();
488
926
  ELONavigator = class extends ContentNavigator {
489
- user;
490
- course;
491
- constructor(user, course) {
492
- super();
493
- this.user = user;
494
- this.course = course;
927
+ /** Human-readable name for CardGenerator interface */
928
+ name;
929
+ constructor(user, course, strategyData) {
930
+ super(user, course, strategyData);
931
+ this.name = strategyData?.name || "ELO";
495
932
  }
496
933
  async getPendingReviews() {
497
934
  const reviews = await this.user.getPendingReviews(this.course.getCourseID());
@@ -508,95 +945,994 @@ var init_elo = __esm({
508
945
  });
509
946
  return ratedReviews.map((r) => {
510
947
  return {
511
- ...r,
512
- contentSourceType: "course",
513
- contentSourceID: this.course.getCourseID(),
514
- cardID: r.cardId,
515
- courseID: r.courseId,
516
- qualifiedID: `${r.courseId}-${r.cardId}`,
517
- reviewID: r._id,
518
- status: "review"
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
+ /**
978
+ * Get new cards with suitability scores based on ELO distance.
979
+ *
980
+ * Cards closer to user's ELO get higher scores.
981
+ * Score formula: max(0, 1 - distance / 500)
982
+ *
983
+ * NOTE: This generator only handles NEW cards. Reviews are handled by
984
+ * SRSNavigator. Use CompositeGenerator to combine both.
985
+ *
986
+ * This method supports both the legacy signature (limit only) and the
987
+ * CardGenerator interface signature (limit, context).
988
+ *
989
+ * @param limit - Maximum number of cards to return
990
+ * @param context - Optional GeneratorContext (used when called via Pipeline)
991
+ */
992
+ async getWeightedCards(limit, context) {
993
+ let userGlobalElo;
994
+ if (context?.userElo !== void 0) {
995
+ userGlobalElo = context.userElo;
996
+ } else {
997
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
998
+ const userElo = toCourseElo3(courseReg.elo);
999
+ userGlobalElo = userElo.global.score;
1000
+ }
1001
+ const newCards = await this.getNewCards(limit);
1002
+ const cardIds = newCards.map((c) => c.cardID);
1003
+ const cardEloData = await this.course.getCardEloData(cardIds);
1004
+ const scored = newCards.map((c, i) => {
1005
+ const cardElo = cardEloData[i]?.global?.score ?? 1e3;
1006
+ const distance = Math.abs(cardElo - userGlobalElo);
1007
+ const score = Math.max(0, 1 - distance / 500);
1008
+ return {
1009
+ cardId: c.cardID,
1010
+ courseId: c.courseID,
1011
+ score,
1012
+ provenance: [
1013
+ {
1014
+ strategy: "elo",
1015
+ strategyName: this.strategyName || this.name,
1016
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1017
+ action: "generated",
1018
+ score,
1019
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), new card`
1020
+ }
1021
+ ]
1022
+ };
1023
+ });
1024
+ scored.sort((a, b) => b.score - a.score);
1025
+ return scored.slice(0, limit);
1026
+ }
1027
+ };
1028
+ }
1029
+ });
1030
+
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
519
1459
  };
520
- });
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
+ }
521
1470
  }
522
- async getNewCards(limit = 99) {
523
- const activeCards = await this.user.getActiveCards();
524
- return (await this.course.getCardsCenteredAtELO(
525
- { limit, elo: "user" },
526
- (c) => {
527
- if (activeCards.some((ac) => c.cardID === ac.cardID)) {
528
- return false;
529
- } else {
530
- return true;
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
+ }
531
1496
  }
532
1497
  }
533
- )).map((c) => {
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) {
534
1564
  return {
535
- ...c,
536
- status: "new"
1565
+ multiplier: 1,
1566
+ interferingTags: [],
1567
+ reason: "No interference detected"
537
1568
  };
538
- });
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 [];
539
1651
  }
540
1652
  };
541
1653
  }
542
1654
  });
543
1655
 
544
- // src/core/navigators/hardcodedOrder.ts
545
- var hardcodedOrder_exports = {};
546
- __export(hardcodedOrder_exports, {
547
- default: () => HardcodedOrderNavigator
1656
+ // src/core/navigators/relativePriority.ts
1657
+ var relativePriority_exports = {};
1658
+ __export(relativePriority_exports, {
1659
+ default: () => RelativePriorityNavigator
548
1660
  });
549
- var HardcodedOrderNavigator;
550
- var init_hardcodedOrder = __esm({
551
- "src/core/navigators/hardcodedOrder.ts"() {
1661
+ var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
1662
+ var init_relativePriority = __esm({
1663
+ "src/core/navigators/relativePriority.ts"() {
552
1664
  "use strict";
553
1665
  init_navigators();
554
- init_logger();
555
- HardcodedOrderNavigator = class extends ContentNavigator {
556
- orderedCardIds = [];
557
- user;
558
- course;
559
- constructor(user, course, strategyData) {
560
- super();
561
- this.user = user;
562
- this.course = course;
563
- if (strategyData.serializedData) {
564
- try {
565
- this.orderedCardIds = JSON.parse(strategyData.serializedData);
566
- } catch (e) {
567
- logger.error("Failed to parse serializedData for HardcodedOrderNavigator", e);
568
- }
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 [];
569
1763
  }
570
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
+ }
571
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
+ }
572
1857
  const reviews = await this.user.getPendingReviews(this.course.getCourseID());
573
- return reviews.map((r) => {
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);
574
1862
  return {
575
- ...r,
576
- contentSourceType: "course",
577
- contentSourceID: this.course.getCourseID(),
578
- cardID: r.cardId,
579
- courseID: r.courseId,
580
- reviewID: r._id,
581
- status: "review"
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
+ ]
582
1876
  };
583
1877
  });
1878
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
584
1879
  }
585
- async getNewCards(limit = 99) {
586
- const activeCardIds = (await this.user.getActiveCards()).map((c) => c.cardID);
587
- const newCardIds = this.orderedCardIds.filter(
588
- (cardId) => !activeCardIds.includes(cardId)
589
- );
590
- const cardsToReturn = newCardIds.slice(0, limit);
591
- return cardsToReturn.map((cardId) => {
592
- return {
593
- cardID: cardId,
594
- courseID: this.course.getCourseID(),
595
- contentSourceType: "course",
596
- contentSourceID: this.course.getCourseID(),
597
- status: "new"
598
- };
599
- });
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 [];
600
1936
  }
601
1937
  };
602
1938
  }
@@ -607,9 +1943,21 @@ var globImport;
607
1943
  var init_ = __esm({
608
1944
  'import("./**/*") in src/core/navigators/index.ts'() {
609
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)),
610
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)),
611
1955
  "./hardcodedOrder.ts": () => Promise.resolve().then(() => (init_hardcodedOrder(), hardcodedOrder_exports)),
612
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_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))
613
1961
  });
614
1962
  }
615
1963
  });
@@ -618,9 +1966,34 @@ var init_ = __esm({
618
1966
  var navigators_exports = {};
619
1967
  __export(navigators_exports, {
620
1968
  ContentNavigator: () => ContentNavigator,
621
- Navigators: () => Navigators
1969
+ NavigatorRole: () => NavigatorRole,
1970
+ NavigatorRoles: () => NavigatorRoles,
1971
+ Navigators: () => Navigators,
1972
+ getCardOrigin: () => getCardOrigin,
1973
+ isFilter: () => isFilter,
1974
+ isGenerator: () => isGenerator
622
1975
  });
623
- var Navigators, ContentNavigator;
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;
624
1997
  var init_navigators = __esm({
625
1998
  "src/core/navigators/index.ts"() {
626
1999
  "use strict";
@@ -628,14 +2001,55 @@ var init_navigators = __esm({
628
2001
  init_();
629
2002
  Navigators = /* @__PURE__ */ ((Navigators2) => {
630
2003
  Navigators2["ELO"] = "elo";
2004
+ Navigators2["SRS"] = "srs";
631
2005
  Navigators2["HARDCODED"] = "hardcodedOrder";
2006
+ Navigators2["HIERARCHY"] = "hierarchyDefinition";
2007
+ Navigators2["INTERFERENCE"] = "interferenceMitigator";
2008
+ Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
632
2009
  return Navigators2;
633
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
+ };
634
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
+ }
635
2047
  /**
2048
+ * Factory method to create navigator instances dynamically.
636
2049
  *
637
- * @param user
638
- * @param strategyData
2050
+ * @param user - User interface
2051
+ * @param course - Course interface
2052
+ * @param strategyData - Strategy configuration document
639
2053
  * @returns the runtime object used to steer a study session.
640
2054
  */
641
2055
  static async create(user, course, strategyData) {
@@ -656,6 +2070,70 @@ var init_navigators = __esm({
656
2070
  }
657
2071
  return new NavigatorImpl(user, course, strategyData);
658
2072
  }
2073
+ /**
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.
2081
+ *
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'.
2086
+ *
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
2093
+ *
2094
+ * This allows existing strategies to work without modification while
2095
+ * new strategies can override with proper scoring and provenance.
2096
+ *
2097
+ * @param limit - Maximum cards to return
2098
+ * @returns Cards sorted by score descending, with provenance trails
2099
+ */
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,
2123
+ provenance: [
2124
+ {
2125
+ strategy: "legacy",
2126
+ strategyName: this.strategyName || "Legacy API",
2127
+ strategyId: this.strategyId || "legacy-fallback",
2128
+ action: "generated",
2129
+ score: 1,
2130
+ reason: "Generated via legacy getPendingReviews(), review"
2131
+ }
2132
+ ]
2133
+ }))
2134
+ ];
2135
+ return weighted.slice(0, limit);
2136
+ }
659
2137
  };
660
2138
  }
661
2139
  });
@@ -665,7 +2143,7 @@ import {
665
2143
  EloToNumber,
666
2144
  Status,
667
2145
  blankCourseElo as blankCourseElo2,
668
- toCourseElo as toCourseElo2
2146
+ toCourseElo as toCourseElo6
669
2147
  } from "@vue-skuilder/common";
670
2148
  var init_courseDB = __esm({
671
2149
  "src/impl/couch/courseDB.ts"() {
@@ -678,11 +2156,17 @@ var init_courseDB = __esm({
678
2156
  init_courseAPI();
679
2157
  init_courseLookupDB();
680
2158
  init_navigators();
2159
+ init_Pipeline();
2160
+ init_PipelineAssembler();
2161
+ init_CompositeGenerator();
2162
+ init_elo();
2163
+ init_srs();
2164
+ init_eloDistance();
681
2165
  }
682
2166
  });
683
2167
 
684
2168
  // src/impl/couch/classroomDB.ts
685
- import moment3 from "moment";
2169
+ import moment4 from "moment";
686
2170
  var init_classroomDB2 = __esm({
687
2171
  "src/impl/couch/classroomDB.ts"() {
688
2172
  "use strict";
@@ -734,7 +2218,7 @@ var init_CouchDBSyncStrategy = __esm({
734
2218
 
735
2219
  // src/impl/couch/index.ts
736
2220
  import fetch3 from "cross-fetch";
737
- import moment4 from "moment";
2221
+ import moment5 from "moment";
738
2222
  import process2 from "process";
739
2223
  function createPouchDBConfig() {
740
2224
  const hasExplicitCredentials = ENV.COUCHDB_USERNAME && ENV.COUCHDB_PASSWORD;
@@ -786,7 +2270,7 @@ var init_couch = __esm({
786
2270
 
787
2271
  // src/impl/common/BaseUserDB.ts
788
2272
  import { Status as Status3 } from "@vue-skuilder/common";
789
- import moment5 from "moment";
2273
+ import moment6 from "moment";
790
2274
  function accomodateGuest() {
791
2275
  logger.log("[funnel] accomodateGuest() called");
792
2276
  if (typeof localStorage === "undefined") {
@@ -1224,7 +2708,7 @@ Currently logged-in as ${this._username}.`
1224
2708
  );
1225
2709
  return reviews.rows.filter((r) => {
1226
2710
  if (r.id.startsWith(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */])) {
1227
- const date = moment5.utc(
2711
+ const date = moment6.utc(
1228
2712
  r.id.substr(DocTypePrefixes["SCHEDULED_CARD" /* SCHEDULED_CARD */].length),
1229
2713
  REVIEW_TIME_FORMAT
1230
2714
  );
@@ -1237,11 +2721,11 @@ Currently logged-in as ${this._username}.`
1237
2721
  }).map((r) => r.doc);
1238
2722
  }
1239
2723
  async getReviewsForcast(daysCount) {
1240
- const time = moment5.utc().add(daysCount, "days");
2724
+ const time = moment6.utc().add(daysCount, "days");
1241
2725
  return this.getReviewstoDate(time);
1242
2726
  }
1243
2727
  async getPendingReviews(course_id) {
1244
- const now = moment5.utc();
2728
+ const now = moment6.utc();
1245
2729
  return this.getReviewstoDate(now, course_id);
1246
2730
  }
1247
2731
  async getScheduledReviewCount(course_id) {
@@ -1528,7 +3012,7 @@ Currently logged-in as ${this._username}.`
1528
3012
  */
1529
3013
  async putCardRecord(record) {
1530
3014
  const cardHistoryID = getCardHistoryID(record.courseID, record.cardID);
1531
- record.timeStamp = moment5.utc(record.timeStamp).toString();
3015
+ record.timeStamp = moment6.utc(record.timeStamp).toString();
1532
3016
  try {
1533
3017
  const cardHistory = await this.update(
1534
3018
  cardHistoryID,
@@ -1544,7 +3028,7 @@ Currently logged-in as ${this._username}.`
1544
3028
  const ret = {
1545
3029
  ...record2
1546
3030
  };
1547
- ret.timeStamp = moment5.utc(record2.timeStamp);
3031
+ ret.timeStamp = moment6.utc(record2.timeStamp);
1548
3032
  return ret;
1549
3033
  });
1550
3034
  return cardHistory;
@@ -1800,12 +3284,24 @@ var init_factory = __esm({
1800
3284
  }
1801
3285
  });
1802
3286
 
3287
+ // src/study/TagFilteredContentSource.ts
3288
+ import { hasActiveFilter } from "@vue-skuilder/common";
3289
+ var init_TagFilteredContentSource = __esm({
3290
+ "src/study/TagFilteredContentSource.ts"() {
3291
+ "use strict";
3292
+ init_courseDB();
3293
+ init_logger();
3294
+ }
3295
+ });
3296
+
1803
3297
  // src/core/interfaces/contentSource.ts
3298
+ import { hasActiveFilter as hasActiveFilter2 } from "@vue-skuilder/common";
1804
3299
  var init_contentSource = __esm({
1805
3300
  "src/core/interfaces/contentSource.ts"() {
1806
3301
  "use strict";
1807
3302
  init_factory();
1808
3303
  init_classroomDB2();
3304
+ init_TagFilteredContentSource();
1809
3305
  }
1810
3306
  });
1811
3307
 
@@ -1860,7 +3356,7 @@ var init_cardProcessor = __esm({
1860
3356
  });
1861
3357
 
1862
3358
  // src/core/bulkImport/types.ts
1863
- var init_types = __esm({
3359
+ var init_types3 = __esm({
1864
3360
  "src/core/bulkImport/types.ts"() {
1865
3361
  "use strict";
1866
3362
  }
@@ -1871,7 +3367,7 @@ var init_bulkImport = __esm({
1871
3367
  "src/core/bulkImport/index.ts"() {
1872
3368
  "use strict";
1873
3369
  init_cardProcessor();
1874
- init_types();
3370
+ init_types3();
1875
3371
  }
1876
3372
  });
1877
3373
 
@@ -2567,9 +4063,6 @@ var init_courseDB3 = __esm({
2567
4063
  async updateNavigationStrategy(_id, _data) {
2568
4064
  throw new Error("Cannot update navigation strategies in static mode");
2569
4065
  }
2570
- async surfaceNavigationStrategy() {
2571
- return this.getNavigationStrategy("ELO");
2572
- }
2573
4066
  // Study Content Source implementation
2574
4067
  async getPendingReviews() {
2575
4068
  return [];