@vue-skuilder/db 0.2.28 → 0.2.29

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 (67) hide show
  1. package/dist/{contentSource-DpQqTG3m.d.cts → contentSource-B6FrSihy.d.cts} +218 -2
  2. package/dist/{contentSource-BoFBwvYa.d.ts → contentSource-CqJmbOZN.d.ts} +218 -2
  3. package/dist/core/index.d.cts +13 -90
  4. package/dist/core/index.d.ts +13 -90
  5. package/dist/core/index.js +587 -179
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +586 -179
  8. package/dist/core/index.mjs.map +1 -1
  9. package/dist/{dataLayerProvider-D_LJT3F4.d.ts → dataLayerProvider-B9_UCvkR.d.ts} +1 -1
  10. package/dist/{dataLayerProvider-Dl3cAAvQ.d.cts → dataLayerProvider-DUxDqMtZ.d.cts} +1 -1
  11. package/dist/diagnostics/index.d.cts +79 -6
  12. package/dist/diagnostics/index.d.ts +79 -6
  13. package/dist/diagnostics/index.js +158 -4
  14. package/dist/diagnostics/index.js.map +1 -1
  15. package/dist/diagnostics/index.mjs +156 -4
  16. package/dist/diagnostics/index.mjs.map +1 -1
  17. package/dist/impl/couch/index.d.cts +11 -2
  18. package/dist/impl/couch/index.d.ts +11 -2
  19. package/dist/impl/couch/index.js +585 -179
  20. package/dist/impl/couch/index.js.map +1 -1
  21. package/dist/impl/couch/index.mjs +585 -179
  22. package/dist/impl/couch/index.mjs.map +1 -1
  23. package/dist/impl/static/index.d.cts +8 -2
  24. package/dist/impl/static/index.d.ts +8 -2
  25. package/dist/impl/static/index.js +582 -179
  26. package/dist/impl/static/index.js.map +1 -1
  27. package/dist/impl/static/index.mjs +582 -179
  28. package/dist/impl/static/index.mjs.map +1 -1
  29. package/dist/index.d.cts +66 -5
  30. package/dist/index.d.ts +66 -5
  31. package/dist/index.js +635 -180
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.mjs +622 -180
  34. package/dist/index.mjs.map +1 -1
  35. package/package.json +3 -3
  36. package/src/core/interfaces/contentSource.ts +7 -0
  37. package/src/core/navigators/Pipeline.ts +145 -13
  38. package/src/core/navigators/PipelineAssembler.ts +19 -40
  39. package/src/core/navigators/PipelineDebugger.ts +11 -2
  40. package/src/core/navigators/SrsDebugger.ts +37 -12
  41. package/src/core/navigators/defaults.ts +29 -5
  42. package/src/core/navigators/filters/WeightedFilter.ts +5 -1
  43. package/src/core/navigators/filters/eloDistance.ts +261 -76
  44. package/src/core/navigators/filters/hierarchyDefinition.ts +5 -1
  45. package/src/core/navigators/filters/index.ts +2 -2
  46. package/src/core/navigators/filters/interferenceMitigator.ts +5 -1
  47. package/src/core/navigators/filters/relativePriority.ts +5 -1
  48. package/src/core/navigators/filters/types.ts +24 -1
  49. package/src/core/navigators/filters/userTagPreference.ts +5 -1
  50. package/src/core/navigators/generators/elo.ts +23 -53
  51. package/src/core/navigators/generators/srs.ts +27 -124
  52. package/src/core/navigators/index.ts +31 -5
  53. package/src/core/navigators/pipelinePlan.ts +245 -0
  54. package/src/core/navigators/regulators.ts +230 -0
  55. package/src/core/types/studySession.ts +3 -0
  56. package/src/diagnostics/dataset.ts +13 -2
  57. package/src/diagnostics/index.ts +3 -0
  58. package/src/diagnostics/loader.ts +5 -2
  59. package/src/diagnostics/pipeline.ts +236 -0
  60. package/src/diagnostics/text.ts +26 -3
  61. package/src/impl/couch/courseDB.ts +13 -0
  62. package/src/impl/static/courseDB.ts +9 -0
  63. package/src/index.ts +4 -0
  64. package/src/study/SessionController.ts +20 -0
  65. package/src/study/SessionOverlay.ts +7 -4
  66. package/tests/core/navigators/PipelineAssembler.test.ts +20 -5
  67. package/tests/core/navigators/eloDistanceFilter.test.ts +9 -9
@@ -532,7 +532,7 @@ function parseCardElo(provenance) {
532
532
  const match = eloEntry.reason.match(/card:\s*(\d+)/);
533
533
  return match ? parseInt(match[1], 10) : void 0;
534
534
  }
