@vue-skuilder/db 0.1.23 → 0.1.25

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/{contentSource-BP9hznNV.d.ts → contentSource-BmnmvH8C.d.ts} +268 -3
  2. package/dist/{contentSource-DsJadoBU.d.cts → contentSource-DfBbaLA-.d.cts} +268 -3
  3. package/dist/core/index.d.cts +310 -6
  4. package/dist/core/index.d.ts +310 -6
  5. package/dist/core/index.js +2606 -666
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +2564 -639
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-CHYrQ5pB.d.cts → dataLayerProvider-BeRXVMs5.d.cts} +1 -1
  10. package/dist/{dataLayerProvider-MDTxXq2l.d.ts → dataLayerProvider-CG9GfaAY.d.ts} +1 -1
  11. package/dist/impl/couch/index.d.cts +11 -3
  12. package/dist/impl/couch/index.d.ts +11 -3
  13. package/dist/impl/couch/index.js +2336 -656
  14. package/dist/impl/couch/index.js.map +1 -1
  15. package/dist/impl/couch/index.mjs +2316 -631
  16. package/dist/impl/couch/index.mjs.map +1 -1
  17. package/dist/impl/static/index.d.cts +4 -4
  18. package/dist/impl/static/index.d.ts +4 -4
  19. package/dist/impl/static/index.js +2312 -632
  20. package/dist/impl/static/index.js.map +1 -1
  21. package/dist/impl/static/index.mjs +2315 -630
  22. package/dist/impl/static/index.mjs.map +1 -1
  23. package/dist/{index-Dj0SEgk3.d.ts → index-BWvO-_rJ.d.ts} +1 -1
  24. package/dist/{index-B_j6u5E4.d.cts → index-Ba7hYbHj.d.cts} +1 -1
  25. package/dist/index.d.cts +278 -20
  26. package/dist/index.d.ts +278 -20
  27. package/dist/index.js +3603 -720
  28. package/dist/index.js.map +1 -1
  29. package/dist/index.mjs +3529 -674
  30. package/dist/index.mjs.map +1 -1
  31. package/dist/{types-DQaXnuoc.d.ts → types-CJrLM1Ew.d.ts} +1 -1
  32. package/dist/{types-Bn0itutr.d.cts → types-W8n-B6HG.d.cts} +1 -1
  33. package/dist/{types-legacy-DDY4N-Uq.d.cts → types-legacy-JXDxinpU.d.cts} +5 -1
  34. package/dist/{types-legacy-DDY4N-Uq.d.ts → types-legacy-JXDxinpU.d.ts} +5 -1
  35. package/dist/util/packer/index.d.cts +3 -3
  36. package/dist/util/packer/index.d.ts +3 -3
  37. package/docs/brainstorm-navigation-paradigm.md +40 -34
  38. package/docs/future-orchestration-vision.md +216 -0
  39. package/docs/navigators-architecture.md +210 -9
  40. package/docs/todo-review-urgency-adaptation.md +205 -0
  41. package/docs/todo-strategy-authoring.md +8 -6
  42. package/package.json +3 -3
  43. package/src/core/index.ts +2 -0
  44. package/src/core/interfaces/contentSource.ts +7 -0
  45. package/src/core/interfaces/userDB.ts +50 -0
  46. package/src/core/navigators/Pipeline.ts +132 -5
  47. package/src/core/navigators/PipelineAssembler.ts +21 -22
  48. package/src/core/navigators/PipelineDebugger.ts +426 -0
  49. package/src/core/navigators/filters/WeightedFilter.ts +141 -0
  50. package/src/core/navigators/filters/types.ts +4 -0
  51. package/src/core/navigators/generators/CompositeGenerator.ts +82 -19
  52. package/src/core/navigators/generators/elo.ts +14 -1
  53. package/src/core/navigators/generators/srs.ts +146 -18
  54. package/src/core/navigators/generators/types.ts +4 -0
  55. package/src/core/navigators/index.ts +203 -13
  56. package/src/core/orchestration/gradient.ts +133 -0
  57. package/src/core/orchestration/index.ts +210 -0
  58. package/src/core/orchestration/learning.ts +250 -0
  59. package/src/core/orchestration/recording.ts +92 -0
  60. package/src/core/orchestration/signal.ts +67 -0
  61. package/src/core/types/contentNavigationStrategy.ts +38 -0
  62. package/src/core/types/learningState.ts +77 -0
  63. package/src/core/types/types-legacy.ts +4 -0
  64. package/src/core/types/userOutcome.ts +51 -0
  65. package/src/courseConfigRegistration.ts +107 -0
  66. package/src/factory.ts +6 -0
  67. package/src/impl/common/BaseUserDB.ts +16 -0
  68. package/src/impl/couch/user-course-relDB.ts +12 -0
  69. package/src/study/MixerDebugger.ts +555 -0
  70. package/src/study/SessionController.ts +159 -20
  71. package/src/study/SessionDebugger.ts +442 -0
  72. package/src/study/SourceMixer.ts +36 -17
  73. package/src/study/TODO-session-scheduling.md +133 -0
  74. package/src/study/index.ts +2 -0
  75. package/src/study/services/EloService.ts +79 -4
  76. package/src/study/services/ResponseProcessor.ts +130 -72
  77. package/src/study/services/SrsService.ts +9 -0
  78. package/tests/core/navigators/Pipeline.test.ts +2 -0
  79. package/tests/core/navigators/PipelineAssembler.test.ts +4 -4
  80. package/docs/todo-evolutionary-orchestration.md +0 -310
@@ -1,7 +1,17 @@
1
+ var __defProp = Object.defineProperty;
1
2
  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
+ };
2
8
  var __esm = (fn, res) => function __init() {
3
9
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
4
10
  };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
5
15
 
6
16
  // src/util/logger.ts
7
17
  var isDevelopment, logger;
@@ -88,7 +98,9 @@ var init_types_legacy = __esm({
88
98
  ["VIEW" /* VIEW */]: "VIEW",
89
99
  ["PEDAGOGY" /* PEDAGOGY */]: "PEDAGOGY",
90
100
  ["NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */]: "NAVIGATION_STRATEGY",
91
- ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE"
101
+ ["STRATEGY_STATE" /* STRATEGY_STATE */]: "STRATEGY_STATE",
102
+ ["USER_OUTCOME" /* USER_OUTCOME */]: "USER_OUTCOME",
103
+ ["STRATEGY_LEARNING_STATE" /* STRATEGY_LEARNING_STATE */]: "STRATEGY_LEARNING_STATE"
92
104
  };
93
105
  }
94
106
  });
@@ -392,6 +404,15 @@ var init_user_course_relDB = __esm({
392
404
  void this.user.updateCourseSettings(this._courseId, updates);
393
405
  }
394
406
  }
