@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
package/dist/index.mjs CHANGED
@@ -812,7 +812,7 @@ function parseCardElo(provenance) {
812
812
  const match = eloEntry.reason.match(/card:\s*(\d+)/);
813
813
  return match ? parseInt(match[1], 10) : void 0;
814
814
  }
815
- function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards, userElo, hints, scoredCards) {
815
+ function buildRunReport(courseId, courseName, generatorName, generators, generatedCount, filters, allCards, selectedCards, userElo, hints, scoredCards, regulators) {
816
816
  const selectedIds = new Set(selectedCards.map((c) => c.cardId));
817
817
  const toReport = (card) => ({
818
818
  cardId: card.cardId,
@@ -820,7 +820,7 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
820
820
  origin: getOrigin(card),
821
821
  generator: card.provenance[0]?.strategyName || card.provenance[0]?.strategy,
822
822
  finalScore: card.score,
823
- cardElo: parseCardElo(card.provenance),
823
+ cardElo: card.cardElo ?? parseCardElo(card.provenance),
824
824
  provenance: card.provenance,
825
825
  tags: card.tags,
826
826
  selected: selectedIds.has(card.cardId)
@@ -898,7 +898,8 @@ function buildRunReport(courseId, courseName, generatorName, generators, generat
898
898
  newSelected,
899
899
  cards,
900
900
  unselectedNew,
901
- discardedTail
901
+ discardedTail,
902
+ ...regulators ? { regulators } : {}
902
903
  };
903
904
  }
904
905
  function formatProvenance(provenance) {
@@ -1622,11 +1623,23 @@ var SrsDebugger_exports = {};
1622
1623
  __export(SrsDebugger_exports, {
1623
1624
  captureSrsBacklog: () => captureSrsBacklog,
1624
1625
  clearSrsBacklogDebug: () => clearSrsBacklogDebug,
1625
- getSrsBacklogDebug: () => getSrsBacklogDebug
1626
+ getSrsBacklogDebug: () => getSrsBacklogDebug,
1627
+ noteReviewPressure: () => noteReviewPressure
1626
1628
  });
1627
1629
  function captureSrsBacklog(snapshot) {
1628
1630
  snapshots.set(snapshot.courseId, snapshot);
1629
1631
  }
1632
+ function noteReviewPressure(courseId, pressure) {
1633
+ const snapshot = snapshots.get(courseId);
1634
+ if (!snapshot) return;
1635
+ snapshots.set(courseId, {
1636
+ ...snapshot,
1637
+ reviewMass: pressure.mass,
1638
+ healthyBacklog: pressure.healthyMass,
1639
+ backlogGrowthRate: pressure.rate,
1640
+ backlogMultiplier: pressure.multiplier
1641
+ });
1642
+ }
1630
1643
  function getSrsBacklogDebug() {
1631
1644
  return [...snapshots.values()].sort((a, b) => b.timestamp - a.timestamp);
1632
1645
  }
@@ -1905,13 +1918,12 @@ __export(elo_exports, {
1905
1918
  default: () => ELONavigator
1906
1919
  });
1907
1920
  import { toCourseElo as toCourseElo2 } from "@vue-skuilder/common";
1908
- var ELO_RELEVANCE_SIGMA, ELONavigator;
1921
+ var ELONavigator;
1909
1922
  var init_elo = __esm({
1910
1923
  "src/core/navigators/generators/elo.ts"() {
1911
1924
  "use strict";
1912
1925
  init_navigators();
1913
1926
  init_logger();
1914
- ELO_RELEVANCE_SIGMA = 300;
1915
1927
  ELONavigator = class extends ContentNavigator {
1916
1928
  /** Human-readable name for CardGenerator interface */
1917
1929
  name;
@@ -1920,10 +1932,8 @@ var init_elo = __esm({
1920
1932
  this.name = strategyData?.name || "ELO";
1921
1933
  }
1922
1934
  /**
1923
- * Get new cards with suitability scores based on ELO distance.
1924
- *
1925
- * Cards closer to user's ELO get higher scores.
1926
- * Score formula: max(0, 1 - distance / 500)
1935
+ * Get the new cards nearest the learner's ELO, each scored with a flat
1936
+ * jitter in [0.5, 1]. Carries each card's ELO for the ELO distance filter.
1927
1937
  *
1928
1938
  * NOTE: This generator only handles NEW cards. Reviews are handled by
1929
1939
  * SRSNavigator. Use CompositeGenerator to combine both.
@@ -1951,20 +1961,20 @@ var init_elo = __esm({
1951
1961
  const scored = newCards.map((c) => {
1952
1962
  const cardElo = c.elo ?? 1e3;
1953
1963
  const distance = Math.abs(cardElo - userGlobalElo);
1954
- const relevance = Math.exp(-((distance / ELO_RELEVANCE_SIGMA) ** 2));
1955
- const samplingKey = relevance * (0.5 + 0.5 * Math.random());
1964
+ const jitter = 0.5 + 0.5 * Math.random();
1956
1965
  return {
1957
1966
  cardId: c.cardID,
1958
1967
  courseId: c.courseID,
1959
- score: samplingKey,
1968
+ score: jitter,
1969
+ cardElo,
1960
1970
  provenance: [
1961
1971
  {
1962
1972
  strategy: "elo",
1963
1973
  strategyName: this.strategyName || this.name,
1964
1974
  strategyId: this.strategyId || "NAVIGATION_STRATEGY-ELO-default",
1965
1975
  action: "generated",
1966
- score: samplingKey,
1967
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), relevance ${relevance.toFixed(3)}, key ${samplingKey.toFixed(3)}`
1976
+ score: jitter,
1977
+ reason: `new card near learner ELO: distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userGlobalElo)}), jitter ${jitter.toFixed(3)}`
1968
1978
  }
1969
1979
  ]
1970
1980
  };
@@ -2840,43 +2850,132 @@ var init_prescribed = __esm({
2840
2850
  }
2841
2851
  });
2842
2852
 
2853
+ // src/core/navigators/regulators.ts
2854
+ var regulators_exports = {};
2855
+ __export(regulators_exports, {
2856
+ DEFAULT_REGULATOR_CONFIG: () => DEFAULT_REGULATOR_CONFIG,
2857
+ INTAKE_CLOCK_KEY: () => INTAKE_CLOCK_KEY,
2858
+ applyReading: () => applyReading,
2859
+ frozenMsAt: () => frozenMsAt,
2860
+ intakeHours: () => intakeHours,
2861
+ intakeReading: () => intakeReading,
2862
+ resetIntakeClock: () => resetIntakeClock,
2863
+ reviewMassReading: () => reviewMassReading,
2864
+ reviewWeight: () => reviewWeight,
2865
+ stepIntakeClock: () => stepIntakeClock
2866
+ });
2867
+ function clamp01(x) {
2868
+ return Math.min(1, Math.max(0, x));
2869
+ }
2870
+ function reviewWeight(card, generatedScore, referenceScore) {
2871
+ if (card.reviewUrgency !== void 0 && generatedScore !== void 0 && generatedScore > 0) {
2872
+ return clamp01(card.reviewUrgency * (card.score / generatedScore));
2873
+ }
2874
+ return clamp01(card.score / referenceScore);
2875
+ }
2876
+ function reviewMassReading(reviews, generatedScores, config = DEFAULT_REGULATOR_CONFIG.reviewMass) {
2877
+ const mass = reviews.reduce(
2878
+ (m, c) => m + reviewWeight(c, generatedScores.get(c.cardId), config.referenceScore),
2879
+ 0
2880
+ );
2881
+ const multiplier = mass > config.healthyMass ? Math.pow(config.rate, (mass - config.healthyMass) / config.healthyMass) : 1;
2882
+ return {
2883
+ name: "review-mass",
2884
+ class: "review",
2885
+ urgency: mass,
2886
+ multiplier,
2887
+ applied: reviews.length,
2888
+ inputs: { due: reviews.length, mass, healthyMass: config.healthyMass }
2889
+ };
2890
+ }
2891
+ function resetIntakeClock(nowMs) {
2892
+ return { lastNewAt: new Date(nowMs).toISOString(), frozenMs: 0, unservableSince: null };
2893
+ }
2894
+ function frozenMsAt(state, nowMs) {
2895
+ const open = state.unservableSince ? Math.max(0, nowMs - Date.parse(state.unservableSince)) : 0;
2896
+ return state.frozenMs + open;
2897
+ }
2898
+ function intakeHours(state, nowMs) {
2899
+ const elapsed = nowMs - Date.parse(state.lastNewAt);
2900
+ return Math.max(0, elapsed - frozenMsAt(state, nowMs)) / 36e5;
2901
+ }
2902
+ function stepIntakeClock(state, nowMs, eligibleNew) {
2903
+ if (eligibleNew === 0 && !state.unservableSince) {
2904
+ return { ...state, unservableSince: new Date(nowMs).toISOString() };
2905
+ }
2906
+ if (eligibleNew > 0 && state.unservableSince) {
2907
+ return { ...state, frozenMs: frozenMsAt(state, nowMs), unservableSince: null };
2908
+ }
2909
+ return state;
2910
+ }
2911
+ function intakeReading(state, nowMs, counts, config = DEFAULT_REGULATOR_CONFIG.intake) {
2912
+ const hours = intakeHours(state, nowMs);
2913
+ const multiplier = counts.eligibleNew > 0 ? Math.pow(config.rate, hours / config.scaleHours) : 1;
2914
+ return {
2915
+ name: "intake",
2916
+ class: "new",
2917
+ urgency: hours,
2918
+ multiplier,
2919
+ applied: counts.eligibleNew,
2920
+ inputs: {
2921
+ hoursSinceNew: hours,
2922
+ frozenHours: frozenMsAt(state, nowMs) / 36e5,
2923
+ eligibleNew: counts.eligibleNew,
2924
+ newCandidates: counts.newCandidates
2925
+ }
2926
+ };
2927
+ }
2928
+ function applyReading(cards, reading) {
2929
+ if (reading.multiplier === 1) return;
2930
+ 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)}`;
2931
+ for (const card of cards) {
2932
+ card.score *= reading.multiplier;
2933
+ card.provenance.push({
2934
+ strategy: "regulator",
2935
+ strategyName: `Regulator: ${REGULATOR_LABEL[reading.name]}`,
2936
+ strategyId: `regulator-${reading.name}`,
2937
+ action: reading.multiplier > 1 ? "boosted" : "penalized",
2938
+ score: card.score,
2939
+ reason
2940
+ });
2941
+ }
2942
+ }
2943
+ var DEFAULT_REGULATOR_CONFIG, INTAKE_CLOCK_KEY, REGULATOR_LABEL;
2944
+ var init_regulators = __esm({
2945
+ "src/core/navigators/regulators.ts"() {
2946
+ "use strict";
2947
+ DEFAULT_REGULATOR_CONFIG = {
2948
+ reviewMass: { referenceScore: 0.95, healthyMass: 20, rate: 2 },
2949
+ intake: { rate: 2, scaleHours: 24 }
2950
+ };
2951
+ INTAKE_CLOCK_KEY = "IntakeClock";
2952
+ REGULATOR_LABEL = {
2953
+ "review-mass": "Review mass",
2954
+ intake: "Intake"
2955
+ };
2956
+ }
2957
+ });
2958
+
2843
2959
  // src/core/navigators/generators/srs.ts
2844
2960
  var srs_exports = {};
2845
2961
  __export(srs_exports, {
2846
2962
  default: () => SRSNavigator
2847
2963
  });
2848
2964
  import moment from "moment";
2849
- var DEFAULT_HEALTHY_BACKLOG, BACKLOG_GROWTH_RATE, SRSNavigator;
2965
+ var SRSNavigator;
2850
2966
  var init_srs = __esm({
2851
2967
  "src/core/navigators/generators/srs.ts"() {
2852
2968
  "use strict";
2853
2969
  init_navigators();
2854
2970
  init_SrsDebugger();
2971
+ init_regulators();
2855
2972
  init_logger();
2856
- DEFAULT_HEALTHY_BACKLOG = 20;
2857
- BACKLOG_GROWTH_RATE = 2;
2858
2973
  SRSNavigator = class extends ContentNavigator {
2859
2974
  /** Human-readable name for CardGenerator interface */
2860
2975
  name;
2861
- /** Healthy backlog threshold - when exceeded, backlog pressure kicks in */
2862
- healthyBacklog;
2863
2976
  constructor(user, course, strategyData) {
2864
2977
  super(user, course, strategyData);
2865
2978
  this.name = strategyData?.name || "SRS";
2866
- const config = this.parseConfig(strategyData?.serializedData);
2867
- this.healthyBacklog = config.healthyBacklog ?? DEFAULT_HEALTHY_BACKLOG;
2868
- }
2869
- /**
2870
- * Parse configuration from serialized JSON.
2871
- */
2872
- parseConfig(serializedData) {
2873
- if (!serializedData) return {};
2874
- try {
2875
- return JSON.parse(serializedData);
2876
- } catch {
2877
- logger.warn("[SRS] Failed to parse strategy config, using defaults");
2878
- return {};
2879
- }
2880
2979
  }
2881
2980
  /**
2882
2981
  * Get review cards scored by urgency.
@@ -2884,7 +2983,6 @@ var init_srs = __esm({
2884
2983
  * Score formula combines:
2885
2984
  * - Relative overdueness: hoursOverdue / intervalHours
2886
2985
  * - Interval recency: exponential decay favoring shorter intervals
2887
- * - Backlog pressure: boost when due reviews exceed healthy threshold
2888
2986
  *
2889
2987
  * Cards not yet due are excluded (not scored as 0).
2890
2988
  *
@@ -2921,7 +3019,6 @@ var init_srs = __esm({
2921
3019
  }
2922
3020
  }
2923
3021
  }
2924
- const backlogMultiplier = this.computeBacklogMultiplier(dueReviews.length);
2925
3022
  const notDue = reviews.filter((r) => !now.isAfter(moment.utc(r.reviewTime)));
2926
3023
  let nextDueIn = null;
2927
3024
  if (notDue.length > 0) {
@@ -2932,9 +3029,8 @@ var init_srs = __esm({
2932
3029
  nextDueIn = until.asHours() < 1 ? `${Math.round(until.asMinutes())}m` : until.asHours() < 24 ? `${Math.round(until.asHours())}h` : `${Math.round(until.asDays())}d`;
2933
3030
  }
2934
3031
  if (dueReviews.length > 0) {
2935
- const pressureNote = backlogMultiplier > 1 ? ` [backlog pressure: \xD7${backlogMultiplier.toFixed(2)}]` : ` [healthy backlog]`;
2936
3032
  logger.info(
2937
- `[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)${pressureNote}`
3033
+ `[SRS] Course ${courseId}: ${dueReviews.length} reviews due now (of ${reviews.length} scheduled)`
2938
3034
  );
2939
3035
  } else if (reviews.length > 0) {
2940
3036
  const sortedByDue = [...reviews].sort(
@@ -2951,11 +3047,12 @@ var init_srs = __esm({
2951
3047
  logger.info(`[SRS] Course ${courseId}: No reviews scheduled`);
2952
3048
  }
2953
3049
  const scored = dueReviews.map((review) => {
2954
- const { score, reason } = this.computeUrgencyScore(review, now, backlogMultiplier);
3050
+ const { score, urgency, reason } = this.computeUrgencyScore(review, now);
2955
3051
  return {
2956
3052
  cardId: review.cardId,
2957
3053
  courseId: review.courseId,
2958
3054
  score,
3055
+ reviewUrgency: urgency,
2959
3056
  reviewID: review._id,
2960
3057
  provenance: [
2961
3058
  {
@@ -2974,47 +3071,20 @@ var init_srs = __esm({
2974
3071
  courseId,
2975
3072
  scheduledTotal: reviews.length,
2976
3073
  dueNow: dueReviews.length,
2977
- healthyBacklog: this.healthyBacklog,
2978
- backlogMultiplier,
2979
- backlogGrowthRate: BACKLOG_GROWTH_RATE,
3074
+ healthyBacklog: DEFAULT_REGULATOR_CONFIG.reviewMass.healthyMass,
3075
+ reviewMass: null,
3076
+ backlogMultiplier: 1,
3077
+ backlogGrowthRate: DEFAULT_REGULATOR_CONFIG.reviewMass.rate,
2980
3078
  topReviewScore: sorted.length > 0 ? sorted[0].score : null,
2981
3079
  nextDueIn,
2982
3080
  timestamp: Date.now()
2983
3081
  });
2984
3082
  return { cards: sorted.slice(0, limit) };
2985
3083
  }
2986
- /**
2987
- * Compute the multiplicative backlog pressure based on number of due reviews.
2988
- *
2989
- * ×1.0 at or below the healthy threshold (no boost); above it, grows as
2990
- * BACKLOG_GROWTH_RATE raised to the excess expressed in multiples of the
2991
- * healthy threshold. Uncapped — self-regulating instead: reviews winning
2992
- * slots depletes dueCount, which drops the ratio and relaxes the multiplier
2993
- * next run.
2994
- *
2995
- * Examples (with default healthyBacklog=20, BACKLOG_GROWTH_RATE=1.5):
2996
- * - 10 due reviews → ×1.00 (healthy)
2997
- * - 20 due reviews → ×1.00 (at threshold, ratio 0)
2998
- * - 40 due reviews → ×1.50 (ratio 1, 2x threshold)
2999
- * - 60 due reviews → ×2.25 (ratio 2, 3x threshold — old hard cap was ×2.00 here)
3000
- * - 100 due reviews → ×5.06 (ratio 4, 5x threshold)
3001
- * - 160 due reviews → ×17.09 (ratio 7, 8x threshold)
3002
- *
3003
- * @param dueCount - Number of reviews currently due
3004
- * @returns Multiplier applied to review urgency (>= 1.0, unbounded)
3005
- */
3006
- computeBacklogMultiplier(dueCount) {
3007
- if (dueCount <= this.healthyBacklog) {
3008
- return 1;
3009
- }
3010
- const excess = dueCount - this.healthyBacklog;
3011
- const ratio = excess / this.healthyBacklog;
3012
- return Math.pow(BACKLOG_GROWTH_RATE, ratio);
3013
- }
3014
3084
  /**
3015
3085
  * Compute urgency score for a review card.
3016
3086
  *
3017
- * Three factors:
3087
+ * Two factors:
3018
3088
  * 1. Relative overdueness = hoursOverdue / intervalHours
3019
3089
  * - 2 days overdue on 3-day interval = 0.67 (urgent)
3020
3090
  * - 2 days overdue on 180-day interval = 0.01 (not urgent)
@@ -3024,20 +3094,14 @@ var init_srs = __esm({
3024
3094
  * - 30 days (720h) → ~0.56
3025
3095
  * - 180 days → ~0.30
3026
3096
  *
3027
- * 3. Backlog pressure = global *multiplier* when review backlog exceeds the
3028
- * healthy threshold (×1.0 healthy → exponential growth, uncapped, above it).
3029
- *
3030
- * Combined: (base 0.5 + urgency factors * 0.45) × backlog multiplier.
3031
- * Per-card range before pressure: ~0.57–0.95. NOT clamped to 1.0 — under a
3032
- * heavy backlog reviews scale onto the open scale to compete with (and exceed)
3033
- * new cards; there's no ceiling at all now, so a bad enough backlog always
3034
- * wins eventually — self-regulating because winning slots depletes dueCount.
3097
+ * Combined: base 0.5 + urgency factors * 0.45, so ~0.57–0.95 per card.
3098
+ * Backlog pressure is applied later, by the regulator stage, which can lift
3099
+ * reviews onto the open scale above new cards (see regulators.ts).
3035
3100
  *
3036
3101
  * @param review - The scheduled card to score
3037
3102
  * @param now - Current time
3038
- * @param backlogMultiplier - Pre-computed backlog multiplier (>= 1.0, unbounded)
3039
3103
  */
3040
- computeUrgencyScore(review, now, backlogMultiplier) {
3104
+ computeUrgencyScore(review, now) {
3041
3105
  const scheduledAt = moment.utc(review.scheduledAt);
3042
3106
  const due = moment.utc(review.reviewTime);
3043
3107
  const intervalHours = Math.max(1, due.diff(scheduledAt, "hours"));
@@ -3046,20 +3110,16 @@ var init_srs = __esm({
3046
3110
  const recencyFactor = 0.3 + 0.7 * Math.exp(-intervalHours / 720);
3047
3111
  const overdueContribution = Math.min(1, Math.max(0, relativeOverdue));
3048
3112
  const urgency = overdueContribution * 0.5 + recencyFactor * 0.5;
3049
- const baseScore = 0.5 + urgency * 0.45;
3050
- const score = baseScore * backlogMultiplier;
3113
+ const score = 0.5 + urgency * 0.45;
3051
3114
  const reasonParts = [
3052
3115
  `${Math.round(hoursOverdue)}h overdue`,
3053
3116
  `interval: ${Math.round(intervalHours)}h`,
3054
3117
  `relative: ${relativeOverdue.toFixed(2)}`,
3055
3118
  `recency: ${recencyFactor.toFixed(2)}`
3056
3119
  ];
3057
- if (backlogMultiplier > 1) {
3058
- reasonParts.push(`backlog: \xD7${backlogMultiplier.toFixed(2)}`);
3059
- }
3060
3120
  reasonParts.push("review");
3061
3121
  const reason = reasonParts.join(", ");
3062
- return { score, reason };
3122
+ return { score, urgency, reason };
3063
3123
  }
3064
3124
  };
3065
3125
  }
@@ -3114,6 +3174,8 @@ var init_WeightedFilter = __esm({
3114
3174
  init_contentNavigationStrategy();
3115
3175
  WeightedFilter = class {
3116
3176
  name;
3177
+ kind;
3178
+ liveOnly;
3117
3179
  inner;
3118
3180
  learnable;
3119
3181
  staticWeight;
@@ -3121,6 +3183,8 @@ var init_WeightedFilter = __esm({
3121
3183
  constructor(inner, learnable = DEFAULT_LEARNABLE_WEIGHT, staticWeight = false, strategyId) {
3122
3184
  this.inner = inner;
3123
3185
  this.name = inner.name;
3186
+ this.kind = inner.kind;
3187
+ this.liveOnly = inner.liveOnly;
3124
3188
  this.learnable = learnable;
3125
3189
  this.staticWeight = staticWeight;
3126
3190
  this.strategyId = strategyId;
@@ -3185,58 +3249,141 @@ var init_WeightedFilter = __esm({
3185
3249
  // src/core/navigators/filters/eloDistance.ts
3186
3250
  var eloDistance_exports = {};
3187
3251
  __export(eloDistance_exports, {
3188
- DEFAULT_HALF_LIFE: () => DEFAULT_HALF_LIFE,
3189
- DEFAULT_MAX_MULTIPLIER: () => DEFAULT_MAX_MULTIPLIER,
3190
- DEFAULT_MIN_MULTIPLIER: () => DEFAULT_MIN_MULTIPLIER,
3191
- createEloDistanceFilter: () => createEloDistanceFilter
3252
+ DEFAULT_ELO_DISTANCE_CONFIG: () => DEFAULT_ELO_DISTANCE_CONFIG,
3253
+ createEloDistanceFilter: () => createEloDistanceFilter,
3254
+ default: () => EloDistanceFilter,
3255
+ tagAwareGap: () => tagAwareGap
3192
3256
  });
3193
3257
  function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
3194
3258
  const normalizedDistance = distance / halfLife;
3195
3259
  const decay = Math.exp(-(normalizedDistance * normalizedDistance));
3196
3260
  return minMultiplier + (maxMultiplier - minMultiplier) * decay;
3197
3261
  }
3262
+ function resolveConfig(config) {
3263
+ return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };
3264
+ }
3265
+ function tagAwareGap(cardTags, cardElo, userElo, minTagCount) {
3266
+ const globalGap = cardElo.global.score - userElo.global.score;
3267
+ const tags = [];
3268
+ for (const tag of cardTags) {
3269
+ const user = userElo.tags[tag];
3270
+ if (!user || user.score === COUNT_ONLY_SENTINEL || user.count < minTagCount) continue;
3271
+ const card = cardElo.tags[tag]?.score ?? cardElo.global.score;
3272
+ tags.push({
3273
+ tag,
3274
+ gap: card - user.score,
3275
+ weight: user.count / (user.count + TAG_CONFIDENCE_HALF)
3276
+ });
3277
+ }
3278
+ if (tags.length === 0) return { gap: globalGap, globalGap, tags };
3279
+ const total = tags.reduce((w, t) => w + t.weight, 0);
3280
+ const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;
3281
+ const lambda = total / (total + 1);
3282
+ return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };
3283
+ }
3284
+ function tagReason(tags, globalGap) {
3285
+ 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(", ");
3286
+ const more = tags.length > 3 ? `, +${tags.length - 3} more` : "";
3287
+ return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? "+" : ""}${Math.round(globalGap)})`;
3288
+ }
3289
+ async function applyEloDistance(cards, context, config, source) {
3290
+ const { course, userElo, userCourseElo } = context;
3291
+ const { halfLife, minMultiplier, maxMultiplier } = config;
3292
+ const tagAware = config.tagAware && userCourseElo !== void 0;
3293
+ const missing = cards.filter((c) => tagAware || c.cardElo === void 0).map((c) => c.cardId);
3294
+ const fetched = /* @__PURE__ */ new Map();
3295
+ if (missing.length > 0) {
3296
+ const elos = await course.getCardEloData(missing);
3297
+ missing.forEach((id, i) => {
3298
+ if (elos[i]) fetched.set(id, elos[i]);
3299
+ });
3300
+ }
3301
+ return cards.map((card) => {
3302
+ const full = fetched.get(card.cardId);
3303
+ const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;
3304
+ let distance = Math.abs(cardElo - userElo);
3305
+ let how = "";
3306
+ if (tagAware && full) {
3307
+ const t = tagAwareGap(card.tags ?? [], full, userCourseElo, config.minTagCount);
3308
+ distance = Math.abs(t.gap);
3309
+ if (t.tags.length > 0) how = tagReason(t.tags, t.globalGap);
3310
+ }
3311
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
3312
+ const newScore = card.score * multiplier;
3313
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
3314
+ return {
3315
+ ...card,
3316
+ cardElo,
3317
+ score: newScore,
3318
+ provenance: [
3319
+ ...card.provenance,
3320
+ {
3321
+ strategy: "eloDistance",
3322
+ strategyName: source.name,
3323
+ strategyId: source.strategyId,
3324
+ action,
3325
+ score: newScore,
3326
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} \u2192 ${multiplier.toFixed(2)}x`
3327
+ }
3328
+ ]
3329
+ };
3330
+ });
3331
+ }
3198
3332
  function createEloDistanceFilter(config) {
3199
- const halfLife = config?.halfLife ?? DEFAULT_HALF_LIFE;
3200
- const minMultiplier = config?.minMultiplier ?? DEFAULT_MIN_MULTIPLIER;
3201
- const maxMultiplier = config?.maxMultiplier ?? DEFAULT_MAX_MULTIPLIER;
3333
+ const resolved = resolveConfig(config);
3334
+ const source = { name: "ELO Distance Filter", strategyId: "ELO_DISTANCE_FILTER" };
3202
3335
  return {
3203
- name: "ELO Distance Filter",
3204
- async transform(cards, context) {
3205
- const { course, userElo } = context;
3206
- const cardIds = cards.map((c) => c.cardId);
3207
- const cardElos = await course.getCardEloData(cardIds);
3208
- return cards.map((card, i) => {
3209
- const cardElo = cardElos[i]?.global?.score ?? 1e3;
3210
- const distance = Math.abs(cardElo - userElo);
3211
- const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
3212
- const newScore = card.score * multiplier;
3213
- const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
3214
- return {
3215
- ...card,
3216
- score: newScore,
3217
- provenance: [
3218
- ...card.provenance,
3219
- {
3220
- strategy: "eloDistance",
3221
- strategyName: "ELO Distance Filter",
3222
- strategyId: "ELO_DISTANCE_FILTER",
3223
- action,
3224
- score: newScore,
3225
- reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)}) \u2192 ${multiplier.toFixed(2)}x`
3226
- }
3227
- ]
3228
- };
3229
- });
3230
- }
3336
+ name: source.name,
3337
+ kind: "signal",
3338
+ liveOnly: true,
3339
+ transform: (cards, context) => applyEloDistance(cards, context, resolved, source)
3231
3340
  };
3232
3341
  }
3233
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
3342
+ var DEFAULT_ELO_DISTANCE_CONFIG, TAG_CONFIDENCE_HALF, COUNT_ONLY_SENTINEL, DEFAULT_CARD_ELO, EloDistanceFilter;
3234
3343
  var init_eloDistance = __esm({
3235
3344
  "src/core/navigators/filters/eloDistance.ts"() {
3236
3345
  "use strict";
3237
- DEFAULT_HALF_LIFE = 200;
3238
- DEFAULT_MIN_MULTIPLIER = 0.3;
3239
- DEFAULT_MAX_MULTIPLIER = 1;
3346
+ init_navigators();
3347
+ DEFAULT_ELO_DISTANCE_CONFIG = {
3348
+ halfLife: 300,
3349
+ minMultiplier: 0.05,
3350
+ maxMultiplier: 1,
3351
+ tagAware: true,
3352
+ minTagCount: 3
3353
+ };
3354
+ TAG_CONFIDENCE_HALF = 10;
3355
+ COUNT_ONLY_SENTINEL = -1;
3356
+ DEFAULT_CARD_ELO = 1e3;
3357
+ EloDistanceFilter = class _EloDistanceFilter extends ContentNavigator {
3358
+ name;
3359
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3360
+ static kind = "signal";
3361
+ kind = _EloDistanceFilter.kind;
3362
+ liveOnly = true;
3363
+ config;
3364
+ constructor(user, course, strategyData) {
3365
+ super(user, course, strategyData);
3366
+ this.name = strategyData.name || "ELO Distance";
3367
+ let parsed;
3368
+ try {
3369
+ parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : void 0;
3370
+ } catch {
3371
+ parsed = void 0;
3372
+ }
3373
+ this.config = resolveConfig(parsed);
3374
+ }
3375
+ transform(cards, context) {
3376
+ return applyEloDistance(cards, context, this.config, {
3377
+ name: this.name,
3378
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-eloDistance-default"
3379
+ });
3380
+ }
3381
+ async getWeightedCards(_limit) {
3382
+ throw new Error(
3383
+ "EloDistanceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
3384
+ );
3385
+ }
3386
+ };
3240
3387
  }
3241
3388
  });
3242
3389
 
@@ -3253,10 +3400,13 @@ var init_hierarchyDefinition = __esm({
3253
3400
  init_navigators();
3254
3401
  init_logger();
3255
3402
  DEFAULT_MIN_COUNT2 = 3;
3256
- HierarchyDefinitionNavigator = class extends ContentNavigator {
3403
+ HierarchyDefinitionNavigator = class _HierarchyDefinitionNavigator extends ContentNavigator {
3257
3404
  config;
3258
3405
  /** Human-readable name for CardFilter interface */
3259
3406
  name;
3407
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3408
+ static kind = "gate";
3409
+ kind = _HierarchyDefinitionNavigator.kind;
3260
3410
  constructor(user, course, strategyData) {
3261
3411
  super(user, course, strategyData);
3262
3412
  this.config = this.parseConfig(strategyData.serializedData);
@@ -3523,10 +3673,13 @@ var init_userTagPreference = __esm({
3523
3673
  "src/core/navigators/filters/userTagPreference.ts"() {
3524
3674
  "use strict";
3525
3675
  init_navigators();
3526
- UserTagPreferenceFilter = class extends ContentNavigator {
3676
+ UserTagPreferenceFilter = class _UserTagPreferenceFilter extends ContentNavigator {
3527
3677
  _strategyData;
3528
3678
  /** Human-readable name for CardFilter interface */
3529
3679
  name;
3680
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3681
+ static kind = "signal";
3682
+ kind = _UserTagPreferenceFilter.kind;
3530
3683
  constructor(user, course, strategyData) {
3531
3684
  super(user, course, strategyData);
3532
3685
  this._strategyData = strategyData;
@@ -3636,6 +3789,7 @@ var init_userTagPreference = __esm({
3636
3789
  // src/core/navigators/filters/index.ts
3637
3790
  var filters_exports = {};
3638
3791
  __export(filters_exports, {
3792
+ EloDistanceFilter: () => EloDistanceFilter,
3639
3793
  UserTagPreferenceFilter: () => UserTagPreferenceFilter,
3640
3794
  createEloDistanceFilter: () => createEloDistanceFilter
3641
3795
  });
@@ -3674,10 +3828,13 @@ var init_interferenceMitigator = __esm({
3674
3828
  DEFAULT_MIN_COUNT3 = 10;
3675
3829
  DEFAULT_MIN_ELAPSED_DAYS = 3;
3676
3830
  DEFAULT_INTERFERENCE_DECAY = 0.8;
3677
- InterferenceMitigatorNavigator = class extends ContentNavigator {
3831
+ InterferenceMitigatorNavigator = class _InterferenceMitigatorNavigator extends ContentNavigator {
3678
3832
  config;
3679
3833
  /** Human-readable name for CardFilter interface */
3680
3834
  name;
3835
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3836
+ static kind = "signal";
3837
+ kind = _InterferenceMitigatorNavigator.kind;
3681
3838
  /** Precomputed map: tag -> set of { partner, decay } it interferes with */
3682
3839
  interferenceMap;
3683
3840
  constructor(user, course, strategyData) {
@@ -3893,10 +4050,13 @@ var init_relativePriority = __esm({
3893
4050
  DEFAULT_PRIORITY = 0.5;
3894
4051
  DEFAULT_PRIORITY_INFLUENCE = 0.5;
3895
4052
  DEFAULT_COMBINE_MODE = "max";
3896
- RelativePriorityNavigator = class extends ContentNavigator {
4053
+ RelativePriorityNavigator = class _RelativePriorityNavigator extends ContentNavigator {
3897
4054
  config;
3898
4055
  /** Human-readable name for CardFilter interface */
3899
4056
  name;
4057
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
4058
+ static kind = "signal";
4059
+ kind = _RelativePriorityNavigator.kind;
3900
4060
  constructor(user, course, strategyData) {
3901
4061
  super(user, course, strategyData);
3902
4062
  this.config = this.parseConfig(strategyData.serializedData);
@@ -4550,6 +4710,8 @@ var init_Pipeline = __esm({
4550
4710
  init_orchestration();
4551
4711
  init_PipelineDebugger();
4552
4712
  init_diversityRerank();
4713
+ init_regulators();
4714
+ init_SrsDebugger();
4553
4715
  VERBOSE_RESULTS = true;
4554
4716
  Pipeline = class extends ContentNavigator {
4555
4717
  generator;
@@ -4575,6 +4737,13 @@ var init_Pipeline = __esm({
4575
4737
  * getWeightedCards() call, then cleared.
4576
4738
  */
4577
4739
  _ephemeralHints = null;
4740
+ /**
4741
+ * The intake valve's clock (see regulators.ts), loaded from strategy state on
4742
+ * first use and kept in memory. Writes are chained so a presentation and a
4743
+ * run can't race each other's revision.
4744
+ */
4745
+ _intakeClock = null;
4746
+ _intakeClockWrite = Promise.resolve();
4578
4747
  /**
4579
4748
  * Create a new pipeline.
4580
4749
  *
@@ -4649,13 +4818,12 @@ var init_Pipeline = __esm({
4649
4818
  }
4650
4819
  }
4651
4820
  generatorSummaries = Array.from(genMap.entries()).map(([name, data]) => {
4652
- const newCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("new card"));
4653
- const reviewCards = data.cards.filter((c) => c.provenance[0]?.reason?.includes("review"));
4821
+ const reviewCount = data.cards.filter((c) => c.reviewID).length;
4654
4822
  return {
4655
4823
  name,
4656
4824
  cardCount: data.cards.length,
4657
- newCount: newCards.length,
4658
- reviewCount: reviewCards.length,
4825
+ newCount: data.cards.length - reviewCount,
4826
+ reviewCount,
4659
4827
  topScore: Math.max(...data.cards.map((c) => c.score), 0)
4660
4828
  };
4661
4829
  });
@@ -4691,19 +4859,24 @@ var init_Pipeline = __esm({
4691
4859
  cards.filter((c) => c.provenance.some((p) => p.strategy === "prescribed")).map((c) => c.cardId)
4692
4860
  );
4693
4861
  const filterImpacts = [];
4862
+ const generatedScores = new Map(cards.map((c) => [c.cardId, c.score]));
4863
+ const gated = /* @__PURE__ */ new Set();
4694
4864
  for (const filter of this.filters) {
4695
4865
  const beforeCount = cards.length;
4696
4866
  const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));
4697
4867
  cards = await filter.transform(cards, context);
4698
4868
  let boosted = 0, penalized = 0, passed = 0;
4699
4869
  const removed = beforeCount - cards.length;
4870
+ const kind = filter.kind ?? "gate";
4700
4871
  for (const card of cards) {
4701
4872
  const before = beforeScores.get(card.cardId) ?? 0;
4702
4873
  if (card.score > before) boosted++;
4703
- else if (card.score < before) penalized++;
4704
- else passed++;
4874
+ else if (card.score < before) {
4875
+ penalized++;
4876
+ if (kind === "gate") gated.add(card.cardId);
4877
+ } else passed++;
4705
4878
  }
4706
- filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
4879
+ filterImpacts.push({ name: filter.name, kind, boosted, penalized, passed, removed });
4707
4880
  if (prescribedIds.size > 0) {
4708
4881
  const survivingIds = new Set(cards.map((c) => c.cardId));
4709
4882
  const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));
@@ -4719,6 +4892,7 @@ var init_Pipeline = __esm({
4719
4892
  }
4720
4893
  const scoredCards = cards;
4721
4894
  cards = cards.filter((c) => c.score > 0);
4895
+ const regulators = await this.regulate(cards, generatedScores, gated);
4722
4896
  const hints = this._ephemeralHints;
4723
4897
  if (hints) {
4724
4898
  this._ephemeralHints = null;
@@ -4755,7 +4929,8 @@ var init_Pipeline = __esm({
4755
4929
  result,
4756
4930
  context.userElo,
4757
4931
  hints ?? void 0,
4758
- scoredCards
4932
+ scoredCards,
4933
+ regulators
4759
4934
  );
4760
4935
  captureRun(report);
4761
4936
  } catch (e) {
@@ -4934,6 +5109,77 @@ var init_Pipeline = __esm({
4934
5109
  logger.info(`[Pipeline] Hints applied: ${beforeCount} \u2192 ${cards.length} cards`);
4935
5110
  return cards;
4936
5111
  }
5112
+ /**
5113
+ * The regulator stage: measure each class's pressure and scale it.
5114
+ *
5115
+ * - Review mass: every due review's SRS urgency times the filters' net
5116
+ * effect on it.
5117
+ * - Intake: servable hours since a new card was presented, applied only to
5118
+ * eligible new cards (no gate penalized them). With none eligible, the
5119
+ * clock freezes.
5120
+ *
5121
+ * Mutates `cards` in place; returns the readings for the run report.
5122
+ */
5123
+ async regulate(cards, generatedScores, gated) {
5124
+ const config = DEFAULT_REGULATOR_CONFIG;
5125
+ const reviews = cards.filter((c) => c.reviewID);
5126
+ const newCards = cards.filter((c) => !c.reviewID);
5127
+ const eligibleNew = newCards.filter((c) => !gated.has(c.cardId));
5128
+ const mass = reviewMassReading(reviews, generatedScores, config.reviewMass);
5129
+ applyReading(reviews, mass);
5130
+ noteReviewPressure(this.course.getCourseID(), {
5131
+ mass: mass.urgency,
5132
+ healthyMass: config.reviewMass.healthyMass,
5133
+ rate: config.reviewMass.rate,
5134
+ multiplier: mass.multiplier
5135
+ });
5136
+ const now = Date.now();
5137
+ const clock = await this.loadIntakeClock(now);
5138
+ const stepped = stepIntakeClock(clock, now, eligibleNew.length);
5139
+ if (stepped !== clock) this.saveIntakeClock(stepped);
5140
+ const intake = intakeReading(
5141
+ stepped,
5142
+ now,
5143
+ { eligibleNew: eligibleNew.length, newCandidates: newCards.length },
5144
+ config.intake
5145
+ );
5146
+ applyReading(eligibleNew, intake);
5147
+ logger.info(
5148
+ `[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)}`
5149
+ );
5150
+ return [mass, intake];
5151
+ }
5152
+ /**
5153
+ * A card was presented. A new card's first presentation discharges the
5154
+ * intake valve: its clock restarts. Called by the SessionController.
5155
+ */
5156
+ notePresented(card) {
5157
+ if (card.status !== "new" || card.courseId !== this.course?.getCourseID()) return;
5158
+ this.saveIntakeClock(resetIntakeClock(Date.now()));
5159
+ }
5160
+ async loadIntakeClock(nowMs) {
5161
+ if (this._intakeClock) return this._intakeClock;
5162
+ let stored = null;
5163
+ try {
5164
+ stored = await this.user.getStrategyState(
5165
+ this.course.getCourseID(),
5166
+ INTAKE_CLOCK_KEY
5167
+ );
5168
+ } catch (e) {
5169
+ logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`);
5170
+ }
5171
+ if (stored) {
5172
+ this._intakeClock = stored;
5173
+ } else {
5174
+ this.saveIntakeClock(resetIntakeClock(nowMs));
5175
+ }
5176
+ return this._intakeClock;
5177
+ }
5178
+ saveIntakeClock(state) {
5179
+ this._intakeClock = state;
5180
+ const courseId = this.course.getCourseID();
5181
+ 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}`));
5182
+ }
4937
5183
  /**
4938
5184
  * Build shared context for generator and filters.
4939
5185
  *
@@ -4944,10 +5190,11 @@ var init_Pipeline = __esm({
4944
5190
  */
4945
5191
  async buildContext() {
4946
5192
  let userElo = 1e3;
5193
+ let userCourseElo;
4947
5194
  try {
4948
5195
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
4949
- const courseElo = toCourseElo5(courseReg.elo);
4950
- userElo = courseElo.global.score;
5196
+ userCourseElo = toCourseElo5(courseReg.elo);
5197
+ userElo = userCourseElo.global.score;
4951
5198
  } catch (e) {
4952
5199
  logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
4953
5200
  }
@@ -4959,6 +5206,7 @@ var init_Pipeline = __esm({
4959
5206
  user: this.user,
4960
5207
  course: this.course,
4961
5208
  userElo,
5209
+ ...userCourseElo ? { userCourseElo } : {},
4962
5210
  orchestration
4963
5211
  };
4964
5212
  }
@@ -5072,7 +5320,7 @@ var init_Pipeline = __esm({
5072
5320
  cards = await this.hydrateTags(cards);
5073
5321
  const fullPool = cards.slice();
5074
5322
  const context = await this.buildContext();
5075
- for (const filter of this.filters) {
5323
+ for (const filter of this.forecastFilters()) {
5076
5324
  cards = await filter.transform(cards, context);
5077
5325
  }
5078
5326
  if (opts?.hints) {
@@ -5091,6 +5339,14 @@ var init_Pipeline = __esm({
5091
5339
  cards.sort((a, b) => b.score - a.score);
5092
5340
  return opts?.limit ? cards.slice(0, opts.limit) : cards;
5093
5341
  }
5342
+ /**
5343
+ * The filters a forecast or card-space scan applies. Those start every card at
5344
+ * 1.0 without a generator, so they skip `liveOnly` filters (ELO distance),
5345
+ * which only make sense against generator scores.
5346
+ */
5347
+ forecastFilters() {
5348
+ return this.filters.filter((f) => !f.liveOnly);
5349
+ }
5094
5350
  /**
5095
5351
  * Scan every card in the course through the filter chain and report
5096
5352
  * how many are "well indicated" (score >= threshold) for the current user.
@@ -5112,7 +5368,7 @@ var init_Pipeline = __esm({
5112
5368
  cards = await this.hydrateTags(cards);
5113
5369
  const context = await this.buildContext();
5114
5370
  const filterBreakdown = [];
5115
- for (const filter of this.filters) {
5371
+ for (const filter of this.forecastFilters()) {
5116
5372
  cards = await filter.transform(cards, context);
5117
5373
  const wi = cards.filter((c) => c.score >= THRESHOLD).length;
5118
5374
  filterBreakdown.push({ name: filter.name, wellIndicated: wi });
@@ -5176,6 +5432,7 @@ var init_Pipeline = __esm({
5176
5432
  // src/core/navigators/defaults.ts
5177
5433
  var defaults_exports = {};
5178
5434
  __export(defaults_exports, {
5435
+ createDefaultEloDistanceStrategy: () => createDefaultEloDistanceStrategy,
5179
5436
  createDefaultEloStrategy: () => createDefaultEloStrategy,
5180
5437
  createDefaultPipeline: () => createDefaultPipeline,
5181
5438
  createDefaultSrsStrategy: () => createDefaultSrsStrategy
@@ -5202,12 +5459,28 @@ function createDefaultSrsStrategy(courseId) {
5202
5459
  serializedData: ""
5203
5460
  };
5204
5461
  }
5462
+ function createDefaultEloDistanceStrategy(courseId) {
5463
+ return {
5464
+ _id: "NAVIGATION_STRATEGY-eloDistance-default",
5465
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
5466
+ name: "ELO Distance (default)",
5467
+ description: "Scales every candidate, new or review, by its distance from the learner's ELO",
5468
+ implementingClass: "eloDistance" /* ELO_DISTANCE */,
5469
+ course: courseId,
5470
+ // Explicit, though the filter would default to it anyway: views show what runs.
5471
+ serializedData: JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG)
5472
+ };
5473
+ }
5205
5474
  function createDefaultPipeline(user, course) {
5206
5475
  const courseId = course.getCourseID();
5207
5476
  const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
5208
5477
  const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
5209
5478
  const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
5210
- const eloDistanceFilter = createEloDistanceFilter();
5479
+ const eloDistanceFilter = new EloDistanceFilter(
5480
+ user,
5481
+ course,
5482
+ createDefaultEloDistanceStrategy(courseId)
5483
+ );
5211
5484
  return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
5212
5485
  }
5213
5486
  var init_defaults = __esm({
@@ -5223,6 +5496,131 @@ var init_defaults = __esm({
5223
5496
  }
5224
5497
  });
5225
5498
 
5499
+ // src/core/navigators/pipelinePlan.ts
5500
+ var pipelinePlan_exports = {};
5501
+ __export(pipelinePlan_exports, {
5502
+ PIPELINE_STAGES: () => PIPELINE_STAGES,
5503
+ planPipeline: () => planPipeline
5504
+ });
5505
+ function planned(strategy, role, origin) {
5506
+ const kind = role === "filter" /* FILTER */ ? getRegisteredFilterKind(strategy.implementingClass) : void 0;
5507
+ return {
5508
+ role,
5509
+ origin,
5510
+ name: strategy.name,
5511
+ implementingClass: strategy.implementingClass,
5512
+ strategy,
5513
+ ...kind ? { kind } : {}
5514
+ };
5515
+ }
5516
+ function planPipeline(strategies, courseId) {
5517
+ if (strategies.length === 0) {
5518
+ return {
5519
+ kind: "default",
5520
+ generators: [
5521
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline"),
5522
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline")
5523
+ ],
5524
+ filters: [
5525
+ planned(
5526
+ createDefaultEloDistanceStrategy(courseId),
5527
+ "filter" /* FILTER */,
5528
+ "default-pipeline"
5529
+ )
5530
+ ],
5531
+ skipped: [],
5532
+ warnings: [],
5533
+ notes: [],
5534
+ regulators: DEFAULT_REGULATOR_CONFIG
5535
+ };
5536
+ }
5537
+ const generators = [];
5538
+ const filters = [];
5539
+ const skipped = [];
5540
+ const warnings = [];
5541
+ for (const s of strategies) {
5542
+ if (isGenerator(s.implementingClass)) {
5543
+ generators.push(planned(s, "generator" /* GENERATOR */, "strategy-doc"));
5544
+ } else if (isFilter(s.implementingClass)) {
5545
+ filters.push(planned(s, "filter" /* FILTER */, "strategy-doc"));
5546
+ } else {
5547
+ skipped.push({ strategy: s, reason: "not a registered generator or filter" });
5548
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
5549
+ }
5550
+ }
5551
+ const declared = new Set(generators.map((g) => g.implementingClass));
5552
+ if (!declared.has(createDefaultEloStrategy(courseId).implementingClass)) {
5553
+ generators.push(
5554
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5555
+ );
5556
+ }
5557
+ if (!declared.has(createDefaultSrsStrategy(courseId).implementingClass)) {
5558
+ generators.push(
5559
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5560
+ );
5561
+ }
5562
+ const eloDistance = createDefaultEloDistanceStrategy(courseId);
5563
+ if (!filters.some((f) => f.implementingClass === eloDistance.implementingClass)) {
5564
+ filters.push(planned(eloDistance, "filter" /* FILTER */, "assembler-default"));
5565
+ }
5566
+ filters.sort((a, b) => a.name.localeCompare(b.name));
5567
+ return {
5568
+ kind: "assembled",
5569
+ generators,
5570
+ filters,
5571
+ skipped,
5572
+ warnings,
5573
+ notes: [],
5574
+ regulators: DEFAULT_REGULATOR_CONFIG
5575
+ };
5576
+ }
5577
+ var PIPELINE_STAGES;
5578
+ var init_pipelinePlan = __esm({
5579
+ "src/core/navigators/pipelinePlan.ts"() {
5580
+ "use strict";
5581
+ init_navigators();
5582
+ init_regulators();
5583
+ init_defaults();
5584
+ PIPELINE_STAGES = [
5585
+ {
5586
+ key: "generate",
5587
+ title: "Generate",
5588
+ 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."
5589
+ },
5590
+ {
5591
+ key: "filter",
5592
+ title: "Filter",
5593
+ 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."
5594
+ },
5595
+ {
5596
+ key: "drop-zero",
5597
+ title: "Drop zero scores",
5598
+ summary: "Candidates whose score reached 0 leave the pool."
5599
+ },
5600
+ {
5601
+ key: "regulate",
5602
+ title: "Regulate",
5603
+ 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."
5604
+ },
5605
+ {
5606
+ key: "hints",
5607
+ title: "Apply hints",
5608
+ 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."
5609
+ },
5610
+ {
5611
+ key: "diversity",
5612
+ title: "Diversity re-rank",
5613
+ 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."
5614
+ },
5615
+ {
5616
+ key: "select",
5617
+ title: "Select",
5618
+ summary: "Highest scores first, up to the run's limit. The session mixes them into its supply queue."
5619
+ }
5620
+ ];
5621
+ }
5622
+ });
5623
+
5226
5624
  // src/core/navigators/PipelineAssembler.ts
5227
5625
  var PipelineAssembler_exports = {};
5228
5626
  __export(PipelineAssembler_exports, {
@@ -5237,16 +5635,16 @@ var init_PipelineAssembler = __esm({
5237
5635
  init_Pipeline();
5238
5636
  init_logger();
5239
5637
  init_CompositeGenerator();
5240
- init_defaults();
5638
+ init_pipelinePlan();
5241
5639
  PipelineAssembler = class {
5242
5640
  /**
5243
5641
  * Assembles a navigation pipeline from strategy documents.
5244
5642
  *
5245
- * 1. Separates into generators and filters by role
5246
- * 2. Validates at least one generator exists (or creates default ELO)
5247
- * 3. Instantiates generators - wraps multiple in CompositeGenerator
5248
- * 4. Instantiates filters
5249
- * 5. Returns Pipeline(generator, filters)
5643
+ * 1. Plans: classifies by role, adds default ELO/SRS and ELO distance, orders filters
5644
+ * (`planPipeline`)
5645
+ * 2. Instantiates generators - wraps multiple in CompositeGenerator
5646
+ * 3. Instantiates filters
5647
+ * 4. Returns Pipeline(generator, filters)
5250
5648
  *
5251
5649
  * @param input - Strategy documents plus user/course interfaces
5252
5650
  * @returns Assembled pipeline and any warnings
@@ -5262,28 +5660,17 @@ var init_PipelineAssembler = __esm({
5262
5660
  warnings
5263
5661
  };
5264
5662
  }
5265
- const generatorStrategies = [];
5266
- const filterStrategies = [];
5267
- for (const s of strategies) {
5268
- if (isGenerator(s.implementingClass)) {
5269
- generatorStrategies.push(s);
5270
- } else if (isFilter(s.implementingClass)) {
5271
- filterStrategies.push(s);
5272
- } else {
5273
- warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
5663
+ const plan = planPipeline(strategies, course.getCourseID());
5664
+ warnings.push(...plan.warnings);
5665
+ for (const n of [...plan.generators, ...plan.filters]) {
5666
+ if (n.origin === "assembler-default") {
5667
+ logger.debug(
5668
+ `[PipelineAssembler] No ${n.implementingClass} ${n.role} configured, adding default`
5669
+ );
5274
5670
  }
5275
5671
  }
5276
- const courseId = course.getCourseID();
5277
- const hasElo = generatorStrategies.some((s) => s.implementingClass === "elo" /* ELO */);
5278
- const hasSrs = generatorStrategies.some((s) => s.implementingClass === "srs" /* SRS */);
5279
- if (!hasElo) {
5280
- logger.debug("[PipelineAssembler] No ELO generator configured, adding default");
5281
- generatorStrategies.push(createDefaultEloStrategy(courseId));
5282
- }
5283
- if (!hasSrs) {
5284
- logger.debug("[PipelineAssembler] No SRS generator configured, adding default");
5285
- generatorStrategies.push(createDefaultSrsStrategy(courseId));
5286
- }
5672
+ const generatorStrategies = plan.generators.map((g) => g.strategy);
5673
+ const sortedFilterStrategies = plan.filters.map((f) => f.strategy);
5287
5674
  if (generatorStrategies.length === 0) {
5288
5675
  warnings.push("No generator strategy found");
5289
5676
  return {
@@ -5305,9 +5692,6 @@ var init_PipelineAssembler = __esm({
5305
5692
  generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
5306
5693
  }
5307
5694
  const filters = [];
5308
- const sortedFilterStrategies = [...filterStrategies].sort(
5309
- (a, b) => a.name.localeCompare(b.name)
5310
- );
5311
5695
  for (const filterStrategy of sortedFilterStrategies) {
5312
5696
  try {
5313
5697
  const nav = await ContentNavigator.create(user, course, filterStrategy);
@@ -5375,7 +5759,9 @@ var init_3 = __esm({
5375
5759
  "./generators/prescribed.ts": () => Promise.resolve().then(() => (init_prescribed(), prescribed_exports)),
5376
5760
  "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
5377
5761
  "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
5378
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
5762
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
5763
+ "./pipelinePlan.ts": () => Promise.resolve().then(() => (init_pipelinePlan(), pipelinePlan_exports)),
5764
+ "./regulators.ts": () => Promise.resolve().then(() => (init_regulators(), regulators_exports))
5379
5765
  });
5380
5766
  }
5381
5767
  });
@@ -5396,6 +5782,7 @@ __export(navigators_exports, {
5396
5782
  drainCapturedRuns: () => drainCapturedRuns,
5397
5783
  getActivePipeline: () => getActivePipeline,
5398
5784
  getCardOrigin: () => getCardOrigin,
5785
+ getRegisteredFilterKind: () => getRegisteredFilterKind,
5399
5786
  getRegisteredNavigator: () => getRegisteredNavigator,
5400
5787
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
5401
5788
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
@@ -5424,6 +5811,10 @@ function hasRegisteredNavigator(implementingClass) {
5424
5811
  function getRegisteredNavigatorRole(implementingClass) {
5425
5812
  return navigatorRegistry.get(implementingClass)?.role;
5426
5813
  }
5814
+ function getRegisteredFilterKind(implementingClass) {
5815
+ const ctor = navigatorRegistry.get(implementingClass)?.constructor;
5816
+ return ctor?.kind;
5817
+ }
5427
5818
  function getRegisteredNavigatorNames() {
5428
5819
  return Array.from(navigatorRegistry.keys());
5429
5820
  }
@@ -5441,17 +5832,20 @@ async function initializeNavigatorRegistry() {
5441
5832
  hierarchyModule,
5442
5833
  interferenceModule,
5443
5834
  relativePriorityModule,
5444
- userTagPreferenceModule
5835
+ userTagPreferenceModule,
5836
+ eloDistanceModule
5445
5837
  ] = await Promise.all([
5446
5838
  Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
5447
5839
  Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
5448
5840
  Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
5449
- Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
5841
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
5842
+ Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports))
5450
5843
  ]);
5451
5844
  registerNavigator("hierarchyDefinition", hierarchyModule.default);
5452
5845
  registerNavigator("interferenceMitigator", interferenceModule.default);
5453
5846
  registerNavigator("relativePriority", relativePriorityModule.default);
5454
5847
  registerNavigator("userTagPreference", userTagPreferenceModule.default);
5848
+ registerNavigator("eloDistance", eloDistanceModule.default);
5455
5849
  logger.debug(
5456
5850
  `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
5457
5851
  );
@@ -5499,6 +5893,7 @@ var init_navigators = __esm({
5499
5893
  Navigators2["INTERFERENCE"] = "interferenceMitigator";
5500
5894
  Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
5501
5895
  Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
5896
+ Navigators2["ELO_DISTANCE"] = "eloDistance";
5502
5897
  return Navigators2;
5503
5898
  })(Navigators || {});
5504
5899
  NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
@@ -5513,7 +5908,8 @@ var init_navigators = __esm({
5513
5908
  ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
5514
5909
  ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
5515
5910
  ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
5516
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
5911
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */,
5912
+ ["eloDistance" /* ELO_DISTANCE */]: "filter" /* FILTER */
5517
5913
  };
5518
5914
  ContentNavigator = class {
5519
5915
  /** User interface for this navigation session */
@@ -6297,6 +6693,14 @@ ${e.stack}` : JSON.stringify(e);
6297
6693
  setEphemeralHints(hints) {
6298
6694
  this._pendingHints = hints;
6299
6695
  }
6696
+ /**
6697
+ * Forward a presentation to the navigator (a new card restarts its intake
6698
+ * clock). Builds the navigator if the cached one has expired.
6699
+ */
6700
+ notePresented(card) {
6701
+ if (card.status !== "new") return;
6702
+ void this._getCurrentUser().then((u) => this._getCachedNavigator(u)).then(({ navigator: navigator2 }) => navigator2.notePresented?.(card)).catch((e) => logger.warn(`[courseDB] Could not note a presentation: ${e}`));
6703
+ }
6300
6704
  async getWeightedCards(limit) {
6301
6705
  const u = await this._getCurrentUser();
6302
6706
  try {
@@ -10667,10 +11071,11 @@ function backlogHtml(backlog) {
10667
11071
  const rows = backlog.map((b) => {
10668
11072
  const hot = b.backlogMultiplier >= 3;
10669
11073
  const multColor = b.backlogMultiplier <= 1 ? "#86efac" : hot ? "#fca5a5" : "#fcd34d";
10670
- const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog}-review excess, unbounded)` : "healthy \u2014 no pressure";
11074
+ const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog} of mass in excess, unbounded)` : "healthy \u2014 no pressure";
11075
+ const mass = b.reviewMass !== null ? ` \xB7 mass ${b.reviewMass.toFixed(1)}` : "";
10671
11076
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10672
11077
  const next = b.nextDueIn ? ` <span style="opacity:.6">\xB7 next due ${esc(b.nextDueIn)}</span>` : "";
10673
- 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>`;
11078
+ 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>`;
10674
11079
  }).join("");
10675
11080
  return `<div style="margin-bottom:6px"><div style="color:#93c5fd">review backpressure</div>${rows}</div>`;
10676
11081
  }
@@ -10809,8 +11214,9 @@ function snapshotToText(s) {
10809
11214
  const headroom = b.backlogMultiplier > 1 ? "climbing" : "healthy";
10810
11215
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10811
11216
  const next = b.nextDueIn ? `, next due ${b.nextDueIn}` : "";
11217
+ const mass = b.reviewMass !== null ? `, mass ${b.reviewMass.toFixed(1)}` : "";
10812
11218
  lines.push(
10813
- ` ${b.courseId.slice(0, 8)}: due ${b.dueNow}/${b.scheduledTotal} (healthy ${b.healthyBacklog})${next}; pressure \xD7${b.backlogMultiplier.toFixed(2)} ${headroom}; top review ${top}`
11219
+ ` ${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}`
10814
11220
  );
10815
11221
  }
10816
11222
  }
@@ -11191,6 +11597,14 @@ function toRunCardTrail(c) {
11191
11597
  }))
11192
11598
  };
11193
11599
  }
11600
+ function persistedReading(r) {
11601
+ return {
11602
+ ...r,
11603
+ urgency: sig4(r.urgency),
11604
+ multiplier: sig4(r.multiplier),
11605
+ inputs: Object.fromEntries(Object.entries(r.inputs).map(([k, v]) => [k, sig4(v)]))
11606
+ };
11607
+ }
11194
11608
  function persistedRunCards(run) {
11195
11609
  const selected = run.cards.filter((c) => c.selected);
11196
11610
  const runnersUp = run.cards.filter((c) => !c.selected).slice(0, PERSISTED_RUNNERS_UP);
@@ -11516,7 +11930,8 @@ var init_SessionController = __esm({
11516
11930
  ...run.hints ? { hints: run.hints } : {},
11517
11931
  ...run.discardedTail ? { discardedTail: run.discardedTail } : {},
11518
11932
  cards: persistedRunCards(run),
11519
- ...run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {}
11933
+ ...run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {},
11934
+ ...run.regulators ? { regulators: run.regulators.map(persistedReading) } : {}
11520
11935
  });
11521
11936
  }
11522
11937
  }
@@ -12277,6 +12692,13 @@ var init_SessionController = __esm({
12277
12692
  queueSource,
12278
12693
  nextItem.score
12279
12694
  );
12695
+ for (const source of this.sources) {
12696
+ source.notePresented?.({
12697
+ cardId: nextItem.cardID,
12698
+ courseId: nextItem.courseID,
12699
+ status: nextItem.status
12700
+ });
12701
+ }
12280
12702
  snapshotQueues(this.supplyQ.length, this.failedQ.length);
12281
12703
  return card;
12282
12704
  }
@@ -14984,6 +15406,11 @@ var init_courseDB2 = __esm({
14984
15406
  setEphemeralHints(hints) {
14985
15407
  this._pendingHints = hints;
14986
15408
  }
15409
+ /** Forward a presentation to the navigator (a new card restarts its intake clock). */
15410
+ notePresented(card) {
15411
+ if (card.status !== "new") return;
15412
+ void this.createNavigator(this.userDB).then((navigator2) => navigator2.notePresented?.(card)).catch((e) => logger.warn(`[static/courseDB] Could not note a presentation: ${e}`));
15413
+ }
14987
15414
  async getWeightedCards(limit) {
14988
15415
  try {
14989
15416
  const navigator2 = await this.createNavigator(this.userDB);
@@ -15897,6 +16324,8 @@ var init_core = __esm({
15897
16324
 
15898
16325
  // src/index.ts
15899
16326
  init_core();
16327
+ init_pipelinePlan();
16328
+ init_regulators();
15900
16329
  init_courseLookupDB();
15901
16330
 
15902
16331
  // src/courseConfigRegistration.ts
@@ -16213,6 +16642,7 @@ export {
16213
16642
  ContentNavigator,
16214
16643
  CouchDBToStaticPacker,
16215
16644
  CourseLookup,
16645
+ DEFAULT_REGULATOR_CONFIG,
16216
16646
  DIVERSITY_FLOOR,
16217
16647
  DIVERSITY_STRENGTH,
16218
16648
  DocType,
@@ -16221,11 +16651,13 @@ export {
16221
16651
  FileSystemError,
16222
16652
  GuestUsername,
16223
16653
  HYDRATION_MARKER_ID,
16654
+ INTAKE_CLOCK_KEY,
16224
16655
  Loggable,
16225
16656
  NOT_SET,
16226
16657
  NavigatorRole,
16227
16658
  NavigatorRoles,
16228
16659
  Navigators,
16660
+ PIPELINE_STAGES,
16229
16661
  QuotaRoundRobinMixer,
16230
16662
  REVIEW_TIME_FORMAT2 as REVIEW_TIME_FORMAT,
16231
16663
  SessionController,
@@ -16233,6 +16665,7 @@ export {
16233
16665
  TagFilteredContentSource,
16234
16666
  _resetDataLayer,
16235
16667
  aggregateOutcomesForGradient,
16668
+ applyReading,
16236
16669
  areQuestionRecords,
16237
16670
  buildStrategyStateId,
16238
16671
  captureMixerRun,
@@ -16251,6 +16684,7 @@ export {
16251
16684
  drainCapturedRuns,
16252
16685
  endSessionTracking,
16253
16686
  ensureAppDataDirectory,
16687
+ frozenMsAt,
16254
16688
  getActiveController,
16255
16689
  getActivePipeline,
16256
16690
  getAppDataDirectory,
@@ -16260,6 +16694,7 @@ export {
16260
16694
  getDbPath,
16261
16695
  getDefaultLearnableWeight,
16262
16696
  getLapses,
16697
+ getRegisteredFilterKind,
16263
16698
  getRegisteredNavigator,
16264
16699
  getRegisteredNavigatorNames,
16265
16700
  getRegisteredNavigatorRole,
@@ -16273,6 +16708,8 @@ export {
16273
16708
  initializeDataDirectory,
16274
16709
  initializeDataLayer,
16275
16710
  initializeNavigatorRegistry,
16711
+ intakeHours,
16712
+ intakeReading,
16276
16713
  isDataShapeRegistered,
16277
16714
  isDataShapeSchemaAvailable,
16278
16715
  isFilter,
@@ -16292,6 +16729,7 @@ export {
16292
16729
  newSessionId,
16293
16730
  parseCardHistoryID,
16294
16731
  pipelineDebugAPI,
16732
+ planPipeline,
16295
16733
  processCustomQuestionsData,
16296
16734
  recordCardPresentation,
16297
16735
  recordUserOutcome,
@@ -16305,12 +16743,16 @@ export {
16305
16743
  removeCustomQuestionTypes,
16306
16744
  removeDataShape,
16307
16745
  removeQuestionType,
16746
+ resetIntakeClock,
16747
+ reviewMassReading,
16748
+ reviewWeight,
16308
16749
  runPeriodUpdate,
16309
16750
  scoreAccuracyInZone,
16310
16751
  sessionDebugAPI,
16311
16752
  setDebugSessionId,
16312
16753
  snapshotQueues,
16313
16754
  startSessionTracking,
16755
+ stepIntakeClock,
16314
16756
  toggleSessionOverlay,
16315
16757
  updateLearningState,
16316
16758
  updateStrategyWeight,