@vue-skuilder/db 0.2.28 → 0.2.30

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 +621 -179
  6. package/dist/core/index.js.map +1 -1
  7. package/dist/core/index.mjs +620 -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 +619 -179
  20. package/dist/impl/couch/index.js.map +1 -1
  21. package/dist/impl/couch/index.mjs +619 -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 +616 -179
  26. package/dist/impl/static/index.js.map +1 -1
  27. package/dist/impl/static/index.mjs +616 -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 +669 -180
  32. package/dist/index.js.map +1 -1
  33. package/dist/index.mjs +656 -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 +320 -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,175 @@ 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
+ mountMultiDimEloToggle: () => mountMultiDimEloToggle,
3256
+ tagAwareGap: () => tagAwareGap
3192
3257
  });
3193
3258
  function computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier) {
3194
3259
  const normalizedDistance = distance / halfLife;
3195
3260
  const decay = Math.exp(-(normalizedDistance * normalizedDistance));
3196
3261
  return minMultiplier + (maxMultiplier - minMultiplier) * decay;
3197
3262
  }
3263
+ function resolveConfig(config) {
3264
+ return { ...DEFAULT_ELO_DISTANCE_CONFIG, ...config };
3265
+ }
3266
+ function readMultiDimElo() {
3267
+ try {
3268
+ return typeof localStorage !== "undefined" && localStorage.getItem(MULTI_DIM_ELO_KEY) === "true";
3269
+ } catch {
3270
+ return false;
3271
+ }
3272
+ }
3273
+ function mountMultiDimEloToggle() {
3274
+ if (typeof window === "undefined") return;
3275
+ const win = window;
3276
+ win.skuilder = win.skuilder || {};
3277
+ Object.defineProperty(win.skuilder, "multiDimElo", {
3278
+ configurable: true,
3279
+ enumerable: true,
3280
+ get: () => multiDimElo,
3281
+ set: (on) => {
3282
+ multiDimElo = on === true;
3283
+ try {
3284
+ if (multiDimElo) localStorage.setItem(MULTI_DIM_ELO_KEY, "true");
3285
+ else localStorage.removeItem(MULTI_DIM_ELO_KEY);
3286
+ } catch (e) {
3287
+ logger.warn(`[EloDistance] multiDimElo not persisted (localStorage unavailable): ${e}`);
3288
+ }
3289
+ logger.info(
3290
+ `[EloDistance] multiDimElo ${multiDimElo ? "on: tag-aware" : "off: per strategy config"} ELO distance from the next replan`
3291
+ );
3292
+ }
3293
+ });
3294
+ }
3295
+ function tagAwareGap(cardTags, cardElo, userElo, minTagCount) {
3296
+ const globalGap = cardElo.global.score - userElo.global.score;
3297
+ const tags = [];
3298
+ for (const tag of cardTags) {
3299
+ const user = userElo.tags[tag];
3300
+ if (!user || user.score === COUNT_ONLY_SENTINEL || user.count < minTagCount) continue;
3301
+ const card = cardElo.tags[tag]?.score ?? cardElo.global.score;
3302
+ tags.push({
3303
+ tag,
3304
+ gap: card - user.score,
3305
+ weight: user.count / (user.count + TAG_CONFIDENCE_HALF)
3306
+ });
3307
+ }
3308
+ if (tags.length === 0) return { gap: globalGap, globalGap, tags };
3309
+ const total = tags.reduce((w, t) => w + t.weight, 0);
3310
+ const tagGap = tags.reduce((g, t) => g + t.weight * t.gap, 0) / total;
3311
+ const lambda = total / (total + 1);
3312
+ return { gap: lambda * tagGap + (1 - lambda) * globalGap, globalGap, tags };
3313
+ }
3314
+ function tagReason(tags, globalGap) {
3315
+ 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(", ");
3316
+ const more = tags.length > 3 ? `, +${tags.length - 3} more` : "";
3317
+ return ` on ${tags.length} shared tag(s) [${shown}${more}] (global ${globalGap >= 0 ? "+" : ""}${Math.round(globalGap)})`;
3318
+ }
3319
+ async function applyEloDistance(cards, context, config, source) {
3320
+ const { course, userElo, userCourseElo } = context;
3321
+ const { halfLife, minMultiplier, maxMultiplier } = config;
3322
+ const tagAware = (config.tagAware || multiDimElo) && userCourseElo !== void 0;
3323
+ const missing = cards.filter((c) => tagAware || c.cardElo === void 0).map((c) => c.cardId);
3324
+ const fetched = /* @__PURE__ */ new Map();
3325
+ if (missing.length > 0) {
3326
+ const elos = await course.getCardEloData(missing);
3327
+ missing.forEach((id, i) => {
3328
+ if (elos[i]) fetched.set(id, elos[i]);
3329
+ });
3330
+ }
3331
+ return cards.map((card) => {
3332
+ const full = fetched.get(card.cardId);
3333
+ const cardElo = full?.global?.score ?? card.cardElo ?? DEFAULT_CARD_ELO;
3334
+ let distance = Math.abs(cardElo - userElo);
3335
+ let how = "";
3336
+ if (tagAware) {
3337
+ const t = full ? tagAwareGap(card.tags ?? [], full, userCourseElo, config.minTagCount) : void 0;
3338
+ if (t) distance = Math.abs(t.gap);
3339
+ how = t?.tags.length ? `, tag-aware${tagReason(t.tags, t.globalGap)}` : ", tag-aware: global (no shared tags)";
3340
+ }
3341
+ const multiplier = computeMultiplier(distance, halfLife, minMultiplier, maxMultiplier);
3342
+ const newScore = card.score * multiplier;
3343
+ const action = multiplier < maxMultiplier - 0.01 ? "penalized" : "passed";
3344
+ return {
3345
+ ...card,
3346
+ cardElo,
3347
+ score: newScore,
3348
+ provenance: [
3349
+ ...card.provenance,
3350
+ {
3351
+ strategy: "eloDistance",
3352
+ strategyName: source.name,
3353
+ strategyId: source.strategyId,
3354
+ action,
3355
+ score: newScore,
3356
+ reason: `ELO distance ${Math.round(distance)} (card: ${Math.round(cardElo)}, user: ${Math.round(userElo)})${how} \u2192 ${multiplier.toFixed(2)}x`
3357
+ }
3358
+ ]
3359
+ };
3360
+ });
3361
+ }
3198
3362
  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;