407
+ async getStrategyState(strategyKey) {
408
+ return this.user.getStrategyState(this._courseId, strategyKey);
409
+ }
410
+ async putStrategyState(strategyKey, data) {
411
+ return this.user.putStrategyState(this._courseId, strategyKey, data);
412
+ }
413
+ async deleteStrategyState(strategyKey) {
414
+ return this.user.deleteStrategyState(this._courseId, strategyKey);
415
+ }
395
416
  async getReviewstoDate(targetDate) {
396
417
  const allReviews = await this.user.getPendingReviews(this._courseId);
397
418
  logger.debug(
@@ -461,351 +482,309 @@ var init_courseLookupDB = __esm({
461
482
  }
462
483
  });
463
484
 
464
- // src/core/navigators/index.ts
465
- function isGenerator(impl) {
466
- return NavigatorRoles[impl] === "generator" /* GENERATOR */;
485
+ // src/core/navigators/PipelineDebugger.ts
486
+ var PipelineDebugger_exports = {};
487
+ __export(PipelineDebugger_exports, {
488
+ buildRunReport: () => buildRunReport,
489
+ captureRun: () => captureRun,
490
+ mountPipelineDebugger: () => mountPipelineDebugger,
491
+ pipelineDebugAPI: () => pipelineDebugAPI
492
+ });
493
+ function getOrigin(card) {
494
+ const firstEntry = card.provenance[0];
495
+ if (!firstEntry) return "unknown";
496
+ const reason = firstEntry.reason?.toLowerCase() || "";
497
+ if (reason.includes("new card")) return "new";
498
+ if (reason.includes("review")) return "review";
499
+ return "unknown";
467
500
  }
468
- function isFilter(impl) {
469
- return NavigatorRoles[impl] === "filter" /* FILTER */;
501
+ function captureRun(report) {
502
+ const fullReport = {
503
+ ...report,
504
+ runId: `run-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
505
+ timestamp: /* @__PURE__ */ new Date()
506
+ };
507
+ runHistory.unshift(fullReport);
508
+ if (runHistory.length > MAX_RUNS) {
509
+ runHistory.pop();
510
+ }
470
511
  }
471
- var NavigatorRoles, ContentNavigator;
472
- var init_navigators = __esm({
473
- "src/core/navigators/index.ts"() {
512
+ function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards) {
513
+ const selectedIds = new Set(selectedCards.map((c) => c.cardId));
514
+ const cards = allCards.map((card) => ({
515
+ cardId: card.cardId,
516
+ courseId: card.courseId,
517
+ origin: getOrigin(card),
518
+ finalScore: card.score,
519
+ provenance: card.provenance,
520
+ selected: selectedIds.has(card.cardId)
521
+ }));
522
+ const reviewsSelected = selectedCards.filter((c) => getOrigin(c) === "review").length;
523
+ const newSelected = selectedCards.filter((c) => getOrigin(c) === "new").length;
524
+ return {
525
+ courseId,
526
+ courseName,
527
+ generatorName,
528
+ generators,
529
+ generatedCount,
530
+ filters,
531
+ finalCount: selectedCards.length,
532
+ reviewsSelected,
533
+ newSelected,
534
+ cards
535
+ };
536
+ }
537
+ function formatProvenance(provenance) {
538
+ return provenance.map((p) => {
539
+ const actionSymbol = p.action === "generated" ? "\u{1F3B2}" : p.action === "boosted" ? "\u2B06\uFE0F" : p.action === "penalized" ? "\u2B07\uFE0F" : "\u27A1\uFE0F";
540
+ return ` ${actionSymbol} ${p.strategyName}: ${p.score.toFixed(3)} - ${p.reason}`;
541
+ }).join("\n");
542
+ }
543
+ function printRunSummary(run) {
544
+ console.group(`\u{1F50D} Pipeline Run: ${run.courseId} (${run.courseName || "unnamed"})`);
545
+ logger.info(`Run ID: ${run.runId}`);
546
+ logger.info(`Time: ${run.timestamp.toISOString()}`);
547
+ logger.info(`Generator: ${run.generatorName} \u2192 ${run.generatedCount} candidates`);
548
+ if (run.generators && run.generators.length > 0) {
549
+ console.group("Generator breakdown:");
550
+ for (const g of run.generators) {
551
+ logger.info(
552
+ ` ${g.name}: ${g.cardCount} cards (${g.newCount} new, ${g.reviewCount} reviews, top: ${g.topScore.toFixed(2)})`
553
+ );
554
+ }
555
+ console.groupEnd();
556
+ }
557
+ if (run.filters.length > 0) {
558
+ console.group("Filter impact:");
559
+ for (const f of run.filters) {
560
+ logger.info(` ${f.name}: \u2191${f.boosted} \u2193${f.penalized} =${f.passed} \u2715${f.removed}`);
561
+ }
562
+ console.groupEnd();
563
+ }
564
+ logger.info(
565
+ `Result: ${run.finalCount} cards selected (${run.newSelected} new, ${run.reviewsSelected} reviews)`
566
+ );
567
+ console.groupEnd();
568
+ }
569
+ function mountPipelineDebugger() {
570
+ if (typeof window === "undefined") return;
571
+ const win = window;
572
+ win.skuilder = win.skuilder || {};
573
+ win.skuilder.pipeline = pipelineDebugAPI;
574
+ }
575
+ var MAX_RUNS, runHistory, pipelineDebugAPI;
576
+ var init_PipelineDebugger = __esm({
577
+ "src/core/navigators/PipelineDebugger.ts"() {
474
578
  "use strict";
475
579
  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;
580
+ MAX_RUNS = 10;
581
+ runHistory = [];
582
+ pipelineDebugAPI = {
493
583
  /**
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.
584
+ * Get raw run history for programmatic access.
499
585
  */
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
- // ============================================================================
586
+ get runs() {
587
+ return [...runHistory];
588
+ },
516
589
  /**
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.
590
+ * Show summary of a specific pipeline run.
522
591
  */
523
- get strategyKey() {
524
- return this.constructor.name;
525
- }
592
+ showRun(idOrIndex = 0) {
593
+ if (runHistory.length === 0) {
594
+ logger.info("[Pipeline Debug] No runs captured yet.");
595
+ return;
596
+ }
597
+ let run;
598
+ if (typeof idOrIndex === "number") {
599
+ run = runHistory[idOrIndex];
600
+ if (!run) {
601
+ logger.info(
602
+ `[Pipeline Debug] No run found at index ${idOrIndex}. History length: ${runHistory.length}`
603
+ );
604
+ return;
605
+ }
606
+ } else {
607
+ run = runHistory.find((r) => r.runId.endsWith(idOrIndex));
608
+ if (!run) {
609
+ logger.info(`[Pipeline Debug] No run found matching ID '${idOrIndex}'.`);
610
+ return;
611
+ }
612
+ }
613
+ printRunSummary(run);
614
+ },
526
615
  /**
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
616
+ * Show summary of the last pipeline run.
531
617
  */
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
- }
618
+ showLastRun() {
619
+ this.showRun(0);
620
+ },
540
621
  /**
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
622
+ * Show detailed provenance for a specific card.
545
623
  */
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
- );
624
+ showCard(cardId) {
625
+ for (const run of runHistory) {
626
+ const card = run.cards.find((c) => c.cardId === cardId);
627
+ if (card) {
628
+ console.group(`\u{1F3B4} Card: ${cardId}`);
629
+ logger.info(`Course: ${card.courseId}`);
630
+ logger.info(`Origin: ${card.origin}`);
631
+ logger.info(`Final score: ${card.finalScore.toFixed(3)}`);
632
+ logger.info(`Selected: ${card.selected ? "Yes \u2705" : "No \u274C"}`);
633
+ logger.info("Provenance:");
634
+ logger.info(formatProvenance(card.provenance));
635
+ console.groupEnd();
636
+ return;
637
+ }
551
638
  }
552
- return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
553
- }
639
+ logger.info(`[Pipeline Debug] Card '${cardId}' not found in recent runs.`);
640
+ },
554
641
  /**
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.
642
+ * Explain why reviews may or may not have been selected.
561
643
  */
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);
644
+ explainReviews() {
645
+ if (runHistory.length === 0) {
646
+ logger.info("[Pipeline Debug] No runs captured yet.");
647
+ return;
648
+ }
649
+ console.group("\u{1F4CB} Review Selection Analysis");
650
+ for (const run of runHistory) {
651
+ console.group(`Run: ${run.courseId} @ ${run.timestamp.toLocaleTimeString()}`);
652
+ const allReviews = run.cards.filter((c) => c.origin === "review");
653
+ const selectedReviews = allReviews.filter((c) => c.selected);
654
+ if (allReviews.length === 0) {
655
+ logger.info("\u274C No reviews were generated. Check SRS logs for why.");
656
+ } else if (selectedReviews.length === 0) {
657
+ logger.info(`\u26A0\uFE0F ${allReviews.length} reviews generated but none selected.`);
658
+ logger.info("Possible reasons:");
659
+ const topNewScore = Math.max(
660
+ ...run.cards.filter((c) => c.origin === "new" && c.selected).map((c) => c.finalScore),
661
+ 0
662
+ );
663
+ const topReviewScore = Math.max(...allReviews.map((c) => c.finalScore), 0);
664
+ if (topReviewScore < topNewScore) {
665
+ logger.info(
666
+ ` - New cards scored higher (top new: ${topNewScore.toFixed(2)}, top review: ${topReviewScore.toFixed(2)})`
667
+ );
576
668
  }
669
+ const topReview = allReviews.sort((a, b) => b.finalScore - a.finalScore)[0];
670
+ if (topReview) {
671
+ logger.info(` - Top review score: ${topReview.finalScore.toFixed(3)}`);
672
+ logger.info(" - Its provenance:");
673
+ logger.info(formatProvenance(topReview.provenance));
674
+ }
675
+ } else {
676
+ logger.info(`\u2705 ${selectedReviews.length}/${allReviews.length} reviews selected.`);
677
+ logger.info("Top selected review:");
678
+ const topSelected = selectedReviews.sort((a, b) => b.finalScore - a.finalScore)[0];
679
+ logger.info(formatProvenance(topSelected.provenance));
577
680
  }
681
+ console.groupEnd();
578
682
  }
579
- if (!NavigatorImpl) {
580
- throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
683
+ console.groupEnd();
684
+ },
685
+ /**
686
+ * Show all runs in compact format.
687
+ */
688
+ listRuns() {
689
+ if (runHistory.length === 0) {
690
+ logger.info("[Pipeline Debug] No runs captured yet.");
691
+ return;
581
692
  }
582
- return new NavigatorImpl(user, course, strategyData);
583
- }
693
+ console.table(
694
+ runHistory.map((r) => ({
695
+ id: r.runId.slice(-8),
696
+ time: r.timestamp.toLocaleTimeString(),
697
+ course: r.courseName || r.courseId.slice(0, 8),
698
+ generated: r.generatedCount,
699
+ selected: r.finalCount,
700
+ new: r.newSelected,
701
+ reviews: r.reviewsSelected
702
+ }))
703
+ );
704
+ },
584
705
  /**
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
706
+ * Export run history as JSON for bug reports.
608
707
  */
609
- async getWeightedCards(_limit) {
610
- throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
708
+ export() {
709
+ const json = JSON.stringify(runHistory, null, 2);
710
+ logger.info("[Pipeline Debug] Run history exported. Copy the returned string or use:");
711
+ logger.info(" copy(window.skuilder.pipeline.export())");
712
+ return json;
713
+ },
714
+ /**
715
+ * Clear run history.
716
+ */
717
+ clear() {
718
+ runHistory.length = 0;
719
+ logger.info("[Pipeline Debug] Run history cleared.");
720
+ },
721
+ /**
722
+ * Show help.
723
+ */
724
+ help() {
725
+ logger.info(`
726
+ \u{1F527} Pipeline Debug API
727
+
728
+ Commands:
729
+ .showLastRun() Show summary of most recent pipeline run
730
+ .showRun(id|index) Show summary of a specific run (by index or ID suffix)
731
+ .showCard(cardId) Show provenance trail for a specific card
732
+ .explainReviews() Analyze why reviews were/weren't selected
733
+ .listRuns() List all captured runs in table format
734
+ .export() Export run history as JSON for bug reports
735
+ .clear() Clear run history
736
+ .runs Access raw run history array
737
+ .help() Show this help message
738
+
739
+ Example:
740
+ window.skuilder.pipeline.showLastRun()
741
+ window.skuilder.pipeline.showRun(1)
742
+ window.skuilder.pipeline.showCard('abc123')
743
+ `);
611
744
  }
612
745
  };
746
+ mountPipelineDebugger();
613
747
  }
614
748
  });
615
749
 
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"() {
750
+ // src/core/navigators/generators/CompositeGenerator.ts
751
+ var CompositeGenerator_exports = {};
752
+ __export(CompositeGenerator_exports, {
753
+ AggregationMode: () => AggregationMode,
754
+ default: () => CompositeGenerator
755
+ });
756
+ var AggregationMode, DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
757
+ var init_CompositeGenerator = __esm({
758
+ "src/core/navigators/generators/CompositeGenerator.ts"() {
656
759
  "use strict";
657
760
  init_navigators();
658
761
  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) {
762
+ AggregationMode = /* @__PURE__ */ ((AggregationMode2) => {
763
+ AggregationMode2["MAX"] = "max";
764
+ AggregationMode2["AVERAGE"] = "average";
765
+ AggregationMode2["FREQUENCY_BOOST"] = "frequencyBoost";
766
+ return AggregationMode2;
767
+ })(AggregationMode || {});
768
+ DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
769
+ FREQUENCY_BOOST_FACTOR = 0.1;
770
+ CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
771
+ /** Human-readable name for CardGenerator interface */
772
+ name = "Composite Generator";
773
+ generators;
774
+ aggregationMode;
775
+ constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
671
776
  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);
777
+ this.generators = generators;
778
+ this.aggregationMode = aggregationMode;
779
+ if (generators.length === 0) {
780
+ throw new Error("CompositeGenerator requires at least one generator");
781
+ }
782
+ logger.debug(
783
+ `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
784
+ );
682
785
  }
683
786
  /**
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
- }
780
- });
781
-
782
- // src/core/navigators/generators/CompositeGenerator.ts
783
- var DEFAULT_AGGREGATION_MODE, FREQUENCY_BOOST_FACTOR, CompositeGenerator;
784
- var init_CompositeGenerator = __esm({
785
- "src/core/navigators/generators/CompositeGenerator.ts"() {
786
- "use strict";
787
- init_navigators();
788
- init_logger();
789
- DEFAULT_AGGREGATION_MODE = "frequencyBoost" /* FREQUENCY_BOOST */;
790
- FREQUENCY_BOOST_FACTOR = 0.1;
791
- CompositeGenerator = class _CompositeGenerator extends ContentNavigator {
792
- /** Human-readable name for CardGenerator interface */
793
- name = "Composite Generator";
794
- generators;
795
- aggregationMode;
796
- constructor(generators, aggregationMode = DEFAULT_AGGREGATION_MODE) {
797
- super();
798
- this.generators = generators;
799
- this.aggregationMode = aggregationMode;
800
- if (generators.length === 0) {
801
- throw new Error("CompositeGenerator requires at least one generator");
802
- }
803
- logger.debug(
804
- `[CompositeGenerator] Created with ${generators.length} generators, mode: ${aggregationMode}`
805
- );
806
- }
807
- /**
808
- * Creates a CompositeGenerator from strategy data.
787
+ * Creates a CompositeGenerator from strategy data.
809
788
  *
810
789
  * This is a convenience factory for use by PipelineAssembler.
811
790
  */
@@ -836,22 +815,55 @@ var init_CompositeGenerator = __esm({
836
815
  const results = await Promise.all(
837
816
  this.generators.map((g) => g.getWeightedCards(limit, context))
838
817
  );
818
+ const generatorSummaries = [];
819
+ results.forEach((cards, index) => {
820
+ const gen = this.generators[index];
821
+ const genName = gen.name || `Generator ${index}`;
822
+ const newCards = cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
823
+ const reviewCards = cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
824
+ if (cards.length > 0) {
825
+ const topScore = Math.max(...cards.map((c) => c.score)).toFixed(2);
826
+ const parts = [];
827
+ if (newCards.length > 0) parts.push(`${newCards.length} new`);
828
+ if (reviewCards.length > 0) parts.push(`${reviewCards.length} reviews`);
829
+ const breakdown = parts.length > 0 ? parts.join(", ") : `${cards.length} cards`;
830
+ generatorSummaries.push(`${genName}: ${breakdown} (top: ${topScore})`);
831
+ } else {
832
+ generatorSummaries.push(`${genName}: 0 cards`);
833
+ }
834
+ });
835
+ logger.info(`[Composite] Generator breakdown: ${generatorSummaries.join(" | ")}`);
839
836
  const byCardId = /* @__PURE__ */ new Map();
840
- for (const cards of results) {
837
+ results.forEach((cards, index) => {
838
+ const gen = this.generators[index];
839
+ let weight = gen.learnable?.weight ?? 1;
840
+ let deviation;
841
+ if (gen.learnable && !gen.staticWeight && context.orchestration) {
842
+ const strategyId = gen.strategyId;
843
+ if (strategyId) {
844
+ weight = context.orchestration.getEffectiveWeight(strategyId, gen.learnable);
845
+ deviation = context.orchestration.getDeviation(strategyId);
846
+ }
847
+ }
841
848
  for (const card of cards) {
849
+ if (card.provenance.length > 0) {
850
+ card.provenance[0].effectiveWeight = weight;
851
+ card.provenance[0].deviation = deviation;
852
+ }
842
853
  const existing = byCardId.get(card.cardId) || [];
843
- existing.push(card);
854
+ existing.push({ card, weight });
844
855
  byCardId.set(card.cardId, existing);
845
856
  }
846
- }
857
+ });
847
858
  const merged = [];
848
- for (const [, cards] of byCardId) {
849
- const aggregatedScore = this.aggregateScores(cards);
859
+ for (const [, items] of byCardId) {
860
+ const cards = items.map((i) => i.card);
861
+ const aggregatedScore = this.aggregateScores(items);
850
862
  const finalScore = Math.min(1, aggregatedScore);
851
863
  const mergedProvenance = cards.flatMap((c) => c.provenance);
852
864
  const initialScore = cards[0].score;
853
865
  const action = finalScore > initialScore ? "boosted" : finalScore < initialScore ? "penalized" : "passed";
854
- const reason = this.buildAggregationReason(cards, finalScore);
866
+ const reason = this.buildAggregationReason(items, finalScore);
855
867
  merged.push({
856
868
  ...cards[0],
857
869
  score: finalScore,
@@ -873,22 +885,26 @@ var init_CompositeGenerator = __esm({
873
885
  /**
874
886
  * Build human-readable reason for score aggregation.
875
887
  */
876
- buildAggregationReason(cards, finalScore) {
888
+ buildAggregationReason(items, finalScore) {
889
+ const cards = items.map((i) => i.card);
877
890
  const count = cards.length;
878
891
  const scores = cards.map((c) => c.score.toFixed(2)).join(", ");
879
892
  if (count === 1) {
880
- return `Single generator, score ${finalScore.toFixed(2)}`;
893
+ const weightMsg = Math.abs(items[0].weight - 1) > 1e-3 ? ` (w=${items[0].weight.toFixed(2)})` : "";
894
+ return `Single generator, score ${finalScore.toFixed(2)}${weightMsg}`;
881
895
  }
882
896
  const strategies = cards.map((c) => c.provenance[0]?.strategy || "unknown").join(", ");
883
897
  switch (this.aggregationMode) {
884
898
  case "max" /* MAX */:
885
899
  return `Max of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
886
900
  case "average" /* AVERAGE */:
887
- return `Average of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
901
+ return `Weighted Avg of ${count} generators (${strategies}): scores [${scores}] \u2192 ${finalScore.toFixed(2)}`;
888
902
  case "frequencyBoost" /* FREQUENCY_BOOST */: {
889
- const avg = cards.reduce((sum, c) => sum + c.score, 0) / count;
903
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
904
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
905
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
890
906
  const boost = 1 + FREQUENCY_BOOST_FACTOR * (count - 1);
891
- return `Frequency boost from ${count} generators (${strategies}): avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
907
+ return `Frequency boost from ${count} generators (${strategies}): w-avg ${avg.toFixed(2)} \xD7 ${boost.toFixed(2)} \u2192 ${finalScore.toFixed(2)}`;
892
908
  }
893
909
  default:
894
910
  return `Aggregated from ${count} generators: ${finalScore.toFixed(2)}`;
@@ -897,16 +913,22 @@ var init_CompositeGenerator = __esm({
897
913
  /**
898
914
  * Aggregate scores from multiple generators for the same card.
899
915
  */
900
- aggregateScores(cards) {
901
- const scores = cards.map((c) => c.score);
916
+ aggregateScores(items) {
917
+ const scores = items.map((i) => i.card.score);
902
918
  switch (this.aggregationMode) {
903
919
  case "max" /* MAX */:
904
920
  return Math.max(...scores);
905
- case "average" /* AVERAGE */:
906
- return scores.reduce((sum, s) => sum + s, 0) / scores.length;
921
+ case "average" /* AVERAGE */: {
922
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
923
+ if (totalWeight === 0) return 0;
924
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
925
+ return weightedSum / totalWeight;
926
+ }
907
927
  case "frequencyBoost" /* FREQUENCY_BOOST */: {
908
- const avg = scores.reduce((sum, s) => sum + s, 0) / scores.length;
909
- const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (cards.length - 1);
928
+ const totalWeight = items.reduce((sum, i) => sum + i.weight, 0);
929
+ const weightedSum = items.reduce((sum, i) => sum + i.card.score * i.weight, 0);
930
+ const avg = totalWeight > 0 ? weightedSum / totalWeight : 0;
931
+ const frequencyBoost = 1 + FREQUENCY_BOOST_FACTOR * (items.length - 1);
910
932
  return avg * frequencyBoost;
911
933
  }
912
934
  default:
@@ -917,134 +939,18 @@ var init_CompositeGenerator = __esm({
917
939
  }
918
940
  });
919
941
 
920
- // src/core/navigators/PipelineAssembler.ts
921
- var PipelineAssembler;
922
- var init_PipelineAssembler = __esm({
923
- "src/core/navigators/PipelineAssembler.ts"() {
924
- "use strict";
925
- init_navigators();
926
- init_Pipeline();
927
- init_types_legacy();
928
- init_logger();
929
- init_CompositeGenerator();
930
- PipelineAssembler = class {
931
- /**
932
- * Assembles a navigation pipeline from strategy documents.
933
- *
934
- * 1. Separates into generators and filters by role
935
- * 2. Validates at least one generator exists (or creates default ELO)
936
- * 3. Instantiates generators - wraps multiple in CompositeGenerator
937
- * 4. Instantiates filters
938
- * 5. Returns Pipeline(generator, filters)
939
- *
940
- * @param input - Strategy documents plus user/course interfaces
941
- * @returns Assembled pipeline and any warnings
942
- */
943
- async assemble(input) {
944
- const { strategies, user, course } = input;
945
- const warnings = [];
946
- if (strategies.length === 0) {
947
- return {
948
- pipeline: null,
949
- generatorStrategies: [],
950
- filterStrategies: [],
951
- warnings
952
- };
953
- }
954
- const generatorStrategies = [];
955
- const filterStrategies = [];
956
- for (const s of strategies) {
957
- if (isGenerator(s.implementingClass)) {
958
- generatorStrategies.push(s);
959
- } else if (isFilter(s.implementingClass)) {
960
- filterStrategies.push(s);
961
- } else {
962
- warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
963
- }
964
- }
965
- if (generatorStrategies.length === 0) {
966
- if (filterStrategies.length > 0) {
967
- logger.debug(
968
- "[PipelineAssembler] No generator found, using default ELO with configured filters"
969
- );
970
- generatorStrategies.push(this.makeDefaultEloStrategy(course.getCourseID()));
971
- } else {
972
- warnings.push("No generator strategy found");
973
- return {
974
- pipeline: null,
975
- generatorStrategies: [],
976
- filterStrategies: [],
977
- warnings
978
- };
979
- }
980
- }
981
- let generator;
982
- if (generatorStrategies.length === 1) {
983
- const nav = await ContentNavigator.create(user, course, generatorStrategies[0]);
984
- generator = nav;
985
- logger.debug(`[PipelineAssembler] Using single generator: ${generatorStrategies[0].name}`);
986
- } else {
987
- logger.debug(
988
- `[PipelineAssembler] Using CompositeGenerator for ${generatorStrategies.length} generators: ${generatorStrategies.map((g) => g.name).join(", ")}`
989
- );
990
- generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
991
- }
992
- const filters = [];
993
- const sortedFilterStrategies = [...filterStrategies].sort(
994
- (a, b) => a.name.localeCompare(b.name)
995
- );
996
- for (const filterStrategy of sortedFilterStrategies) {
997
- try {
998
- const nav = await ContentNavigator.create(user, course, filterStrategy);
999
- if ("transform" in nav && typeof nav.transform === "function") {
1000
- filters.push(nav);
1001
- logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
1002
- } else {
1003
- warnings.push(
1004
- `Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
1005
- );
1006
- }
1007
- } catch (e) {
1008
- warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
1009
- }
1010
- }
1011
- const pipeline = new Pipeline(generator, filters, user, course);
1012
- logger.debug(
1013
- `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
1014
- );
1015
- return {
1016
- pipeline,
1017
- generatorStrategies,
1018
- filterStrategies: sortedFilterStrategies,
1019
- warnings
1020
- };
1021
- }
1022
- /**
1023
- * Creates a default ELO generator strategy.
1024
- * Used when filters are configured but no generator is specified.
1025
- */
1026
- makeDefaultEloStrategy(courseId) {
1027
- return {
1028
- _id: "NAVIGATION_STRATEGY-ELO-default",
1029
- course: courseId,
1030
- docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
1031
- name: "ELO (default)",
1032
- description: "Default ELO-based generator",
1033
- implementingClass: "elo" /* ELO */,
1034
- serializedData: ""
1035
- };
1036
- }
1037
- };
1038
- }
1039
- });
1040
-
1041
942
  // src/core/navigators/generators/elo.ts
1042
- import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
943
+ var elo_exports = {};
944
+ __export(elo_exports, {
945
+ default: () => ELONavigator
946
+ });
947
+ import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
1043
948
  var ELONavigator;
1044
949
  var init_elo = __esm({
1045
950
  "src/core/navigators/generators/elo.ts"() {
1046
951
  "use strict";
1047
952
  init_navigators();
953
+ init_logger();
1048
954
  ELONavigator = class extends ContentNavigator {
1049
955
  /** Human-readable name for CardGenerator interface */
1050
956
  name;
@@ -1073,7 +979,7 @@ var init_elo = __esm({
1073
979
  userGlobalElo = context.userElo;
1074
980
  } else {
1075
981
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
1076
- const userElo = toCourseElo3(courseReg.elo);
982
+ const userElo = toCourseElo2(courseReg.elo);
1077
983
  userGlobalElo = userElo.global.score;
1078
984
  }
1079
985
  const activeCards = await this.user.getActiveCards();
@@ -1104,205 +1010,1961 @@ var init_elo = __esm({
1104
1010
  };
1105
1011
  });
1106
1012
  scored.sort((a, b) => b.score - a.score);
1107
- return scored.slice(0, limit);
1013
+ const result = scored.slice(0, limit);
1014
+ if (result.length > 0) {
1015
+ const topScores = result.slice(0, 3).map((c) => c.score.toFixed(2)).join(", ");
1016
+ logger.info(
1017
+ `[ELO] Course ${this.course.getCourseID()}: ${result.length} new cards (top scores: ${topScores})`
1018
+ );
1019
+ } else {
1020
+ logger.info(`[ELO] Course ${this.course.getCourseID()}: No new cards available`);
1021
+ }
1022
+ return result;
1023
+ }
1024
+ };
1025
+ }
1026
+ });
1027
+
1028
+ // src/core/navigators/generators/index.ts
1029
+ var generators_exports = {};
1030
+ var init_generators = __esm({
1031
+ "src/core/navigators/generators/index.ts"() {
1032
+ "use strict";
1033
+ }
1034
+ });
1035
+
1036
+ // src/core/navigators/generators/srs.ts
1037
+ var srs_exports = {};
1038
+ __export(srs_exports, {
1039
+ default: () => SRSNavigator
1040
+ });
1041
+ import moment3 from "moment";
1042
+ var DEFAULT_HEALTHY_BACKLOG, MAX_BACKLOG_PRESSURE, SRSNavigator;
1043
+ var init_srs = __esm({
1044
+ "src/core/navigators/generators/srs.ts"() {
1045
+ "use strict";
1046
+ init_navigators();
1047
+ init_logger();
1048
+ DEFAULT_HEALTHY_BACKLOG = 20;
1049
+ MAX_BACKLOG_PRESSURE = 0.5;
1050
+ SRSNavigator = class extends ContentNavigator {
1051
+ /** Human-readable name for CardGenerator interface */
1052
+ name;
1053
+ /** Healthy backlog threshold - when exceeded, backlog pressure kicks in */
1054
+ healthyBacklog;
1055
+ constructor(user, course, strategyData) {
1056
+ super(user, course, strategyData);
1057
+ this.name = strategyData?.name || "SRS";
1058
+ const config = this.parseConfig(strategyData?.serializedData);
1059
+ this.healthyBacklog = config.healthyBacklog ?? DEFAULT_HEALTHY_BACKLOG;
1060
+ }
1061
+ /**
1062
+ * Parse configuration from serialized JSON.
1063
+ */
1064
+ parseConfig(serializedData) {
1065
+ if (!serializedData) return {};
1066
+ try {
1067
+ return JSON.parse(serializedData);
1068
+ } catch {
1069
+ logger.warn("[SRS] Failed to parse strategy config, using defaults");
1070
+ return {};
1071
+ }
1072
+ }
1073
+ /**
1074
+ * Get review cards scored by urgency.
1075
+ *
1076
+ * Score formula combines:
1077
+ * - Relative overdueness: hoursOverdue / intervalHours
1078
+ * - Interval recency: exponential decay favoring shorter intervals
1079
+ * - Backlog pressure: boost when due reviews exceed healthy threshold
1080
+ *
1081
+ * Cards not yet due are excluded (not scored as 0).
1082
+ *
1083
+ * This method supports both the legacy signature (limit only) and the
1084
+ * CardGenerator interface signature (limit, context).
1085
+ *
1086
+ * @param limit - Maximum number of cards to return
1087
+ * @param _context - Optional GeneratorContext (currently unused, but required for interface)
1088
+ */
1089
+ async getWeightedCards(limit, _context) {
1090
+ if (!this.user || !this.course) {
1091
+ throw new Error("SRSNavigator requires user and course to be set");
1092
+ }
1093
+ const courseId = this.course.getCourseID();
1094
+ const reviews = await this.user.getPendingReviews(courseId);
1095
+ const now = moment3.utc();
1096
+ const dueReviews = reviews.filter((r) => now.isAfter(moment3.utc(r.reviewTime)));
1097
+ const backlogPressure = this.computeBacklogPressure(dueReviews.length);
1098
+ if (dueReviews.length > 0) {
1099
+ const pressureNote = backlogPressure > 0 ? ` [backlog pressure: +${backlogPressure.toFixed(2)}]` : ` [healthy backlog]`;
1100
+ logger.info(
1101
+ `[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)${pressureNote}`
1102
+ );
1103
+ } else if (reviews.length > 0) {
1104
+ const sortedByDue = [...reviews].sort(
1105
+ (a, b) => moment3.utc(a.reviewTime).diff(moment3.utc(b.reviewTime))
1106
+ );
1107
+ const nextDue = sortedByDue[0];
1108
+ const nextDueTime = moment3.utc(nextDue.reviewTime);
1109
+ const untilDue = moment3.duration(nextDueTime.diff(now));
1110
+ const untilDueStr = untilDue.asHours() < 1 ? `${Math.round(untilDue.asMinutes())}m` : untilDue.asHours() < 24 ? `${Math.round(untilDue.asHours())}h` : `${Math.round(untilDue.asDays())}d`;
1111
+ logger.info(
1112
+ `[SRS] Course ${courseId}: 0 reviews due now (${reviews.length} scheduled, next in ${untilDueStr})`
1113
+ );
1114
+ } else {
1115
+ logger.info(`[SRS] Course ${courseId}: No reviews scheduled`);
1116
+ }
1117
+ const scored = dueReviews.map((review) => {
1118
+ const { score, reason } = this.computeUrgencyScore(review, now, backlogPressure);
1119
+ return {
1120
+ cardId: review.cardId,
1121
+ courseId: review.courseId,
1122
+ score,
1123
+ reviewID: review._id,
1124
+ provenance: [
1125
+ {
1126
+ strategy: "srs",
1127
+ strategyName: this.strategyName || this.name,
1128
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1129
+ action: "generated",
1130
+ score,
1131
+ reason
1132
+ }
1133
+ ]
1134
+ };
1135
+ });
1136
+ return scored.sort((a, b) => b.score - a.score).slice(0, limit);
1137
+ }
1138
+ /**
1139
+ * Compute backlog pressure based on number of due reviews.
1140
+ *
1141
+ * Backlog pressure is 0 when at or below healthy threshold,
1142
+ * and increases linearly above it, maxing out at MAX_BACKLOG_PRESSURE.
1143
+ *
1144
+ * Examples (with default healthyBacklog=20):
1145
+ * - 10 due reviews → 0.00 (healthy)
1146
+ * - 20 due reviews → 0.00 (at threshold)
1147
+ * - 40 due reviews → 0.25 (2x threshold)
1148
+ * - 60 due reviews → 0.50 (3x threshold, maxed)
1149
+ *
1150
+ * @param dueCount - Number of reviews currently due
1151
+ * @returns Backlog pressure score to add to urgency (0 to MAX_BACKLOG_PRESSURE)
1152
+ */
1153
+ computeBacklogPressure(dueCount) {
1154
+ if (dueCount <= this.healthyBacklog) {
1155
+ return 0;
1156
+ }
1157
+ const excess = dueCount - this.healthyBacklog;
1158
+ const pressure = excess / this.healthyBacklog * (MAX_BACKLOG_PRESSURE / 2);
1159
+ return Math.min(MAX_BACKLOG_PRESSURE, pressure);
1160
+ }
1161
+ /**
1162
+ * Compute urgency score for a review card.
1163
+ *
1164
+ * Three factors:
1165
+ * 1. Relative overdueness = hoursOverdue / intervalHours
1166
+ * - 2 days overdue on 3-day interval = 0.67 (urgent)
1167
+ * - 2 days overdue on 180-day interval = 0.01 (not urgent)
1168
+ *
1169
+ * 2. Interval recency factor = 0.3 + 0.7 * exp(-intervalHours / 720)
1170
+ * - 24h interval → ~1.0 (very recent learning)
1171
+ * - 30 days (720h) → ~0.56
1172
+ * - 180 days → ~0.30
1173
+ *
1174
+ * 3. Backlog pressure = global boost when review backlog exceeds healthy threshold
1175
+ * - At healthy backlog: 0
1176
+ * - At 2x healthy: +0.25
1177
+ * - At 3x+ healthy: +0.50 (max)
1178
+ *
1179
+ * Combined: base 0.5 + (urgency factors * 0.45) + backlog pressure
1180
+ * Result range: 0.5 to 1.0 (uncapped to allow high-urgency reviews to compete with new cards)
1181
+ *
1182
+ * @param review - The scheduled card to score
1183
+ * @param now - Current time
1184
+ * @param backlogPressure - Pre-computed backlog pressure (0 to 0.5)
1185
+ */
1186
+ computeUrgencyScore(review, now, backlogPressure) {
1187
+ const scheduledAt = moment3.utc(review.scheduledAt);
1188
+ const due = moment3.utc(review.reviewTime);
1189
+ const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
1190
+ const hoursOverdue = now.diff(due, "hours");
1191
+ const relativeOverdue = hoursOverdue / intervalHours;
1192
+ const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
1193
+ const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
1194
+ const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
1195
+ const baseScore = 0.5 + urgency * 0.45;
1196
+ const score = Math.min(1, baseScore + backlogPressure);
1197
+ const reasonParts = [
1198
+ `${Math.round(hoursOverdue)}h overdue`,
1199
+ `interval: ${Math.round(intervalHours)}h`,
1200
+ `relative: ${relativeOverdue.toFixed(2)}`,
1201
+ `recency: ${recencyFactor.toFixed(2)}`
1202
+ ];
1203
+ if (backlogPressure > 0) {
1204
+ reasonParts.push(`backlog: +${backlogPressure.toFixed(2)}`);
1205
+ }
1206
+ reasonParts.push("review");
1207
+ const reason = reasonParts.join(", ");
1208
+ return { score, reason };
1209
+ }
1210
+ };
1211
+ }
1212
+ });
1213
+
1214
+ // src/core/navigators/generators/types.ts
1215
+ var types_exports = {};
1216
+ var init_types = __esm({
1217
+ "src/core/navigators/generators/types.ts"() {
1218
+ "use strict";
1219
+ }
1220
+ });
1221
+
1222
+ // import("./generators/**/*") in src/core/navigators/index.ts
1223
+ var globImport_generators;
1224
+ var init_ = __esm({
1225
+ 'import("./generators/**/*") in src/core/navigators/index.ts'() {
1226
+ globImport_generators = __glob({
1227
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
1228
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
1229
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
1230
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
1231
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports))
1232
+ });
1233
+ }
1234
+ });
1235
+
1236
+ // src/core/types/contentNavigationStrategy.ts
1237
+ var DEFAULT_LEARNABLE_WEIGHT;
1238
+ var init_contentNavigationStrategy = __esm({
1239
+ "src/core/types/contentNavigationStrategy.ts"() {
1240
+ "use strict";
1241
+ DEFAULT_LEARNABLE_WEIGHT = {
1242
+ weight: 1,
1243
+ confidence: 0.1,
1244
+ // Low confidence initially = wide exploration
1245
+ sampleSize: 0
1246
+ };
1247
+ }
1248
+ });
1249
+
1250
+ // src/core/navigators/filters/WeightedFilter.ts
1251
+ var WeightedFilter_exports = {};
1252
+ __export(WeightedFilter_exports, {
1253
+ WeightedFilter: () => WeightedFilter
1254
+ });
1255
+ var WeightedFilter;
1256
+ var init_WeightedFilter = __esm({
1257
+ "src/core/navigators/filters/WeightedFilter.ts"() {
1258
+ "use strict";
1259
+ init_contentNavigationStrategy();
1260
+ WeightedFilter = class {
1261
+ name;
1262
+ inner;
1263
+ learnable;
1264
+ staticWeight;
1265
+ strategyId;
1266
+ constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
1267
+ this.inner = inner;
1268
+ this.name = inner.name;
1269
+ this.learnable = learnable;
1270
+ this.staticWeight = staticWeight;
1271
+ this.strategyId = strategyId;
1272
+ }
1273
+ /**
1274
+ * Apply the inner filter, then scale its effect by the configured weight.
1275
+ */
1276
+ async transform(cards, context) {
1277
+ let effectiveWeight = this.learnable.weight;
1278
+ let deviation;
1279
+ if (!this.staticWeight && context.orchestration) {
1280
+ const strategyId = this.strategyId || this.inner.strategyId || this.name;
1281
+ effectiveWeight = context.orchestration.getEffectiveWeight(strategyId, this.learnable);
1282
+ deviation = context.orchestration.getDeviation(strategyId);
1283
+ }
1284
+ if (Math.abs(effectiveWeight - 1) < 1e-3) {
1285
+ return this.inner.transform(cards, context);
1286
+ }
1287
+ const originalScores = /* @__PURE__ */ new Map();
1288
+ for (const card of cards) {
1289
+ originalScores.set(card.cardId, card.score);
1290
+ }
1291
+ const transformedCards = await this.inner.transform(cards, context);
1292
+ return transformedCards.map((card) => {
1293
+ const originalScore = originalScores.get(card.cardId);
1294
+ if (originalScore === void 0 || originalScore === 0 || card.score === 0) {
1295
+ return card;
1296
+ }
1297
+ const rawEffect = card.score / originalScore;
1298
+ if (Math.abs(rawEffect - 1) < 1e-4) {
1299
+ return card;
1300
+ }
1301
+ const weightedEffect = Math.pow(rawEffect, effectiveWeight);
1302
+ const newScore = originalScore * weightedEffect;
1303
+ const lastProvIndex = card.provenance.length - 1;
1304
+ const lastProv = card.provenance[lastProvIndex];
1305
+ if (lastProv) {
1306
+ const updatedProvenance = [...card.provenance];
1307
+ updatedProvenance[lastProvIndex] = {
1308
+ ...lastProv,
1309
+ score: newScore,
1310
+ effectiveWeight,
1311
+ deviation
1312
+ // We can optionally append to the reason, but the structured field is key
1313
+ };
1314
+ return {
1315
+ ...card,
1316
+ score: newScore,
1317
+ provenance: updatedProvenance
1318
+ };
1319
+ }
1320
+ return {
1321
+ ...card,
1322
+ score: newScore
1323
+ };
1324
+ });
1325
+ }
1326
+ };
1327
+ }
1328
+ });
1329
+
1330
+ // src/core/navigators/filters/eloDistance.ts
1331
+ var eloDistance_exports = {};
1332
+ __export(eloDistance_exports, {
1333
+ DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
1334
+ DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
1335
+ DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
1336
+ createEloDistanceFilter: () => createEloDistanceFilter
1337
+ });
1338
+ function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
1339
+ const normalizedDistance = distance / halfLife;
1340
+ const decay = Math.exp(-(normalizedDistance * normalizedDistance));
1341
+ return minMultiplier + (maxMultiplier - minMultiplier) * decay;
1342
+ }
1343
+ function createEloDistanceFilter(config) {
1344
+ const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
1345
+ const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
1346
+ const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
1347
+ return {
1348
+ name: "ELO Distance Filter",
1349
+ async transform(cards, context) {
1350
+ const { course, userElo } = context;
1351
+ const cardIds = cards.map((c) => c.cardId);
1352
+ const cardElos = await course.getCardEloData(cardIds);
1353
+ return cards.map((card, i) => {
1354
+ const cardElo = cardElos[i]?.global?.score ?? 1e3;
1355
+ const distance = Math.abs(cardElo - userElo);
1356
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
1357
+ const newScore = card.score * multiplier;
1358
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
1359
+ return {
1360
+ ...card,
1361
+ score: newScore,
1362
+ provenance: [
1363
+ ...card.provenance,
1364
+ {
1365
+ strategy: "eloDistance",
1366
+ strategyName: "ELO Distance Filter",
1367
+ strategyId: "ELO_DISTANCE_FILTER",
1368
+ action,
1369
+ score: newScore,
1370
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
1371
+ }
1372
+ ]
1373
+ };
1374
+ });
1375
+ }
1376
+ };
1377
+ }
1378
+ var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
1379
+ var init_eloDistance = __esm({
1380
+ "src/core/navigators/filters/eloDistance.ts"() {
1381
+ "use strict";
1382
+ DEFAULT_HALF_LIFE = 200;
1383
+ DEFAULT_MIN_MULTIPLIER = 0.3;
1384
+ DEFAULT_MAX_MULTIPLIER = 1;
1385
+ }
1386
+ });
1387
+
1388
+ // src/core/navigators/filters/hierarchyDefinition.ts
1389
+ var hierarchyDefinition_exports = {};
1390
+ __export(hierarchyDefinition_exports, {
1391
+ default: () => HierarchyDefinitionNavigator
1392
+ });
1393
+ import { toCourseElo as toCourseElo3 } from "@vue-skuilder/common";
1394
+ var DEFAULT_MIN_COUNT, HierarchyDefinitionNavigator;
1395
+ var init_hierarchyDefinition = __esm({
1396
+ "src/core/navigators/filters/hierarchyDefinition.ts"() {
1397
+ "use strict";
1398
+ init_navigators();
1399
+ DEFAULT_MIN_COUNT = 3;
1400
+ HierarchyDefinitionNavigator = class extends ContentNavigator {
1401
+ config;
1402
+ /** Human-readable name for CardFilter interface */
1403
+ name;
1404
+ constructor(user, course, strategyData) {
1405
+ super(user, course, strategyData);
1406
+ this.config = this.parseConfig(strategyData.serializedData);
1407
+ this.name = strategyData.name || "Hierarchy Definition";
1408
+ }
1409
+ parseConfig(serializedData) {
1410
+ try {
1411
+ const parsed = JSON.parse(serializedData);
1412
+ return {
1413
+ prerequisites: parsed.prerequisites || {}
1414
+ };
1415
+ } catch {
1416
+ return {
1417
+ prerequisites: {}
1418
+ };
1419
+ }
1420
+ }
1421
+ /**
1422
+ * Check if a specific prerequisite is satisfied
1423
+ */
1424
+ isPrerequisiteMet(prereq, userTagElo, userGlobalElo) {
1425
+ if (!userTagElo) return false;
1426
+ const minCount = prereq.masteryThreshold?.minCount ?? DEFAULT_MIN_COUNT;
1427
+ if (userTagElo.count < minCount) return false;
1428
+ if (prereq.masteryThreshold?.minElo !== void 0) {
1429
+ return userTagElo.score >= prereq.masteryThreshold.minElo;
1430
+ } else {
1431
+ return userTagElo.score >= userGlobalElo;
1432
+ }
1433
+ }
1434
+ /**
1435
+ * Get the set of tags the user has mastered.
1436
+ * A tag is "mastered" if it appears as a prerequisite somewhere and meets its threshold.
1437
+ */
1438
+ async getMasteredTags(context) {
1439
+ const mastered = /* @__PURE__ */ new Set();
1440
+ try {
1441
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1442
+ const userElo = toCourseElo3(courseReg.elo);
1443
+ for (const prereqs of Object.values(this.config.prerequisites)) {
1444
+ for (const prereq of prereqs) {
1445
+ const tagElo = userElo.tags[prereq.tag];
1446
+ if (this.isPrerequisiteMet(prereq, tagElo, userElo.global.score)) {
1447
+ mastered.add(prereq.tag);
1448
+ }
1449
+ }
1450
+ }
1451
+ } catch {
1452
+ }
1453
+ return mastered;
1454
+ }
1455
+ /**
1456
+ * Get the set of tags that are unlocked (prerequisites met)
1457
+ */
1458
+ getUnlockedTags(masteredTags) {
1459
+ const unlocked = /* @__PURE__ */ new Set();
1460
+ for (const [tagId, prereqs] of Object.entries(this.config.prerequisites)) {
1461
+ const allPrereqsMet = prereqs.every((prereq) => masteredTags.has(prereq.tag));
1462
+ if (allPrereqsMet) {
1463
+ unlocked.add(tagId);
1464
+ }
1465
+ }
1466
+ return unlocked;
1467
+ }
1468
+ /**
1469
+ * Check if a tag has prerequisites defined in config
1470
+ */
1471
+ hasPrerequisites(tagId) {
1472
+ return tagId in this.config.prerequisites;
1473
+ }
1474
+ /**
1475
+ * Check if a card is unlocked and generate reason.
1476
+ */
1477
+ async checkCardUnlock(card, _course, unlockedTags, masteredTags) {
1478
+ try {
1479
+ const cardTags = card.tags ?? [];
1480
+ const lockedTags = cardTags.filter(
1481
+ (tag) => this.hasPrerequisites(tag) && !unlockedTags.has(tag)
1482
+ );
1483
+ if (lockedTags.length === 0) {
1484
+ const tagList = cardTags.length > 0 ? cardTags.join(", ") : "none";
1485
+ return {
1486
+ isUnlocked: true,
1487
+ reason: `Prerequisites met, tags: ${tagList}`
1488
+ };
1489
+ }
1490
+ const missingPrereqs = lockedTags.flatMap((tag) => {
1491
+ const prereqs = this.config.prerequisites[tag] || [];
1492
+ return prereqs.filter((p) => !masteredTags.has(p.tag)).map((p) => p.tag);
1493
+ });
1494
+ return {
1495
+ isUnlocked: false,
1496
+ reason: `Blocked: missing prerequisites ${missingPrereqs.join(", ")} for tags ${lockedTags.join(", ")}`
1497
+ };
1498
+ } catch {
1499
+ return {
1500
+ isUnlocked: true,
1501
+ reason: "Prerequisites check skipped (tag lookup failed)"
1502
+ };
1503
+ }
1504
+ }
1505
+ /**
1506
+ * CardFilter.transform implementation.
1507
+ *
1508
+ * Apply prerequisite gating to cards. Cards with locked tags receive score: 0.
1509
+ */
1510
+ async transform(cards, context) {
1511
+ const masteredTags = await this.getMasteredTags(context);
1512
+ const unlockedTags = this.getUnlockedTags(masteredTags);
1513
+ const gated = [];
1514
+ for (const card of cards) {
1515
+ const { isUnlocked, reason } = await this.checkCardUnlock(
1516
+ card,
1517
+ context.course,
1518
+ unlockedTags,
1519
+ masteredTags
1520
+ );
1521
+ const finalScore = isUnlocked ? card.score : 0;
1522
+ const action = isUnlocked ? "passed" : "penalized";
1523
+ gated.push({
1524
+ ...card,
1525
+ score: finalScore,
1526
+ provenance: [
1527
+ ...card.provenance,
1528
+ {
1529
+ strategy: "hierarchyDefinition",
1530
+ strategyName: this.strategyName || this.name,
1531
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-hierarchy",
1532
+ action,
1533
+ score: finalScore,
1534
+ reason
1535
+ }
1536
+ ]
1537
+ });
1538
+ }
1539
+ return gated;
1540
+ }
1541
+ /**
1542
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1543
+ *
1544
+ * Use transform() via Pipeline instead.
1545
+ */
1546
+ async getWeightedCards(_limit) {
1547
+ throw new Error(
1548
+ "HierarchyDefinitionNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1549
+ );
1550
+ }
1551
+ };
1552
+ }
1553
+ });
1554
+
1555
+ // src/core/navigators/filters/userTagPreference.ts
1556
+ var userTagPreference_exports = {};
1557
+ __export(userTagPreference_exports, {
1558
+ default: () => UserTagPreferenceFilter
1559
+ });
1560
+ var UserTagPreferenceFilter;
1561
+ var init_userTagPreference = __esm({
1562
+ "src/core/navigators/filters/userTagPreference.ts"() {
1563
+ "use strict";
1564
+ init_navigators();
1565
+ UserTagPreferenceFilter = class extends ContentNavigator {
1566
+ _strategyData;
1567
+ /** Human-readable name for CardFilter interface */
1568
+ name;
1569
+ constructor(user, course, strategyData) {
1570
+ super(user, course, strategyData);
1571
+ this._strategyData = strategyData;
1572
+ this.name = strategyData.name || "User Tag Preferences";
1573
+ }
1574
+ /**
1575
+ * Compute multiplier for a card based on its tags and user preferences.
1576
+ * Returns the maximum multiplier among all matching tags, or 1.0 if no matches.
1577
+ */
1578
+ computeMultiplier(cardTags, boostMap) {
1579
+ const multipliers = cardTags.map((tag) => boostMap[tag]).filter((val) => val !== void 0);
1580
+ if (multipliers.length === 0) {
1581
+ return 1;
1582
+ }
1583
+ return Math.max(...multipliers);
1584
+ }
1585
+ /**
1586
+ * Build human-readable reason for the filter's decision.
1587
+ */
1588
+ buildReason(cardTags, boostMap, multiplier) {
1589
+ const matchingTags = cardTags.filter((tag) => boostMap[tag] === multiplier);
1590
+ if (multiplier === 0) {
1591
+ return `Excluded by user preference: ${matchingTags.join(", ")} (${multiplier}x)`;
1592
+ }
1593
+ if (multiplier < 1) {
1594
+ return `Penalized by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1595
+ }
1596
+ if (multiplier > 1) {
1597
+ return `Boosted by user preference: ${matchingTags.join(", ")} (${multiplier.toFixed(2)}x)`;
1598
+ }
1599
+ return "No matching user preferences";
1600
+ }
1601
+ /**
1602
+ * CardFilter.transform implementation.
1603
+ *
1604
+ * Apply user tag preferences:
1605
+ * 1. Read preferences from strategy state
1606
+ * 2. If no preferences, pass through unchanged
1607
+ * 3. For each card:
1608
+ * - Look up tag in boost record
1609
+ * - If tag found: apply multiplier (0 = exclude, 1 = neutral, >1 = boost)
1610
+ * - If multiple tags match: use max multiplier
1611
+ * - Append provenance with clear reason
1612
+ */
1613
+ async transform(cards, _context) {
1614
+ const prefs = await this.getStrategyState();
1615
+ if (!prefs || Object.keys(prefs.boost).length === 0) {
1616
+ return cards.map((card) => ({
1617
+ ...card,
1618
+ provenance: [
1619
+ ...card.provenance,
1620
+ {
1621
+ strategy: "userTagPreference",
1622
+ strategyName: this.strategyName || this.name,
1623
+ strategyId: this.strategyId || this._strategyData._id,
1624
+ action: "passed",
1625
+ score: card.score,
1626
+ reason: "No user tag preferences configured"
1627
+ }
1628
+ ]
1629
+ }));
1630
+ }
1631
+ const adjusted = await Promise.all(
1632
+ cards.map(async (card) => {
1633
+ const cardTags = card.tags ?? [];
1634
+ const multiplier = this.computeMultiplier(cardTags, prefs.boost);
1635
+ const finalScore = Math.min(1, card.score * multiplier);
1636
+ let action;
1637
+ if (multiplier === 0 || multiplier < 1) {
1638
+ action = "penalized";
1639
+ } else if (multiplier > 1) {
1640
+ action = "boosted";
1641
+ } else {
1642
+ action = "passed";
1643
+ }
1644
+ return {
1645
+ ...card,
1646
+ score: finalScore,
1647
+ provenance: [
1648
+ ...card.provenance,
1649
+ {
1650
+ strategy: "userTagPreference",
1651
+ strategyName: this.strategyName || this.name,
1652
+ strategyId: this.strategyId || this._strategyData._id,
1653
+ action,
1654
+ score: finalScore,
1655
+ reason: this.buildReason(cardTags, prefs.boost, multiplier)
1656
+ }
1657
+ ]
1658
+ };
1659
+ })
1660
+ );
1661
+ return adjusted;
1662
+ }
1663
+ /**
1664
+ * Legacy getWeightedCards - throws as filters should not be used as generators.
1665
+ */
1666
+ async getWeightedCards(_limit) {
1667
+ throw new Error(
1668
+ "UserTagPreferenceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1669
+ );
1670
+ }
1671
+ };
1672
+ }
1673
+ });
1674
+
1675
+ // src/core/navigators/filters/index.ts
1676
+ var filters_exports = {};
1677
+ __export(filters_exports, {
1678
+ UserTagPreferenceFilter: () => UserTagPreferenceFilter,
1679
+ createEloDistanceFilter: () => createEloDistanceFilter
1680
+ });
1681
+ var init_filters = __esm({
1682
+ "src/core/navigators/filters/index.ts"() {
1683
+ "use strict";
1684
+ init_eloDistance();
1685
+ init_userTagPreference();
1686
+ }
1687
+ });
1688
+
1689
+ // src/core/navigators/filters/inferredPreferenceStub.ts
1690
+ var inferredPreferenceStub_exports = {};
1691
+ __export(inferredPreferenceStub_exports, {
1692
+ INFERRED_PREFERENCE_NAVIGATOR_STUB: () => INFERRED_PREFERENCE_NAVIGATOR_STUB
1693
+ });
1694
+ var INFERRED_PREFERENCE_NAVIGATOR_STUB;
1695
+ var init_inferredPreferenceStub = __esm({
1696
+ "src/core/navigators/filters/inferredPreferenceStub.ts"() {
1697
+ "use strict";
1698
+ INFERRED_PREFERENCE_NAVIGATOR_STUB = true;
1699
+ }
1700
+ });
1701
+
1702
+ // src/core/navigators/filters/interferenceMitigator.ts
1703
+ var interferenceMitigator_exports = {};
1704
+ __export(interferenceMitigator_exports, {
1705
+ default: () => InterferenceMitigatorNavigator
1706
+ });
1707
+ import { toCourseElo as toCourseElo4 } from "@vue-skuilder/common";
1708
+ var DEFAULT_MIN_COUNT2, DEFAULT_MIN_ELAPSED_DAYS, DEFAULT_INTERFERENCE_DECAY, InterferenceMitigatorNavigator;
1709
+ var init_interferenceMitigator = __esm({
1710
+ "src/core/navigators/filters/interferenceMitigator.ts"() {
1711
+ "use strict";
1712
+ init_navigators();
1713
+ DEFAULT_MIN_COUNT2 = 10;
1714
+ DEFAULT_MIN_ELAPSED_DAYS = 3;
1715
+ DEFAULT_INTERFERENCE_DECAY = 0.8;
1716
+ InterferenceMitigatorNavigator = class extends ContentNavigator {
1717
+ config;
1718
+ /** Human-readable name for CardFilter interface */
1719
+ name;
1720
+ /** Precomputed map: tag -> set of { partner, decay } it interferes with */
1721
+ interferenceMap;
1722
+ constructor(user, course, strategyData) {
1723
+ super(user, course, strategyData);
1724
+ this.config = this.parseConfig(strategyData.serializedData);
1725
+ this.interferenceMap = this.buildInterferenceMap();
1726
+ this.name = strategyData.name || "Interference Mitigator";
1727
+ }
1728
+ parseConfig(serializedData) {
1729
+ try {
1730
+ const parsed = JSON.parse(serializedData);
1731
+ let sets = parsed.interferenceSets || [];
1732
+ if (sets.length > 0 && Array.isArray(sets[0])) {
1733
+ sets = sets.map((tags) => ({ tags }));
1734
+ }
1735
+ return {
1736
+ interferenceSets: sets,
1737
+ maturityThreshold: {
1738
+ minCount: parsed.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2,
1739
+ minElo: parsed.maturityThreshold?.minElo,
1740
+ minElapsedDays: parsed.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS
1741
+ },
1742
+ defaultDecay: parsed.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY
1743
+ };
1744
+ } catch {
1745
+ return {
1746
+ interferenceSets: [],
1747
+ maturityThreshold: {
1748
+ minCount: DEFAULT_MIN_COUNT2,
1749
+ minElapsedDays: DEFAULT_MIN_ELAPSED_DAYS
1750
+ },
1751
+ defaultDecay: DEFAULT_INTERFERENCE_DECAY
1752
+ };
1753
+ }
1754
+ }
1755
+ /**
1756
+ * Build a map from each tag to its interference partners with decay coefficients.
1757
+ * If tags A, B, C are in an interference group with decay 0.8, then:
1758
+ * - A interferes with B (decay 0.8) and C (decay 0.8)
1759
+ * - B interferes with A (decay 0.8) and C (decay 0.8)
1760
+ * - etc.
1761
+ */
1762
+ buildInterferenceMap() {
1763
+ const map = /* @__PURE__ */ new Map();
1764
+ for (const group of this.config.interferenceSets) {
1765
+ const decay = group.decay ?? this.config.defaultDecay ?? DEFAULT_INTERFERENCE_DECAY;
1766
+ for (const tag of group.tags) {
1767
+ if (!map.has(tag)) {
1768
+ map.set(tag, []);
1769
+ }
1770
+ const partners = map.get(tag);
1771
+ for (const other of group.tags) {
1772
+ if (other !== tag) {
1773
+ const existing = partners.find((p) => p.partner === other);
1774
+ if (existing) {
1775
+ existing.decay = Math.max(existing.decay, decay);
1776
+ } else {
1777
+ partners.push({ partner: other, decay });
1778
+ }
1779
+ }
1780
+ }
1781
+ }
1782
+ }
1783
+ return map;
1784
+ }
1785
+ /**
1786
+ * Get the set of tags that are currently immature for this user.
1787
+ * A tag is immature if the user has interacted with it but hasn't
1788
+ * reached the maturity threshold.
1789
+ */
1790
+ async getImmatureTags(context) {
1791
+ const immature = /* @__PURE__ */ new Set();
1792
+ try {
1793
+ const courseReg = await context.user.getCourseRegDoc(context.course.getCourseID());
1794
+ const userElo = toCourseElo4(courseReg.elo);
1795
+ const minCount = this.config.maturityThreshold?.minCount ?? DEFAULT_MIN_COUNT2;
1796
+ const minElo = this.config.maturityThreshold?.minElo;
1797
+ const minElapsedDays = this.config.maturityThreshold?.minElapsedDays ?? DEFAULT_MIN_ELAPSED_DAYS;
1798
+ const minCountForElapsed = minElapsedDays * 2;
1799
+ for (const [tagId, tagElo] of Object.entries(userElo.tags)) {
1800
+ if (tagElo.count === 0) continue;
1801
+ const belowCount = tagElo.count < minCount;
1802
+ const belowElo = minElo !== void 0 && tagElo.score < minElo;
1803
+ const belowElapsed = tagElo.count < minCountForElapsed;
1804
+ if (belowCount || belowElo || belowElapsed) {
1805
+ immature.add(tagId);
1806
+ }
1807
+ }
1808
+ } catch {
1809
+ }
1810
+ return immature;
1811
+ }
1812
+ /**
1813
+ * Get all tags that interfere with any immature tag, along with their decay coefficients.
1814
+ * These are the tags we want to avoid introducing.
1815
+ */
1816
+ getTagsToAvoid(immatureTags) {
1817
+ const avoid = /* @__PURE__ */ new Map();
1818
+ for (const immatureTag of immatureTags) {
1819
+ const partners = this.interferenceMap.get(immatureTag);
1820
+ if (partners) {
1821
+ for (const { partner, decay } of partners) {
1822
+ if (!immatureTags.has(partner)) {
1823
+ const existing = avoid.get(partner) ?? 0;
1824
+ avoid.set(partner, Math.max(existing, decay));
1825
+ }
1826
+ }
1827
+ }
1828
+ }
1829
+ return avoid;
1830
+ }
1831
+ /**
1832
+ * Compute interference score reduction for a card.
1833
+ * Returns: { multiplier, interfering tags, reason }
1834
+ */
1835
+ computeInterferenceEffect(cardTags, tagsToAvoid, immatureTags) {
1836
+ if (tagsToAvoid.size === 0) {
1837
+ return {
1838
+ multiplier: 1,
1839
+ interferingTags: [],
1840
+ reason: "No interference detected"
1841
+ };
1842
+ }
1843
+ let multiplier = 1;
1844
+ const interferingTags = [];
1845
+ for (const tag of cardTags) {
1846
+ const decay = tagsToAvoid.get(tag);
1847
+ if (decay !== void 0) {
1848
+ interferingTags.push(tag);
1849
+ multiplier *= 1 - decay;
1850
+ }
1851
+ }
1852
+ if (interferingTags.length === 0) {
1853
+ return {
1854
+ multiplier: 1,
1855
+ interferingTags: [],
1856
+ reason: "No interference detected"
1857
+ };
1858
+ }
1859
+ const causingTags = /* @__PURE__ */ new Set();
1860
+ for (const tag of interferingTags) {
1861
+ for (const immatureTag of immatureTags) {
1862
+ const partners = this.interferenceMap.get(immatureTag);
1863
+ if (partners?.some((p) => p.partner === tag)) {
1864
+ causingTags.add(immatureTag);
1865
+ }
1866
+ }
1867
+ }
1868
+ const reason = `Interferes with immature tags ${Array.from(causingTags).join(", ")} (tags: ${interferingTags.join(", ")}, multiplier: ${multiplier.toFixed(2)})`;
1869
+ return { multiplier, interferingTags, reason };
1870
+ }
1871
+ /**
1872
+ * CardFilter.transform implementation.
1873
+ *
1874
+ * Apply interference-aware scoring. Cards with tags that interfere with
1875
+ * immature learnings get reduced scores.
1876
+ */
1877
+ async transform(cards, context) {
1878
+ const immatureTags = await this.getImmatureTags(context);
1879
+ const tagsToAvoid = this.getTagsToAvoid(immatureTags);
1880
+ const adjusted = [];
1881
+ for (const card of cards) {
1882
+ const cardTags = card.tags ?? [];
1883
+ const { multiplier, reason } = this.computeInterferenceEffect(
1884
+ cardTags,
1885
+ tagsToAvoid,
1886
+ immatureTags
1887
+ );
1888
+ const finalScore = card.score * multiplier;
1889
+ const action = multiplier < 1 ? "penalized" : multiplier > 1 ? "boosted" : "passed";
1890
+ adjusted.push({
1891
+ ...card,
1892
+ score: finalScore,
1893
+ provenance: [
1894
+ ...card.provenance,
1895
+ {
1896
+ strategy: "interferenceMitigator",
1897
+ strategyName: this.strategyName || this.name,
1898
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-interference",
1899
+ action,
1900
+ score: finalScore,
1901
+ reason
1902
+ }
1903
+ ]
1904
+ });
1905
+ }
1906
+ return adjusted;
1907
+ }
1908
+ /**
1909
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
1910
+ *
1911
+ * Use transform() via Pipeline instead.
1912
+ */
1913
+ async getWeightedCards(_limit) {
1914
+ throw new Error(
1915
+ "InterferenceMitigatorNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
1916
+ );
1917
+ }
1918
+ };
1919
+ }
1920
+ });
1921
+
1922
+ // src/core/navigators/filters/relativePriority.ts
1923
+ var relativePriority_exports = {};
1924
+ __export(relativePriority_exports, {
1925
+ default: () => RelativePriorityNavigator
1926
+ });
1927
+ var DEFAULT_PRIORITY, DEFAULT_PRIORITY_INFLUENCE, DEFAULT_COMBINE_MODE, RelativePriorityNavigator;
1928
+ var init_relativePriority = __esm({
1929
+ "src/core/navigators/filters/relativePriority.ts"() {
1930
+ "use strict";
1931
+ init_navigators();
1932
+ DEFAULT_PRIORITY = 0.5;
1933
+ DEFAULT_PRIORITY_INFLUENCE = 0.5;
1934
+ DEFAULT_COMBINE_MODE = "max";
1935
+ RelativePriorityNavigator = class extends ContentNavigator {
1936
+ config;
1937
+ /** Human-readable name for CardFilter interface */
1938
+ name;
1939
+ constructor(user, course, strategyData) {
1940
+ super(user, course, strategyData);
1941
+ this.config = this.parseConfig(strategyData.serializedData);
1942
+ this.name = strategyData.name || "Relative Priority";
1943
+ }
1944
+ parseConfig(serializedData) {
1945
+ try {
1946
+ const parsed = JSON.parse(serializedData);
1947
+ return {
1948
+ tagPriorities: parsed.tagPriorities || {},
1949
+ defaultPriority: parsed.defaultPriority ?? DEFAULT_PRIORITY,
1950
+ combineMode: parsed.combineMode ?? DEFAULT_COMBINE_MODE,
1951
+ priorityInfluence: parsed.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE
1952
+ };
1953
+ } catch {
1954
+ return {
1955
+ tagPriorities: {},
1956
+ defaultPriority: DEFAULT_PRIORITY,
1957
+ combineMode: DEFAULT_COMBINE_MODE,
1958
+ priorityInfluence: DEFAULT_PRIORITY_INFLUENCE
1959
+ };
1960
+ }
1961
+ }
1962
+ /**
1963
+ * Look up the priority for a tag.
1964
+ */
1965
+ getTagPriority(tagId) {
1966
+ return this.config.tagPriorities[tagId] ?? this.config.defaultPriority ?? DEFAULT_PRIORITY;
1967
+ }
1968
+ /**
1969
+ * Compute combined priority for a card based on its tags.
1970
+ */
1971
+ computeCardPriority(cardTags) {
1972
+ if (cardTags.length === 0) {
1973
+ return this.config.defaultPriority ?? DEFAULT_PRIORITY;
1974
+ }
1975
+ const priorities = cardTags.map((tag) => this.getTagPriority(tag));
1976
+ switch (this.config.combineMode) {
1977
+ case "max":
1978
+ return Math.max(...priorities);
1979
+ case "min":
1980
+ return Math.min(...priorities);
1981
+ case "average":
1982
+ return priorities.reduce((sum, p) => sum + p, 0) / priorities.length;
1983
+ default:
1984
+ return Math.max(...priorities);
1985
+ }
1986
+ }
1987
+ /**
1988
+ * Compute boost factor based on priority.
1989
+ *
1990
+ * The formula: 1 + (priority - 0.5) * priorityInfluence
1991
+ *
1992
+ * This creates a multiplier centered around 1.0:
1993
+ * - Priority 1.0 with influence 0.5 → 1.25 (25% boost)
1994
+ * - Priority 0.5 with any influence → 1.00 (neutral)
1995
+ * - Priority 0.0 with influence 0.5 → 0.75 (25% reduction)
1996
+ */
1997
+ computeBoostFactor(priority) {
1998
+ const influence = this.config.priorityInfluence ?? DEFAULT_PRIORITY_INFLUENCE;
1999
+ return 1 + (priority - 0.5) * influence;
2000
+ }
2001
+ /**
2002
+ * Build human-readable reason for priority adjustment.
2003
+ */
2004
+ buildPriorityReason(cardTags, priority, boostFactor, finalScore) {
2005
+ if (cardTags.length === 0) {
2006
+ return `No tags, neutral priority (${priority.toFixed(2)})`;
2007
+ }
2008
+ const tagList = cardTags.slice(0, 3).join(", ");
2009
+ const more = cardTags.length > 3 ? ` (+${cardTags.length - 3} more)` : "";
2010
+ if (boostFactor === 1) {
2011
+ return `Neutral priority (${priority.toFixed(2)}) for tags: ${tagList}${more}`;
2012
+ } else if (boostFactor > 1) {
2013
+ return `High-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 boost ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
2014
+ } else {
2015
+ return `Low-priority tags: ${tagList}${more} (priority ${priority.toFixed(2)} \u2192 reduce ${boostFactor.toFixed(2)}x \u2192 ${finalScore.toFixed(2)})`;
2016
+ }
2017
+ }
2018
+ /**
2019
+ * CardFilter.transform implementation.
2020
+ *
2021
+ * Apply priority-adjusted scoring. Cards with high-priority tags get boosted,
2022
+ * cards with low-priority tags get reduced scores.
2023
+ */
2024
+ async transform(cards, _context) {
2025
+ const adjusted = await Promise.all(
2026
+ cards.map(async (card) => {
2027
+ const cardTags = card.tags ?? [];
2028
+ const priority = this.computeCardPriority(cardTags);
2029
+ const boostFactor = this.computeBoostFactor(priority);
2030
+ const finalScore = Math.max(0, Math.min(1, card.score * boostFactor));
2031
+ const action = boostFactor > 1 ? "boosted" : boostFactor < 1 ? "penalized" : "passed";
2032
+ const reason = this.buildPriorityReason(cardTags, priority, boostFactor, finalScore);
2033
+ return {
2034
+ ...card,
2035
+ score: finalScore,
2036
+ provenance: [
2037
+ ...card.provenance,
2038
+ {
2039
+ strategy: "relativePriority",
2040
+ strategyName: this.strategyName || this.name,
2041
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-priority",
2042
+ action,
2043
+ score: finalScore,
2044
+ reason
2045
+ }
2046
+ ]
2047
+ };
2048
+ })
2049
+ );
2050
+ return adjusted;
2051
+ }
2052
+ /**
2053
+ * Legacy getWeightedCards - now throws as filters should not be used as generators.
2054
+ *
2055
+ * Use transform() via Pipeline instead.
2056
+ */
2057
+ async getWeightedCards(_limit) {
2058
+ throw new Error(
2059
+ "RelativePriorityNavigator is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
2060
+ );
2061
+ }
2062
+ };
2063
+ }
2064
+ });
2065
+
2066
+ // src/core/navigators/filters/types.ts
2067
+ var types_exports2 = {};
2068
+ var init_types2 = __esm({
2069
+ "src/core/navigators/filters/types.ts"() {
2070
+ "use strict";
2071
+ }
2072
+ });
2073
+
2074
+ // src/core/navigators/filters/userGoalStub.ts
2075
+ var userGoalStub_exports = {};
2076
+ __export(userGoalStub_exports, {
2077
+ USER_GOAL_NAVIGATOR_STUB: () => USER_GOAL_NAVIGATOR_STUB
2078
+ });
2079
+ var USER_GOAL_NAVIGATOR_STUB;
2080
+ var init_userGoalStub = __esm({
2081
+ "src/core/navigators/filters/userGoalStub.ts"() {
2082
+ "use strict";
2083
+ USER_GOAL_NAVIGATOR_STUB = true;
2084
+ }
2085
+ });
2086
+
2087
+ // import("./filters/**/*") in src/core/navigators/index.ts
2088
+ var globImport_filters;
2089
+ var init_2 = __esm({
2090
+ 'import("./filters/**/*") in src/core/navigators/index.ts'() {
2091
+ globImport_filters = __glob({
2092
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
2093
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2094
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2095
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2096
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
2097
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2098
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2099
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
2100
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
2101
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
2102
+ });
2103
+ }
2104
+ });
2105
+
2106
+ // src/core/orchestration/gradient.ts
2107
+ var init_gradient = __esm({
2108
+ "src/core/orchestration/gradient.ts"() {
2109
+ "use strict";
2110
+ init_logger();
2111
+ }
2112
+ });
2113
+
2114
+ // src/core/orchestration/learning.ts
2115
+ var init_learning = __esm({
2116
+ "src/core/orchestration/learning.ts"() {
2117
+ "use strict";
2118
+ init_contentNavigationStrategy();
2119
+ init_types_legacy();
2120
+ init_logger();
2121
+ }
2122
+ });
2123
+
2124
+ // src/core/orchestration/signal.ts
2125
+ var init_signal = __esm({
2126
+ "src/core/orchestration/signal.ts"() {
2127
+ "use strict";
2128
+ }
2129
+ });
2130
+
2131
+ // src/core/orchestration/recording.ts
2132
+ var init_recording = __esm({
2133
+ "src/core/orchestration/recording.ts"() {
2134
+ "use strict";
2135
+ init_signal();
2136
+ init_types_legacy();
2137
+ init_logger();
2138
+ }
2139
+ });
2140
+
2141
+ // src/core/orchestration/index.ts
2142
+ function fnv1a(str) {
2143
+ let hash = 2166136261;
2144
+ for (let i = 0; i < str.length; i++) {
2145
+ hash ^= str.charCodeAt(i);
2146
+ hash = Math.imul(hash, 16777619);
2147
+ }
2148
+ return hash >>> 0;
2149
+ }
2150
+ function computeDeviation(userId, strategyId, salt) {
2151
+ const input = `${userId}:${strategyId}:${salt}`;
2152
+ const hash = fnv1a(input);
2153
+ const normalized = hash / 4294967296;
2154
+ return normalized * 2 - 1;
2155
+ }
2156
+ function computeSpread(confidence) {
2157
+ const clampedConfidence = Math.max(0, Math.min(1, confidence));
2158
+ return MAX_SPREAD - clampedConfidence * (MAX_SPREAD - MIN_SPREAD);
2159
+ }
2160
+ function computeEffectiveWeight(learnable, userId, strategyId, salt) {
2161
+ const deviation = computeDeviation(userId, strategyId, salt);
2162
+ const spread = computeSpread(learnable.confidence);
2163
+ const adjustment = deviation * spread * learnable.weight;
2164
+ const effective = learnable.weight + adjustment;
2165
+ return Math.max(MIN_WEIGHT, Math.min(MAX_WEIGHT, effective));
2166
+ }
2167
+ async function createOrchestrationContext(user, course) {
2168
+ let courseConfig;
2169
+ try {
2170
+ courseConfig = await course.getCourseConfig();
2171
+ } catch (e) {
2172
+ logger.error(`[Orchestration] Failed to load course config: ${e}`);
2173
+ courseConfig = {
2174
+ name: "Unknown",
2175
+ description: "",
2176
+ public: false,
2177
+ deleted: false,
2178
+ creator: "",
2179
+ admins: [],
2180
+ moderators: [],
2181
+ dataShapes: [],
2182
+ questionTypes: [],
2183
+ orchestration: { salt: "default" }
2184
+ };
2185
+ }
2186
+ const userId = user.getUsername();
2187
+ const salt = courseConfig.orchestration?.salt || "default_salt";
2188
+ return {
2189
+ user,
2190
+ course,
2191
+ userId,
2192
+ courseConfig,
2193
+ getEffectiveWeight(strategyId, learnable) {
2194
+ return computeEffectiveWeight(learnable, userId, strategyId, salt);
2195
+ },
2196
+ getDeviation(strategyId) {
2197
+ return computeDeviation(userId, strategyId, salt);
2198
+ }
2199
+ };
2200
+ }
2201
+ var MIN_SPREAD, MAX_SPREAD, MIN_WEIGHT, MAX_WEIGHT;
2202
+ var init_orchestration = __esm({
2203
+ "src/core/orchestration/index.ts"() {
2204
+ "use strict";
2205
+ init_logger();
2206
+ init_gradient();
2207
+ init_learning();
2208
+ init_signal();
2209
+ init_recording();
2210
+ MIN_SPREAD = 0.1;
2211
+ MAX_SPREAD = 0.5;
2212
+ MIN_WEIGHT = 0.1;
2213
+ MAX_WEIGHT = 3;
2214
+ }
2215
+ });
2216
+
2217
+ // src/core/navigators/Pipeline.ts
2218
+ var Pipeline_exports = {};
2219
+ __export(Pipeline_exports, {
2220
+ Pipeline: () => Pipeline
2221
+ });
2222
+ import { toCourseElo as toCourseElo5 } from "@vue-skuilder/common";
2223
+ function logPipelineConfig(generator, filters) {
2224
+ const filterList = filters.length > 0 ? "\n - " + filters.map((f) => f.name).join("\n - ") : " none";
2225
+ logger.info(
2226
+ `[Pipeline] Configuration:
2227
+ Generator: ${generator.name}
2228
+ Filters:${filterList}`
2229
+ );
2230
+ }
2231
+ function logTagHydration(cards, tagsByCard) {
2232
+ const totalTags = Array.from(tagsByCard.values()).reduce((sum, tags) => sum + tags.length, 0);
2233
+ const cardsWithTags = Array.from(tagsByCard.values()).filter((tags) => tags.length > 0).length;
2234
+ logger.debug(
2235
+ `[Pipeline] Tag hydration: ${cards.length} cards, ${cardsWithTags} have tags (${totalTags} total tags) - single batch query`
2236
+ );
2237
+ }
2238
+ function logExecutionSummary(generatorName, generatedCount, filterCount, finalCount, topScores, filterImpacts) {
2239
+ const scoreDisplay = topScores.length > 0 ? topScores.map((s) => s.toFixed(2)).join(", ") : "none";
2240
+ let filterSummary = "";
2241
+ if (filterImpacts.length > 0) {
2242
+ const impacts = filterImpacts.map((f) => {
2243
+ const parts = [];
2244
+ if (f.boosted > 0) parts.push(`+${f.boosted}`);
2245
+ if (f.penalized > 0) parts.push(`-${f.penalized}`);
2246
+ if (f.passed > 0) parts.push(`=${f.passed}`);
2247
+ return `${f.name}: ${parts.join("/")}`;
2248
+ });
2249
+ filterSummary = `
2250
+ Filter impact: ${impacts.join(", ")}`;
2251
+ }
2252
+ logger.info(
2253
+ `[Pipeline] Execution: ${generatorName} produced ${generatedCount} \u2192 ${filterCount} filters \u2192 ${finalCount} results (top scores: ${scoreDisplay})` + filterSummary + `
2254
+ \u{1F4A1} Inspect: window.skuilder.pipeline`
2255
+ );
2256
+ }
2257
+ function logCardProvenance(cards, maxCards = 3) {
2258
+ const cardsToLog = cards.slice(0, maxCards);
2259
+ logger.debug(`[Pipeline] Provenance for top ${cardsToLog.length} cards:`);
2260
+ for (const card of cardsToLog) {
2261
+ logger.debug(`[Pipeline] ${card.cardId} (final score: ${card.score.toFixed(3)}):`);
2262
+ for (const entry of card.provenance) {
2263
+ const scoreChange = entry.score.toFixed(3);
2264
+ const action = entry.action.padEnd(9);
2265
+ logger.debug(
2266
+ `[Pipeline] ${action} ${scoreChange} - ${entry.strategyName}: ${entry.reason}`
2267
+ );
2268
+ }
2269
+ }
2270
+ }
2271
+ var Pipeline;
2272
+ var init_Pipeline = __esm({
2273
+ "src/core/navigators/Pipeline.ts"() {
2274
+ "use strict";
2275
+ init_navigators();
2276
+ init_logger();
2277
+ init_orchestration();
2278
+ init_PipelineDebugger();
2279
+ Pipeline = class extends ContentNavigator {
2280
+ generator;
2281
+ filters;
2282
+ /**
2283
+ * Create a new pipeline.
2284
+ *
2285
+ * @param generator - The generator (or CompositeGenerator) that produces candidates
2286
+ * @param filters - Filters to apply sequentially (order doesn't matter for multipliers)
2287
+ * @param user - User database interface
2288
+ * @param course - Course database interface
2289
+ */
2290
+ constructor(generator, filters, user, course) {
2291
+ super();
2292
+ this.generator = generator;
2293
+ this.filters = filters;
2294
+ this.user = user;
2295
+ this.course = course;
2296
+ course.getCourseConfig().then((cfg) => {
2297
+ logger.debug(`[pipeline] Crated pipeline for ${cfg.name}`);
2298
+ }).catch((e) => {
2299
+ logger.error(`[pipeline] Failed to lookup courseCfg: ${e}`);
2300
+ });
2301
+ logPipelineConfig(generator, filters);
2302
+ }
2303
+ /**
2304
+ * Get weighted cards by running generator and applying filters.
2305
+ *
2306
+ * 1. Build shared context (user ELO, etc.)
2307
+ * 2. Get candidates from generator (passing context)
2308
+ * 3. Batch hydrate tags for all candidates
2309
+ * 4. Apply each filter sequentially
2310
+ * 5. Remove zero-score cards
2311
+ * 6. Sort by score descending
2312
+ * 7. Return top N
2313
+ *
2314
+ * @param limit - Maximum number of cards to return
2315
+ * @returns Cards sorted by score descending
2316
+ */
2317
+ async getWeightedCards(limit) {
2318
+ const context = await this.buildContext();
2319
+ const overFetchMultiplier = 2 + this.filters.length * 0.5;
2320
+ const fetchLimit = Math.ceil(limit * overFetchMultiplier);
2321
+ logger.debug(
2322
+ `[Pipeline] Fetching ${fetchLimit} candidates from generator '${this.generator.name}'`
2323
+ );
2324
+ let cards = await this.generator.getWeightedCards(fetchLimit, context);
2325
+ const generatedCount = cards.length;
2326
+ let generatorSummaries;
2327
+ if (this.generator.generators) {
2328
+ const genMap = /* @__PURE__ */ new Map();
2329
+ for (const card of cards) {
2330
+ const firstProv = card.provenance[0];
2331
+ if (firstProv) {
2332
+ const genName = firstProv.strategyName;
2333
+ if (!genMap.has(genName)) {
2334
+ genMap.set(genName, { cards: [] });
2335
+ }
2336
+ genMap.get(genName).cards.push(card);
2337
+ }
2338
+ }
2339
+ generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {
2340
+ const newCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
2341
+ const reviewCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
2342
+ return {
2343
+ name,
2344
+ cardCount: data.cards.length,
2345
+ newCount: newCards.length,
2346
+ reviewCount: reviewCards.length,
2347
+ topScore: Math.max(...data.cards.map((c) => c.score), 0)
2348
+ };
2349
+ });
2350
+ }
2351
+ logger.debug(`[Pipeline] Generator returned ${generatedCount} candidates`);
2352
+ cards = await this.hydrateTags(cards);
2353
+ const allCardsBeforeFiltering = [...cards];
2354
+ const filterImpacts = [];
2355
+ for (const filter of this.filters) {
2356
+ const beforeCount = cards.length;
2357
+ const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));
2358
+ cards = await filter.transform(cards, context);
2359
+ let boosted = 0, penalized = 0, passed = 0;
2360
+ const removed = beforeCount - cards.length;
2361
+ for (const card of cards) {
2362
+ const before = beforeScores.get(card.cardId) ?? 0;
2363
+ if (card.score > before) boosted++;
2364
+ else if (card.score < before) penalized++;
2365
+ else passed++;
2366
+ }
2367
+ filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
2368
+ logger.debug(`[Pipeline] Filter '${filter.name}': ${beforeScores.size} \u2192 ${cards.length} cards (\u2191${boosted} \u2193${penalized} =${passed})`);
2369
+ }
2370
+ cards = cards.filter((c) => c.score > 0);
2371
+ cards.sort((a, b) => b.score - a.score);
2372
+ const result = cards.slice(0, limit);
2373
+ const topScores = result.slice(0, 3).map((c) => c.score);
2374
+ logExecutionSummary(
2375
+ this.generator.name,
2376
+ generatedCount,
2377
+ this.filters.length,
2378
+ result.length,
2379
+ topScores,
2380
+ filterImpacts
2381
+ );
2382
+ logCardProvenance(result, 3);
2383
+ try {
2384
+ const courseName = await this.course?.getCourseConfig().then((c) => c.name).catch(() => void 0);
2385
+ const report = buildRunReport(
2386
+ this.course?.getCourseID() || "unknown",
2387
+ courseName,
2388
+ this.generator.name,
2389
+ generatorSummaries,
2390
+ generatedCount,
2391
+ filterImpacts,
2392
+ allCardsBeforeFiltering,
2393
+ result
2394
+ );
2395
+ captureRun(report);
2396
+ } catch (e) {
2397
+ logger.debug(`[Pipeline] Failed to capture debug run: ${e}`);
2398
+ }
2399
+ return result;
2400
+ }
2401
+ /**
2402
+ * Batch hydrate tags for all cards.
2403
+ *
2404
+ * Fetches tags for all cards in a single database query and attaches them
2405
+ * to the WeightedCard objects. Filters can then use card.tags instead of
2406
+ * making individual getAppliedTags() calls.
2407
+ *
2408
+ * @param cards - Cards to hydrate
2409
+ * @returns Cards with tags populated
2410
+ */
2411
+ async hydrateTags(cards) {
2412
+ if (cards.length === 0) {
2413
+ return cards;
2414
+ }
2415
+ const cardIds = cards.map((c) => c.cardId);
2416
+ const tagsByCard = await this.course.getAppliedTagsBatch(cardIds);
2417
+ logTagHydration(cards, tagsByCard);
2418
+ return cards.map((card) => ({
2419
+ ...card,
2420
+ tags: tagsByCard.get(card.cardId) ?? []
2421
+ }));
2422
+ }
2423
+ /**
2424
+ * Build shared context for generator and filters.
2425
+ *
2426
+ * Called once per getWeightedCards() invocation.
2427
+ * Contains data that the generator and multiple filters might need.
2428
+ *
2429
+ * The context satisfies both GeneratorContext and FilterContext interfaces.
2430
+ */
2431
+ async buildContext() {
2432
+ let userElo = 1e3;
2433
+ try {
2434
+ const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
2435
+ const courseElo = toCourseElo5(courseReg.elo);
2436
+ userElo = courseElo.global.score;
2437
+ } catch (e) {
2438
+ logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
2439
+ }
2440
+ const orchestration = await createOrchestrationContext(this.user, this.course);
2441
+ return {
2442
+ user: this.user,
2443
+ course: this.course,
2444
+ userElo,
2445
+ orchestration
2446
+ };
2447
+ }
2448
+ /**
2449
+ * Get the course ID for this pipeline.
2450
+ */
2451
+ getCourseID() {
2452
+ return this.course.getCourseID();
2453
+ }
2454
+ /**
2455
+ * Get orchestration context for outcome recording.
2456
+ */
2457
+ async getOrchestrationContext() {
2458
+ return createOrchestrationContext(this.user, this.course);
2459
+ }
2460
+ /**
2461
+ * Get IDs of all strategies in this pipeline.
2462
+ * Used to record which strategies contributed to an outcome.
2463
+ */
2464
+ getStrategyIds() {
2465
+ const ids = [];
2466
+ const extractId = (obj) => {
2467
+ if (obj.strategyId) return obj.strategyId;
2468
+ return null;
2469
+ };
2470
+ const genId = extractId(this.generator);
2471
+ if (genId) ids.push(genId);
2472
+ if (this.generator.generators && Array.isArray(this.generator.generators)) {
2473
+ this.generator.generators.forEach((g) => {
2474
+ const subId = extractId(g);
2475
+ if (subId) ids.push(subId);
2476
+ });
2477
+ }
2478
+ for (const filter of this.filters) {
2479
+ const fId = extractId(filter);
2480
+ if (fId) ids.push(fId);
2481
+ }
2482
+ return [...new Set(ids)];
2483
+ }
2484
+ };
2485
+ }
2486
+ });
2487
+
2488
+ // src/core/navigators/defaults.ts
2489
+ var defaults_exports = {};
2490
+ __export(defaults_exports, {
2491
+ createDefaultEloStrategy: () => createDefaultEloStrategy,
2492
+ createDefaultPipeline: () => createDefaultPipeline,
2493
+ createDefaultSrsStrategy: () => createDefaultSrsStrategy
2494
+ });
2495
+ function createDefaultEloStrategy(courseId) {
2496
+ return {
2497
+ _id: "NAVIGATION_STRATEGY-ELO-default",
2498
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
2499
+ name: "ELO (default)",
2500
+ description: "Default ELO-based navigation strategy for new cards",
2501
+ implementingClass: "elo" /* ELO */,
2502
+ course: courseId,
2503
+ serializedData: ""
2504
+ };
2505
+ }
2506
+ function createDefaultSrsStrategy(courseId) {
2507
+ return {
2508
+ _id: "NAVIGATION_STRATEGY-SRS-default",
2509
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
2510
+ name: "SRS (default)",
2511
+ description: "Default SRS-based navigation strategy for reviews",
2512
+ implementingClass: "srs" /* SRS */,
2513
+ course: courseId,
2514
+ serializedData: ""
2515
+ };
2516
+ }
2517
+ function createDefaultPipeline(user, course) {
2518
+ const courseId = course.getCourseID();
2519
+ const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
2520
+ const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
2521
+ const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
2522
+ const eloDistanceFilter = createEloDistanceFilter();
2523
+ return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
2524
+ }
2525
+ var init_defaults = __esm({
2526
+ "src/core/navigators/defaults.ts"() {
2527
+ "use strict";
2528
+ init_navigators();
2529
+ init_Pipeline();
2530
+ init_CompositeGenerator();
2531
+ init_elo();
2532
+ init_srs();
2533
+ init_eloDistance();
2534
+ init_types_legacy();
2535
+ }
2536
+ });
2537
+
2538
+ // src/core/navigators/PipelineAssembler.ts
2539
+ var PipelineAssembler_exports = {};
2540
+ __export(PipelineAssembler_exports, {
2541
+ PipelineAssembler: () => PipelineAssembler
2542
+ });
2543
+ var PipelineAssembler;
2544
+ var init_PipelineAssembler = __esm({
2545
+ "src/core/navigators/PipelineAssembler.ts"() {
2546
+ "use strict";
2547
+ init_navigators();
2548
+ init_WeightedFilter();
2549
+ init_Pipeline();
2550
+ init_logger();
2551
+ init_CompositeGenerator();
2552
+ init_defaults();
2553
+ PipelineAssembler = class {
2554
+ /**
2555
+ * Assembles a navigation pipeline from strategy documents.
2556
+ *
2557
+ * 1. Separates into generators and filters by role
2558
+ * 2. Validates at least one generator exists (or creates default ELO)
2559
+ * 3. Instantiates generators - wraps multiple in CompositeGenerator
2560
+ * 4. Instantiates filters
2561
+ * 5. Returns Pipeline(generator, filters)
2562
+ *
2563
+ * @param input - Strategy documents plus user/course interfaces
2564
+ * @returns Assembled pipeline and any warnings
2565
+ */
2566
+ async assemble(input) {
2567
+ const { strategies, user, course } = input;
2568
+ const warnings = [];
2569
+ if (strategies.length === 0) {
2570
+ return {
2571
+ pipeline: null,
2572
+ generatorStrategies: [],
2573
+ filterStrategies: [],
2574
+ warnings
2575
+ };
2576
+ }
2577
+ const generatorStrategies = [];
2578
+ const filterStrategies = [];
2579
+ for (const s of strategies) {
2580
+ if (isGenerator(s.implementingClass)) {
2581
+ generatorStrategies.push(s);
2582
+ } else if (isFilter(s.implementingClass)) {
2583
+ filterStrategies.push(s);
2584
+ } else {
2585
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
2586
+ }
2587
+ }
2588
+ if (generatorStrategies.length === 0) {
2589
+ if (filterStrategies.length > 0) {
2590
+ logger.debug(
2591
+ "[PipelineAssembler] No generator found, using default ELO and SRS with configured filters"
2592
+ );
2593
+ const courseId = course.getCourseID();
2594
+ generatorStrategies.push(createDefaultEloStrategy(courseId));
2595
+ generatorStrategies.push(createDefaultSrsStrategy(courseId));
2596
+ } else {
2597
+ warnings.push("No generator strategy found");
2598
+ return {
2599
+ pipeline: null,
2600
+ generatorStrategies: [],
2601
+ filterStrategies: [],
2602
+ warnings
2603
+ };
2604
+ }
2605
+ }
2606
+ let generator;
2607
+ if (generatorStrategies.length === 1) {
2608
+ const nav = await ContentNavigator.create(user, course, generatorStrategies[0]);
2609
+ generator = nav;
2610
+ logger.debug(`[PipelineAssembler] Using single generator: ${generatorStrategies[0].name}`);
2611
+ } else {
2612
+ logger.debug(
2613
+ `[PipelineAssembler] Using CompositeGenerator for ${generatorStrategies.length} generators: ${generatorStrategies.map((g) => g.name).join(", ")}`
2614
+ );
2615
+ generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
2616
+ }
2617
+ const filters = [];
2618
+ const sortedFilterStrategies = [...filterStrategies].sort(
2619
+ (a, b) => a.name.localeCompare(b.name)
2620
+ );
2621
+ for (const filterStrategy of sortedFilterStrategies) {
2622
+ try {
2623
+ const nav = await ContentNavigator.create(user, course, filterStrategy);
2624
+ if ("transform" in nav && typeof nav.transform === "function") {
2625
+ let filter = nav;
2626
+ if (filterStrategy.learnable) {
2627
+ filter = new WeightedFilter(
2628
+ filter,
2629
+ filterStrategy.learnable,
2630
+ filterStrategy.staticWeight,
2631
+ filterStrategy._id
2632
+ );
2633
+ }
2634
+ filters.push(filter);
2635
+ logger.debug(`[PipelineAssembler] Added filter: ${filterStrategy.name}`);
2636
+ } else {
2637
+ warnings.push(
2638
+ `Filter '${filterStrategy.name}' does not implement CardFilter.transform(), skipping`
2639
+ );
2640
+ }
2641
+ } catch (e) {
2642
+ warnings.push(`Failed to instantiate filter '${filterStrategy.name}': ${e}`);
2643
+ }
2644
+ }
2645
+ const pipeline = new Pipeline(generator, filters, user, course);
2646
+ logger.debug(
2647
+ `[PipelineAssembler] Assembled pipeline with ${generatorStrategies.length} generator(s) and ${filters.length} filter(s)`
2648
+ );
2649
+ return {
2650
+ pipeline,
2651
+ generatorStrategies,
2652
+ filterStrategies: sortedFilterStrategies,
2653
+ warnings
2654
+ };
2655
+ }
2656
+ };
2657
+ }
2658
+ });
2659
+
2660
+ // import("./**/*") in src/core/navigators/index.ts
2661
+ var globImport;
2662
+ var init_3 = __esm({
2663
+ 'import("./**/*") in src/core/navigators/index.ts'() {
2664
+ globImport = __glob({
2665
+ "./Pipeline.ts": () => Promise.resolve().then(() => (init_Pipeline(), Pipeline_exports)),
2666
+ "./PipelineAssembler.ts": () => Promise.resolve().then(() => (init_PipelineAssembler(), PipelineAssembler_exports)),
2667
+ "./PipelineDebugger.ts": () => Promise.resolve().then(() => (init_PipelineDebugger(), PipelineDebugger_exports)),
2668
+ "./defaults.ts": () => Promise.resolve().then(() => (init_defaults(), defaults_exports)),
2669
+ "./filters/WeightedFilter.ts": () => Promise.resolve().then(() => (init_WeightedFilter(), WeightedFilter_exports)),
2670
+ "./filters/eloDistance.ts": () => Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports)),
2671
+ "./filters/hierarchyDefinition.ts": () => Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2672
+ "./filters/index.ts": () => Promise.resolve().then(() => (init_filters(), filters_exports)),
2673
+ "./filters/inferredPreferenceStub.ts": () => Promise.resolve().then(() => (init_inferredPreferenceStub(), inferredPreferenceStub_exports)),
2674
+ "./filters/interferenceMitigator.ts": () => Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2675
+ "./filters/relativePriority.ts": () => Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2676
+ "./filters/types.ts": () => Promise.resolve().then(() => (init_types2(), types_exports2)),
2677
+ "./filters/userGoalStub.ts": () => Promise.resolve().then(() => (init_userGoalStub(), userGoalStub_exports)),
2678
+ "./filters/userTagPreference.ts": () => Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
2679
+ "./generators/CompositeGenerator.ts": () => Promise.resolve().then(() => (init_CompositeGenerator(), CompositeGenerator_exports)),
2680
+ "./generators/elo.ts": () => Promise.resolve().then(() => (init_elo(), elo_exports)),
2681
+ "./generators/index.ts": () => Promise.resolve().then(() => (init_generators(), generators_exports)),
2682
+ "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
2683
+ "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
2684
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
2685
+ });
2686
+ }
2687
+ });
2688
+
2689
+ // src/core/navigators/index.ts
2690
+ var navigators_exports = {};
2691
+ __export(navigators_exports, {
2692
+ ContentNavigator: () => ContentNavigator,
2693
+ NavigatorRole: () => NavigatorRole,
2694
+ NavigatorRoles: () => NavigatorRoles,
2695
+ Navigators: () => Navigators,
2696
+ getCardOrigin: () => getCardOrigin,
2697
+ getRegisteredNavigator: () => getRegisteredNavigator,
2698
+ getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
2699
+ hasRegisteredNavigator: () => hasRegisteredNavigator,
2700
+ initializeNavigatorRegistry: () => initializeNavigatorRegistry,
2701
+ isFilter: () => isFilter,
2702
+ isGenerator: () => isGenerator,
2703
+ mountPipelineDebugger: () => mountPipelineDebugger,
2704
+ pipelineDebugAPI: () => pipelineDebugAPI,
2705
+ registerNavigator: () => registerNavigator
2706
+ });
2707
+ function registerNavigator(implementingClass, constructor) {
2708
+ navigatorRegistry.set(implementingClass, constructor);
2709
+ logger.debug(`[NavigatorRegistry] Registered: ${implementingClass}`);
2710
+ }
2711
+ function getRegisteredNavigator(implementingClass) {
2712
+ return navigatorRegistry.get(implementingClass);
2713
+ }
2714
+ function hasRegisteredNavigator(implementingClass) {
2715
+ return navigatorRegistry.has(implementingClass);
2716
+ }
2717
+ function getRegisteredNavigatorNames() {
2718
+ return Array.from(navigatorRegistry.keys());
2719
+ }
2720
+ async function initializeNavigatorRegistry() {
2721
+ logger.debug("[NavigatorRegistry] Initializing built-in navigators...");
2722
+ const [eloModule, srsModule] = await Promise.all([
2723
+ Promise.resolve().then(() => (init_elo(), elo_exports)),
2724
+ Promise.resolve().then(() => (init_srs(), srs_exports))
2725
+ ]);
2726
+ registerNavigator("elo", eloModule.default);
2727
+ registerNavigator("srs", srsModule.default);
2728
+ const [
2729
+ hierarchyModule,
2730
+ interferenceModule,
2731
+ relativePriorityModule,
2732
+ userTagPreferenceModule
2733
+ ] = await Promise.all([
2734
+ Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
2735
+ Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
2736
+ Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
2737
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
2738
+ ]);
2739
+ registerNavigator("hierarchyDefinition", hierarchyModule.default);
2740
+ registerNavigator("interferenceMitigator", interferenceModule.default);
2741
+ registerNavigator("relativePriority", relativePriorityModule.default);
2742
+ registerNavigator("userTagPreference", userTagPreferenceModule.default);
2743
+ logger.debug(
2744
+ `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
2745
+ );
2746
+ }
2747
+ function getCardOrigin(card) {
2748
+ if (card.provenance.length === 0) {
2749
+ throw new Error("Card has no provenance - cannot determine origin");
2750
+ }
2751
+ const firstEntry = card.provenance[0];
2752
+ const reason = firstEntry.reason.toLowerCase();
2753
+ if (reason.includes("failed")) {
2754
+ return "failed";
2755
+ }
2756
+ if (reason.includes("review")) {
2757
+ return "review";
2758
+ }
2759
+ return "new";
2760
+ }
2761
+ function isGenerator(impl) {
2762
+ return NavigatorRoles[impl] === "generator" /* GENERATOR */;
2763
+ }
2764
+ function isFilter(impl) {
2765
+ return NavigatorRoles[impl] === "filter" /* FILTER */;
2766
+ }
2767
+ var navigatorRegistry, Navigators, NavigatorRole, NavigatorRoles, ContentNavigator;
2768
+ var init_navigators = __esm({
2769
+ "src/core/navigators/index.ts"() {
2770
+ "use strict";
2771
+ init_PipelineDebugger();
2772
+ init_logger();
2773
+ init_();
2774
+ init_2();
2775
+ init_3();
2776
+ navigatorRegistry = /* @__PURE__ */ new Map();
2777
+ Navigators = /* @__PURE__ */ ((Navigators2) => {
2778
+ Navigators2["ELO"] = "elo";
2779
+ Navigators2["SRS"] = "srs";
2780
+ Navigators2["HIERARCHY"] = "hierarchyDefinition";
2781
+ Navigators2["INTERFERENCE"] = "interferenceMitigator";
2782
+ Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
2783
+ Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
2784
+ return Navigators2;
2785
+ })(Navigators || {});
2786
+ NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
2787
+ NavigatorRole2["GENERATOR"] = "generator";
2788
+ NavigatorRole2["FILTER"] = "filter";
2789
+ return NavigatorRole2;
2790
+ })(NavigatorRole || {});
2791
+ NavigatorRoles = {
2792
+ ["elo" /* ELO */]: "generator" /* GENERATOR */,
2793
+ ["srs" /* SRS */]: "generator" /* GENERATOR */,
2794
+ ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
2795
+ ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
2796
+ ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
2797
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
2798
+ };
2799
+ ContentNavigator = class {
2800
+ /** User interface for this navigation session */
2801
+ user;
2802
+ /** Course interface for this navigation session */
2803
+ course;
2804
+ /** Human-readable name for this strategy instance (from ContentNavigationStrategyData.name) */
2805
+ strategyName;
2806
+ /** Unique document ID for this strategy instance (from ContentNavigationStrategyData._id) */
2807
+ strategyId;
2808
+ /** Evolutionary weighting configuration */
2809
+ learnable;
2810
+ /** Whether to bypass deviation (manual/static weighting) */
2811
+ staticWeight;
2812
+ /**
2813
+ * Constructor for standard navigators.
2814
+ * Call this from subclass constructors to initialize common fields.
2815
+ *
2816
+ * Note: CompositeGenerator and Pipeline call super() without args, then set
2817
+ * user/course fields directly if needed.
2818
+ */
2819
+ constructor(user, course, strategyData) {
2820
+ this.user = user;
2821
+ this.course = course;
2822
+ if (strategyData) {
2823
+ this.strategyName = strategyData.name;
2824
+ this.strategyId = strategyData._id;
2825
+ this.learnable = strategyData.learnable;
2826
+ this.staticWeight = strategyData.staticWeight;
2827
+ }
2828
+ }
2829
+ // ============================================================================
2830
+ // STRATEGY STATE HELPERS
2831
+ // ============================================================================
2832
+ //
2833
+ // These methods allow strategies to persist their own state (user preferences,
2834
+ // learned patterns, temporal tracking) in the user database.
2835
+ //
2836
+ // ============================================================================
2837
+ /**
2838
+ * Unique key identifying this strategy for state storage.
2839
+ *
2840
+ * Defaults to the constructor name (e.g., "UserTagPreferenceFilter").
2841
+ * Override in subclasses if multiple instances of the same strategy type
2842
+ * need separate state storage.
2843
+ */
2844
+ get strategyKey() {
2845
+ return this.constructor.name;
1108
2846
  }
1109
- };
1110
- }
1111
- });
1112
-
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";
2847
+ /**
2848
+ * Get this strategy's persisted state for the current course.
2849
+ *
2850
+ * @returns The strategy's data payload, or null if no state exists
2851
+ * @throws Error if user or course is not initialized
2852
+ */
2853
+ async getStrategyState() {
2854
+ if (!this.user || !this.course) {
2855
+ throw new Error(
2856
+ `Cannot get strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2857
+ );
2858
+ }
2859
+ return this.user.getStrategyState(this.course.getCourseID(), this.strategyKey);
1127
2860
  }
1128
2861
  /**
1129
- * Get review cards scored by urgency.
2862
+ * Persist this strategy's state for the current course.
1130
2863
  *
1131
- * Score formula combines:
1132
- * - Relative overdueness: hoursOverdue / intervalHours
1133
- * - Interval recency: exponential decay favoring shorter intervals
2864
+ * @param data - The strategy's data payload to store
2865
+ * @throws Error if user or course is not initialized
2866
+ */
2867
+ async putStrategyState(data) {
2868
+ if (!this.user || !this.course) {
2869
+ throw new Error(
2870
+ `Cannot put strategy state: navigator not properly initialized. Ensure user and course are provided to constructor.`
2871
+ );
2872
+ }
2873
+ return this.user.putStrategyState(this.course.getCourseID(), this.strategyKey, data);
2874
+ }
2875
+ /**
2876
+ * Factory method to create navigator instances.
1134
2877
  *
1135
- * Cards not yet due are excluded (not scored as 0).
2878
+ * First checks the navigator registry for a pre-registered constructor.
2879
+ * If not found, falls back to dynamic import (for custom navigators).
1136
2880
  *
1137
- * This method supports both the legacy signature (limit only) and the
1138
- * CardGenerator interface signature (limit, context).
2881
+ * For reliable operation in test environments, call initializeNavigatorRegistry()
2882
+ * before using this method.
1139
2883
  *
1140
- * @param limit - Maximum number of cards to return
1141
- * @param _context - Optional GeneratorContext (currently unused, but required for interface)
2884
+ * @param user - User interface
2885
+ * @param course - Course interface
2886
+ * @param strategyData - Strategy configuration document
2887
+ * @returns the runtime object used to steer a study session.
1142
2888
  */
1143
- async getWeightedCards(limit, _context) {
1144
- if (!this.user || !this.course) {
1145
- throw new Error("SRSNavigator requires user and course to be set");
2889
+ static async create(user, course, strategyData) {
2890
+ const implementingClass = strategyData.implementingClass;
2891
+ const RegisteredImpl = getRegisteredNavigator(implementingClass);
2892
+ if (RegisteredImpl) {
2893
+ logger.debug(`[ContentNavigator.create] Using registered navigator: ${implementingClass}`);
2894
+ return new RegisteredImpl(user, course, strategyData);
1146
2895
  }
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,
1157
- provenance: [
1158
- {
1159
- strategy: "srs",
1160
- strategyName: this.strategyName || this.name,
1161
- strategyId: this.strategyId || "NAVIGATION_STRATEGY-SRS-default",
1162
- action: "generated",
1163
- score,
1164
- reason
1165
- }
1166
- ]
1167
- };
1168
- });
1169
- logger.debug(`[srsNav] got ${scored.length} weighted cards`);
1170
- return scored.sort((a, b) => b.score - a.score).slice(0, limit);
2896
+ logger.debug(
2897
+ `[ContentNavigator.create] Navigator not in registry, attempting dynamic import: ${implementingClass}`
2898
+ );
2899
+ let NavigatorImpl;
2900
+ const variations = [".ts", ".js", ""];
2901
+ for (const ext of variations) {
2902
+ try {
2903
+ const module = await globImport_generators(`./generators/${implementingClass}${ext}`);
2904
+ NavigatorImpl = module.default;
2905
+ if (NavigatorImpl) break;
2906
+ } catch (e) {
2907
+ logger.debug(`Failed to load generator ${implementingClass}${ext}:`, e);
2908
+ }
2909
+ try {
2910
+ const module = await globImport_filters(`./filters/${implementingClass}${ext}`);
2911
+ NavigatorImpl = module.default;
2912
+ if (NavigatorImpl) break;
2913
+ } catch (e) {
2914
+ logger.debug(`Failed to load filter ${implementingClass}${ext}:`, e);
2915
+ }
2916
+ try {
2917
+ const module = await globImport(`./${implementingClass}${ext}`);
2918
+ NavigatorImpl = module.default;
2919
+ if (NavigatorImpl) break;
2920
+ } catch (e) {
2921
+ logger.debug(`Failed to load legacy ${implementingClass}${ext}:`, e);
2922
+ }
2923
+ if (NavigatorImpl) break;
2924
+ }
2925
+ if (!NavigatorImpl) {
2926
+ throw new Error(`Could not load navigator implementation for: ${implementingClass}`);
2927
+ }
2928
+ return new NavigatorImpl(user, course, strategyData);
1171
2929
  }
1172
2930
  /**
1173
- * Compute urgency score for a review card.
2931
+ * Get cards with suitability scores and provenance trails.
1174
2932
  *
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)
2933
+ * **This is the PRIMARY API for navigation strategies.**
1179
2934
  *
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
2935
+ * Returns cards ranked by suitability score (0-1). Higher scores indicate
2936
+ * better candidates for presentation. Each card includes a provenance trail
2937
+ * documenting how strategies contributed to the final score.
2938
+ *
2939
+ * ## Implementation Required
2940
+ * All navigation strategies MUST override this method. The base class does
2941
+ * not provide a default implementation.
2942
+ *
2943
+ * ## For Generators
2944
+ * Override this method to generate candidates and compute scores based on
2945
+ * your strategy's logic (e.g., ELO proximity, review urgency). Create the
2946
+ * initial provenance entry with action='generated'.
2947
+ *
2948
+ * ## For Filters
2949
+ * Filters should implement the CardFilter interface instead and be composed
2950
+ * via Pipeline. Filters do not directly implement getWeightedCards().
1184
2951
  *
1185
- * Combined: base 0.5 + weighted average of factors * 0.45
1186
- * Result range: approximately 0.5 to 0.95
2952
+ * @param limit - Maximum cards to return
2953
+ * @returns Cards sorted by score descending, with provenance trails
1187
2954
  */
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 };
2955
+ async getWeightedCards(_limit) {
2956
+ throw new Error(`${this.constructor.name} must implement getWeightedCards(). `);
1200
2957
  }
1201
2958
  };
1202
2959
  }
1203
2960
  });
1204
2961
 
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
-
1300
2962
  // src/impl/couch/courseDB.ts
1301
2963
  import {
1302
2964
  EloToNumber,
1303
2965
  Status,
1304
2966
  blankCourseElo as blankCourseElo2,
1305
- toCourseElo as toCourseElo4
2967
+ toCourseElo as toCourseElo6
1306
2968
  } from "@vue-skuilder/common";
1307
2969
  var init_courseDB = __esm({
1308
2970
  "src/impl/couch/courseDB.ts"() {
@@ -2445,6 +4107,19 @@ Currently logged-in as ${this._username}.`
2445
4107
  };
2446
4108
  await this.localDB.put(doc);
2447
4109
  }
4110
+ async putUserOutcome(record) {
4111
+ try {
4112
+ await this.localDB.put(record);
4113
+ } catch (err) {
4114
+ if (err.status === 409) {
4115
+ const existing = await this.localDB.get(record._id);
4116
+ record._rev = existing._rev;
4117
+ await this.localDB.put(record);
4118
+ } else {
4119
+ throw err;
4120
+ }
4121
+ }
4122
+ }
2448
4123
  async deleteStrategyState(courseId, strategyKey) {
2449
4124
  const docId = buildStrategyStateId(courseId, strategyKey);
2450
4125
  try {
@@ -2481,6 +4156,7 @@ var init_factory = __esm({
2481
4156
  "use strict";
2482
4157
  init_common();
2483
4158
  init_logger();
4159
+ init_navigators();
2484
4160
  NOT_SET = "NOT_SET";
2485
4161
  ENV = {
2486
4162
  COUCHDB_SERVER_PROTOCOL: NOT_SET,
@@ -2562,6 +4238,13 @@ var init_strategyState = __esm({
2562
4238
  }
2563
4239
  });
2564
4240
 
4241
+ // src/core/types/userOutcome.ts
4242
+ var init_userOutcome = __esm({
4243
+ "src/core/types/userOutcome.ts"() {
4244
+ "use strict";
4245
+ }
4246
+ });
4247
+
2565
4248
  // src/core/bulkImport/cardProcessor.ts
2566
4249
  import { Status as Status4 } from "@vue-skuilder/common";
2567
4250
  var init_cardProcessor = __esm({
@@ -2572,7 +4255,7 @@ var init_cardProcessor = __esm({
2572
4255
  });
2573
4256
 
2574
4257
  // src/core/bulkImport/types.ts
2575
- var init_types = __esm({
4258
+ var init_types3 = __esm({
2576
4259
  "src/core/bulkImport/types.ts"() {
2577
4260
  "use strict";
2578
4261
  }
@@ -2583,7 +4266,7 @@ var init_bulkImport = __esm({
2583
4266
  "src/core/bulkImport/index.ts"() {
2584
4267
  "use strict";
2585
4268
  init_cardProcessor();
2586
- init_types();
4269
+ init_types3();
2587
4270
  }
2588
4271
  });
2589
4272
 
@@ -2595,10 +4278,12 @@ var init_core = __esm({
2595
4278
  init_types_legacy();
2596
4279
  init_user();
2597
4280
  init_strategyState();
4281
+ init_userOutcome();
2598
4282
  init_Loggable();
2599
4283
  init_util();
2600
4284
  init_navigators();
2601
4285
  init_bulkImport();
4286
+ init_orchestration();
2602
4287
  }
2603
4288
  });
2604
4289