535
- function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards, userElo, hints, scoredCards) {
535
+ function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards, userElo, hints, scoredCards, regulators) {
536
536
  const selectedIds = new Set(selectedCards.map((c) => c.cardId));
537
537
  const toReport = (card) => ({
538
538
  cardId: card.cardId,
@@ -540,7 +540,7 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
540
540
  origin: getOrigin(card),
541
541
  generator: card.provenance[0]?.strategyName || card.provenance[0]?.strategy,
542
542
  finalScore: card.score,
543
- cardElo: parseCardElo(card.provenance),
543
+ cardElo: card.cardElo ?? parseCardElo(card.provenance),
544
544
  provenance: card.provenance,
545
545
  tags: card.tags,
546
546
  selected: selectedIds.has(card.cardId)
@@ -618,7 +618,8 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
618
618
  newSelected,
619
619
  cards,
620
620
  unselectedNew,
621
- discardedTail
621
+ discardedTail,
622
+ ...regulators ? { regulators } : {}
622
623
  };
623
624
  }
624
625
  function formatProvenance(provenance) {
@@ -1342,11 +1343,23 @@ var SrsDebugger_exports = {};
1342
1343
  __export(SrsDebugger_exports, {
1343
1344
  captureSrsBacklog: () => captureSrsBacklog,
1344
1345
  clearSrsBacklogDebug: () => clearSrsBacklogDebug,
1345
- getSrsBacklogDebug: () => getSrsBacklogDebug
1346
+ getSrsBacklogDebug: () => getSrsBacklogDebug,
1347
+ noteReviewPressure: () => noteReviewPressure
1346
1348
  });
1347
1349
  function captureSrsBacklog(snapshot) {
1348
1350
  snapshots.set(snapshot.courseId, snapshot);
1349
1351
  }
1352
+ function noteReviewPressure(courseId, pressure) {
1353
+ const snapshot = snapshots.get(courseId);
1354
+ if (!snapshot) return;
1355
+ snapshots.set(courseId, {
1356
+ ...snapshot,
1357
+ reviewMass: pressure.mass,
1358
+ healthyBacklog: pressure.healthyMass,
1359
+ backlogGrowthRate: pressure.rate,
1360
+ backlogMultiplier: pressure.multiplier
1361
+ });
1362
+ }
1350
1363
  function getSrsBacklogDebug() {
1351
1364
  return [...snapshots.values()].sort((a, b) => b.timestamp - a.timestamp);
1352
1365
  }
@@ -1624,14 +1637,13 @@ var elo_exports = {};
1624
1637
  __export(elo_exports, {
1625
1638
  default: () => ELONavigator
1626
1639
  });
1627
- var import_common5, ELO_RELEVANCE_SIGMA, ELONavigator;
1640
+ var import_common5, ELONavigator;
1628
1641
  var init_elo = __esm({
1629
1642
  "src/core/navigators/generators/elo.ts"() {
1630
1643
  "use strict";
1631
1644
  init_navigators();
1632
1645
  import_common5 = require("@vue-skuilder/common");
1633
1646
  init_logger();
1634
- ELO_RELEVANCE_SIGMA = 300;
1635
1647
  ELONavigator = class extends ContentNavigator {
1636
1648
  /** Human-readable name for CardGenerator interface */
1637
1649
  name;
@@ -1640,10 +1652,8 @@ var init_elo = __esm({
1640
1652
  this.name = strategyData?.name || "ELO";
1641
1653
  }
1642
1654
  /**
1643
- * Get new cards with suitability scores based on ELO distance.
1644
- *
1645
- * Cards closer to user's ELO get higher scores.
1646
- * Score formula: max(0, 1 - distance / 500)
1655
+ * Get the new cards nearest the learner's ELO, each scored with a flat
1656
+ * jitter in [0.5, 1]. Carries each card's ELO for the ELO distance filter.
1647
1657
  *
1648
1658
  * NOTE: This generator only handles NEW cards. Reviews are handled by
1649
1659
  * SRSNavigator. Use CompositeGenerator to combine both.
@@ -1671,20 +1681,20 @@ var init_elo = __esm({
1671
1681
  const scored = newCards.map((c) => {
1672
1682
  const cardElo = c.elo ?? 1e3;
1673
1683
  const distance = Math.abs(cardElo - userGlobalElo);
1674
- const relevance = Math.exp(-((distance / ELO_RELEVANCE_SIGMA) ** 2));
1675
- const samplingKey = relevance * (0.5 + 0.5 * Math.random());
1684
+ const jitter = 0.5 + 0.5 * Math.random();
1676
1685
  return {
1677
1686
  cardId: c.cardID,
1678
1687
  courseId: c.courseID,
1679
- score: samplingKey,
1688
+ score: jitter,
1689
+ cardElo,
1680
1690
  provenance: [
1681
1691
  {
1682
1692
  strategy: "elo",
1683
1693
  strategyName: this.strategyName || this.name,
1684
1694
  strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1685
1695
  action: "generated",
1686
- score: samplingKey,
1687
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), relevance ${relevance.toFixed(3)}, key ${samplingKey.toFixed(3)}`
1696
+ score: jitter,
1697
+ reason: `new card near learner ELO: distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), jitter ${jitter.toFixed(3)}`
1688
1698
  }
1689
1699
  ]
1690
1700
  };
@@ -2560,43 +2570,132 @@ var init_prescribed = __esm({
2560
2570
  }
2561
2571
  });
2562
2572
 
2573
+ // src/core/navigators/regulators.ts
2574
+ var regulators_exports = {};
2575
+ __export(regulators_exports, {
2576
+ DEFAULT_REGULATOR_CONFIG: () => DEFAULT_REGULATOR_CONFIG,
2577
+ INTAKE_CLOCK_KEY: () => INTAKE_CLOCK_KEY,
2578
+ applyReading: () => applyReading,
2579
+ frozenMsAt: () => frozenMsAt,
2580
+ intakeHours: () => intakeHours,
2581
+ intakeReading: () => intakeReading,
2582
+ resetIntakeClock: () => resetIntakeClock,
2583
+ reviewMassReading: () => reviewMassReading,
2584
+ reviewWeight: () => reviewWeight,
2585
+ stepIntakeClock: () => stepIntakeClock
2586
+ });
2587
+ function clamp01(x) {
2588
+ return Math.min(1, Math.max(0, x));
2589
+ }
2590
+ function reviewWeight(card, generatedScore, referenceScore) {
2591
+ if (card.reviewUrgency !== void 0 && generatedScore !== void 0 && generatedScore > 0) {
2592
+ return clamp01(card.reviewUrgency * (card.score / generatedScore));
2593
+ }
2594
+ return clamp01(card.score / referenceScore);
2595
+ }
2596
+ function reviewMassReading(reviews, generatedScores, config = DEFAULT_REGULATOR_CONFIG.reviewMass) {
2597
+ const mass = reviews.reduce(
2598
+ (m, c) => m + reviewWeight(c, generatedScores.get(c.cardId), config.referenceScore),
2599
+ 0
2600
+ );
2601
+ const multiplier = mass > config.healthyMass ? Math.pow(config.rate, (mass - config.healthyMass) / config.healthyMass) : 1;
2602
+ return {
2603
+ name: "review-mass",
2604
+ class: "review",
2605
+ urgency: mass,
2606
+ multiplier,
2607
+ applied: reviews.length,
2608
+ inputs: { due: reviews.length, mass, healthyMass: config.healthyMass }
2609
+ };
2610
+ }
2611
+ function resetIntakeClock(nowMs) {
2612
+ return { lastNewAt: new Date(nowMs).toISOString(), frozenMs: 0, unservableSince: null };
2613
+ }
2614
+ function frozenMsAt(state, nowMs) {
2615
+ const open = state.unservableSince ? Math.max(0, nowMs - Date.parse(state.unservableSince)) : 0;
2616
+ return state.frozenMs + open;
2617
+ }
2618
+ function intakeHours(state, nowMs) {
2619
+ const elapsed = nowMs - Date.parse(state.lastNewAt);
2620
+ return Math.max(0, elapsed - frozenMsAt(state, nowMs)) / 36e5;
2621
+ }
2622
+ function stepIntakeClock(state, nowMs, eligibleNew) {
2623
+ if (eligibleNew === 0 && !state.unservableSince) {
2624
+ return { ...state, unservableSince: new Date(nowMs).toISOString() };
2625
+ }
2626
+ if (eligibleNew > 0 && state.unservableSince) {
2627
+ return { ...state, frozenMs: frozenMsAt(state, nowMs), unservableSince: null };
2628
+ }
2629
+ return state;
2630
+ }
2631
+ function intakeReading(state, nowMs, counts, config = DEFAULT_REGULATOR_CONFIG.intake) {
2632
+ const hours = intakeHours(state, nowMs);
2633
+ const multiplier = counts.eligibleNew > 0 ? Math.pow(config.rate, hours / config.scaleHours) : 1;
2634
+ return {
2635
+ name: "intake",
2636
+ class: "new",
2637
+ urgency: hours,
2638
+ multiplier,
2639
+ applied: counts.eligibleNew,
2640
+ inputs: {
2641
+ hoursSinceNew: hours,
2642
+ frozenHours: frozenMsAt(state, nowMs) / 36e5,
2643
+ eligibleNew: counts.eligibleNew,
2644
+ newCandidates: counts.newCandidates
2645
+ }
2646
+ };
2647
+ }
2648
+ function applyReading(cards, reading) {
2649
+ if (reading.multiplier === 1) return;
2650
+ const reason = reading.name === "review-mass" ? `review mass ${reading.urgency.toFixed(1)} (healthy ${reading.inputs.healthyMass}) \u2192 \xD7${reading.multiplier.toFixed(2)}` : `${reading.urgency.toFixed(1)}h since a new card \u2192 \xD7${reading.multiplier.toFixed(2)}`;
2651
+ for (const card of cards) {
2652
+ card.score *= reading.multiplier;
2653
+ card.provenance.push({
2654
+ strategy: "regulator",
2655
+ strategyName: `Regulator: ${REGULATOR_LABEL[reading.name]}`,
2656
+ strategyId: `regulator-${reading.name}`,
2657
+ action: reading.multiplier > 1 ? "boosted" : "penalized",
2658
+ score: card.score,
2659
+ reason
2660
+ });
2661
+ }
2662
+ }
2663
+ var DEFAULT_REGULATOR_CONFIG, INTAKE_CLOCK_KEY, REGULATOR_LABEL;
2664
+ var init_regulators = __esm({
2665
+ "src/core/navigators/regulators.ts"() {
2666
+ "use strict";
2667
+ DEFAULT_REGULATOR_CONFIG = {
2668
+ reviewMass: { referenceScore: 0.95, healthyMass: 20, rate: 2 },
2669
+ intake: { rate: 2, scaleHours: 24 }
2670
+ };
2671
+ INTAKE_CLOCK_KEY = "IntakeClock";
2672
+ REGULATOR_LABEL = {
2673
+ "review-mass": "Review mass",
2674
+ intake: "Intake"
2675
+ };
2676
+ }
2677
+ });
2678
+
2563
2679
  // src/core/navigators/generators/srs.ts
2564
2680
  var srs_exports = {};
2565
2681
  __export(srs_exports, {
2566
2682
  default: () => SRSNavigator
2567
2683
  });
2568
- var import_moment, DEFAULT_HEALTHY_BACKLOG, BACKLOG_GROWTH_RATE, SRSNavigator;
2684
+ var import_moment, SRSNavigator;
2569
2685
  var init_srs = __esm({
2570
2686
  "src/core/navigators/generators/srs.ts"() {
2571
2687
  "use strict";
2572
2688
  import_moment = __toESM(require("moment"), 1);
2573
2689
  init_navigators();
2574
2690
  init_SrsDebugger();
2691
+ init_regulators();
2575
2692
  init_logger();
2576
- DEFAULT_HEALTHY_BACKLOG = 20;
2577
- BACKLOG_GROWTH_RATE = 2;
2578
2693
  SRSNavigator = class extends ContentNavigator {
2579
2694
  /** Human-readable name for CardGenerator interface */
2580
2695
  name;
2581
- /** Healthy backlog threshold - when exceeded, backlog pressure kicks in */
2582
- healthyBacklog;
2583
2696
  constructor(user, course, strategyData) {
2584
2697
  super(user, course, strategyData);
2585
2698
  this.name = strategyData?.name || "SRS";
2586
- const config = this.parseConfig(strategyData?.serializedData);
2587
- this.healthyBacklog = config.healthyBacklog ?? DEFAULT_HEALTHY_BACKLOG;
2588
- }
2589
- /**
2590
- * Parse configuration from serialized JSON.
2591
- */
2592
- parseConfig(serializedData) {
2593
- if (!serializedData) return {};
2594
- try {
2595
- return JSON.parse(serializedData);
2596
- } catch {
2597
- logger.warn("[SRS] Failed to parse strategy config, using defaults");
2598
- return {};
2599
- }
2600
2699
  }
2601
2700
  /**
2602
2701
  * Get review cards scored by urgency.
@@ -2604,7 +2703,6 @@ var init_srs = __esm({
2604
2703
  * Score formula combines:
2605
2704
  * - Relative overdueness: hoursOverdue / intervalHours
2606
2705
  * - Interval recency: exponential decay favoring shorter intervals
2607
- * - Backlog pressure: boost when due reviews exceed healthy threshold
2608
2706
  *
2609
2707
  * Cards not yet due are excluded (not scored as 0).
2610
2708
  *
@@ -2641,7 +2739,6 @@ var init_srs = __esm({
2641
2739
  }
2642
2740
  }
2643
2741
  }
2644
- const backlogMultiplier = this.computeBacklogMultiplier(dueReviews.length);
2645
2742
  const notDue = reviews.filter((r) => !now.isAfter(import_moment.default.utc(r.reviewTime)));
2646
2743
  let nextDueIn = null;
2647
2744
  if (notDue.length > 0) {
@@ -2652,9 +2749,8 @@ var init_srs = __esm({
2652
2749
  nextDueIn = until.asHours() < 1 ? `${Math.round(until.asMinutes())}m` : until.asHours() < 24 ? `${Math.round(until.asHours())}h` : `${Math.round(until.asDays())}d`;
2653
2750
  }
2654
2751
  if (dueReviews.length > 0) {
2655
- const pressureNote = backlogMultiplier > 1 ? ` [backlog pressure: \xD7${backlogMultiplier.toFixed(2)}]` : ` [healthy backlog]`;
2656
2752
  logger.info(
2657
- `[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)${pressureNote}`
2753
+ `[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)`
2658
2754
  );
2659
2755
  } else if (reviews.length > 0) {
2660
2756
  const sortedByDue = [...reviews].sort(
@@ -2671,11 +2767,12 @@ var init_srs = __esm({
2671
2767
  logger.info(`[SRS] Course ${courseId}: No reviews scheduled`);
2672
2768
  }
2673
2769
  const scored = dueReviews.map((review) => {
2674
- const { score, reason } = this.computeUrgencyScore(review, now, backlogMultiplier);
2770
+ const { score, urgency, reason } = this.computeUrgencyScore(review, now);
2675
2771
  return {
2676
2772
  cardId: review.cardId,
2677
2773
  courseId: review.courseId,
2678
2774
  score,
2775
+ reviewUrgency: urgency,
2679
2776
  reviewID: review._id,
2680
2777
  provenance: [
2681
2778
  {
@@ -2694,47 +2791,20 @@ var init_srs = __esm({
2694
2791
  courseId,
2695
2792
  scheduledTotal: reviews.length,
2696
2793
  dueNow: dueReviews.length,
2697
- healthyBacklog: this.healthyBacklog,
2698
- backlogMultiplier,
2699
- backlogGrowthRate: BACKLOG_GROWTH_RATE,
2794
+ healthyBacklog: DEFAULT_REGULATOR_CONFIG.reviewMass.healthyMass,
2795
+ reviewMass: null,
2796
+ backlogMultiplier: 1,
2797
+ backlogGrowthRate: DEFAULT_REGULATOR_CONFIG.reviewMass.rate,
2700
2798
  topReviewScore: sorted.length > 0 ? sorted[0].score : null,
2701
2799
  nextDueIn,
2702
2800
  timestamp: Date.now()
2703
2801
  });
2704
2802
  return { cards: sorted.slice(0, limit) };
2705
2803
  }
2706
- /**
2707
- * Compute the multiplicative backlog pressure based on number of due reviews.
2708
- *
2709
- * ×1.0 at or below the healthy threshold (no boost); above it, grows as
2710
- * BACKLOG_GROWTH_RATE raised to the excess expressed in multiples of the
2711
- * healthy threshold. Uncapped — self-regulating instead: reviews winning
2712
- * slots depletes dueCount, which drops the ratio and relaxes the multiplier
2713
- * next run.
2714
- *
2715
- * Examples (with default healthyBacklog=20, BACKLOG_GROWTH_RATE=1.5):
2716
- * - 10 due reviews → ×1.00 (healthy)
2717
- * - 20 due reviews → ×1.00 (at threshold, ratio 0)
2718
- * - 40 due reviews → ×1.50 (ratio 1, 2x threshold)
2719
- * - 60 due reviews → ×2.25 (ratio 2, 3x threshold — old hard cap was ×2.00 here)
2720
- * - 100 due reviews → ×5.06 (ratio 4, 5x threshold)
2721
- * - 160 due reviews → ×17.09 (ratio 7, 8x threshold)
2722
- *
2723
- * @param dueCount - Number of reviews currently due
2724
- * @returns Multiplier applied to review urgency (>= 1.0, unbounded)
2725
- */
2726
- computeBacklogMultiplier(dueCount) {
2727
- if (dueCount <= this.healthyBacklog) {
2728
- return 1;
2729
- }
2730
- const excess = dueCount - this.healthyBacklog;
2731
- const ratio = excess / this.healthyBacklog;
2732
- return Math.pow(BACKLOG_GROWTH_RATE, ratio);
2733
- }
2734
2804
  /**
2735
2805
  * Compute urgency score for a review card.
2736
2806
  *
2737
- * Three factors:
2807
+ * Two factors:
2738
2808
  * 1. Relative overdueness = hoursOverdue / intervalHours
2739
2809
  * - 2 days overdue on 3-day interval = 0.67 (urgent)
2740
2810
  * - 2 days overdue on 180-day interval = 0.01 (not urgent)
@@ -2744,20 +2814,14 @@ var init_srs = __esm({
2744
2814
  * - 30 days (720h) → ~0.56
2745
2815
  * - 180 days → ~0.30
2746
2816
  *
2747
- * 3. Backlog pressure = global *multiplier* when review backlog exceeds the
2748
- * healthy threshold (×1.0 healthy → exponential growth, uncapped, above it).
2749
- *
2750
- * Combined: (base 0.5 + urgency factors * 0.45) × backlog multiplier.
2751
- * Per-card range before pressure: ~0.57–0.95. NOT clamped to 1.0 — under a
2752
- * heavy backlog reviews scale onto the open scale to compete with (and exceed)
2753
- * new cards; there's no ceiling at all now, so a bad enough backlog always
2754
- * wins eventually — self-regulating because winning slots depletes dueCount.
2817
+ * Combined: base 0.5 + urgency factors * 0.45, so ~0.57–0.95 per card.
2818
+ * Backlog pressure is applied later, by the regulator stage, which can lift
2819
+ * reviews onto the open scale above new cards (see regulators.ts).
2755
2820
  *
2756
2821
  * @param review - The scheduled card to score
2757
2822
  * @param now - Current time
2758
- * @param backlogMultiplier - Pre-computed backlog multiplier (>= 1.0, unbounded)
2759
2823
  */
2760
- computeUrgencyScore(review, now, backlogMultiplier) {
2824
+ computeUrgencyScore(review, now) {
2761
2825
  const scheduledAt = import_moment.default.utc(review.scheduledAt);
2762
2826
  const due = import_moment.default.utc(review.reviewTime);
2763
2827
  const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
@@ -2766,20 +2830,16 @@ var init_srs = __esm({
2766
2830
  const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
2767
2831
  const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
2768
2832
  const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
2769
- const baseScore = 0.5 + urgency * 0.45;
2770
- const score = baseScore * backlogMultiplier;
2833
+ const score = 0.5 + urgency * 0.45;
2771
2834
  const reasonParts = [
2772
2835
  `${Math.round(hoursOverdue)}h overdue`,
2773
2836
  `interval: ${Math.round(intervalHours)}h`,
2774
2837
  `relative: ${relativeOverdue.toFixed(2)}`,
2775
2838
  `recency: ${recencyFactor.toFixed(2)}`
2776
2839
  ];
2777
- if (backlogMultiplier > 1) {
2778
- reasonParts.push(`backlog: \xD7${backlogMultiplier.toFixed(2)}`);
2779
- }
2780
2840
  reasonParts.push("review");
2781
2841
  const reason = reasonParts.join(", ");
2782
- return { score, reason };
2842
+ return { score, urgency, reason };
2783
2843
  }
2784
2844
  };
2785
2845
  }
@@ -2834,6 +2894,8 @@ var init_WeightedFilter = __esm({
2834
2894
  init_contentNavigationStrategy();
2835
2895
  WeightedFilter = class {
2836
2896
  name;
2897
+ kind;
2898
+ liveOnly;
2837
2899
  inner;
2838
2900
  learnable;
2839
2901
  staticWeight;
@@ -2841,6 +2903,8 @@ var init_WeightedFilter = __esm({
2841
2903
  constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
2842
2904
  this.inner = inner;
2843
2905
  this.name = inner.name;
2906
+ this.kind = inner.kind;
2907
+ this.liveOnly = inner.liveOnly;
2844
2908
  this.learnable = learnable;
2845
2909
  this.staticWeight = staticWeight;
2846
2910
  this.strategyId = strategyId;
@@ -2905,58 +2969,141 @@ var init_WeightedFilter = __esm({
2905
2969
  // src/core/navigators/filters/eloDistance.ts
2906
2970
  var eloDistance_exports = {};
2907
2971
  __export(eloDistance_exports, {
2908
- DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
2909
- DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
2910
- DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
2911
- createEloDistanceFilter: () => createEloDistanceFilter
2972
+ DEFAULT_ELO_DISTANCE_CONFIG: () => DEFAULT_ELO_DISTANCE_CONFIG,
2973
+ createEloDistanceFilter: () => createEloDistanceFilter,
2974
+ default: () => EloDistanceFilter,
2975
+ tagAwareGap: () => tagAwareGap
2912
2976
  });
2913
2977
  function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
2914
2978
  const normalizedDistance = distance / halfLife;
2915
2979
  const decay = Math.exp(-(normalizedDistance * normalizedDistance));
2916
2980
  return minMultiplier + (maxMultiplier - minMultiplier) * decay;
2917
2981
  }
2982
+ function resolveConfig(config) {
2983
+ return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };
2984
+ }
2985
+ function tagAwareGap(cardTags, cardElo, userElo, minTagCount) {
2986
+ const globalGap = cardElo.global.score - userElo.global.score;
2987
+ const tags = [];
2988
+ for (const tag of cardTags) {
2989
+ const user = userElo.tags[tag];
2990
+ if (!user || user.score === COUNT_ONLY_SENTINEL || user.count < minTagCount) continue;
2991
+ const card = cardElo.tags[tag]?.score ?? cardElo.global.score;
2992
+ tags.push({
2993
+ tag,
2994
+ gap: card - user.score,
2995
+ weight: user.count / (user.count + TAG_CONFIDENCE_HALF)
2996
+ });
2997
+ }
2998
+ if (tags.length === 0) return { gap: globalGap, globalGap, tags };
2999
+ const total = tags.reduce((w, t) => w + t.weight, 0);
3000
+ const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;
3001
+ const lambda = total / (total + 1);
3002
+ return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };
3003
+ }
3004
+ function tagReason(tags, globalGap) {
3005
+ const shown = [...tags].sort((a, b) => Math.abs(b.gap) * b.weight - Math.abs(a.gap) * a.weight).slice(0, 3).map((t) => `${t.tag} ${t.gap >= 0 ? "+" : ""}${Math.round(t.gap)}`).join(", ");
3006
+ const more = tags.length > 3 ? `, +${tags.length - 3} more` : "";
3007
+ return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? "+" : ""}${Math.round(globalGap)})`;
3008
+ }
3009
+ async function applyEloDistance(cards, context, config, source) {
3010
+ const { course, userElo, userCourseElo } = context;
3011
+ const { halfLife, minMultiplier, maxMultiplier } = config;
3012
+ const tagAware = config.tagAware && userCourseElo !== void 0;
3013
+ const missing = cards.filter((c) => tagAware || c.cardElo === void 0).map((c) => c.cardId);
3014
+ const fetched = /* @__PURE__ */ new Map();
3015
+ if (missing.length > 0) {
3016
+ const elos = await course.getCardEloData(missing);
3017
+ missing.forEach((id, i) => {
3018
+ if (elos[i]) fetched.set(id, elos[i]);
3019
+ });
3020
+ }
3021
+ return cards.map((card) => {
3022
+ const full = fetched.get(card.cardId);
3023
+ const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;
3024
+ let distance = Math.abs(cardElo - userElo);
3025
+ let how = "";
3026
+ if (tagAware && full) {
3027
+ const t = tagAwareGap(card.tags ?? [], full, userCourseElo, config.minTagCount);
3028
+ distance = Math.abs(t.gap);
3029
+ if (t.tags.length > 0) how = tagReason(t.tags, t.globalGap);
3030
+ }
3031
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
3032
+ const newScore = card.score * multiplier;
3033
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
3034
+ return {
3035
+ ...card,
3036
+ cardElo,
3037
+ score: newScore,
3038
+ provenance: [
3039
+ ...card.provenance,
3040
+ {
3041
+ strategy: "eloDistance",
3042
+ strategyName: source.name,
3043
+ strategyId: source.strategyId,
3044
+ action,
3045
+ score: newScore,
3046
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} \u2192 ${multiplier.toFixed(2)}x`
3047
+ }
3048
+ ]
3049
+ };
3050
+ });
3051
+ }
2918
3052
  function createEloDistanceFilter(config) {
2919
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
2920
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
2921
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
3053
+ const resolved = resolveConfig(config);
3054
+ const source = { name: "ELO Distance Filter", strategyId: "ELO_DISTANCE_FILTER" };
2922
3055
  return {
2923
- name: "ELO Distance Filter",
2924
- async transform(cards, context) {
2925
- const { course, userElo } = context;
2926
- const cardIds = cards.map((c) => c.cardId);
2927
- const cardElos = await course.getCardEloData(cardIds);
2928
- return cards.map((card, i) => {
2929
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
2930
- const distance = Math.abs(cardElo - userElo);
2931
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
2932
- const newScore = card.score * multiplier;
2933
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
2934
- return {
2935
- ...card,
2936
- score: newScore,
2937
- provenance: [
2938
- ...card.provenance,
2939
- {
2940
- strategy: "eloDistance",
2941
- strategyName: "ELO Distance Filter",
2942
- strategyId: "ELO_DISTANCE_FILTER",
2943
- action,
2944
- score: newScore,
2945
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
2946
- }
2947
- ]
2948
- };
2949
- });
2950
- }
3056
+ name: source.name,
3057
+ kind: "signal",
3058
+ liveOnly: true,
3059
+ transform: (cards, context) => applyEloDistance(cards, context, resolved, source)
2951
3060
  };
2952
3061
  }
2953
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
3062
+ var DEFAULT_ELO_DISTANCE_CONFIG, TAG_CONFIDENCE_HALF, COUNT_ONLY_SENTINEL, DEFAULT_CARD_ELO, EloDistanceFilter;
2954
3063
  var init_eloDistance = __esm({
2955
3064
  "src/core/navigators/filters/eloDistance.ts"() {
2956
3065
  "use strict";
2957
- DEFAULT_HALF_LIFE = 200;
2958
- DEFAULT_MIN_MULTIPLIER = 0.3;
2959
- DEFAULT_MAX_MULTIPLIER = 1;
3066
+ init_navigators();
3067
+ DEFAULT_ELO_DISTANCE_CONFIG = {
3068
+ halfLife: 300,
3069
+ minMultiplier: 0.05,
3070
+ maxMultiplier: 1,
3071
+ tagAware: true,
3072
+ minTagCount: 3
3073
+ };
3074
+ TAG_CONFIDENCE_HALF = 10;
3075
+ COUNT_ONLY_SENTINEL = -1;
3076
+ DEFAULT_CARD_ELO = 1e3;
3077
+ EloDistanceFilter = class _EloDistanceFilter extends ContentNavigator {
3078
+ name;
3079
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3080
+ static kind = "signal";
3081
+ kind = _EloDistanceFilter.kind;
3082
+ liveOnly = true;
3083
+ config;
3084
+ constructor(user, course, strategyData) {
3085
+ super(user, course, strategyData);
3086
+ this.name = strategyData.name || "ELO Distance";
3087
+ let parsed;
3088
+ try {
3089
+ parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : void 0;
3090
+ } catch {
3091
+ parsed = void 0;
3092
+ }
3093
+ this.config = resolveConfig(parsed);
3094
+ }
3095
+ transform(cards, context) {
3096
+ return applyEloDistance(cards, context, this.config, {
3097
+ name: this.name,
3098
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-eloDistance-default"
3099
+ });
3100
+ }
3101
+ async getWeightedCards(_limit) {
3102
+ throw new Error(
3103
+ "EloDistanceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
3104
+ );
3105
+ }
3106
+ };
2960
3107
  }
2961
3108
  });
2962
3109
 
@@ -2973,10 +3120,13 @@ var init_hierarchyDefinition = __esm({
2973
3120
  import_common6 = require("@vue-skuilder/common");
2974
3121
  init_logger();
2975
3122
  DEFAULT_MIN_COUNT2 = 3;
2976
- HierarchyDefinitionNavigator = class extends ContentNavigator {
3123
+ HierarchyDefinitionNavigator = class _HierarchyDefinitionNavigator extends ContentNavigator {
2977
3124
  config;
2978
3125
  /** Human-readable name for CardFilter interface */
2979
3126
  name;
3127
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3128
+ static kind = "gate";
3129
+ kind = _HierarchyDefinitionNavigator.kind;
2980
3130
  constructor(user, course, strategyData) {
2981
3131
  super(user, course, strategyData);
2982
3132
  this.config = this.parseConfig(strategyData.serializedData);
@@ -3243,10 +3393,13 @@ var init_userTagPreference = __esm({
3243
3393
  "src/core/navigators/filters/userTagPreference.ts"() {
3244
3394
  "use strict";
3245
3395
  init_navigators();
3246
- UserTagPreferenceFilter = class extends ContentNavigator {
3396
+ UserTagPreferenceFilter = class _UserTagPreferenceFilter extends ContentNavigator {
3247
3397
  _strategyData;
3248
3398
  /** Human-readable name for CardFilter interface */
3249
3399
  name;
3400
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3401
+ static kind = "signal";
3402
+ kind = _UserTagPreferenceFilter.kind;
3250
3403
  constructor(user, course, strategyData) {
3251
3404
  super(user, course, strategyData);
3252
3405
  this._strategyData = strategyData;
@@ -3356,6 +3509,7 @@ var init_userTagPreference = __esm({
3356
3509
  // src/core/navigators/filters/index.ts
3357
3510
  var filters_exports = {};
3358
3511
  __export(filters_exports, {
3512
+ EloDistanceFilter: () => EloDistanceFilter,
3359
3513
  UserTagPreferenceFilter: () => UserTagPreferenceFilter,
3360
3514
  createEloDistanceFilter: () => createEloDistanceFilter
3361
3515
  });
@@ -3394,10 +3548,13 @@ var init_interferenceMitigator = __esm({
3394
3548
  DEFAULT_MIN_COUNT3 = 10;
3395
3549
  DEFAULT_MIN_ELAPSED_DAYS = 3;
3396
3550
  DEFAULT_INTERFERENCE_DECAY = 0.8;
3397
- InterferenceMitigatorNavigator = class extends ContentNavigator {
3551
+ InterferenceMitigatorNavigator = class _InterferenceMitigatorNavigator extends ContentNavigator {
3398
3552
  config;
3399
3553
  /** Human-readable name for CardFilter interface */
3400
3554
  name;
3555
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3556
+ static kind = "signal";
3557
+ kind = _InterferenceMitigatorNavigator.kind;
3401
3558
  /** Precomputed map: tag -> set of { partner, decay } it interferes with */
3402
3559
  interferenceMap;
3403
3560
  constructor(user, course, strategyData) {
@@ -3613,10 +3770,13 @@ var init_relativePriority = __esm({
3613
3770
  DEFAULT_PRIORITY = 0.5;
3614
3771
  DEFAULT_PRIORITY_INFLUENCE = 0.5;
3615
3772
  DEFAULT_COMBINE_MODE = "max";
3616
- RelativePriorityNavigator = class extends ContentNavigator {
3773
+ RelativePriorityNavigator = class _RelativePriorityNavigator extends ContentNavigator {
3617
3774
  config;
3618
3775
  /** Human-readable name for CardFilter interface */
3619
3776
  name;
3777
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3778
+ static kind = "signal";
3779
+ kind = _RelativePriorityNavigator.kind;
3620
3780
  constructor(user, course, strategyData) {
3621
3781
  super(user, course, strategyData);
3622
3782
  this.config = this.parseConfig(strategyData.serializedData);
@@ -4024,6 +4184,8 @@ var init_Pipeline = __esm({
4024
4184
  init_orchestration();
4025
4185
  init_PipelineDebugger();
4026
4186
  init_diversityRerank();
4187
+ init_regulators();
4188
+ init_SrsDebugger();
4027
4189
  VERBOSE_RESULTS = true;
4028
4190
  Pipeline = class extends ContentNavigator {
4029
4191
  generator;
@@ -4049,6 +4211,13 @@ var init_Pipeline = __esm({
4049
4211
  * getWeightedCards() call, then cleared.
4050
4212
  */
4051
4213
  _ephemeralHints = null;
4214
+ /**
4215
+ * The intake valve's clock (see regulators.ts), loaded from strategy state on
4216
+ * first use and kept in memory. Writes are chained so a presentation and a
4217
+ * run can't race each other's revision.
4218
+ */
4219
+ _intakeClock = null;
4220
+ _intakeClockWrite = Promise.resolve();
4052
4221
  /**
4053
4222
  * Create a new pipeline.
4054
4223
  *
@@ -4123,13 +4292,12 @@ var init_Pipeline = __esm({
4123
4292
  }
4124
4293
  }
4125
4294
  generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {
4126
- const newCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
4127
- const reviewCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
4295
+ const reviewCount = data.cards.filter((c) => c.reviewID).length;
4128
4296
  return {
4129
4297
  name,
4130
4298
  cardCount: data.cards.length,
4131
- newCount: newCards.length,
4132
- reviewCount: reviewCards.length,
4299
+ newCount: data.cards.length - reviewCount,
4300
+ reviewCount,
4133
4301
  topScore: Math.max(...data.cards.map((c) => c.score), 0)
4134
4302
  };
4135
4303
  });
@@ -4165,19 +4333,24 @@ var init_Pipeline = __esm({
4165
4333
  cards.filter((c) => c.provenance.some((p) => p.strategy === "prescribed")).map((c) => c.cardId)
4166
4334
  );
4167
4335
  const filterImpacts = [];
4336
+ const generatedScores = new Map(cards.map((c) => [c.cardId, c.score]));
4337
+ const gated = /* @__PURE__ */ new Set();
4168
4338
  for (const filter of this.filters) {
4169
4339
  const beforeCount = cards.length;
4170
4340
  const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));
4171
4341
  cards = await filter.transform(cards, context);
4172
4342
  let boosted = 0, penalized = 0, passed = 0;
4173
4343
  const removed = beforeCount - cards.length;
4344
+ const kind = filter.kind ?? "gate";
4174
4345
  for (const card of cards) {
4175
4346
  const before = beforeScores.get(card.cardId) ?? 0;
4176
4347
  if (card.score > before) boosted++;
4177
- else if (card.score < before) penalized++;
4178
- else passed++;
4348
+ else if (card.score < before) {
4349
+ penalized++;
4350
+ if (kind === "gate") gated.add(card.cardId);
4351
+ } else passed++;
4179
4352
  }
4180
- filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
4353
+ filterImpacts.push({ name: filter.name, kind, boosted, penalized, passed, removed });
4181
4354
  if (prescribedIds.size > 0) {
4182
4355
  const survivingIds = new Set(cards.map((c) => c.cardId));
4183
4356
  const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));
@@ -4193,6 +4366,7 @@ var init_Pipeline = __esm({
4193
4366
  }
4194
4367
  const scoredCards = cards;
4195
4368
  cards = cards.filter((c) => c.score > 0);
4369
+ const regulators = await this.regulate(cards, generatedScores, gated);
4196
4370
  const hints = this._ephemeralHints;
4197
4371
  if (hints) {
4198
4372
  this._ephemeralHints = null;
@@ -4229,7 +4403,8 @@ var init_Pipeline = __esm({
4229
4403
  result,
4230
4404
  context.userElo,
4231
4405
  hints ?? void 0,
4232
- scoredCards
4406
+ scoredCards,
4407
+ regulators
4233
4408
  );
4234
4409
  captureRun(report);
4235
4410
  } catch (e) {
@@ -4408,6 +4583,77 @@ var init_Pipeline = __esm({
4408
4583
  logger.info(`[Pipeline] Hints applied: ${beforeCount} \u2192 ${cards.length} cards`);
4409
4584
  return cards;
4410
4585
  }
4586
+ /**
4587
+ * The regulator stage: measure each class's pressure and scale it.
4588
+ *
4589
+ * - Review mass: every due review's SRS urgency times the filters' net
4590
+ * effect on it.
4591
+ * - Intake: servable hours since a new card was presented, applied only to
4592
+ * eligible new cards (no gate penalized them). With none eligible, the
4593
+ * clock freezes.
4594
+ *
4595
+ * Mutates `cards` in place; returns the readings for the run report.
4596
+ */
4597
+ async regulate(cards, generatedScores, gated) {
4598
+ const config = DEFAULT_REGULATOR_CONFIG;
4599
+ const reviews = cards.filter((c) => c.reviewID);
4600
+ const newCards = cards.filter((c) => !c.reviewID);
4601
+ const eligibleNew = newCards.filter((c) => !gated.has(c.cardId));
4602
+ const mass = reviewMassReading(reviews, generatedScores, config.reviewMass);
4603
+ applyReading(reviews, mass);
4604
+ noteReviewPressure(this.course.getCourseID(), {
4605
+ mass: mass.urgency,
4606
+ healthyMass: config.reviewMass.healthyMass,
4607
+ rate: config.reviewMass.rate,
4608
+ multiplier: mass.multiplier
4609
+ });
4610
+ const now = Date.now();
4611
+ const clock = await this.loadIntakeClock(now);
4612
+ const stepped = stepIntakeClock(clock, now, eligibleNew.length);
4613
+ if (stepped !== clock) this.saveIntakeClock(stepped);
4614
+ const intake = intakeReading(
4615
+ stepped,
4616
+ now,
4617
+ { eligibleNew: eligibleNew.length, newCandidates: newCards.length },
4618
+ config.intake
4619
+ );
4620
+ applyReading(eligibleNew, intake);
4621
+ logger.info(
4622
+ `[Pipeline:regulators] review mass ${mass.urgency.toFixed(1)} over ${reviews.length} due \u2192 \xD7${mass.multiplier.toFixed(2)}; intake ${intake.urgency.toFixed(1)}h, ${eligibleNew.length}/${newCards.length} new eligible \u2192 \xD7${intake.multiplier.toFixed(2)}`
4623
+ );
4624
+ return [mass, intake];
4625
+ }
4626
+ /**
4627
+ * A card was presented. A new card's first presentation discharges the
4628
+ * intake valve: its clock restarts. Called by the SessionController.
4629
+ */
4630
+ notePresented(card) {
4631
+ if (card.status !== "new" || card.courseId !== this.course?.getCourseID()) return;
4632
+ this.saveIntakeClock(resetIntakeClock(Date.now()));
4633
+ }
4634
+ async loadIntakeClock(nowMs) {
4635
+ if (this._intakeClock) return this._intakeClock;
4636
+ let stored = null;
4637
+ try {
4638
+ stored = await this.user.getStrategyState(
4639
+ this.course.getCourseID(),
4640
+ INTAKE_CLOCK_KEY
4641
+ );
4642
+ } catch (e) {
4643
+ logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`);
4644
+ }
4645
+ if (stored) {
4646
+ this._intakeClock = stored;
4647
+ } else {
4648
+ this.saveIntakeClock(resetIntakeClock(nowMs));
4649
+ }
4650
+ return this._intakeClock;
4651
+ }
4652
+ saveIntakeClock(state) {
4653
+ this._intakeClock = state;
4654
+ const courseId = this.course.getCourseID();
4655
+ this._intakeClockWrite = this._intakeClockWrite.then(() => this.user.putStrategyState(courseId, INTAKE_CLOCK_KEY, state)).catch((e) => logger.warn(`[Pipeline:regulators] Could not save the intake clock: ${e}`));
4656
+ }
4411
4657
  /**
4412
4658
  * Build shared context for generator and filters.
4413
4659
  *
@@ -4418,10 +4664,11 @@ var init_Pipeline = __esm({
4418
4664
  */
4419
4665
  async buildContext() {
4420
4666
  let userElo = 1e3;
4667
+ let userCourseElo;
4421
4668
  try {
4422
4669
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
4423
- const courseElo = (0, import_common8.toCourseElo)(courseReg.elo);
4424
- userElo = courseElo.global.score;
4670
+ userCourseElo = (0, import_common8.toCourseElo)(courseReg.elo);
4671
+ userElo = userCourseElo.global.score;
4425
4672
  } catch (e) {
4426
4673
  logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
4427
4674
  }
@@ -4433,6 +4680,7 @@ var init_Pipeline = __esm({
4433
4680
  user: this.user,
4434
4681
  course: this.course,
4435
4682
  userElo,
4683
+ ...userCourseElo ? { userCourseElo } : {},
4436
4684
  orchestration
4437
4685
  };
4438
4686
  }
@@ -4546,7 +4794,7 @@ var init_Pipeline = __esm({
4546
4794
  cards = await this.hydrateTags(cards);
4547
4795
  const fullPool = cards.slice();
4548
4796
  const context = await this.buildContext();
4549
- for (const filter of this.filters) {
4797
+ for (const filter of this.forecastFilters()) {
4550
4798
  cards = await filter.transform(cards, context);
4551
4799
  }
4552
4800
  if (opts?.hints) {
@@ -4565,6 +4813,14 @@ var init_Pipeline = __esm({
4565
4813
  cards.sort((a, b) => b.score - a.score);
4566
4814
  return opts?.limit ? cards.slice(0, opts.limit) : cards;
4567
4815
  }
4816
+ /**
4817
+ * The filters a forecast or card-space scan applies. Those start every card at
4818
+ * 1.0 without a generator, so they skip `liveOnly` filters (ELO distance),
4819
+ * which only make sense against generator scores.
4820
+ */
4821
+ forecastFilters() {
4822
+ return this.filters.filter((f) => !f.liveOnly);
4823
+ }
4568
4824
  /**
4569
4825
  * Scan every card in the course through the filter chain and report
4570
4826
  * how many are "well indicated" (score >= threshold) for the current user.
@@ -4586,7 +4842,7 @@ var init_Pipeline = __esm({
4586
4842
  cards = await this.hydrateTags(cards);
4587
4843
  const context = await this.buildContext();
4588
4844
  const filterBreakdown = [];
4589
- for (const filter of this.filters) {
4845
+ for (const filter of this.forecastFilters()) {
4590
4846
  cards = await filter.transform(cards, context);
4591
4847
  const wi = cards.filter((c) => c.score >= THRESHOLD).length;
4592
4848
  filterBreakdown.push({ name: filter.name, wellIndicated: wi });
@@ -4650,6 +4906,7 @@ var init_Pipeline = __esm({
4650
4906
  // src/core/navigators/defaults.ts
4651
4907
  var defaults_exports = {};
4652
4908
  __export(defaults_exports, {
4909
+ createDefaultEloDistanceStrategy: () => createDefaultEloDistanceStrategy,
4653
4910
  createDefaultEloStrategy: () => createDefaultEloStrategy,
4654
4911
  createDefaultPipeline: () => createDefaultPipeline,
4655
4912
  createDefaultSrsStrategy: () => createDefaultSrsStrategy
@@ -4676,12 +4933,28 @@ function createDefaultSrsStrategy(courseId) {
4676
4933
  serializedData: ""
4677
4934
  };
4678
4935
  }
4936
+ function createDefaultEloDistanceStrategy(courseId) {
4937
+ return {
4938
+ _id: "NAVIGATION_STRATEGY-eloDistance-default",
4939
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
4940
+ name: "ELO Distance (default)",
4941
+ description: "Scales every candidate, new or review, by its distance from the learner's ELO",
4942
+ implementingClass: "eloDistance" /* ELO_DISTANCE */,
4943
+ course: courseId,
4944
+ // Explicit, though the filter would default to it anyway: views show what runs.
4945
+ serializedData: JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG)
4946
+ };
4947
+ }
4679
4948
  function createDefaultPipeline(user, course) {
4680
4949
  const courseId = course.getCourseID();
4681
4950
  const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
4682
4951
  const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
4683
4952
  const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
4684
- const eloDistanceFilter = createEloDistanceFilter();
4953
+ const eloDistanceFilter = new EloDistanceFilter(
4954
+ user,
4955
+ course,
4956
+ createDefaultEloDistanceStrategy(courseId)
4957
+ );
4685
4958
  return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
4686
4959
  }
4687
4960
  var init_defaults = __esm({
@@ -4697,6 +4970,131 @@ var init_defaults = __esm({
4697
4970
  }
4698
4971
  });
4699
4972
 
4973
+ // src/core/navigators/pipelinePlan.ts
4974
+ var pipelinePlan_exports = {};
4975
+ __export(pipelinePlan_exports, {
4976
+ PIPELINE_STAGES: () => PIPELINE_STAGES,
4977
+ planPipeline: () => planPipeline
4978
+ });
4979
+ function planned(strategy, role, origin) {
4980
+ const kind = role === "filter" /* FILTER */ ? getRegisteredFilterKind(strategy.implementingClass) : void 0;
4981
+ return {
4982
+ role,
4983
+ origin,
4984
+ name: strategy.name,
4985
+ implementingClass: strategy.implementingClass,
4986
+ strategy,
4987
+ ...kind ? { kind } : {}
4988
+ };
4989
+ }
4990
+ function planPipeline(strategies, courseId) {
4991
+ if (strategies.length === 0) {
4992
+ return {
4993
+ kind: "default",
4994
+ generators: [
4995
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline"),
4996
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline")
4997
+ ],
4998
+ filters: [
4999
+ planned(
5000
+ createDefaultEloDistanceStrategy(courseId),
5001
+ "filter" /* FILTER */,
5002
+ "default-pipeline"
5003
+ )
5004
+ ],
5005
+ skipped: [],
5006
+ warnings: [],
5007
+ notes: [],
5008
+ regulators: DEFAULT_REGULATOR_CONFIG
5009
+ };
5010
+ }
5011
+ const generators = [];
5012
+ const filters = [];
5013
+ const skipped = [];
5014
+ const warnings = [];
5015
+ for (const s of strategies) {
5016
+ if (isGenerator(s.implementingClass)) {
5017
+ generators.push(planned(s, "generator" /* GENERATOR */, "strategy-doc"));
5018
+ } else if (isFilter(s.implementingClass)) {
5019
+ filters.push(planned(s, "filter" /* FILTER */, "strategy-doc"));
5020
+ } else {
5021
+ skipped.push({ strategy: s, reason: "not a registered generator or filter" });
5022
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
5023
+ }
5024
+ }
5025
+ const declared = new Set(generators.map((g) => g.implementingClass));
5026
+ if (!declared.has(createDefaultEloStrategy(courseId).implementingClass)) {
5027
+ generators.push(
5028
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5029
+ );
5030
+ }
5031
+ if (!declared.has(createDefaultSrsStrategy(courseId).implementingClass)) {
5032
+ generators.push(
5033
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5034
+ );
5035
+ }
5036
+ const eloDistance = createDefaultEloDistanceStrategy(courseId);
5037
+ if (!filters.some((f) => f.implementingClass === eloDistance.implementingClass)) {
5038
+ filters.push(planned(eloDistance, "filter" /* FILTER */, "assembler-default"));
5039
+ }
5040
+ filters.sort((a, b) => a.name.localeCompare(b.name));
5041
+ return {
5042
+ kind: "assembled",
5043
+ generators,
5044
+ filters,
5045
+ skipped,
5046
+ warnings,
5047
+ notes: [],
5048
+ regulators: DEFAULT_REGULATOR_CONFIG
5049
+ };
5050
+ }
5051
+ var PIPELINE_STAGES;
5052
+ var init_pipelinePlan = __esm({
5053
+ "src/core/navigators/pipelinePlan.ts"() {
5054
+ "use strict";
5055
+ init_navigators();
5056
+ init_regulators();
5057
+ init_defaults();
5058
+ PIPELINE_STAGES = [
5059
+ {
5060
+ key: "generate",
5061
+ title: "Generate",
5062
+ summary: "Each generator proposes candidates (up to 500 in all), scored on what is specific to its source. A card proposed by several generators keeps their mean score, raised 10% per extra generator."
5063
+ },
5064
+ {
5065
+ key: "filter",
5066
+ title: "Filter",
5067
+ summary: "Each filter multiplies candidate scores, in the order shown. A gate says a card is not ready yet; a signal expresses preference. Gates usually penalize rather than remove, so a gated card stays in the pool at a low score."
5068
+ },
5069
+ {
5070
+ key: "drop-zero",
5071
+ title: "Drop zero scores",
5072
+ summary: "Candidates whose score reached 0 leave the pool."
5073
+ },
5074
+ {
5075
+ key: "regulate",
5076
+ title: "Regulate",
5077
+ summary: "Balances reviews against new cards. Review mass: the due reviews weighed by their filtered scores; above a healthy level, every review is lifted. Intake: hours since a new card was last presented; new cards no gate penalized are lifted, and the clock stops while there are none."
5078
+ },
5079
+ {
5080
+ key: "hints",
5081
+ title: "Apply hints",
5082
+ summary: "The session's hints (from the app: an intro's follow-up, a difficulty boost) exclude, boost, or require cards. Required cards skip the filters entirely."
5083
+ },
5084
+ {
5085
+ key: "diversity",
5086
+ title: "Diversity re-rank",
5087
+ summary: "Demotes candidates that repeat a distinctive tag already ranked above them, so one concept or answer cannot take the whole head of the queue. Sees this run only, not what the session already served."
5088
+ },
5089
+ {
5090
+ key: "select",
5091
+ title: "Select",
5092
+ summary: "Highest scores first, up to the run's limit. The session mixes them into its supply queue."
5093
+ }
5094
+ ];
5095
+ }
5096
+ });
5097
+
4700
5098
  // src/core/navigators/PipelineAssembler.ts
4701
5099
  var PipelineAssembler_exports = {};
4702
5100
  __export(PipelineAssembler_exports, {
@@ -4711,16 +5109,16 @@ var init_PipelineAssembler = __esm({
4711
5109
  init_Pipeline();
4712
5110
  init_logger();
4713
5111
  init_CompositeGenerator();
4714
- init_defaults();
5112
+ init_pipelinePlan();
4715
5113
  PipelineAssembler = class {
4716
5114
  /**
4717
5115
  * Assembles a navigation pipeline from strategy documents.
4718
5116
  *
4719
- * 1. Separates into generators and filters by role
4720
- * 2. Validates at least one generator exists (or creates default ELO)
4721
- * 3. Instantiates generators - wraps multiple in CompositeGenerator
4722
- * 4. Instantiates filters
4723
- * 5. Returns Pipeline(generator, filters)
5117
+ * 1. Plans: classifies by role, adds default ELO/SRS and ELO distance, orders filters
5118
+ * (`planPipeline`)
5119
+ * 2. Instantiates generators - wraps multiple in CompositeGenerator
5120
+ * 3. Instantiates filters
5121
+ * 4. Returns Pipeline(generator, filters)
4724
5122
  *
4725
5123
  * @param input - Strategy documents plus user/course interfaces
4726
5124
  * @returns Assembled pipeline and any warnings
@@ -4736,28 +5134,17 @@ var init_PipelineAssembler = __esm({
4736
5134
  warnings
4737
5135
  };
4738
5136
  }
4739
- const generatorStrategies = [];
4740
- const filterStrategies = [];
4741
- for (const s of strategies) {
4742
- if (isGenerator(s.implementingClass)) {
4743
- generatorStrategies.push(s);
4744
- } else if (isFilter(s.implementingClass)) {
4745
- filterStrategies.push(s);
4746
- } else {
4747
- warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
5137
+ const plan = planPipeline(strategies, course.getCourseID());
5138
+ warnings.push(...plan.warnings);
5139
+ for (const n of [...plan.generators, ...plan.filters]) {
5140
+ if (n.origin === "assembler-default") {
5141
+ logger.debug(
5142
+ `[PipelineAssembler] No ${n.implementingClass} ${n.role} configured, adding default`
5143
+ );
4748
5144
  }
4749
5145
  }
4750
- const courseId = course.getCourseID();
4751
- const hasElo = generatorStrategies.some((s) => s.implementingClass === "elo" /* ELO */);
4752
- const hasSrs = generatorStrategies.some((s) => s.implementingClass === "srs" /* SRS */);
4753
- if (!hasElo) {
4754
- logger.debug("[PipelineAssembler] No ELO generator configured, adding default");
4755
- generatorStrategies.push(createDefaultEloStrategy(courseId));
4756
- }
4757
- if (!hasSrs) {
4758
- logger.debug("[PipelineAssembler] No SRS generator configured, adding default");
4759
- generatorStrategies.push(createDefaultSrsStrategy(courseId));
4760
- }
5146
+ const generatorStrategies = plan.generators.map((g) => g.strategy);
5147
+ const sortedFilterStrategies = plan.filters.map((f) => f.strategy);
4761
5148
  if (generatorStrategies.length === 0) {
4762
5149
  warnings.push("No generator strategy found");
4763
5150
  return {
@@ -4779,9 +5166,6 @@ var init_PipelineAssembler = __esm({
4779
5166
  generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
4780
5167
  }
4781
5168
  const filters = [];
4782
- const sortedFilterStrategies = [...filterStrategies].sort(
4783
- (a, b) => a.name.localeCompare(b.name)
4784
- );
4785
5169
  for (const filterStrategy of sortedFilterStrategies) {
4786
5170
  try {
4787
5171
  const nav = await ContentNavigator.create(user, course, filterStrategy);
@@ -4849,7 +5233,9 @@ var init_3 = __esm({
4849
5233
  "./generators/prescribed.ts": () => Promise.resolve().then(() => (init_prescribed(), prescribed_exports)),
4850
5234
  "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
4851
5235
  "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
4852
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
5236
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
5237
+ "./pipelinePlan.ts": () => Promise.resolve().then(() => (init_pipelinePlan(), pipelinePlan_exports)),
5238
+ "./regulators.ts": () => Promise.resolve().then(() => (init_regulators(), regulators_exports))
4853
5239
  });
4854
5240
  }
4855
5241
  });
@@ -4870,6 +5256,7 @@ __export(navigators_exports, {
4870
5256
  drainCapturedRuns: () => drainCapturedRuns,
4871
5257
  getActivePipeline: () => getActivePipeline,
4872
5258
  getCardOrigin: () => getCardOrigin,
5259
+ getRegisteredFilterKind: () => getRegisteredFilterKind,
4873
5260
  getRegisteredNavigator: () => getRegisteredNavigator,
4874
5261
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
4875
5262
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
@@ -4898,6 +5285,10 @@ function hasRegisteredNavigator(implementingClass) {
4898
5285
  function getRegisteredNavigatorRole(implementingClass) {
4899
5286
  return navigatorRegistry.get(implementingClass)?.role;
4900
5287
  }
5288
+ function getRegisteredFilterKind(implementingClass) {
5289
+ const ctor = navigatorRegistry.get(implementingClass)?.constructor;
5290
+ return ctor?.kind;
5291
+ }
4901
5292
  function getRegisteredNavigatorNames() {
4902
5293
  return Array.from(navigatorRegistry.keys());
4903
5294
  }
@@ -4915,17 +5306,20 @@ async function initializeNavigatorRegistry() {
4915
5306
  hierarchyModule,
4916
5307
  interferenceModule,
4917
5308
  relativePriorityModule,
4918
- userTagPreferenceModule
5309
+ userTagPreferenceModule,
5310
+ eloDistanceModule
4919
5311
  ] = await Promise.all([
4920
5312
  Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
4921
5313
  Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
4922
5314
  Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
4923
- Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
5315
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
5316
+ Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports))
4924
5317
  ]);
4925
5318
  registerNavigator("hierarchyDefinition", hierarchyModule.default);
4926
5319
  registerNavigator("interferenceMitigator", interferenceModule.default);
4927
5320
  registerNavigator("relativePriority", relativePriorityModule.default);
4928
5321
  registerNavigator("userTagPreference", userTagPreferenceModule.default);
5322
+ registerNavigator("eloDistance", eloDistanceModule.default);
4929
5323
  logger.debug(
4930
5324
  `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
4931
5325
  );
@@ -4973,6 +5367,7 @@ var init_navigators = __esm({
4973
5367
  Navigators2["INTERFERENCE"] = "interferenceMitigator";
4974
5368
  Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
4975
5369
  Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
5370
+ Navigators2["ELO_DISTANCE"] = "eloDistance";
4976
5371
  return Navigators2;
4977
5372
  })(Navigators || {});
4978
5373
  NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
@@ -4987,7 +5382,8 @@ var init_navigators = __esm({
4987
5382
  ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
4988
5383
  ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
4989
5384
  ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
4990
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
5385
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */,
5386
+ ["eloDistance" /* ELO_DISTANCE */]: "filter" /* FILTER */
4991
5387
  };
4992
5388
  ContentNavigator = class {
4993
5389
  /** User interface for this navigation session */
@@ -6831,10 +7227,11 @@ function backlogHtml(backlog) {
6831
7227
  const rows = backlog.map((b) => {
6832
7228
  const hot = b.backlogMultiplier >= 3;
6833
7229
  const multColor = b.backlogMultiplier <= 1 ? "#86efac" : hot ? "#fca5a5" : "#fcd34d";
6834
- const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog}-review excess, unbounded)` : "healthy \u2014 no pressure";
7230
+ const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog} of mass in excess, unbounded)` : "healthy \u2014 no pressure";
7231
+ const mass = b.reviewMass !== null ? ` \xB7 mass ${b.reviewMass.toFixed(1)}` : "";
6835
7232
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
6836
7233
  const next = b.nextDueIn ? ` <span style="opacity:.6">\xB7 next due ${esc(b.nextDueIn)}</span>` : "";
6837
- return `<div style="margin-left:6px"><span style="opacity:.7">${esc(b.courseId.slice(0, 8))}</span> due ${b.dueNow}/${b.scheduledTotal} <span style="opacity:.6">(healthy ${b.healthyBacklog})</span>${next}<div style="margin-left:6px">pressure <span style="color:${multColor}">\xD7${b.backlogMultiplier.toFixed(2)}</span> <span style="opacity:.6">${headroom} \xB7 top review ${top}</span></div></div>`;
7234
+ return `<div style="margin-left:6px"><span style="opacity:.7">${esc(b.courseId.slice(0, 8))}</span> due ${b.dueNow}/${b.scheduledTotal}${mass} <span style="opacity:.6">(healthy mass ${b.healthyBacklog})</span>${next}<div style="margin-left:6px">pressure <span style="color:${multColor}">\xD7${b.backlogMultiplier.toFixed(2)}</span> <span style="opacity:.6">${headroom} \xB7 top review ${top}</span></div></div>`;
6838
7235
  }).join("");
6839
7236
  return `<div style="margin-bottom:6px"><div style="color:#93c5fd">review backpressure</div>${rows}</div>`;
6840
7237
  }
@@ -6973,8 +7370,9 @@ function snapshotToText(s) {
6973
7370
  const headroom = b.backlogMultiplier > 1 ? "climbing" : "healthy";
6974
7371
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
6975
7372
  const next = b.nextDueIn ? `, next due ${b.nextDueIn}` : "";
7373
+ const mass = b.reviewMass !== null ? `, mass ${b.reviewMass.toFixed(1)}` : "";
6976
7374
  lines.push(
6977
- ` ${b.courseId.slice(0, 8)}: due ${b.dueNow}/${b.scheduledTotal} (healthy ${b.healthyBacklog})${next}; pressure \xD7${b.backlogMultiplier.toFixed(2)} ${headroom}; top review ${top}`
7375
+ ` ${b.courseId.slice(0, 8)}: due ${b.dueNow}/${b.scheduledTotal}${mass} (healthy mass ${b.healthyBacklog})${next}; pressure \xD7${b.backlogMultiplier.toFixed(2)} ${headroom}; top review ${top}`
6978
7376
  );
6979
7377
  }
6980
7378
  }
@@ -9999,6 +10397,11 @@ var init_courseDB3 = __esm({
9999
10397
  setEphemeralHints(hints) {
10000
10398
  this._pendingHints = hints;
10001
10399
  }
10400
+ /** Forward a presentation to the navigator (a new card restarts its intake clock). */
10401
+ notePresented(card) {
10402
+ if (card.status !== "new") return;
10403
+ void this.createNavigator(this.userDB).then((navigator2) => navigator2.notePresented?.(card)).catch((e) => logger.warn(`[static/courseDB] Could not note a presentation: ${e}`));
10404
+ }
10002
10405
  async getWeightedCards(limit) {
10003
10406
  try {
10004
10407
  const navigator2 = await this.createNavigator(this.userDB);