3363
+ const resolved = resolveConfig(config);
3364
+ const source = { name: "ELO Distance Filter", strategyId: "ELO_DISTANCE_FILTER" };
3202
3365
  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
- }
3366
+ name: source.name,
3367
+ kind: "signal",
3368
+ liveOnly: true,
3369
+ transform: (cards, context) => applyEloDistance(cards, context, resolved, source)
3231
3370
  };
3232
3371
  }
3233
- var DEFAULT_HALF_LIFE, DEFAULT_MIN_MULTIPLIER, DEFAULT_MAX_MULTIPLIER;
3372
+ var DEFAULT_ELO_DISTANCE_CONFIG, TAG_CONFIDENCE_HALF, COUNT_ONLY_SENTINEL, DEFAULT_CARD_ELO, MULTI_DIM_ELO_KEY, multiDimElo, EloDistanceFilter;
3234
3373
  var init_eloDistance = __esm({
3235
3374
  "src/core/navigators/filters/eloDistance.ts"() {
3236
3375
  "use strict";
3237
- DEFAULT_HALF_LIFE = 200;
3238
- DEFAULT_MIN_MULTIPLIER = 0.3;
3239
- DEFAULT_MAX_MULTIPLIER = 1;
3376
+ init_navigators();
3377
+ init_logger();
3378
+ DEFAULT_ELO_DISTANCE_CONFIG = {
3379
+ halfLife: 300,
3380
+ minMultiplier: 0.05,
3381
+ maxMultiplier: 1,
3382
+ tagAware: false,
3383
+ minTagCount: 3
3384
+ };
3385
+ TAG_CONFIDENCE_HALF = 10;
3386
+ COUNT_ONLY_SENTINEL = -1;
3387
+ DEFAULT_CARD_ELO = 1e3;
3388
+ MULTI_DIM_ELO_KEY = "skuilder:multiDimElo";
3389
+ multiDimElo = readMultiDimElo();
3390
+ mountMultiDimEloToggle();
3391
+ EloDistanceFilter = class _EloDistanceFilter extends ContentNavigator {
3392
+ name;
3393
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3394
+ static kind = "signal";
3395
+ kind = _EloDistanceFilter.kind;
3396
+ liveOnly = true;
3397
+ config;
3398
+ constructor(user, course, strategyData) {
3399
+ super(user, course, strategyData);
3400
+ this.name = strategyData.name || "ELO Distance";
3401
+ let parsed;
3402
+ try {
3403
+ parsed = strategyData.serializedData ? JSON.parse(strategyData.serializedData) : void 0;
3404
+ } catch {
3405
+ parsed = void 0;
3406
+ }
3407
+ this.config = resolveConfig(parsed);
3408
+ }
3409
+ transform(cards, context) {
3410
+ return applyEloDistance(cards, context, this.config, {
3411
+ name: this.name,
3412
+ strategyId: this.strategyId || "NAVIGATION_STRATEGY-eloDistance-default"
3413
+ });
3414
+ }
3415
+ async getWeightedCards(_limit) {
3416
+ throw new Error(
3417
+ "EloDistanceFilter is a filter and should not be used as a generator. Use Pipeline with a generator and this filter via transform()."
3418
+ );
3419
+ }
3420
+ };
3240
3421
  }
3241
3422
  });
3242
3423
 
@@ -3253,10 +3434,13 @@ var init_hierarchyDefinition = __esm({
3253
3434
  init_navigators();
3254
3435
  init_logger();
3255
3436
  DEFAULT_MIN_COUNT2 = 3;
3256
- HierarchyDefinitionNavigator = class extends ContentNavigator {
3437
+ HierarchyDefinitionNavigator = class _HierarchyDefinitionNavigator extends ContentNavigator {
3257
3438
  config;
3258
3439
  /** Human-readable name for CardFilter interface */
3259
3440
  name;
3441
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3442
+ static kind = "gate";
3443
+ kind = _HierarchyDefinitionNavigator.kind;
3260
3444
  constructor(user, course, strategyData) {
3261
3445
  super(user, course, strategyData);
3262
3446
  this.config = this.parseConfig(strategyData.serializedData);
@@ -3523,10 +3707,13 @@ var init_userTagPreference = __esm({
3523
3707
  "src/core/navigators/filters/userTagPreference.ts"() {
3524
3708
  "use strict";
3525
3709
  init_navigators();
3526
- UserTagPreferenceFilter = class extends ContentNavigator {
3710
+ UserTagPreferenceFilter = class _UserTagPreferenceFilter extends ContentNavigator {
3527
3711
  _strategyData;
3528
3712
  /** Human-readable name for CardFilter interface */
3529
3713
  name;
3714
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3715
+ static kind = "signal";
3716
+ kind = _UserTagPreferenceFilter.kind;
3530
3717
  constructor(user, course, strategyData) {
3531
3718
  super(user, course, strategyData);
3532
3719
  this._strategyData = strategyData;
@@ -3636,6 +3823,7 @@ var init_userTagPreference = __esm({
3636
3823
  // src/core/navigators/filters/index.ts
3637
3824
  var filters_exports = {};
3638
3825
  __export(filters_exports, {
3826
+ EloDistanceFilter: () => EloDistanceFilter,
3639
3827
  UserTagPreferenceFilter: () => UserTagPreferenceFilter,
3640
3828
  createEloDistanceFilter: () => createEloDistanceFilter
3641
3829
  });
@@ -3674,10 +3862,13 @@ var init_interferenceMitigator = __esm({
3674
3862
  DEFAULT_MIN_COUNT3 = 10;
3675
3863
  DEFAULT_MIN_ELAPSED_DAYS = 3;
3676
3864
  DEFAULT_INTERFERENCE_DECAY = 0.8;
3677
- InterferenceMitigatorNavigator = class extends ContentNavigator {
3865
+ InterferenceMitigatorNavigator = class _InterferenceMitigatorNavigator extends ContentNavigator {
3678
3866
  config;
3679
3867
  /** Human-readable name for CardFilter interface */
3680
3868
  name;
3869
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
3870
+ static kind = "signal";
3871
+ kind = _InterferenceMitigatorNavigator.kind;
3681
3872
  /** Precomputed map: tag -> set of { partner, decay } it interferes with */
3682
3873
  interferenceMap;
3683
3874
  constructor(user, course, strategyData) {
@@ -3893,10 +4084,13 @@ var init_relativePriority = __esm({
3893
4084
  DEFAULT_PRIORITY = 0.5;
3894
4085
  DEFAULT_PRIORITY_INFLUENCE = 0.5;
3895
4086
  DEFAULT_COMBINE_MODE = "max";
3896
- RelativePriorityNavigator = class extends ContentNavigator {
4087
+ RelativePriorityNavigator = class _RelativePriorityNavigator extends ContentNavigator {
3897
4088
  config;
3898
4089
  /** Human-readable name for CardFilter interface */
3899
4090
  name;
4091
+ /** See CardFilter.kind. Static, so the pipeline plan can read it without an instance. */
4092
+ static kind = "signal";
4093
+ kind = _RelativePriorityNavigator.kind;
3900
4094
  constructor(user, course, strategyData) {
3901
4095
  super(user, course, strategyData);
3902
4096
  this.config = this.parseConfig(strategyData.serializedData);
@@ -4550,6 +4744,8 @@ var init_Pipeline = __esm({
4550
4744
  init_orchestration();
4551
4745
  init_PipelineDebugger();
4552
4746
  init_diversityRerank();
4747
+ init_regulators();
4748
+ init_SrsDebugger();
4553
4749
  VERBOSE_RESULTS = true;
4554
4750
  Pipeline = class extends ContentNavigator {
4555
4751
  generator;
@@ -4575,6 +4771,13 @@ var init_Pipeline = __esm({
4575
4771
  * getWeightedCards() call, then cleared.
4576
4772
  */
4577
4773
  _ephemeralHints = null;
4774
+ /**
4775
+ * The intake valve's clock (see regulators.ts), loaded from strategy state on
4776
+ * first use and kept in memory. Writes are chained so a presentation and a
4777
+ * run can't race each other's revision.
4778
+ */
4779
+ _intakeClock = null;
4780
+ _intakeClockWrite = Promise.resolve();
4578
4781
  /**
4579
4782
  * Create a new pipeline.
4580
4783
  *
@@ -4649,13 +4852,12 @@ var init_Pipeline = __esm({
4649
4852
  }
4650
4853
  }
4651
4854
  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"));
4855
+ const reviewCount = data.cards.filter((c) => c.reviewID).length;
4654
4856
  return {
4655
4857
  name,
4656
4858
  cardCount: data.cards.length,
4657
- newCount: newCards.length,
4658
- reviewCount: reviewCards.length,
4859
+ newCount: data.cards.length - reviewCount,
4860
+ reviewCount,
4659
4861
  topScore: Math.max(...data.cards.map((c) => c.score), 0)
4660
4862
  };
4661
4863
  });
@@ -4691,19 +4893,24 @@ var init_Pipeline = __esm({
4691
4893
  cards.filter((c) => c.provenance.some((p) => p.strategy === "prescribed")).map((c) => c.cardId)
4692
4894
  );
4693
4895
  const filterImpacts = [];
4896
+ const generatedScores = new Map(cards.map((c) => [c.cardId, c.score]));
4897
+ const gated = /* @__PURE__ */ new Set();
4694
4898
  for (const filter of this.filters) {
4695
4899
  const beforeCount = cards.length;
4696
4900
  const beforeScores = new Map(cards.map((c) => [c.cardId, c.score]));
4697
4901
  cards = await filter.transform(cards, context);
4698
4902
  let boosted = 0, penalized = 0, passed = 0;
4699
4903
  const removed = beforeCount - cards.length;
4904
+ const kind = filter.kind ?? "gate";
4700
4905
  for (const card of cards) {
4701
4906
  const before = beforeScores.get(card.cardId) ?? 0;
4702
4907
  if (card.score > before) boosted++;
4703
- else if (card.score < before) penalized++;
4704
- else passed++;
4908
+ else if (card.score < before) {
4909
+ penalized++;
4910
+ if (kind === "gate") gated.add(card.cardId);
4911
+ } else passed++;
4705
4912
  }
4706
- filterImpacts.push({ name: filter.name, boosted, penalized, passed, removed });
4913
+ filterImpacts.push({ name: filter.name, kind, boosted, penalized, passed, removed });
4707
4914
  if (prescribedIds.size > 0) {
4708
4915
  const survivingIds = new Set(cards.map((c) => c.cardId));
4709
4916
  const killedPrescribed = [...prescribedIds].filter((id) => !survivingIds.has(id));
@@ -4719,6 +4926,7 @@ var init_Pipeline = __esm({
4719
4926
  }
4720
4927
  const scoredCards = cards;
4721
4928
  cards = cards.filter((c) => c.score > 0);
4929
+ const regulators = await this.regulate(cards, generatedScores, gated);
4722
4930
  const hints = this._ephemeralHints;
4723
4931
  if (hints) {
4724
4932
  this._ephemeralHints = null;
@@ -4755,7 +4963,8 @@ var init_Pipeline = __esm({
4755
4963
  result,
4756
4964
  context.userElo,
4757
4965
  hints ?? void 0,
4758
- scoredCards
4966
+ scoredCards,
4967
+ regulators
4759
4968
  );
4760
4969
  captureRun(report);
4761
4970
  } catch (e) {
@@ -4934,6 +5143,77 @@ var init_Pipeline = __esm({
4934
5143
  logger.info(`[Pipeline] Hints applied: ${beforeCount} \u2192 ${cards.length} cards`);
4935
5144
  return cards;
4936
5145
  }
5146
+ /**
5147
+ * The regulator stage: measure each class's pressure and scale it.
5148
+ *
5149
+ * - Review mass: every due review's SRS urgency times the filters' net
5150
+ * effect on it.
5151
+ * - Intake: servable hours since a new card was presented, applied only to
5152
+ * eligible new cards (no gate penalized them). With none eligible, the
5153
+ * clock freezes.
5154
+ *
5155
+ * Mutates `cards` in place; returns the readings for the run report.
5156
+ */
5157
+ async regulate(cards, generatedScores, gated) {
5158
+ const config = DEFAULT_REGULATOR_CONFIG;
5159
+ const reviews = cards.filter((c) => c.reviewID);
5160
+ const newCards = cards.filter((c) => !c.reviewID);
5161
+ const eligibleNew = newCards.filter((c) => !gated.has(c.cardId));
5162
+ const mass = reviewMassReading(reviews, generatedScores, config.reviewMass);
5163
+ applyReading(reviews, mass);
5164
+ noteReviewPressure(this.course.getCourseID(), {
5165
+ mass: mass.urgency,
5166
+ healthyMass: config.reviewMass.healthyMass,
5167
+ rate: config.reviewMass.rate,
5168
+ multiplier: mass.multiplier
5169
+ });
5170
+ const now = Date.now();
5171
+ const clock = await this.loadIntakeClock(now);
5172
+ const stepped = stepIntakeClock(clock, now, eligibleNew.length);
5173
+ if (stepped !== clock) this.saveIntakeClock(stepped);
5174
+ const intake = intakeReading(
5175
+ stepped,
5176
+ now,
5177
+ { eligibleNew: eligibleNew.length, newCandidates: newCards.length },
5178
+ config.intake
5179
+ );
5180
+ applyReading(eligibleNew, intake);
5181
+ logger.info(
5182
+ `[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)}`
5183
+ );
5184
+ return [mass, intake];
5185
+ }
5186
+ /**
5187
+ * A card was presented. A new card's first presentation discharges the
5188
+ * intake valve: its clock restarts. Called by the SessionController.
5189
+ */
5190
+ notePresented(card) {
5191
+ if (card.status !== "new" || card.courseId !== this.course?.getCourseID()) return;
5192
+ this.saveIntakeClock(resetIntakeClock(Date.now()));
5193
+ }
5194
+ async loadIntakeClock(nowMs) {
5195
+ if (this._intakeClock) return this._intakeClock;
5196
+ let stored = null;
5197
+ try {
5198
+ stored = await this.user.getStrategyState(
5199
+ this.course.getCourseID(),
5200
+ INTAKE_CLOCK_KEY
5201
+ );
5202
+ } catch (e) {
5203
+ logger.warn(`[Pipeline:regulators] Could not read the intake clock: ${e}`);
5204
+ }
5205
+ if (stored) {
5206
+ this._intakeClock = stored;
5207
+ } else {
5208
+ this.saveIntakeClock(resetIntakeClock(nowMs));
5209
+ }
5210
+ return this._intakeClock;
5211
+ }
5212
+ saveIntakeClock(state) {
5213
+ this._intakeClock = state;
5214
+ const courseId = this.course.getCourseID();
5215
+ 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}`));
5216
+ }
4937
5217
  /**
4938
5218
  * Build shared context for generator and filters.
4939
5219
  *
@@ -4944,10 +5224,11 @@ var init_Pipeline = __esm({
4944
5224
  */
4945
5225
  async buildContext() {
4946
5226
  let userElo = 1e3;
5227
+ let userCourseElo;
4947
5228
  try {
4948
5229
  const courseReg = await this.user.getCourseRegDoc(this.course.getCourseID());
4949
- const courseElo = toCourseElo5(courseReg.elo);
4950
- userElo = courseElo.global.score;
5230
+ userCourseElo = toCourseElo5(courseReg.elo);
5231
+ userElo = userCourseElo.global.score;
4951
5232
  } catch (e) {
4952
5233
  logger.debug(`[Pipeline] Could not get user ELO, using default: ${e}`);
4953
5234
  }
@@ -4959,6 +5240,7 @@ var init_Pipeline = __esm({
4959
5240
  user: this.user,
4960
5241
  course: this.course,
4961
5242
  userElo,
5243
+ ...userCourseElo ? { userCourseElo } : {},
4962
5244
  orchestration
4963
5245
  };
4964
5246
  }
@@ -5072,7 +5354,7 @@ var init_Pipeline = __esm({
5072
5354
  cards = await this.hydrateTags(cards);
5073
5355
  const fullPool = cards.slice();
5074
5356
  const context = await this.buildContext();
5075
- for (const filter of this.filters) {
5357
+ for (const filter of this.forecastFilters()) {
5076
5358
  cards = await filter.transform(cards, context);
5077
5359
  }
5078
5360
  if (opts?.hints) {
@@ -5091,6 +5373,14 @@ var init_Pipeline = __esm({
5091
5373
  cards.sort((a, b) => b.score - a.score);
5092
5374
  return opts?.limit ? cards.slice(0, opts.limit) : cards;
5093
5375
  }
5376
+ /**
5377
+ * The filters a forecast or card-space scan applies. Those start every card at
5378
+ * 1.0 without a generator, so they skip `liveOnly` filters (ELO distance),
5379
+ * which only make sense against generator scores.
5380
+ */
5381
+ forecastFilters() {
5382
+ return this.filters.filter((f) => !f.liveOnly);
5383
+ }
5094
5384
  /**
5095
5385
  * Scan every card in the course through the filter chain and report
5096
5386
  * how many are "well indicated" (score >= threshold) for the current user.
@@ -5112,7 +5402,7 @@ var init_Pipeline = __esm({
5112
5402
  cards = await this.hydrateTags(cards);
5113
5403
  const context = await this.buildContext();
5114
5404
  const filterBreakdown = [];
5115
- for (const filter of this.filters) {
5405
+ for (const filter of this.forecastFilters()) {
5116
5406
  cards = await filter.transform(cards, context);
5117
5407
  const wi = cards.filter((c) => c.score >= THRESHOLD).length;
5118
5408
  filterBreakdown.push({ name: filter.name, wellIndicated: wi });
@@ -5176,6 +5466,7 @@ var init_Pipeline = __esm({
5176
5466
  // src/core/navigators/defaults.ts
5177
5467
  var defaults_exports = {};
5178
5468
  __export(defaults_exports, {
5469
+ createDefaultEloDistanceStrategy: () => createDefaultEloDistanceStrategy,
5179
5470
  createDefaultEloStrategy: () => createDefaultEloStrategy,
5180
5471
  createDefaultPipeline: () => createDefaultPipeline,
5181
5472
  createDefaultSrsStrategy: () => createDefaultSrsStrategy
@@ -5202,12 +5493,28 @@ function createDefaultSrsStrategy(courseId) {
5202
5493
  serializedData: ""
5203
5494
  };
5204
5495
  }
5496
+ function createDefaultEloDistanceStrategy(courseId) {
5497
+ return {
5498
+ _id: "NAVIGATION_STRATEGY-eloDistance-default",
5499
+ docType: "NAVIGATION_STRATEGY" /* NAVIGATION_STRATEGY */,
5500
+ name: "ELO Distance (default)",
5501
+ description: "Scales every candidate, new or review, by its distance from the learner's ELO",
5502
+ implementingClass: "eloDistance" /* ELO_DISTANCE */,
5503
+ course: courseId,
5504
+ // Explicit, though the filter would default to it anyway: views show what runs.
5505
+ serializedData: JSON.stringify(DEFAULT_ELO_DISTANCE_CONFIG)
5506
+ };
5507
+ }
5205
5508
  function createDefaultPipeline(user, course) {
5206
5509
  const courseId = course.getCourseID();
5207
5510
  const eloNavigator = new ELONavigator(user, course, createDefaultEloStrategy(courseId));
5208
5511
  const srsNavigator = new SRSNavigator(user, course, createDefaultSrsStrategy(courseId));
5209
5512
  const compositeGenerator = new CompositeGenerator([eloNavigator, srsNavigator]);
5210
- const eloDistanceFilter = createEloDistanceFilter();
5513
+ const eloDistanceFilter = new EloDistanceFilter(
5514
+ user,
5515
+ course,
5516
+ createDefaultEloDistanceStrategy(courseId)
5517
+ );
5211
5518
  return new Pipeline(compositeGenerator, [eloDistanceFilter], user, course);
5212
5519
  }
5213
5520
  var init_defaults = __esm({
@@ -5223,6 +5530,131 @@ var init_defaults = __esm({
5223
5530
  }
5224
5531
  });
5225
5532
 
5533
+ // src/core/navigators/pipelinePlan.ts
5534
+ var pipelinePlan_exports = {};
5535
+ __export(pipelinePlan_exports, {
5536
+ PIPELINE_STAGES: () => PIPELINE_STAGES,
5537
+ planPipeline: () => planPipeline
5538
+ });
5539
+ function planned(strategy, role, origin) {
5540
+ const kind = role === "filter" /* FILTER */ ? getRegisteredFilterKind(strategy.implementingClass) : void 0;
5541
+ return {
5542
+ role,
5543
+ origin,
5544
+ name: strategy.name,
5545
+ implementingClass: strategy.implementingClass,
5546
+ strategy,
5547
+ ...kind ? { kind } : {}
5548
+ };
5549
+ }
5550
+ function planPipeline(strategies, courseId) {
5551
+ if (strategies.length === 0) {
5552
+ return {
5553
+ kind: "default",
5554
+ generators: [
5555
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline"),
5556
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "default-pipeline")
5557
+ ],
5558
+ filters: [
5559
+ planned(
5560
+ createDefaultEloDistanceStrategy(courseId),
5561
+ "filter" /* FILTER */,
5562
+ "default-pipeline"
5563
+ )
5564
+ ],
5565
+ skipped: [],
5566
+ warnings: [],
5567
+ notes: [],
5568
+ regulators: DEFAULT_REGULATOR_CONFIG
5569
+ };
5570
+ }
5571
+ const generators = [];
5572
+ const filters = [];
5573
+ const skipped = [];
5574
+ const warnings = [];
5575
+ for (const s of strategies) {
5576
+ if (isGenerator(s.implementingClass)) {
5577
+ generators.push(planned(s, "generator" /* GENERATOR */, "strategy-doc"));
5578
+ } else if (isFilter(s.implementingClass)) {
5579
+ filters.push(planned(s, "filter" /* FILTER */, "strategy-doc"));
5580
+ } else {
5581
+ skipped.push({ strategy: s, reason: "not a registered generator or filter" });
5582
+ warnings.push(`Unknown strategy type '${s.implementingClass}', skipping: ${s.name}`);
5583
+ }
5584
+ }
5585
+ const declared = new Set(generators.map((g) => g.implementingClass));
5586
+ if (!declared.has(createDefaultEloStrategy(courseId).implementingClass)) {
5587
+ generators.push(
5588
+ planned(createDefaultEloStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5589
+ );
5590
+ }
5591
+ if (!declared.has(createDefaultSrsStrategy(courseId).implementingClass)) {
5592
+ generators.push(
5593
+ planned(createDefaultSrsStrategy(courseId), "generator" /* GENERATOR */, "assembler-default")
5594
+ );
5595
+ }
5596
+ const eloDistance = createDefaultEloDistanceStrategy(courseId);
5597
+ if (!filters.some((f) => f.implementingClass === eloDistance.implementingClass)) {
5598
+ filters.push(planned(eloDistance, "filter" /* FILTER */, "assembler-default"));
5599
+ }
5600
+ filters.sort((a, b) => a.name.localeCompare(b.name));
5601
+ return {
5602
+ kind: "assembled",
5603
+ generators,
5604
+ filters,
5605
+ skipped,
5606
+ warnings,
5607
+ notes: [],
5608
+ regulators: DEFAULT_REGULATOR_CONFIG
5609
+ };
5610
+ }
5611
+ var PIPELINE_STAGES;
5612
+ var init_pipelinePlan = __esm({
5613
+ "src/core/navigators/pipelinePlan.ts"() {
5614
+ "use strict";
5615
+ init_navigators();
5616
+ init_regulators();
5617
+ init_defaults();
5618
+ PIPELINE_STAGES = [
5619
+ {
5620
+ key: "generate",
5621
+ title: "Generate",
5622
+ 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."
5623
+ },
5624
+ {
5625
+ key: "filter",
5626
+ title: "Filter",
5627
+ 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."
5628
+ },
5629
+ {
5630
+ key: "drop-zero",
5631
+ title: "Drop zero scores",
5632
+ summary: "Candidates whose score reached 0 leave the pool."
5633
+ },
5634
+ {
5635
+ key: "regulate",
5636
+ title: "Regulate",
5637
+ 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."
5638
+ },
5639
+ {
5640
+ key: "hints",
5641
+ title: "Apply hints",
5642
+ 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."
5643
+ },
5644
+ {
5645
+ key: "diversity",
5646
+ title: "Diversity re-rank",
5647
+ 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."
5648
+ },
5649
+ {
5650
+ key: "select",
5651
+ title: "Select",
5652
+ summary: "Highest scores first, up to the run's limit. The session mixes them into its supply queue."
5653
+ }
5654
+ ];
5655
+ }
5656
+ });
5657
+
5226
5658
  // src/core/navigators/PipelineAssembler.ts
5227
5659
  var PipelineAssembler_exports = {};
5228
5660
  __export(PipelineAssembler_exports, {
@@ -5237,16 +5669,16 @@ var init_PipelineAssembler = __esm({
5237
5669
  init_Pipeline();
5238
5670
  init_logger();
5239
5671
  init_CompositeGenerator();
5240
- init_defaults();
5672
+ init_pipelinePlan();
5241
5673
  PipelineAssembler = class {
5242
5674
  /**
5243
5675
  * Assembles a navigation pipeline from strategy documents.
5244
5676
  *
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)
5677
+ * 1. Plans: classifies by role, adds default ELO/SRS and ELO distance, orders filters
5678
+ * (`planPipeline`)
5679
+ * 2. Instantiates generators - wraps multiple in CompositeGenerator
5680
+ * 3. Instantiates filters
5681
+ * 4. Returns Pipeline(generator, filters)
5250
5682
  *
5251
5683
  * @param input - Strategy documents plus user/course interfaces
5252
5684
  * @returns Assembled pipeline and any warnings
@@ -5262,28 +5694,17 @@ var init_PipelineAssembler = __esm({
5262
5694
  warnings
5263
5695
  };
5264
5696
  }
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}`);
5697
+ const plan = planPipeline(strategies, course.getCourseID());
5698
+ warnings.push(...plan.warnings);
5699
+ for (const n of [...plan.generators, ...plan.filters]) {
5700
+ if (n.origin === "assembler-default") {
5701
+ logger.debug(
5702
+ `[PipelineAssembler] No ${n.implementingClass} ${n.role} configured, adding default`
5703
+ );
5274
5704
  }
5275
5705
  }
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
- }
5706
+ const generatorStrategies = plan.generators.map((g) => g.strategy);
5707
+ const sortedFilterStrategies = plan.filters.map((f) => f.strategy);
5287
5708
  if (generatorStrategies.length === 0) {
5288
5709
  warnings.push("No generator strategy found");
5289
5710
  return {
@@ -5305,9 +5726,6 @@ var init_PipelineAssembler = __esm({
5305
5726
  generator = await CompositeGenerator.fromStrategies(user, course, generatorStrategies);
5306
5727
  }
5307
5728
  const filters = [];
5308
- const sortedFilterStrategies = [...filterStrategies].sort(
5309
- (a, b) => a.name.localeCompare(b.name)
5310
- );
5311
5729
  for (const filterStrategy of sortedFilterStrategies) {
5312
5730
  try {
5313
5731
  const nav = await ContentNavigator.create(user, course, filterStrategy);
@@ -5375,7 +5793,9 @@ var init_3 = __esm({
5375
5793
  "./generators/prescribed.ts": () => Promise.resolve().then(() => (init_prescribed(), prescribed_exports)),
5376
5794
  "./generators/srs.ts": () => Promise.resolve().then(() => (init_srs(), srs_exports)),
5377
5795
  "./generators/types.ts": () => Promise.resolve().then(() => (init_types(), types_exports)),
5378
- "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports))
5796
+ "./index.ts": () => Promise.resolve().then(() => (init_navigators(), navigators_exports)),
5797
+ "./pipelinePlan.ts": () => Promise.resolve().then(() => (init_pipelinePlan(), pipelinePlan_exports)),
5798
+ "./regulators.ts": () => Promise.resolve().then(() => (init_regulators(), regulators_exports))
5379
5799
  });
5380
5800
  }
5381
5801
  });
@@ -5396,6 +5816,7 @@ __export(navigators_exports, {
5396
5816
  drainCapturedRuns: () => drainCapturedRuns,
5397
5817
  getActivePipeline: () => getActivePipeline,
5398
5818
  getCardOrigin: () => getCardOrigin,
5819
+ getRegisteredFilterKind: () => getRegisteredFilterKind,
5399
5820
  getRegisteredNavigator: () => getRegisteredNavigator,
5400
5821
  getRegisteredNavigatorNames: () => getRegisteredNavigatorNames,
5401
5822
  getRegisteredNavigatorRole: () => getRegisteredNavigatorRole,
@@ -5424,6 +5845,10 @@ function hasRegisteredNavigator(implementingClass) {
5424
5845
  function getRegisteredNavigatorRole(implementingClass) {
5425
5846
  return navigatorRegistry.get(implementingClass)?.role;
5426
5847
  }
5848
+ function getRegisteredFilterKind(implementingClass) {
5849
+ const ctor = navigatorRegistry.get(implementingClass)?.constructor;
5850
+ return ctor?.kind;
5851
+ }
5427
5852
  function getRegisteredNavigatorNames() {
5428
5853
  return Array.from(navigatorRegistry.keys());
5429
5854
  }
@@ -5441,17 +5866,20 @@ async function initializeNavigatorRegistry() {
5441
5866
  hierarchyModule,
5442
5867
  interferenceModule,
5443
5868
  relativePriorityModule,
5444
- userTagPreferenceModule
5869
+ userTagPreferenceModule,
5870
+ eloDistanceModule
5445
5871
  ] = await Promise.all([
5446
5872
  Promise.resolve().then(() => (init_hierarchyDefinition(), hierarchyDefinition_exports)),
5447
5873
  Promise.resolve().then(() => (init_interferenceMitigator(), interferenceMitigator_exports)),
5448
5874
  Promise.resolve().then(() => (init_relativePriority(), relativePriority_exports)),
5449
- Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports))
5875
+ Promise.resolve().then(() => (init_userTagPreference(), userTagPreference_exports)),
5876
+ Promise.resolve().then(() => (init_eloDistance(), eloDistance_exports))
5450
5877
  ]);
5451
5878
  registerNavigator("hierarchyDefinition", hierarchyModule.default);
5452
5879
  registerNavigator("interferenceMitigator", interferenceModule.default);
5453
5880
  registerNavigator("relativePriority", relativePriorityModule.default);
5454
5881
  registerNavigator("userTagPreference", userTagPreferenceModule.default);
5882
+ registerNavigator("eloDistance", eloDistanceModule.default);
5455
5883
  logger.debug(
5456
5884
  `[NavigatorRegistry] Initialized ${navigatorRegistry.size} navigators: ${getRegisteredNavigatorNames().join(", ")}`
5457
5885
  );
@@ -5499,6 +5927,7 @@ var init_navigators = __esm({
5499
5927
  Navigators2["INTERFERENCE"] = "interferenceMitigator";
5500
5928
  Navigators2["RELATIVE_PRIORITY"] = "relativePriority";
5501
5929
  Navigators2["USER_TAG_PREFERENCE"] = "userTagPreference";
5930
+ Navigators2["ELO_DISTANCE"] = "eloDistance";
5502
5931
  return Navigators2;
5503
5932
  })(Navigators || {});
5504
5933
  NavigatorRole = /* @__PURE__ */ ((NavigatorRole2) => {
@@ -5513,7 +5942,8 @@ var init_navigators = __esm({
5513
5942
  ["hierarchyDefinition" /* HIERARCHY */]: "filter" /* FILTER */,
5514
5943
  ["interferenceMitigator" /* INTERFERENCE */]: "filter" /* FILTER */,
5515
5944
  ["relativePriority" /* RELATIVE_PRIORITY */]: "filter" /* FILTER */,
5516
- ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */
5945
+ ["userTagPreference" /* USER_TAG_PREFERENCE */]: "filter" /* FILTER */,
5946
+ ["eloDistance" /* ELO_DISTANCE */]: "filter" /* FILTER */
5517
5947
  };
5518
5948
  ContentNavigator = class {
5519
5949
  /** User interface for this navigation session */
@@ -6297,6 +6727,14 @@ ${e.stack}` : JSON.stringify(e);
6297
6727
  setEphemeralHints(hints) {
6298
6728
  this._pendingHints = hints;
6299
6729
  }
6730
+ /**
6731
+ * Forward a presentation to the navigator (a new card restarts its intake
6732
+ * clock). Builds the navigator if the cached one has expired.
6733
+ */
6734
+ notePresented(card) {
6735
+ if (card.status !== "new") return;
6736
+ 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}`));
6737
+ }
6300
6738
  async getWeightedCards(limit) {
6301
6739
  const u = await this._getCurrentUser();
6302
6740
  try {
@@ -10667,10 +11105,11 @@ function backlogHtml(backlog) {
10667
11105
  const rows = backlog.map((b) => {
10668
11106
  const hot = b.backlogMultiplier >= 3;
10669
11107
  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";
11108
+ const headroom = b.backlogMultiplier > 1 ? `climbing (\xD7${b.backlogGrowthRate.toFixed(2)} per ${b.healthyBacklog} of mass in excess, unbounded)` : "healthy \u2014 no pressure";
11109
+ const mass = b.reviewMass !== null ? ` \xB7 mass ${b.reviewMass.toFixed(1)}` : "";
10671
11110
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10672
11111
  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>`;
11112
+ 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
11113
  }).join("");
10675
11114
  return `<div style="margin-bottom:6px"><div style="color:#93c5fd">review backpressure</div>${rows}</div>`;
10676
11115
  }
@@ -10809,8 +11248,9 @@ function snapshotToText(s) {
10809
11248
  const headroom = b.backlogMultiplier > 1 ? "climbing" : "healthy";
10810
11249
  const top = b.topReviewScore !== null ? b.topReviewScore.toFixed(2) : "\u2014";
10811
11250
  const next = b.nextDueIn ? `, next due ${b.nextDueIn}` : "";
11251
+ const mass = b.reviewMass !== null ? `, mass ${b.reviewMass.toFixed(1)}` : "";
10812
11252
  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}`
11253
+ ` ${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
11254
  );
10815
11255
  }
10816
11256
  }
@@ -11191,6 +11631,14 @@ function toRunCardTrail(c) {
11191
11631
  }))
11192
11632
  };
11193
11633
  }
11634
+ function persistedReading(r) {
11635
+ return {
11636
+ ...r,
11637
+ urgency: sig4(r.urgency),
11638
+ multiplier: sig4(r.multiplier),
11639
+ inputs: Object.fromEntries(Object.entries(r.inputs).map(([k, v]) => [k, sig4(v)]))
11640
+ };
11641
+ }
11194
11642
  function persistedRunCards(run) {
11195
11643
  const selected = run.cards.filter((c) => c.selected);
11196
11644
  const runnersUp = run.cards.filter((c) => !c.selected).slice(0, PERSISTED_RUNNERS_UP);
@@ -11516,7 +11964,8 @@ var init_SessionController = __esm({
11516
11964
  ...run.hints ? { hints: run.hints } : {},
11517
11965
  ...run.discardedTail ? { discardedTail: run.discardedTail } : {},
11518
11966
  cards: persistedRunCards(run),
11519
- ...run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {}
11967
+ ...run.unselectedNew ? { unselectedNew: persistedUnselectedNew(run.unselectedNew) } : {},
11968
+ ...run.regulators ? { regulators: run.regulators.map(persistedReading) } : {}
11520
11969
  });
11521
11970
  }
11522
11971
  }
@@ -12277,6 +12726,13 @@ var init_SessionController = __esm({
12277
12726
  queueSource,
12278
12727
  nextItem.score
12279
12728
  );
12729
+ for (const source of this.sources) {
12730
+ source.notePresented?.({
12731
+ cardId: nextItem.cardID,
12732
+ courseId: nextItem.courseID,
12733
+ status: nextItem.status
12734
+ });
12735
+ }
12280
12736
  snapshotQueues(this.supplyQ.length, this.failedQ.length);
12281
12737
  return card;
12282
12738
  }
@@ -14984,6 +15440,11 @@ var init_courseDB2 = __esm({
14984
15440
  setEphemeralHints(hints) {
14985
15441
  this._pendingHints = hints;
14986
15442
  }
15443
+ /** Forward a presentation to the navigator (a new card restarts its intake clock). */
15444
+ notePresented(card) {
15445
+ if (card.status !== "new") return;
15446
+ void this.createNavigator(this.userDB).then((navigator2) => navigator2.notePresented?.(card)).catch((e) => logger.warn(`[static/courseDB] Could not note a presentation: ${e}`));
15447
+ }
14987
15448
  async getWeightedCards(limit) {
14988
15449
  try {
14989
15450
  const navigator2 = await this.createNavigator(this.userDB);
@@ -15897,6 +16358,8 @@ var init_core = __esm({
15897
16358
 
15898
16359
  // src/index.ts
15899
16360
  init_core();
16361
+ init_pipelinePlan();
16362
+ init_regulators();
15900
16363
  init_courseLookupDB();
15901
16364
 
15902
16365
  // src/courseConfigRegistration.ts
@@ -16213,6 +16676,7 @@ export {
16213
16676
  ContentNavigator,
16214
16677
  CouchDBToStaticPacker,
16215
16678
  CourseLookup,
16679
+ DEFAULT_REGULATOR_CONFIG,
16216
16680
  DIVERSITY_FLOOR,
16217
16681
  DIVERSITY_STRENGTH,
16218
16682
  DocType,
@@ -16221,11 +16685,13 @@ export {
16221
16685
  FileSystemError,
16222
16686
  GuestUsername,
16223
16687
  HYDRATION_MARKER_ID,
16688
+ INTAKE_CLOCK_KEY,
16224
16689
  Loggable,
16225
16690
  NOT_SET,
16226
16691
  NavigatorRole,
16227
16692
  NavigatorRoles,
16228
16693
  Navigators,
16694
+ PIPELINE_STAGES,
16229
16695
  QuotaRoundRobinMixer,
16230
16696
  REVIEW_TIME_FORMAT2 as REVIEW_TIME_FORMAT,
16231
16697
  SessionController,
@@ -16233,6 +16699,7 @@ export {
16233
16699
  TagFilteredContentSource,
16234
16700
  _resetDataLayer,
16235
16701
  aggregateOutcomesForGradient,
16702
+ applyReading,
16236
16703
  areQuestionRecords,
16237
16704
  buildStrategyStateId,
16238
16705
  captureMixerRun,
@@ -16251,6 +16718,7 @@ export {
16251
16718
  drainCapturedRuns,
16252
16719
  endSessionTracking,
16253
16720
  ensureAppDataDirectory,
16721
+ frozenMsAt,
16254
16722
  getActiveController,
16255
16723
  getActivePipeline,
16256
16724
  getAppDataDirectory,
@@ -16260,6 +16728,7 @@ export {
16260
16728
  getDbPath,
16261
16729
  getDefaultLearnableWeight,
16262
16730
  getLapses,
16731
+ getRegisteredFilterKind,
16263
16732
  getRegisteredNavigator,
16264
16733
  getRegisteredNavigatorNames,
16265
16734
  getRegisteredNavigatorRole,
@@ -16273,6 +16742,8 @@ export {
16273
16742
  initializeDataDirectory,
16274
16743
  initializeDataLayer,
16275
16744
  initializeNavigatorRegistry,
16745
+ intakeHours,
16746
+ intakeReading,
16276
16747
  isDataShapeRegistered,
16277
16748
  isDataShapeSchemaAvailable,
16278
16749
  isFilter,
@@ -16292,6 +16763,7 @@ export {
16292
16763
  newSessionId,
16293
16764
  parseCardHistoryID,
16294
16765
  pipelineDebugAPI,
16766
+ planPipeline,
16295
16767
  processCustomQuestionsData,
16296
16768
  recordCardPresentation,
16297
16769
  recordUserOutcome,
@@ -16305,12 +16777,16 @@ export {
16305
16777
  removeCustomQuestionTypes,
16306
16778
  removeDataShape,
16307
16779
  removeQuestionType,
16780
+ resetIntakeClock,
16781
+ reviewMassReading,
16782
+ reviewWeight,
16308
16783
  runPeriodUpdate,
16309
16784
  scoreAccuracyInZone,
16310
16785
  sessionDebugAPI,
16311
16786
  setDebugSessionId,
16312
16787
  snapshotQueues,
16313
16788
  startSessionTracking,
16789
+ stepIntakeClock,
16314
16790
  toggleSessionOverlay,
16315
16791
  updateLearningState,
16316
16792
  updateStrategyWeight,